logo svg
logo

January 4, 2026

Updated: November 5, 2026

What Is TOCTOU? Time-of-Check to Time-of-Use Race Condition

Understanding the TOCTOU race condition vulnerability, real-world exploits, and how attackers abuse timing gaps.

Mohammed Khalil

Mohammed Khalil

Featured Image

TOCTOU (time-of-check to time-of-use) is a race condition in which a program checks a resource, such as a file’s permissions, an account balance or a user’s access, and then acts on it in a separate, later step. If an attacker or another process changes the resource in that gap, the program acts on something it never checked. MITRE catalogs the weakness as CWE-367. The fix is not a better check: remove the separate check, make the check and the use one atomic operation, or verify the object you actually opened.

Time of check to time of use (TOCTOU) is a well known class of software bug caused by a race condition. It occurs when a program checks a condition or resource state, and then uses that resource later, assuming nothing changed in between. In that tiny time gap, an attacker can swoop in to modify the state for example, swapping out a file or altering a value so that the later use operates on something malicious. This vulnerability has been recognized for decades in traditional operating systems, yet it remains highly relevant today. Modern cloud applications, container platforms, and even serverless functions often perform asynchronous or multi step operations, which means TOCTOU bugs still surface in new forms. In short, whenever a system makes a security decision at one moment and acts on it at a later moment, there’s a risk that a clever attacker might exploit the gap. TOCTOU conditions frequently show up in attack/defense scenarios from low level OS exploits to logic flaws in web applications so security engineers encounter this pattern in many contexts.

DeepStrike's Red Teaming Services chain application weaknesses, including race conditions, into realistic attack paths that go beyond the flaws automated scanners report.

How Time of Check Time of Use Works

At its core, TOCTOU is about a timing window between a check and an action. Here’s how it typically works step by step:

  1. Time of Check: The application or system performs a check on a resource’s state. For example, a program might verify that a file exists and is not writable by unauthorized users, or an authentication service checks if a password is correct. At this moment, the program trusts that the condition it checked file is safe, password is valid, etc. will hold true going forward.
  2. Pause/Gap: After the check, there is a gap often very brief, potentially microseconds or milliseconds before the program actually uses the resource. This gap might be due to normal code execution steps, input/output delays, or scheduling of different threads/processes. In many cases, the program does not lock or guard the resource during this interval.
  3. Time of Use: The program then uses the resource based on the earlier check. For instance, it opens the file and writes to it, or issues a session token to the user who just passed login. It assumes the conditions are the same as when it was checked.

A TOCTOU race condition arises if an attacker can intervene during step 2 the gap and change the resource or system state in a way that invalidates the initial check. Because the program doesn’t realize the state changed, it proceeds to step 3 and performs actions under false assumptions.

Consider a classic file system example on a Unix-like OS: a setuid root program wants to append data to file.txt on behalf of a normal user. It first calls access("file.txt", W_OK) to check if the user should have permission to write that file. If the check passes, it then calls open("file.txt", O_WRONLY) to write to the file. The flaw is that access and open are separate calls operating on a filename, not a guaranteed constant file object. An attacker can exploit the gap by quickly swapping out file.txt for a symlink to a protected file say, /etc/passwd after the access check but before the open. The privileged program then unknowingly opens and writes to the protected file with root privileges. In effect, the attacker wins the race: the time of check saw a benign file, but by time of use it’s a malicious link resulting in unauthorized modification of a critical system file. This is how a simple check/use discrepancy can lead to a serious security breach.

TOCTOU flow: a file check and use with a symlink swap in the gap, vs one atomic open and a check of the same handle

TOCTOU isn’t limited to files. Any scenario where something is verified, then later acted on, can be vulnerable. In concurrent programming, one thread might validate a variable’s value while another thread changes it before it’s used. In distributed systems or databases, one component might check a record e.g. does the user have enough balance? and then another action debits the balance; if an attacker triggers a concurrent change, the outcome might violate business logic. The common theme is non atomic operations: the check and the use are separate, and without proper synchronization, this opens a race window. Attackers have various tricks to enlarge this window or improve their odds, such as running many attempts in parallel or slowing down the victim program e.g. by forcing heavy I/O operations that give the attacker more time. If the timing lines up in the attacker’s favor even once, the TOCTOU attack succeeds.

