---
title: 'TOCTOU Races: Timing Vulnerabilities'
url: https://www.emergentmind.com/topics/time-of-check-to-time-of-use-toctou-races
type: topic
---

# TOCTOU Races: Timing Vulnerabilities

Searching arXiv for the provided TOCTOU-related papers to ground the article in current literature.
Time-of-Check-to-Time-of-Use (TOCTOU) races are timing vulnerabilities in which a system validates some resource or state at one moment and later uses that resource under the assumption that the validated property still holds, even though the state may have changed in the interim. In the supplied literature, this pattern appears across operating systems, remote attestation, in-memory malware detection, browser and desktop GUI agents, AI coding-agent harnesses, private blocklisting, and concurrent resource management. A common formulation is that a check occurs at time \(t_{\text{check}}\) and a use occurs at time \(t_{\text{use}}\); the vulnerability arises when the relevant state differs between those moments, so that the action is performed on stale assumptions [2508.03879][2607.05743][2603.00476][2604.15641][2604.15641]. The surveyed work also makes clear that TOCTOU is not restricted to classic pathname and permission bugs: it recurs wherever validation is separated from action without an enforceable freshness or atomicity guarantee [2607.05743][2508.17155].

## 1. Definition and formal structure

TOCTOU is described as a race condition in which a program or system checks a condition, assumes it remains true, and then acts later after the checked state may already have changed [2508.03879][2603.00476][2604.15641][2604.15641][2508.17155]. The supplied material repeatedly characterizes the defect as a mismatch between validation time and action time. One source states that the system “checks a condition, assumes it is still true, but the condition changes before the system takes action” [2508.17155]. Another states that TOCTOU vulnerabilities “describe inconsistencies that occur when a resource is validated as safe for use but, when actually used later, would have been discovered as unsafe if checked at that time” [2604.15641].

Several papers render this pattern explicitly in timing notation. In the RX-INT threat model, a periodic memory scanner inspects a module at \(t_{\text{check}}\), an attacker alters and executes code at \(t_{\text{attack}}\), restores the original bytes at \(t_{\text{cleanup}}\), and the next scan occurs at \(t_{\text{next}}\); the attack succeeds if
\[
t_{\text{check}} < t_{\text{attack}} < t_{\text{cleanup}} < t_{\text{next}}
\]
because the detector never observes the malicious state [2508.03879]. In agent security, the desired invariant is expressed as
\[
\text{check}(s, t_c) \land \text{use}(s, t_u) \Rightarrow \text{state}(s, t_u) = \text{state}(s, t_c)
\]
and a TOCTOU violation as
\[
\text{check}(s, t_c) \land \text{use}(s, t_u) \land \text{state}(s, t_u) \neq \text{state}(s, t_c)
\]
with \(t_u > t_c\) [2607.05743]. Browser-use agents are modeled similarly by defining page state at observation time \(s_c\), page state at action time \(s_u\), and a target-binding function \(\textsf{Bind}(a,s)\); the vulnerability condition is
\[
s_c \neq s_u \;\wedge\; \textsf{Bind}(a, s_c) \neq \textsf{Bind}(a, s_u)
\]
so that an action selected against one page state resolves to a different target when executed later [2603.00476].

A recurring abstraction in the literature is that TOCTOU is a broader “state-validation problem” rather than merely a low-level bug class [2607.05743]. One survey summarizes the root cause as “authorization is checked once and trusted forever,” and applies that description to permissions, validated files, tool metadata, project trust decisions, and web state [2607.05743]. This suggests that TOCTOU is best understood as a temporal invalidation of a previously accepted predicate.

## 2. Classical systems roots and concurrent resource races

The traditional systems understanding of TOCTOU centers on mutable references, especially file-system names, permissions, and path resolution [2603.00476][2201.11764][2508.17155][2603.03141]. The standard pattern is that a process checks a pathname or file property and later performs `open(2)`, `unlink(2)`, or another operation assuming the same object is still being referenced; symlink substitution, directory renaming, or other concurrent changes can redirect the operation to a different object [2603.00476][2603.03141]. The browser-agent work explicitly frames this as “check-then-use” on a mutable reference and notes that the web platform lacks an atomic check-and-act primitive, making the browser analogue structurally similar to OS pathname races [2603.00476].

