TOCTOU (time-of-check to time-of-use) is a class of race condition vulnerabilities in which a program verifies a property of a resource, such as a file’s owner or a value’s bounds, and then uses that resource later, after an attacker has had the chance to change it in the gap between the two steps. Among software vulnerabilities in cybersecurity, it is cataloged as CWE-367, a child of the broader race condition weakness CWE-362.
The core flaw is an unsafe assumption of atomicity: the code treats check and use as one indivisible operation when the operating system, hardware or another thread can intervene between them. Exploitation can lead to privilege escalation, unauthorized file access, data corruption or bypassed security policies.
How a TOCTOU race condition works
A TOCTOU flaw requires three ingredients: a check on some state, a later use that relies on the check still being true, and a shared resource that another actor can modify in between. The interval between check and use is called the race window, and it may last from nanoseconds to seconds.
The classic example is a privileged Unix program that calls access() to confirm that the real user may write to a path, then calls open() on the same path. Between those calls, an attacker replaces the file with a symbolic link to /etc/passwd. The check validated one object; the use acts on another, now with root privileges.
| Phase | Victim program | Attacker action |
|---|---|---|
| Check | Verifies path, permission or value | Presents a harmless resource |
| Race window | Performs other work or is descheduled | Swaps the resource, for example via symlink |
| Use | Opens, executes or writes the resource | Benefits from the victim’s privileges |
| Outcome | Acts on an unintended object | Gains access, escalates or corrupts data |
Attackers widen narrow windows with techniques such as filesystem mazes of deeply nested directories, heavy system load, or repeated attempts in a tight loop. Because each try is cheap, a window that succeeds once in thousands of attempts is often practically exploitable.
Types and locations of TOCTOU vulnerabilities
TOCTOU is not limited to files. Any boundary where state is validated once and trusted later can host the pattern, which is why the flaw appears in operating system kernels, web applications and hardware interfaces alike.
| Location | Checked state | Typical consequence |
|---|---|---|
| Filesystem | Path, ownership, permissions | Privilege escalation via symlinks |
| Kernel system calls | User-space buffer contents | Double-fetch kernel memory corruption |
| Web applications | Account balance, coupon status | Duplicate withdrawals or redemptions |
| Databases | Row value before update | Lost updates, inconsistent records |
| Hardware and firmware | Signed image or measured code | Bypassed secure boot or attestation |
The double-fetch variant is especially serious in kernels and hypervisors: the kernel reads a length from user memory, validates it, then reads it again for use while another thread has changed it. This can produce a buffer overflow even though bounds checking appeared correct in the source code.
TOCTOU compared with related weaknesses
TOCTOU is a specific shape of race condition, defined by the check-then-use sequence. Distinguishing it from neighboring weaknesses helps in classification within CWE and in choosing a fix.
| Weakness | Defining feature | Relationship to TOCTOU |
|---|---|---|
| Race condition (CWE-362) | Unsynchronized concurrent access | Parent class of TOCTOU |
| Use-after-free | Memory used after release | Often triggered by a race, but different root cause |
| Symlink following (CWE-59) | Resolving links to unintended targets | Common exploitation path for file TOCTOU |
| Improper input validation | Missing or weak checks | TOCTOU has a valid check that later becomes stale |
| Speculative execution flaws | Microarchitectural bypass of checks | Conceptually similar check-use gap in hardware |
The essential difference from simple validation bugs is that in TOCTOU the check itself is correct. The defect lies in the assumption that the result stays true, which is why code review that only verifies the presence of checks often misses it.
Preventing and mitigating TOCTOU
The most reliable defense is to eliminate the gap by making check and use a single atomic operation, or by checking the very object that will be used rather than a name that can be rebound.
| Technique | How it helps | Example |
|---|---|---|
| Operate on file descriptors | Binds checks to an opened object | open() then fstat() instead of stat() then open() |
| Atomic creation flags | Fails if the object already exists | O_CREAT with O_EXCL, O_NOFOLLOW |
| Drop privileges first | Lets the kernel enforce permissions | Temporarily switch effective user ID |
| Database transactions | Serializes read and write | SELECT ... FOR UPDATE, conditional updates |
| Copy once, then validate | Removes double fetches | Kernel copies user data to private memory |
Developers should also avoid access() for security decisions, use directory-relative calls such as openat(), and place temporary files in private directories. Static analyzers and fuzzers with thread interleaving support can detect many patterns, but design-level atomicity remains more dependable than detection.
Severity, detection and common misconceptions
TOCTOU severity varies widely. A flaw in a setuid binary or kernel is often rated high on CVSS because it yields root, while a race in a web shopping cart may cause financial loss without system compromise. Scoring usually reflects high attack complexity, since winning the race is not guaranteed.
- A small window is not a safe window: automated retries make millisecond and even microsecond windows exploitable.
- Single-core systems are not immune: preemption and interrupts still allow interleaving.
- Adding a second check does not help: it only creates another stale result.
- Memory-safe languages do not prevent TOCTOU: the flaw lives in logic and shared external state.
The idea in brief
TOCTOU happens when a program checks something and then trusts that check a moment too long. In that short pause, someone else swaps what was checked for something different.
Picture a guard who inspects a sealed box, approves it, then turns away to fill in a form. While the guard is writing, someone replaces the box with another one, and the guard waves it through. The inspection was correct; the timing was the problem. The fix is to inspect and hand over the box in one motion, so nothing can change in between.
A practical scenario
A system administrator maintains a backup utility that runs as root and lets ordinary users restore files into their home directories. The tool checks that the destination path belongs to the requesting user with stat(), then writes the restored data with open() a few milliseconds later.
During a security review, a tester writes a short script that repeatedly swaps the destination between a normal file and a symbolic link to /etc/shadow. After about two minutes of retries, the race succeeds and the utility overwrites the password hash file with attacker-controlled content, giving the tester a path to root access.
The team rewrites the tool to drop privileges to the requesting user before opening the destination, adds O_NOFOLLOW, and verifies ownership with fstat() on the open descriptor. Repeated testing with the same script for several hours produces no successful exploit, and the fix ships before release.