]> git.ipfire.org Git - thirdparty/systemd.git/blame - docs/TEMPORARY_DIRECTORIES.md
NEWS: add warnings about read-only fs and libkmod being dlopen'ed
[thirdparty/systemd.git] / docs / TEMPORARY_DIRECTORIES.md
CommitLineData
b04d8490 1---
422128b4 2title: Using /tmp/ and /var/tmp/ Safely
4cdca0af 3category: Interfaces
b41a3f66 4layout: default
0aff7b75 5SPDX-License-Identifier: LGPL-2.1-or-later
b04d8490
LP
6---
7
422128b4 8# Using `/tmp/` and `/var/tmp/` Safely
b04d8490
LP
9
10`/tmp/` and `/var/tmp/` are two world-writable directories Linux systems
11provide for temporary files. The former is typically on `tmpfs` and thus
12backed by RAM/swap, and flushed out on each reboot. The latter is typically a
13proper, persistent file system, and thus backed by physical storage. This
14means:
15
161. `/tmp/` should be used for smaller, size-bounded files only; `/var/tmp/`
17 should be used for everything else.
18
192. Data that shall survive a boot cycle shouldn't be placed in `/tmp/`.
20
21If the `$TMPDIR` environment variable is set, use that path, and neither use
22`/tmp/` nor `/var/tmp/` directly.
23
24See
25[file-hierarchy(7)](https://www.freedesktop.org/software/systemd/man/file-hierarchy.html)
26for details about these two (and most other) directories of a Linux system.
27
28## Common Namespace
29
30Note that `/tmp/` and `/var/tmp/` each define a common namespace shared by all
31local software. This means guessable file or directory names below either
32directory directly translate into a 🚨 Denial-of-Service (DoS) 🚨 vulnerability
33or worse: if some software creates a file or directory `/tmp/foo` then any
34other software that wants to create the same file or directory `/tmp/foo`
35either will fail (as the file already exists) or might be tricked into using
56ee4d70 36untrusted files. Hence: do not use guessable names in `/tmp/` or `/var/tmp/` —
b04d8490
LP
37if you do you open yourself up to a local DoS exploit or worse. (You can get
38away with using guessable names, if you pre-create subdirectories below `/tmp/`
39for them, like X11 does with `/tmp/.X11-unix/` through `tmpfiles.d/`
40drop-ins. However this is not recommended, as it is fully safe only if these
41directories are pre-created during early boot, and thus problematic if package
42installation during runtime is permitted.)
43
44To protect yourself against these kinds of attacks Linux provides a couple of
45APIs that help you avoiding guessable names. Specifically:
46
e2285c57 471. Use [`mkstemp()`](https://man7.org/linux/man-pages/man3/mkstemp.3.html)
b04d8490 48 (POSIX), `mkostemp()` (glibc),
e2285c57
MB
49 [`mkdtemp()`](https://man7.org/linux/man-pages/man3/mkdtemp.3.html) (POSIX),
50 [`tmpfile()`](https://man7.org/linux/man-pages/man3/tmpfile.3.html) (C89)
b04d8490 51
e2285c57 522. Use [`open()`](https://man7.org/linux/man-pages/man2/open.2.html) with
b04d8490
LP
53 `O_TMPFILE` (Linux)
54
e2285c57 553. [`memfd_create()`](https://man7.org/linux/man-pages/man2/memfd_create.2.html)
b04d8490
LP
56 (Linux; this doesn't bother with `/tmp/` or `/var/tmp/` at all, but uses the
57 same RAM/swap backing as `tmpfs` uses, hence is very similar to `/tmp/`
58 semantics.)
59
60For system services systemd provides the `PrivateTmp=` boolean setting. If
61turned on for a service (👍 which is highly recommended), `/tmp/` and
62`/var/tmp/` are replaced by private sub-directories, implemented through Linux
63file system namespacing and bind mounts. This means from the service's point of
64view `/tmp/` and `/var/tmp/` look and behave like they normally do, but in
65reality they are private sub-directories of the host's real `/tmp/` and
66`/var/tmp/`, and thus not system-wide locations anymore, but service-specific
67ones. This reduces the surface for local DoS attacks substantially. While it is
68recommended to turn this option on, it's highly recommended for applications
69not to rely on this solely to avoid DoS vulnerabilities, because this option is
70not available in environments where file system namespaces are prohibited, for
71example in certain container environments. This option is hence an extra line
72of defense, but should not be used as an excuse to rely on guessable names in
73`/tmp/` and `/var/tmp/`. When this option is used, the per-service temporary
74directories are removed whenever the service shuts down, hence the lifecycle of
75temporary files stored in it is substantially different from the case where
76this option is not used. Also note that some applications use `/tmp/` and
77`/var/tmp/` for sharing files and directories. If this option is turned on this
78is not possible anymore as after all each service gets its own instances of
79both directories.
80
81## Automatic Clean-Up
82
83By default, `systemd-tmpfiles` will apply a concept of ⚠️ "ageing" to all files
84and directories stored in `/tmp/` and `/var/tmp/`. This means that files that
85have neither been changed nor read within a specific time frame are
86automatically removed in regular intervals. (This concept is not new to
f6e94c5f 87`systemd-tmpfiles`, it's inherited from previous subsystems such as
b04d8490
LP
88`tmpwatch`.) By default files in `/tmp/` are cleaned up after 10 days, and
89those in `/var/tmp` after 30 days.
90
91This automatic clean-up is important to ensure disk usage of these temporary
92directories doesn't grow without bounds, even when programs abort unexpectedly
93or otherwise don't clean up the temporary files/directories they create. On the
94other hand it creates problems for long-running software that does not expect
95temporary files it operates on to be suddenly removed. There are a couple of
96strategies to avoid these issues:
97
981. Make sure to always keep a file descriptor to the temporary files you
99 operate on open, and only access the files through them. This way it doesn't
100 matter whether the files have been unlinked from the file system: as long as
101 you have the file descriptor open you can still access the file for both
102 reading and writing. When operating this way it is recommended to delete the
103 files right after creating them to ensure that on unexpected program
104 termination the files or directories are implicitly released by the kernel.
105
1062. 🥇 Use `memfd_create()` or `O_TMPFILE`. This is an extension of the
107 suggestion above: files created this way are never linked under a filename
108 in the file system. This means they are not subject to ageing (as they come
109 unlinked out of the box), and there's no time window where a directory entry
110 for the file exists in the file system, and thus behaviour is fully robust
111 towards unexpected program termination as there are never files on disk that
112 need to be explicitly deleted.
113
65e179a1
DDM
1143. 🥇 Take an exclusive or shared BSD file lock ([`flock()`](
115 https://man7.org/linux/man-pages/man2/flock.2.html)) on files and directories
116 you don't want to be removed. This is particularly interesting when operating
117 on more than a single file, or on file nodes that are not plain regular files,
118 for example when extracting a tarball to a temporary directory. The ageing
119 algorithm will skip all directories (and everything below them) and files that
120 are locked through a BSD file lock. As BSD file locks are automatically released
b04d8490
LP
121 when the file descriptor they are taken on is closed, and all file
122 descriptors opened by a process are implicitly closed when it exits, this is
123 a robust mechanism that ensures all temporary files are subject to ageing
124 when the program that owns them dies, but not while it is still running. Use
125 this when decompressing tarballs that contain files with old
126 modification/access times, as extracted files are otherwise immediately
127 candidates for deletion by the ageing algorithm. The
e2285c57 128 [`flock`](https://man7.org/linux/man-pages/man1/flock.1.html) tool of the
65e179a1 129 `util-linux` packages makes this concept available to shell scripts.
b04d8490
LP
130
1314. Keep the access time of all temporary files created current. In regular
132 intervals, use `utimensat()` or a related call to update the access time
133 ("atime") of all files that shall be kept around. Since the ageing algorithm
134 looks at the access time of files when deciding whether to delete them, it's
135 sufficient to update their access times in sufficiently frequent intervals to
136 ensure the files are not deleted. Since most applications (and tools such as
137 `ls`) primarily care for the modification time (rather than the access time)
138 using the access time for this purpose should be acceptable.
139
1405. Set the "sticky" bit on regular files. The ageing logic skips deletion of
141 all regular files that have the sticky bit (`chmod +t`) set. This is
142 honoured for regular files only however, and has no effect on directories as
143 the sticky bit has a different meaning for them.
144
1456. Don't use `/tmp/` or `/var/tmp/`, but use your own sub-directory under
146 `/run/` or `$XDG_RUNTIME_DIRECTORY` (the former if privileged, the latter if
147 unprivileged), or `/var/lib/` and `~/.config/` (similar, but with
148 persistency and suitable for larger data). The two temporary directories
149 `/tmp/` and `/var/tmp/` come with the implicit clean-up semantics described
150 above. When this is not desired, it's possible to create private per-package
151 runtime or state directories, and place all temporary files there. However,
152 do note that this means opting out of any kind of automatic clean-up, and it
153 is hence particularly essential that the program cleans up generated files
154 in these directories when they are no longer needed, in particular when the
155 program dies unexpectedly. Note: this strategy is only really suitable for
156 packages that operate in a "system wide singleton" fashion with "long"
5238e957 157 persistence of its data or state, i.e. as opposed to programs that run in
b04d8490
LP
158 multiple parallel or short-living instances. This is because a private
159 directory under `/run` (and the other mentioned directories) is itself
160 system and package specific singleton with greater longevity.
161
1625. Exclude your temporary files from clean-ups via a `tmpfiles.d/` drop-in
163 (which includes drop-ins in the runtime-only directory
164 `/run/tmpfiles.d/`). The `x`/`X` line types may be used to exclude files
165 matching the specified globbing patterns from the ageing logic. If this is
166 used, automatic clean-up is not done for matching files and directory, and
167 much like with the previous option it's hence essential that the program
168 generating these temporary files carefully removes the temporary files it
169 creates again, and in particular so if it dies unexpectedly.
170
171🥇 The semantics of options 2 (in case you only deal with temporary files, not
172directories) and 3 (in case you deal with both) in the list above are in most
173cases the most preferable. It is thus recommended to stick to these two
174options.
175
176While the ageing logic is very useful as a safety concept to ensure unused
177files and directories are eventually removed a well written program avoids even
178creating files that need such a clean-up. In particular:
179
1801. Use `memfd_create()` or `O_TMPFILE` when creating temporary files.
181
1822. `unlink()` temporary files right after creating them. This is very similar
183 to `O_TMPFILE` behaviour: consider deleting temporary files right after
184 creating them, while keeping open a file descriptor to them. Unlike
185 `O_TMPFILE` this method also works on older Linux systems and other OSes
186 that do not implement `O_TMPFILE`.
187
188## Disk Quota
189
190Generally, files allocated from `/tmp/` and `/var/tmp/` are allocated from a
191pool shared by all local users. Moreover the space available in `/tmp/` is
192generally more restricted than `/var/tmp/`. This means, that in particular in
193`/tmp/` space should be considered scarce, and programs need to be prepared
194that no space is available. Essential programs might require a fallback logic
195using a different location for storing temporary files hence. Non-essential
196programs at least need to be prepared for `ENOSPC` errors and generate useful,
197actionable error messages.
198
199Some setups employ per-user quota on `/var/tmp/` and possibly `/tmp/`, to make
200`ENOSPC` situations less likely, and harder to trigger from unprivileged
201users. However, in the general case no such per-user quota is implemented
202though, in particular not when `tmpfs` is used as backing file system, because
203— even today — `tmpfs` still provides no native quota support in the kernel.
204
205## Early Boot Considerations
206
207Both `/tmp/` and `/var/tmp/` are not necessarily available during early boot,
208or — if they are available early — are not writable. This means software that
209is intended to run during early boot (i.e. before `basic.target` — or more
210specifically `local-fs.target` — is up) should not attempt to make use of
211either. Interfaces such as `memfd_create()` or files below a package-specific
212directory in `/run/` are much better options in this case. (Note that some
213packages instead use `/dev/shm/` for temporary files during early boot; this is
214not advisable however, as it offers no benefits over a private directory in
215`/run/` as both are backed by the same concept: `tmpfs`. The directory
216`/dev/shm/` exists to back POSIX shared memory (see
e2285c57 217[`shm_open()`](https://man7.org/linux/man-pages/man3/shm_open.3.html) and
b04d8490
LP
218related calls), and not as a place for temporary files. `/dev/shm` is
219problematic as it is world-writable and there's no automatic clean-up logic in
220place.)