Concurrent shared-memory systems exhibit an analogous form in “read–destruct races,” where one process reads and then uses a resource while another concurrently overwrites and destructs it [2002.07053]. The paper “Concurrent Reference Counting and Resource Management in Wait-free Constant Time” [2002.07053] treats these races as a specific TOCTOU form and introduces an acquire–retire interface with `acquire`, `release`, `retire`, and `eject` primitives. Its stated guarantee is that if an `acquire` is linked to an `eject`, then all matching `release`s occur before `eject`, so that destruction after `eject` cannot overlap the protected use [2002.07053]. The same work applies this to memory reclamation, reference-counted objects, and ownership-managed objects, precisely to prevent a thread from reading a pointer, file stream, or object and then having another thread free or destroy it before use completes [2002.07053].

The short-race literature further connects TOCTOU to predictive race analysis. “Efficient Dynamic Algorithms to Predict Short Races” [2603.03141] distinguishes semantic TOCTOU races from lower-level data races but notes that TOCTOU patterns often manifest as predictive races over shared state. It defines short races by a span bound \(w\), where a race pair \((e_i,e_j)\) is short if the subtrace from \(e_i\) to \(e_j\) contains at most \(w\) events [2603.03141]. A plausible implication is that TOCTOU bugs are often operationally short because checks and uses are usually close in program order, making short-race detectors a natural fit for prioritizing actionable TOCTOU findings.

## 3. Remote attestation and integrity-checking TOCTOU

Remote attestation research treats TOCTOU as a mismatch between when software state is measured and when that measurement is relied upon [2005.03873][2201.11764][2502.07053]. In “On the TOCTOU Problem in Remote Attestation” [2005.03873], the core issue is that conventional remote attestation reveals only the state of the binary at attestation time. Malware can install itself, execute, and erase itself between attestations, or detect an incoming request and restore a clean image before the measurement begins [2005.03873]. That work formalizes a TOCTOU-security game in which a verifier accepts if \(\mathsf{Vrfy}(\sigma_c,c,M,\cdots)=1\) even though there exists \(t_i\) between a reference time \(t_0\) and attestation time \(t_{att}\) such that \(AR(t_i)\neq M\) [2005.03873].

RATA addresses this by storing a protected Last Modification Time \(LMT\) within the attested range \(AR\), updating it whenever executable memory changes, and including it in the attested token [2005.03873]. Two constructions are given: RATAa for devices with real-time clocks and RATAb for devices without them [2005.03873]. In RATAa, the verifier accepts only if \(t_{LMT}<t_0\) and the attestation MAC matches the expected memory image \(M\) [2005.03873]. In RATAb, challenge values themselves serve as modification markers, and the verifier tracks them across rounds [2005.03873]. The paper states that, compared with current remote attestation architectures that “offer no TOCTOU protection,” RATA incurs no extra runtime overhead and “substantially reduces computational costs of RA execution” [2005.03873].

A complementary attack on DICE shows the opposite direction: a clean boot-time measurement can be reused after compromise [2201.11764]. “A TOCTOU Attack on DICE Attestation” [2201.11764] describes a layered architecture in which boot logic measures firmware and derives an alias attestation key, but that key is later handed to application code. The attack installs malware during application runtime, copies the valid attestation key to flash, and after reboot overwrites the newly derived key in RAM with the previously stored clean key, so that later attestations continue to validate even though the application image now contains malware [2201.11764]. This is explicitly a check-at-boot, use-at-runtime discrepancy.

At network scale, TRAIN splits TOCTOU into intra-device and inter-device windows [2502.07053]. The intra-device window is the period between successive attestation instances for one device; the inter-device window is the variance between the earliest and latest attestation across devices in the network [2502.07053]. TRAIN uses synchronized attestation, constant-time per-device reports, and hybrid roots of trust derived from RATA or CASU plus GAROTA’s NetTCB and TimerTCB [2502.07053]. The paper gives the scheduling equations
\[
t_{timeout} = n \cdot (t_{request} + t_{hash} + t_{report}) + t_{MAC} + t_{slack}
\]
and
\[
t_{attest} = Height_{Net} \cdot (t_{request} + t_{hash}) + t_{slack} + t_{current}
\]
for the RTC-based variant [2502.07053]. It reports request verification time of approximately \(13\) ms and report generation time of approximately \(29.5\text{–}29.8\) ms at \(8\) MHz, both constant in the size of program memory [2502.07053]. This suggests that minimizing the time and skew of attestation itself is a direct TOCTOU mitigation strategy.

