Section 9.26

Time-of-check to time-of-use (TOCTOU)

Definition

Time-of-check to time-of-use (TOCTOU) is a kind of race condition §9.2, a flaw whose outcome depends on the relative timing of activities that run at the same time. A program checks a property of something, then uses that thing in a separate, later step, and another actor changes it in between. The use then acts on something that was never checked. The change can be to the object itself, such as bytes in memory, or to which object a name selects, such as the file a path leads to.

The idea

The classic case comes from Unix-like operating systems such as Linux. A program installed with the setuid permission runs with the privileges of its owner, often the all-powerful root account, whichever user starts it. Such a program should write a file for the user who started it only if that user may write the file. It first calls access, a system call (a request from a program to the core of the operating system, the kernel) that answers whether the user who started the program, not the program’s owner, may write a given path. If the answer is yes, it calls open on the same path and writes. Between the two calls, the user replaces the file with a symbolic link §13.10, a small file whose content is another path that the system follows automatically, and points the link at a file that only root may write. access approved the user’s own file. open, running with the privileges of root, follows the link and opens the protected file. The Linux manual page for access warns against exactly this sequence.

The picture is a photograph. The check photographs the object, and the photograph is accurate when it is taken, but the use acts later on the live scene, on whatever is there by then. A check describes one object at one moment, and a use is safe only if it acts on that same object while the checked property still holds. The picture stops at one point. A photograph and the scene are obviously different things, whereas the check and the use usually name the object by the same path or pointer, and the identical spelling hides that the two steps can reach different objects.

How it works

Three ingredients make a TOCTOU flaw (the abbreviation is also written TOCTTOU).

  1. A check. The program establishes a property, such as “the caller may write this file” or “this length fits the buffer”, about something it reaches through a reference: a path name, a pointer, an index or an identifier.

  2. A separate use. Later, the program reaches the thing again through the same reference, or reads its value again, and acts as if the property still holds. The interval between the check and the use is called the window.

  3. Another actor. During the window, another process, thread, interrupt handler §6.12 or hardware device can change what the reference selects, or change the state of the selected object.

Remove any one of the three and the flaw disappears.

The flaw takes several common forms.

Every repair removes the window or makes it harmless.

  1. Let the use perform the check. Request the operation with exactly the authority the check was meant to confirm, so that the system checks and acts in one indivisible step. The setuid program temporarily switches its effective user identity, the identity the kernel uses for permission checks, to the user who started it, and then calls open; the kernel refuses the open if that user may not write the file. The open flags O_CREAT and O_EXCL together create a file and fail if the name already exists, which replaces a separate “does it exist?” check. For a value in shared memory, a compare-and-swap §9.9 writes a new value only if memory still holds the value that the check saw.

  2. Resolve once, then work through a handle. Open the object first and receive a handle that names the object itself, not its path. On Unix-like systems the handle is a file descriptor §15.21, a small number that keeps referring to the opened file even if its name is later moved or deleted. Check through the handle, for example with fstat, which reports the owner and type of an open file, and use the same handle. Refuse links during the lookup where the program does not want them: O_NOFOLLOW makes open fail if the last part of the path is a symbolic link, and on Linux the call openat2 with the flag RESOLVE_NO_SYMLINKS refuses a symbolic link in any part of the path.

  3. Copy once, check the copy, use the copy. Copy data that another party can write into memory that only the checking component can write, check the copy, and use only the copy. This removes double fetches and changes after verification.

  4. Freeze or lock the object. Make the object unchangeable for the length of the window, or protect it with a lock, provided every actor that could change the object must take that lock. Advisory file locks on Unix-like systems bind only the programs that choose to check them, so they do not stop an attacker.

Worked example

A path name race. A setuid program owned by root appends a line to /home/user/report, a file in a directory that the user who started the program owns. Times are in microseconds (millionths of a second) after the program begins.

  1. At 0 microseconds the program calls access on /home/user/report. The name leads to the user’s own regular file, the user may write it, and the check passes.

  2. At 40 microseconds the user deletes report and creates a symbolic link named report that points to /etc/passwd, the system’s account file, which only root may write.

  3. At 80 microseconds the program calls open on /home/user/report with the privileges of root. The lookup follows the new link, and the program appends the user’s line to /etc/passwd.

The path was spelled the same way both times, but the file it selected changed. The window lasted 80−0=8080 - 0 = 80 microseconds.

A short window is not a defense. The user can run the program again and again. Suppose one attempt, one run with one timed swap, succeeds with probability p=0.001p = 0.001, and the user makes n=5000n = 5000 attempts. Every attempt fails with probability (1−p)n=0.9995000(1 - p)^n = 0.999^{5000}. Writing ln\ln for the natural logarithm and e≈2.718e \approx 2.718 for its base, 0.9995000=e5000×ln0.999=e5000×(−0.0010005)=e−5.0025≈0.00670.999^{5000} = e^{5000 \times \ln 0.999} = e^{5000 \times (-0.0010005)} = e^{-5.0025} \approx 0.0067. At least one attempt succeeds with probability 1−0.0067=0.99331 - 0.0067 = 0.9933, about 99.3%.