TOCTOU in Code: Vulnerable vs Fixed Examples

The two examples below are lab-safe illustrations of the pattern, not exploits. Each shows the check and the use as separate steps, then the same task written so the gap disappears.

File example (Python on Linux or macOS)

text
import os

# Vulnerable: check the name, then use the name
if not os.path.exists(path):          # time of check
    with open(path, "w") as f:        # time of use: follows a link planted in between
        f.write(data)
text
import os

# Fixed: one atomic call that fails if anything already exists at that name
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
fd = os.open(path, flags, 0o600)      # check and use happen together
with os.fdopen(fd, "w") as f:
    f.write(data)

With O_CREAT and O_EXCL set, the operating system creates the file only if nothing, not even a symbolic link, already exists at that name, so there is no separate check left to race. When the file must already exist, open it once with O_NOFOLLOW, then inspect the open descriptor with os.fstat() instead of the path. If a privileged program writes on behalf of a user, drop to that user’s privileges before the open, which is one of the mitigations CWE-367 lists.

Database example (SQL)

text
-- Vulnerable: read, decide in application code, then write
SELECT balance FROM accounts WHERE id = 42;
-- application checks balance >= 100, then:
UPDATE accounts SET balance = balance - 100 WHERE id = 42;
text
-- Fixed: the condition and the change are one atomic statement
UPDATE accounts
SET balance = balance - 100
WHERE id = 42 AND balance >= 100;
-- 0 rows updated means the check failed: reject the request

Two concurrent requests can both pass the SELECT check before either UPDATE runs, so the account is debited twice. Putting the condition in the WHERE clause lets the database apply the check and the change together. For multi-step logic, lock the row with SELECT ... FOR UPDATE inside a transaction, or enforce the rule with a unique constraint. Web testers call this a limit-overrun race; PortSwigger’s race conditions topic covers how it shows up in coupons, gift cards and rate limits. Static analysis catches some file patterns, but logic races like this one usually need dynamic or manual testing, as our comparison of SAST, DAST, IAST and RASP explains.

Real World Examples

OS Level File Exploits: The classic TOCTOU example described above using a symlink to replace a file between access and open has been used in the wild for privilege escalation. For instance, early versions of the BSD mail utility had a TOCTOU bug with temporary files that attackers could exploit with malicious symlinks. Similarly, a known weakness in a setuid program allowed attackers to overwrite /etc/passwd by exploiting the tiny gap between a permission check and file open. These are not just theoretical scenarios real attackers have leveraged such races to gain root control. In fact, TOCTOU race bugs are a common avenue for local privilege escalation on Unix systems tricking a privileged program to do something on your behalf that you couldn’t normally do. Security auditors often search for this pattern in code, because it frequently signals a possible elevation of privileges if an attacker can access the system.

Docker Container Breakout: TOCTOU issues persist in modern container environments. A notable case was a 2019 Docker vulnerability CVE-2018-15664 affecting all current versions of Docker at the time. It involved the docker cp command, which copies files between the host and a container. The Docker software would resolve a file path inside the container, then later use that path on the host and this was done in a non atomic way. Attackers found they could insert a malicious symlink in the container’s filesystem during the short interval between Docker checking the path and Docker actually using it. The result? An attacker with minimal access inside a container could trick Docker into copying data to any path on the host system, effectively granting read write access to files on the host as root. This TOCTOU race turned a container escape from a fear into reality an attacker could break out of the container sandbox by exploiting the time gap in path resolution. Docker patched the issue by fixing the symlink handling to close that race window. This example shows that even container orchestration tools must be wary of race condition vulnerabilities in how they handle file operations across trust boundaries.