## 4. In-memory malware, fileless threats, and memory-forensics races

The RX-INT work frames TOCTOU as central to in-memory threat detection [2508.03879]. In that setting, a periodic scanner inspects process memory, while an attacker performs manual mapping, module stomping, or other fileless injection techniques entirely in address space and then restores the original bytes before the next scan [2508.03879]. The paper describes this explicitly: “An adversary can perform a module stomp, execute their payload, and restore the original bytes of the legitimate module in a window of opportunity that is shorter than the polling interval of a periodic scanner” [2508.03879].

The threat model includes manual PE mapping, often followed by erasing PE headers so that the payload becomes executable `MEM_PRIVATE` memory with no standard PE metadata; module stomping, in which `.text` of an existing DLL is made writable and overwritten; remote thread creation by `CreateRemoteThread` or `NtCreateThreadEx`; thread hijacking; `QueueUserAPC`; and post-injection cloaking tactics such as fake start addresses and suppressed `DLL_THREAD_ATTACH` notifications [2508.03879]. The paper emphasizes that “private, executable memory is not inherently suspicious,” because JIT runtimes and browsers also generate executable `MEM_PRIVATE` regions [2508.03879]. This ambiguity makes selective or periodic scanning attractive, and therefore TOCTOU-prone.

RX-INT’s architecture combines a kernel-mode driver, a real-time thread-creation callback via `PsSetCreateThreadNotifyRoutine`, and a stateful VAD scanner that baselines committed memory regions and hashes executable `MEM_IMAGE` regions using XXH64 [2508.03879]. The key claim is that “a suspicious event from the thread monitor immediately triggers an out-of-band scan from the VAD scanner, mitigating the TOCTOU race condition” [2508.03879]. When a new thread starts in a `MEM_IMAGE` region, the callback treats this as a “stomp hint,” signals the scanner via `KeSetEvent`, and the scanner compares current hashes against its baseline [2508.03879]. For executable image region \(R\), the baseline and current hashes are
\[
h_{\text{baseline}}(R) = \text{XXH64}(R_{\text{initial}}), \qquad
h_{\text{current}}(R) = \text{XXH64}(R_{\text{current}})
\]
and a mismatch indicates module stomping or inline modification [2508.03879].

The evaluation contrasts RX-INT with PE-sieve. In a module-stomping test that “simulated an adversary stomping the Beep function in kernel32.dll, executing a payload, and immediately restoring the original bytes,” PE-sieve “was unable to detect the fast cleanup attack” and “lost the TOCTOU race,” whereas RX-INT’s `OnThreadNotify` callback triggered an immediate VAD scan that detected the content hash mismatch before restoration [2508.03879]. Additional reported figures include idle monitoring below \(0.1\%\) kernel CPU, active detection in Chrome at approximately \(0.46\%\) CPU in release build, non-paged pool footprint around \(340\) KB, and paged pool around \(6\) MB for complex processes [2508.03879]. The paper’s larger point is that event-driven detection tied to the time of execution can succeed where periodic user-mode snapshots fail.

## 5. TOCTOU in AI agents, browser agents, and GUI agents

Recent work extends TOCTOU from OS resources to agent pipelines, web interfaces, and desktop GUIs [2607.05743][2508.17155][2603.00476][2604.18860]. The 2026 survey on execution security for AI coding agents classifies TOCTOU as Category 5 and defines it as a race where an agent validates a file, webpage structure, policy, project trust state, or tool metadata and later acts on a stale copy after that state changes [2607.05743]. The survey explicitly equates TOCTOU with “checked once, trusted forever” and argues that TOCTOU and Model Context Protocol threats are structurally the same validate-then-act problem [2607.05743].