A double fetch. A kernel service copies a request from memory that the calling program can still write. The request begins with a 4-byte length field, and the kernel’s own buffer holds 64 bytes.

  1. First read: the length field holds 48. The check 48≤6448 \le 64 passes.

  2. A second thread of the caller changes the field to 200.

  3. Second read: the kernel reads the field again, gets 200, and copies 200 bytes into its 64-byte buffer.

The copy writes 200−64=136200 - 64 = 136 bytes past the end of the buffer. The repair is to read the field once into a local variable that only the kernel can write, check that variable, and use that same variable as the copy length.

Stated precisely

Let RR be the reference the program uses, such as a path name or a pointer. Let cc be the time of the check and uu the later time of the use, so the window is the interval from cc to uu. Write objt(R)\mathrm{obj}_t(R) for the object that RR selects at time tt, and P(x,t)P(x, t) for the statement that the checked property holds for object xx at time tt. The check establishes P(objc(R),c)P(\mathrm{obj}_c(R), c). The use is correct only if P(obju(R),u)P(\mathrm{obj}_u(R), u) holds, and the first statement does not imply the second. The second is guaranteed if both of the following hold for every behavior that the threat model §1.2 (the account of what attackers can do) allows the other actors.

  1. Identity stability: objt(R)=objc(R)\mathrm{obj}_t(R) = \mathrm{obj}_c(R) for every tt from cc to uu, so the use reaches the object that was checked.

  2. Property stability: P(objc(R),t)P(\mathrm{obj}_c(R), t) holds for every tt from cc to uu, so the checked object still has the property when it is used.

A handle gives identity stability but not property stability: the file behind a file descriptor is fixed, while its content and its owner can still change. A private copy gives both, for the copied bytes. An operation that checks and acts in one indivisible step leaves no window, so neither condition is needed.

Limits and common mistakes

Narrowing the window is not a repair. Faster code, or a second check just before the use, shortens or moves the window, but a window remains, and repeated attempts defeat a small chance per attempt. An attacker can often widen the window, for example by making the path lookup slow with a long chain of nested directories.

A handle fixes which object is used, not what the object contains. If another party can still write the opened file, its bytes can change after the check. A hash of the content, a short fingerprint computed by a cryptographic hash function §5.1, describes the bytes read at that moment. It does not stop later changes, and reopening the file by name may reach a different file altogether.

Comparing identities is weaker than holding a handle. A common pattern checks the file by path, opens it, and compares the device and inode numbers of the two; an inode is the file system’s internal record of a file, and its number identifies the file on one device. The comparison is fooled if the checked file is deleted and its number is given to a new file in between, a hazard called inode reuse §15.24.

One processor is enough. The other actor need not run in parallel: preemption, in which the operating system pauses one activity to run another, an interrupt handler, or a DMA §4.36 (direct memory access) engine, hardware that writes memory without the processor, can change state inside the window.

System defenses narrow the problem without removing it. Linux, for example, can refuse to follow a symbolic link in a shared, world-writable directory such as /tmp when the link belongs to neither the follower nor the directory’s owner. A race through the attacker’s own directory, as in the worked example, is unaffected.

The flaw is not limited to files. It occurs with shared memory, device registers, database rows and cached authorization decisions. The Common Weakness Enumeration (CWE), a public catalog of software weaknesses, lists it as CWE-367.

Questions answered

Can a symlink target change between validation and open?

Yes, the file that a symbolic link leads to can change between validation and open. A symbolic link (symlink) is a small file whose content is a path that the system follows automatically, and every call that uses the link’s name looks it up anew. A link cannot be edited in place, but it can be replaced in one step: create a new link under a temporary name, then rename it over the old one. Validation and open are separate calls, so between them any process that may write to the directory holding the link can make the name lead elsewhere, or replace a directory further up the path. The open then reaches a file that was never validated. This is a time-of-check to time-of-use (TOCTOU) flaw, and repeated attempts make even a window of microseconds exploitable.

The repair binds validation and use to one object. Open first, refusing links where they are not wanted: O_NOFOLLOW rejects a link in the last part of the path, and on Linux openat2 with RESOLVE_NO_SYMLINKS rejects links in every part, or with RESOLVE_BENEATH keeps the whole lookup inside one chosen directory. Then validate through the returned file descriptor, for example with fstat, and use only that descriptor. If the validation is a permission check, open the file with the requesting user’s own identity, so that the kernel checks and opens in one step. Comparing path strings, or converting the path to its canonical form (the absolute path with every link resolved) with realpath, does not help: the path can change after that step too.

Related entries: Overflow-safe range check (§4.17), Complete mediation (§1.16), Compare-and-swap (§9.9), Race condition (§9.2), Trust boundary (§1.3), Namespace and symlink resolution (§13.9), Hard link versus symbolic link (§13.10), File descriptor versus pathname (§15.21), Inode reuse (§15.24). Further reading: [141].