Authentication Race in Web App: TOCTOU isn’t only about files or OS kernels; it can appear in application logic too. A real world case from a 2025 bug bounty write-up involved a web login system with an interesting bug. The application would check a user’s password, and if correct, proceed to generate an authentication token. Normally this is fine, check password, then issue a token. But due to heavy load and slow database calls, an attacker discovered a race condition: by flooding the server with login attempts during moments of high latency, it was possible to get multiple requests past the password check before the system updated the login attempt state. In other words, request 1 checks the password it’s wrong, but the system hasn’t marked a failure yet due to slowness, then request 2 also checks for wrong password checks and passes because the first is still processing, and so on and eventually tokens are issued for several wrong passwords. The attacker essentially outran the check. This is a TOCTOU flaw in an authentication flow: the system checked is login allowed? and used that result to issue tokens, but the state changed multiple parallel requests in between, causing an inconsistent outcome. The result was a broken authentication scenario where wrong credentials could sporadically succeed. The fix was to make the check and token issuance atomic or at least serialized per account so that no two login attempts could slip through in parallel.

Cloud Service Outage: Not all TOCTOU consequences are attacker driven; sometimes they cause accidental outages. In October 2025, Amazon Web Services AWS suffered a major disruption in its DynamoDB service due to a race condition in internal DNS management. Essentially, automation applied an outdated DNS configuration after a new one had already been deployed and cleaned up. The time gap between checking the current plan and applying changes led to deletion of the wrong IP addresses, causing widespread service failures. This incident, while not a malicious attack, is a real world TOCTOU bug manifesting at cloud scale showing that even extremely well engineered systems can fall prey to timing windows. It underscores that TOCTOU issues can have safety and availability impacts beyond just security. A tiny timing mistake in code logic can cascade into a regional outage.

These examples demonstrate how TOCTOU vulnerabilities span from low level system software up to high level cloud and application logic. Attackers have leveraged them for everything from privilege escalation on a single machine to container escape techniques in virtualized environments. Even defenders running complex cloud services have to account for race conditions to avoid costly mistakes. In all cases, the pattern is the same: a check that isn’t immediately followed by a committed action can be a weak link.

Recent TOCTOU Vulnerabilities (2025–2026)

TOCTOU is not only a historical Unix problem. Two widely deployed open-source projects shipped TOCTOU fixes between November 2025 and January 2026:

DisclosedComponentIdentifierWhat racedFixed in
Nov 5, 2025runc, the low-level container runtimeCVE-2025-31133, CVE-2025-52565Container setup mounts: a path such as /dev/null or /dev/pts/$n could be replaced with a symlink before runc bind-mounted it, exposing writable procfs files and enabling a container breakoutrunc 1.2.8, 1.3.3, 1.4.0-rc.3
Dec 15, 2025filelock, a Python file-locking libraryCVE-2025-68146The library checked whether the lock file existed, then opened it with O_TRUNC; a symlink planted in between let a local attacker truncate a victim filefilelock 3.20.1
Jan 9, 2026filelock SoftFileLockGHSA-qmgc-5h2g-mvrwGap between a writability check and lock file creationfilelock 3.20.3

Sources: the runc maintainers’ oss-security notice (it covers a third, related runc flaw, CVE-2025-52881), the NVD entry for CVE-2025-68146, and the SoftFileLock advisory.

Both fixes follow the rule shown in the code examples above. filelock added O_NOFOLLOW so the open fails on a symlink, and on Windows it refuses reparse points. runc’s patch set added an inode verification helper and safer reopening of paths, so the runtime checks the object it holds rather than trusting a name. For defenders, the practical step is to track runc, containerd and the host kernel as patch-critical components, as our container security guide recommends, and to run containers with user namespaces where you can.

Why Time of Check Time of Use Is Important

TOCTOU might sound like a niche technical detail, but its importance in security is huge. The implications of a successful TOCTOU exploit are often critical:

