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).
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.
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.
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.
Path name races. The operating system resolves a path name, looking up each directory and then the final name, every time a call uses it. A check by name and a use by name are two separate lookups. A symbolic link, a renamed file or a swapped directory anywhere along the path can make the second lookup reach another file.
Double fetch. A more privileged component, such as an operating system kernel, reads a value from memory that a less privileged caller can still write, checks it, and later reads the same memory again to use the value. The caller changes the value between the two reads.
Verified data in writable storage. A program verifies data in a buffer that another party can still write, for example by checking the digital signature §5.14 of a software update, and later installs the contents of that buffer.
Stale authorization §1.7. A permission or an ownership is checked, then revoked or transferred, and the earlier approval is used afterwards.
Every repair removes the window or makes it harmless.
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
setuidprogram temporarily switches its effective user identity, the identity the kernel uses for permission checks, to the user who started it, and then callsopen; the kernel refuses the open if that user may not write the file. The open flagsO_CREATandO_EXCLtogether 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.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_NOFOLLOWmakesopenfail if the last part of the path is a symbolic link, and on Linux the callopenat2with the flagRESOLVE_NO_SYMLINKSrefuses a symbolic link in any part of the path.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.
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.
At 0 microseconds the program calls
accesson/home/user/report. The name leads to the user’s own regular file, the user may write it, and the check passes.At 40 microseconds the user deletes
reportand creates a symbolic link namedreportthat points to/etc/passwd, the system’s account file, which onlyrootmay write.At 80 microseconds the program calls
openon/home/user/reportwith the privileges ofroot. 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 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 , and the user makes attempts. Every attempt fails with probability . Writing for the natural logarithm and for its base, . At least one attempt succeeds with probability , 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.
First read: the length field holds 48. The check passes.
A second thread of the caller changes the field to 200.
Second read: the kernel reads the field again, gets 200, and copies 200 bytes into its 64-byte buffer.
The copy writes 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 be the reference the program uses, such as a path name or a pointer. Let be the time of the check and the later time of the use, so the window is the interval from to . Write for the object that selects at time , and for the statement that the checked property holds for object at time . The check establishes . The use is correct only if 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.
Identity stability: for every from to , so the use reaches the object that was checked.
Property stability: holds for every from to , 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].