“Mind the Gap: Time-of-Check to Time-of-Use Vulnerabilities in LLM-Enabled Agents” [2508.17155] studies this pattern in tool-using agents built with LangGraph and GPT‑4o over AgentDojo environments spanning Banking, Slack, Travel, and Workspace [2508.17155]. The benchmark, TOCTOU-Bench, contains \(66\) realistic user tasks derived from \(97\) original tasks after excluding injection tasks and tasks with fewer than two tool calls; \(56/66\) tasks are labeled as containing a possible TOCTOU vulnerability [2508.17155]. The paper reports that combining prompt rewriting, state-integrity monitoring, and tool-fusing reduces vulnerabilities in executed trajectories from \(12\%\) to \(8\%\), achieves up to \(25\%\) detection accuracy using automated detection methods, produces a \(3\%\) decrease in vulnerable plan generation, and reduces the attack window by \(95\%\) [2508.17155]. In the Slack and combined experiments, the attack window falls from roughly \(1.70\text{–}1.77\) seconds to \(0.07\text{–}0.08\) seconds after tool fusion [2508.17155].

Browser-use agents instantiate TOCTOU at the interface level [2603.00476]. The agent loop is observation \(\rightarrow\) planning \(\rightarrow\) action, with planning latency often taking seconds while the webpage remains live and mutable [2603.00476]. The benchmark spans synthesized and real-world sites and evaluates \(10\) popular open-source agents, including structured text agents, screenshot-based agents, and multimodal hybrids [2603.00476]. The paper states that all \(10\) agents exhibit TOCTOU vulnerabilities on at least one manipulation type, and most are vulnerable across UI changes, data changes, and expiring state [2603.00476]. Its mitigation uses `MutationObserver` and `ResizeObserver` to validate DOM and layout state immediately before action execution; on the OpenAI CUA Sample App, the unmitigated and prompt-only systems show a \(100\%\) trigger ratio across Types I–III, while pre-execution validation shows \(0\%\) trigger ratio in the tested cases [2603.00476]. The remaining vulnerable gap is approximately \(0.13\) s per action, compared to around \(10\) s planning latency, a reduction factor of about \(77\); stress tests report \(0.2\%\) and \(0.3\%\) successful triggers in contrived schedules [2603.00476]. Additional latency is reported as below \(0.05\) s per plan–validate–act loop [2603.00476].

Desktop GUI agents face a closely related “observation-to-action gap” [2604.18860]. The paper measures this gap across OSWorld tasks and reports mean \(\Delta = 6.51\,\text{s}\), standard deviation \(3.59\,\text{s}\), minimum \(3.18\,\text{s}\), and maximum \(13.23\,\text{s}\) [2604.18860]. It formalizes the resulting failure as a Visual Atomicity Violation: an intended click at coordinate \(\mathbf{c}\) targets element \(e^*\) at \(T_{\text{obs}}\), but a distinct attacker-controlled element \(e_A\) occupies \(\mathbf{c}\) at \(T_{\text{act}}\) [2604.18860]. Three primitives are evaluated: Notification Overlay Hijack, Window Focus Manipulation, and Web DOM Injection [2604.18860]. Primitive B achieves \(100\%\) spatial and trigger success over \(45\) trials for Claude 4.6; Primitive C yields \(100\%\) spatial attack success and \(100\%\) behavioral success for Claude and Qwen, with \(91.1\%\) for GPT-4o [2604.18860]. The proposed PUSV defense combines masked pixel SSIM, global screenshot diff, and X Window snapshot diff, reaches \(100\%\) Action Interception Rate across \(180\) adversarial trials for Primitives A and B with zero false positives and less than \(0.1\) s overhead, but has approximately \(0\%\) AIR against Primitive C because DOM-only changes can leave screenshots pixel-identical [2604.18860]. This demonstrates that purely visual TOCTOU defenses have structural blind spots when semantic state changes have zero visual footprint.

The AI-agent survey also ties TOCTOU to real CVEs, including Claude Code startup-trust and project-load issues, framing them as trust-boundary races where execution occurs before a user’s trust decision takes effect [2607.05743]. That placement broadens TOCTOU from interface dynamics to authorization sequencing in agent harnesses.

## 6. Mitigation patterns, design principles, and unresolved issues