From a defender’s perspective, TOCTOU is important because it’s both subtle and pervasive. It’s subtle in that the code might work correctly 99.999% of the time the race window could be milliseconds or less so it slips past normal testing. But it’s pervasive because modern software is full of concurrency: multi-threading, microservices, asynchronous processing, etc., all of which introduce potential check/use gaps. As we move more to cloud and distributed architectures, there are more places where check then act logic occurs, often across different components. Attackers know this, and they actively hunt for race conditions as a way to do things like file tampering, escaping sandboxes, or messing with business logic. In recent years, researchers have highlighted TOCTOU flaws in everything from blockchain smart contracts to CI/CD pipeline tools, reinforcing that the issue spans many domains.

Finally, TOCTOU is important because it’s not easy to completely eliminate, even for experienced developers. It often requires rethinking how to perform actions in one atomic step or using special synchronization mechanisms. So, educating engineers and analysts about TOCTOU helps ensure they design systems with this in mind for example, avoiding the naive check then act pattern when dealing with critical resources. Recognizing a TOCTOU scenario early can prevent a severe vulnerability down the line.

Common Abuse or Misuse

When attackers target a TOCTOU vulnerability, they are exploiting the system’s assumption of consistency. Here’s how such attacks are typically abused:

In summary, attackers abuse TOCTOU by manipulating timing. They focus on high value scenarios like file writes, permission changes, or process hand offs and craft ways to inject themselves at just the right moment. Because of the inherent unpredictability of timing, these attacks can be inconsistent, but when they do hit, they can be devastating. This cat and mouse over microseconds is a unique aspect of TOCTOU exploitation that makes it both interesting and dangerous in the realm of privilege escalation techniques and other advanced attacks.

Detection & Monitoring

Detecting a TOCTOU attack or even the presence of a vulnerability is challenging, but not impossible. Security teams and monitoring systems can use several approaches:

In practice, detecting a TOCTOU attack often requires correlating multiple signals and having a deep understanding of expected system behavior. Many organizations learn of TOCTOU issues post fact through an incident or bug bounty rather than catching them live. Therefore, while monitoring can help, the emphasis is on prevention and safe design. Nonetheless, for high value systems, setting up alerts on suspicious race like patterns e.g., rapid fire file operations, high volumes of system calls around a sensitive action can provide a useful early warning.

Mitigation & Prevention

For UK teams reducing race-condition exposure, preventing TOCTOU vulnerabilities is fundamentally about eliminating or narrowing the gap between check and use, or avoiding the check altogether. Here are key strategies:

Mitigating TOCTOU often requires careful thinking and sometimes platform specific solutions, because a true fix might involve operating system support for example, transactions in filesystems, which are rare. However, following the above best practices drastically reduces the likelihood of introducing a TOCTOU flaw. The main goal is eliminating the gap or protecting it: do things in one step, or if you must check then use, control that interim period tightly with locks or re validation. As an added layer, code reviews and threat modeling should explicitly consider race conditions for any security critical logic. It’s better to assume an attacker will try to thread the needle between your checks, and code defensively against that.

Related Concepts

TOCTOU race conditions are part of a broader family of issues in concurrent and secure programming. It’s helpful to understand related concepts:

In summary, TOCTOU is one example of the challenges in concurrency and state management. By studying it, one touches on many core concepts in security and software engineering, from race conditions at large to specific exploit patterns and defensive coding strategies.

FAQs

TOCTOU is a specific type of race condition. All TOCTOU bugs are race conditions, but not all race conditions are TOCTOU. In particular, TOCTOU (time of check to time of use) refers to a pattern where a system checks a condition and later uses that result, with a window in between where the state can change. Other race conditions might involve two updates colliding, or ordering issues without a check/use scenario. Think of TOCTOU as a subset focused on security checks being invalidated by timing. It’s commonly associated with file access patterns, authentication flows, etc., whereas a generic race condition could be any timing issue in code for example, two threads updating a counter simultaneously. In essence: TOCTOU = a race that breaks a check then acts as an assumption.

