TOCTOU

Also known as: Time-of-check to time-of-use

On this page 7

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.

PhaseVictim programAttacker action
CheckVerifies path, permission or valuePresents a harmless resource
Race windowPerforms other work or is descheduledSwaps the resource, for example via symlink
UseOpens, executes or writes the resourceBenefits from the victim’s privileges
OutcomeActs on an unintended objectGains access, escalates or corrupts data
Phases of a typical TOCTOU attack

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.

LocationChecked stateTypical consequence
FilesystemPath, ownership, permissionsPrivilege escalation via symlinks
Kernel system callsUser-space buffer contentsDouble-fetch kernel memory corruption
Web applicationsAccount balance, coupon statusDuplicate withdrawals or redemptions
DatabasesRow value before updateLost updates, inconsistent records
Hardware and firmwareSigned image or measured codeBypassed secure boot or attestation
Where TOCTOU flaws occur

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 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.

WeaknessDefining featureRelationship to TOCTOU
Race condition (CWE-362)Unsynchronized concurrent accessParent class of TOCTOU
Use-after-freeMemory used after releaseOften triggered by a race, but different root cause
Symlink following (CWE-59)Resolving links to unintended targetsCommon exploitation path for file TOCTOU
Improper input validationMissing or weak checksTOCTOU has a valid check that later becomes stale
Speculative execution flawsMicroarchitectural bypass of checksConceptually similar check-use gap in hardware
TOCTOU and neighboring weakness classes

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.

TechniqueHow it helpsExample
Operate on file descriptorsBinds checks to an opened objectopen() then fstat() instead of stat() then open()
Atomic creation flagsFails if the object already existsO_CREAT with O_EXCL, O_NOFOLLOW
Drop privileges firstLets the kernel enforce permissionsTemporarily switch effective user ID
Database transactionsSerializes read and writeSELECT ... FOR UPDATE, conditional updates
Copy once, then validateRemoves double fetchesKernel copies user data to private memory
Effective TOCTOU countermeasures

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.