Across the supplied literature, TOCTOU mitigations fall into a small number of recurring patterns. The first is to shrink or eliminate the gap between validation and action. In systems security this appears as atomic system calls, stable object handles, and lock-based synchronization [2603.00476][2002.07053][2603.03141]. In agent systems it appears as prompt rewrites that require revalidation at use time, tool-fusing that collapses read–write pairs into one operation, and pre-execution validation immediately before click dispatch [2508.17155][2603.00476]. In RX-INT it appears as binding memory checks to thread-creation events rather than periodic polling [2508.03879]. In TRAIN it appears as synchronized attestation so that network state is measured at nearly the same time across devices [2502.07053].

The second pattern is to maintain protected or persistent state across time. RX-INT baselines VAD regions and hashes executable image content [2508.03879]. RATA stores a protected last-modification marker inside the attested memory region [2005.03873]. Half-Moon Cookie stores an allowlist state \((\text{nonce}, \tau, z, k_{\text{emb}})\) on the server and invalidates the allowlist whenever the blocklist changes [2604.15641]. The AI-agent survey recommends revocable, time-limited capability tokens to counter “checked once, trusted forever” [2607.05743]. These mechanisms do not remove time, but encode freshness or modification history into later decisions.

The third pattern is to move checking to a more privileged or trustworthy layer. RX-INT runs in kernel mode to avoid user-mode API hooking and to traverse the kernel’s actual VAD tree [2508.03879]. RATA, TRAIN, and CASU depend on hardware-enforced memory and timer properties [2005.03873][2502.07053]. The desktop GUI defense argues for OS+DOM defense-in-depth because screenshot-only middleware cannot observe DOM-only rebinding [2604.18860]. This suggests that TOCTOU defenses inherit the observability limits of the layer that implements them.

The fourth pattern is cryptographic or logical binding of evidence to the specific item or state being used. Half-Moon Cookie is the clearest example. It performs an expensive private explicit blocklist check and then a fast implicit check at time of use, designed specifically so recipients can “more efficiently confirm the previous result before using the item, thereby avoiding TOCTOU attacks” [2604.15641]. The token
\[
\tau = \embed(w) + \hash(w,\embed(w),z)
\]
binds the content \(w\), its embedding, and the random mask \(z\) [2604.15641]. The system clears the allowlist whenever the blocklist is updated, so signed or cached prior approval cannot outlive policy changes [2604.15641]. The paper gives explicit implicit-check performance figures for a 100KB input: communication \(7.2 \times 10^{-3}\) MB and response time \(0.19\) s, compared with much higher figures for fuzzy PSI and exact PSI baselines [2604.15641]. The authors nonetheless state that the design “reduce[s] the time window in which a TOCTOU inconsistency can be exploited rather than eliminating it entirely” [2604.15641].

Several limitations recur. Kernel-mode or hypervisor-compromising adversaries remain out of scope in RX-INT, which proposes hypervisor-based EPT enforcement as future work [2508.03879]. Browser and desktop agent defenses leave a residual nonzero gap and may suffer false positives or visibility gaps, especially for cross-origin or DOM-only changes [2603.00476][2604.18860]. AI-agent TOCTOU detection based only on tool-pair classification remains context-insensitive, with modest TPR and AUC [2508.17155]. RATA assumes secure hardware and excludes physical tampering and side channels [2005.03873]. TRAIN assumes a secure TCB and excludes physical attacks and strong network DoS [2502.07053]. DICE demonstrates that clean boot-time measurements are insufficient if runtime code can later reuse attestation credentials [2201.11764]. A plausible implication is that TOCTOU cannot be solved purely by faster checking; it requires explicit freshness semantics, binding across layers, and resistance to rollback or replay.

The literature therefore converges on a general view: TOCTOU races arise whenever a system validates mutable external state and later acts as though that validation were still current. Whether the state is a pathname, a firmware image, executable memory, a webpage, a GUI surface, a repository trust decision, or a private blocklist result, the central problem is temporal separation without enforced continuity [2508.03879][2607.05743][2005.03873][2604.15641]. The strongest defenses either make check and use effectively atomic, or they preserve enough trusted history and binding information that a stale validation cannot be mistaken for a fresh one.

Source: https://www.emergentmind.com/topics/time-of-check-to-time-of-use-toctou-races