They absolutely can occur in web and cloud contexts. While TOCTOU was originally identified in operating systems file and permission checks, the concept applies anywhere a state is checked and later used. Web applications can have TOCTOU bugs in workflows as the login token example shows, or in things like multi step transactions e.g., checking inventory, then placing an order an attacker could manipulate inventory in between. Cloud systems, especially distributed ones, are rife with potential races because different microservices or automation scripts might be operating without a global lock. CI/CD pipelines, serverless function deployments, container scheduling if any of these check a condition and assume it stays true, that assumption can be violated. Even hardware and network protocols can have race conditions. For instance, an API that first validates a request and then processes it asynchronously could be vulnerable if an attacker manages to swap the payload or context in between. So, TOCTOU is a cross cutting concern, not just an OS/filesystem issue.

Exploiting TOCTOU requires precise timing, but attackers use several techniques. If it’s a local software like a program on a computer, an attacker often writes a script or program that runs in parallel with the victim program. They might continuously perform the malicious action e.g., creating a symlink, as in our file example hoping one attempt lands in the right moment. Attackers can also slow down the victim program to widen the race window for example, by forcing heavy disk operations or large inputs that take time to process. In multi threaded scenarios, they may attempt to yield or sleep strategically or set high thread priorities for their exploit thread. For remote or web exploits, it could involve sending requests in rapid succession or out of order to trick the system like sending two nearly simultaneous requests to exploit a sequence. In advanced cases, attackers analyze code to pinpoint the race window and use custom tools to trigger at just the right microsecond. Tools like fuzzers or race conditions exploit frameworks that can systematically try to hit these conditions. Ultimately, the attacker’s goal is to perform an action in the gap: after the check but before the use. If they succeed even once, they might get the protected action to execute e.g., writing to a file or creating a session under false pretenses.

One well known example is the Docker symlink race CVE-2018-15664 we discussed, where exploiting TOCTOU yielded root access on the host from within a container. Another classic is the Dirty COW vulnerability CVE-2016-5195 in Linux while not a check/use of a file name, it was a race condition in the memory subsystem that let a user write to read only memory by exploiting a timing issue in copy on write. Dirty COW is often mentioned in the same breath as TOCTOU as it was a timing issue leading to privilege escalation, although the mechanism differed it wasn’t a separate check and use, but it was still about a race in enforcement. In the realm of Windows, a number of race conditions in system calls and registry access have been found e.g., issues where an attacker monitors a privileged operation creating a temporary object and quickly replaces it. Additionally, Pwn2Own contest exploits have included TOCTOU: at Pwn2Own Vancouver 2023, Synacktiv used a TOCTOU flaw to compromise the Gateway of a Tesla Model 3. These examples underscore how both modern and old systems have been impacted by TOCTOU.

The difficulty lies in the nature of concurrency and the abstractions we use in programming. Many programming languages and system APIs make it natural to write code in a check then act style. It's intuitive: if OK, then do X. Without careful thought, a developer might not realize that between the if and the do, something can change. Also, some operations simply don’t have an easy atomic API, forcing developers to do multi step procedures. Operating systems historically didn’t provide easy ways to, say, open this file only if it still has the same properties I checked in one go. Another challenge is that these issues rarely surface in testing; unless you specifically create a race condition, the code might run perfectly thousands of times and fail only once in a blue moon. That lulls developers into a false sense of safety. The timing has to be just wrong to manifest the bug, and typical testing doesn’t simulate an attacker deliberately trying to mess with timing. Additionally, truly avoiding TOCTOU often requires deeper changes: using locking, redesigning logic, or using newer APIs which might be non-trivial or have performance trade offs. Lastly, understanding concurrency bugs requires a different mindset thinking about what could happen out of order which is a notoriously tricky aspect of programming. Even experienced engineers can overlook these corner cases, especially when under time pressure. Tools and code reviews help, but they’re not foolproof. In summary, TOCTOU bugs hide in the gaps between operations, and our development processes often don’t examine those gaps closely.

For U.S. teams testing TOCTOU vulnerabilities, there are several practical approaches, including code audits, dynamic race testing, penetration testing, fuzzing, and instrumentation.

Ultimately, testing for TOCTOU requires creativity. You have to think like an attacker who does have control over timing. Often, a combination of code review to find where the critical check/use sequences are and targeted dynamic tests to try to exploit each one is the best approach. Keep in mind that proving a negative that no race exists is difficult; the goal is to get reasonable assurance by testing the most likely spots and using safer patterns.

Yes, over the years, OS developers have introduced measures to mitigate common TOCTOU scenarios, though there’s no universal solution yet. For example, modern Unix/Linux systems have added syscall variants and flags to reduce race windows: openat with directory file descriptors can constrain file path resolution to a known directory making it harder to swap in a malicious path, O_NOFOLLOW flag prevents following symlinks when opening files so even if an attacker creates a symlink at the last moment, the open will fail rather than follow it. Linux also has security settings like restricting symlinks in /tmp the fs.protected_symlinks sysctl which specifically aims at the symlink based TOCTOU attacks it won’t let a privileged program follow a symlink owned by another user in a sticky world writable directory. Windows introduced Transaction NTFS TxF to allow file operations to be done in transactions theoretically, one could do a check and use in a transaction and commit only if all was consistent. However, Microsoft has deprecated that feature due to complexity and performance issues. On the hardware side, some isolation techniques like Intel SGX enclaves, etc. can enforce that certain memory can’t be tampered with during critical sections, which can indirectly help. Another example: virtualization and container runtimes are being designed to minimize sharing of resources so that one container’s operations can’t interfere with another’s essentially a race condition mitigation by isolation. Lastly, the concept of filesystem transactions or journals can help ensure consistency, but making those available to developers for arbitrary use is still not common. In summary, OSes do provide better primitives now like safer file APIs, robust locking, and flags to avoid following links, and security aware developers should leverage those. But until systems can automatically make every check and use atomic, which is a hard problem, TOCTOU will remain something we must design around.

TOCTOU stands for time-of-check to time-of-use. It is also written TOCTTOU or TOC/TOU, and MITRE catalogs it as CWE-367, “Time-of-check Time-of-use (TOCTOU) Race Condition.” The name describes the two moments that matter: when a program checks a resource and when it later uses it.

Remove the gap rather than strengthening the check. Use one atomic operation that both checks and acts, such as open() with O_CREAT | O_EXCL or a conditional SQL UPDATE, or open the resource once and validate the handle you hold instead of the name. Where neither is possible, take the lock before the check, not after it, and run the action with the caller’s privileges so a lost race cannot turn into privilege escalation.

TOCTOU is CWE-367. In MITRE’s hierarchy it is a child of CWE-362, the general race condition weakness (concurrent execution using a shared resource with improper synchronization), and the parent of CWE-363, race condition enabling link following, which is the symlink case described above.

Time of check to time of use vulnerabilities teach a vital lesson: trust is temporal. A system might validate something at one point in time, but if it acts on that validation later, it must account for the world having changed in the meantime. TOCTOU bugs have been the culprit behind many high impact exploits and outages, precisely because they undermine fundamental assumptions in software e.g., the file I opened is still the same file I checked. As cybersecurity architects and engineers, being aware of TOCTOU means we develop with a healthy skepticism towards multi step operations. The key takeaways are to strive for atomicity in critical processes, use the proper safeguards, locks, transactions, safe APIs when a check/use sequence is unavoidable, and appreciate that attackers will try to race you if there’s a gain to be had. By preemptively closing those race windows, we significantly strengthen the security and robustness of our systems. In a world of parallel processing and distributed computing, that mindset is more important than ever.

About the Author

Mohammed Khalil is a Cybersecurity Architect at DeepStrike, specializing in advanced penetration testing and offensive security operations. With certifications including CISSP, OSCP, and OSWE, he has led numerous red team engagements, focusing on cloud security, application vulnerabilities, and adversary emulation. His work involves dissecting complex attack chains and developing resilient defense strategies for clients in the finance, healthcare, and technology sectors.

background
Let's hack you before real hackers do

Stay secure with DeepStrike penetration testing services. Reach out for a quote or customized technical proposal today

Contact Us