{
  "id": "time-of-check-to-time-of-use",
  "title": "Time-of-check to time-of-use",
  "lang": "en",
  "source_lang": "en",
  "summary": "Time-of-check to time-of-use is a race condition in which a resource changes between validation and a later operation that relies on that validation.",
  "category": "computer-science",
  "subcategory": "networks-security",
  "type": "concept",
  "aliases": [
    "TOCTOU",
    "TOCTTOU",
    "Time-of-check/time-of-use race",
    "Check-then-use race"
  ],
  "generated_at": "2026-11-05",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/time-of-check-to-time-of-use/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/time-of-check-to-time-of-use/",
      "json": "https://aiwiki.page/zh/time-of-check-to-time-of-use.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "Time-of-check to time-of-use (TOCTOU) is a class of race condition in which a program checks a resource or condition and later acts on the assumption that the checked property still holds, although an intervening change can invalidate it. The resource may be a file, a shared variable, a database record, an authorization policy, or a remote service. TOCTOU can cause ordinary correctness failures or become a security vulnerability when an attacker can influence the state between the check and the use.\n\nThe essential problem is not simply that time passes between two operations. It is that the program lacks a guarantee connecting the state it validated to the state on which it eventually acts."
    },
    {
      "heading": "Mechanism",
      "text": "A TOCTOU sequence typically has three stages:\n\n- Check: a program observes a property, such as whether a file exists, an account has sufficient funds, or a user has permission.\n- Intervening change: another actor modifies the relevant state or changes which resource a name refers to.\n- Use: the program performs an operation based on the earlier observation.\n\nLet \\(P(S)\\) be the condition checked in state \\(S\\). A successful check at time \\(t_c\\) establishes\n\n\\[P(S(t_c)) = \\mathrm{true}.\\]\n\nAn operation performed at a later time \\(t_u\\) may require\n\n\\[P(S(t_u)) = \\mathrm{true}.\\]\n\nThe first statement does not imply the second unless the system preserves the relevant property or validates it as part of the operation.\n\nTOCTOU is commonly associated with concurrent computing, but the vulnerable program need not contain multiple threads. A single-threaded process can race with another process, an operating-system activity, or a remote client. Execution can be interleaved on a single processor; simultaneous execution on multiple processors is unnecessary.\n\nThe interval between check and use is often called the race window. A short window can make a failure harder to reproduce, but does not establish correctness. Repeated attempts or influence over scheduling and resource access can make apparently rare interleavings consequential."
    },
    {
      "heading": "File-system example",
      "text": "A classic case occurs when a program validates a pathname and subsequently opens that pathname. In a file system, a pathname is a means of locating an object, not an immutable reference to that object.\n\nConsider this illustrative pseudocode:\n\nif path_identifies_acceptable_file(path):\n    handle = open(path)\n    write(handle, data)\n\nThe check and open independently resolve path. Between them, another process might rename a directory entry, replace a file, or introduce a symbolic link. The open operation can therefore reach a different object from the one examined by the check.\n\nA possible sequence is:\n\nStep | Checking program | Other process\n1 | Examines report and accepts its properties |\n2 |  | Replaces report with a link to another file\n3 | Opens report and writes data |\n\nIf the checking program has privileges unavailable to the other process, this can cause it to modify a resource that the other process could not modify directly. Whether exploitation succeeds depends on directory permissions, link-handling behavior, process privileges, and the exact operations involved.\n\nOn Unix and POSIX systems, checking a pathname with access() before opening it is a well-known example of a potentially unsafe check-then-use pattern. The calls also have different credential semantics: access() ordinarily checks using real user and group IDs, whereas opening normally uses the credentials applicable to the actual operation. This distinction matters independently of the race.\n\nChecking immediately before opening is not equivalent to checking and opening as one protected operation. Nor does merely testing whether the final pathname component is a symbolic link protect against changes in parent directories."
    },
    {
      "heading": "Other forms",
      "text": "Shared application state\n\nA program may test whether a queue is nonempty and then remove an item. If another thread removes the final item between those steps, the removal may fail or violate an application assumption.\n\nSimilarly, separately checking an inventory count and then decrementing it can allow multiple requests to claim the same remaining item. Individually safe reads and writes do not make their combination safe. The relevant guarantee must cover the entire check-and-update operation.\n\nDatabases\n\nIn a database, an application might read a balance, decide that a withdrawal is permitted, and later update the balance. Concurrent requests can each make decisions based on a state that no longer applies.\n\nA database transaction can address this problem, but its effectiveness depends on the isolation level and the operations used. Merely placing statements inside a transaction does not guarantee that every relevant concurrency anomaly is excluded. Appropriate locking, serializable execution, or a conditional update may be necessary.\n\nFor example, a database can evaluate a condition and perform an update within one statement:\n\nUPDATE inventory\nSET quantity = quantity - 1\nWHERE item_id = 42 AND quantity > 0;\n\nThe application then checks whether a row was affected. With suitable database concurrency guarantees, this combines the condition with the state change rather than relying on an earlier read.\n\nAuthorization and distributed systems\n\nAn access-control decision can become stale if permissions, ownership, or group membership change before a later action. A service may also validate a resource identifier and subsequently act on a replacement resource associated with that identifier.\n\nIn distributed computing, network delays and independently changing services make these gaps especially visible. A cached authorization result, quoted price, resource version, or availability check describes an observation, not necessarily a reservation.\n\nNot every change after authorization constitutes a defect. Some systems deliberately grant authority at a defined point and allow an already authorized operation to finish. Whether a TOCTOU problem exists therefore depends on the intended policy: the question is when the condition must hold and how that requirement is enforced."
    },
    {
      "heading": "Prevention and design approaches",
      "text": "Combine validation and action\n\nThe strongest general approach is to use an atomic operation that evaluates the required condition and performs the action under one concurrency guarantee.\n\nExamples include exclusive file creation, conditional database updates, and compare-and-exchange operations on shared state. A failed condition becomes an ordinary operation result rather than a separate preliminary observation.\n\nAtomicity is relative to a specified operation and set of observers. An operation that atomically changes a directory entry, for example, does not automatically protect earlier validation or subsequent changes to file contents.\n\nProtect the complete critical section\n\nA mutex or other synchronization mechanism can protect both the check and the use as one critical section. This works only if every relevant actor follows the same synchronization protocol.\n\nAn application-local lock does not stop an unrelated process from modifying a shared directory. Some file locks are advisory, and a lock on one object may not protect the pathname used to locate it. The protection must cover the state whose stability the operation actually requires.\n\nUse stable references\n\nFor file operations, a common approach is to acquire a file descriptor, inspect the opened object through that descriptor, and perform subsequent operations through the same descriptor. This avoids resolving a mutable pathname again for each step.\n\nHowever, a stable reference generally stabilizes object identity, not every property of the object. Another process may still change its contents or permissions. Validation must occur before any action that depends on it, and opening must not itself have an unacceptable side effect, such as truncating the file before inspection.\n\nDirectory-relative interfaces and path-resolution restrictions can further constrain which objects may be reached. Their guarantees depend on the particular operating system and interface.\n\nDetect changes and retry\n\nOptimistic concurrency control associates state with a version and accepts an update only if the expected version still matches. A conflict causes the operation to fail or retry.\n\nThe comparison and update must themselves be indivisible. Checking a version and then performing an unconditional write merely recreates the original problem. Version schemes must also account for replacement or reuse where these could make different states appear identical.\n\nLimit consequences\n\nLeast privilege and restricted access to shared resources reduce opportunities for exploitation and limit potential damage. They complement concurrency guarantees rather than replacing them."
    },
    {
      "heading": "Detection and verification",
      "text": "Code review can identify check-then-use sequences by asking:\n\n- What state does the check establish?\n- Which actors can change that state?\n- Does the later operation refer to the same object?\n- What guarantees preserve the required property until use?\n\nStatic analysis can flag suspicious operation pairs, such as checking a pathname before reopening it. Such warnings require interpretation because surrounding synchronization or resource ownership may make a sequence safe.\n\nDynamic testing can force competing operations into the race window. Stress testing and controlled scheduling can expose failures, but successful tests do not establish that every possible interleaving is safe.\n\nFormal verification and model checking can assess whether an implementation preserves a required invariant under modeled interference. Their conclusions depend on assumptions about the environment, including which actors can modify resources and what atomicity the underlying interfaces provide.\n\nA TOCTOU race need not be a low-level data race: every individual access can be synchronized while the larger sequence remains incorrect. Conversely, two separated operations are not inherently vulnerable if ownership, immutability, synchronization, or transactional semantics preserve the required condition throughout."
    }
  ],
  "links": [
    "race-condition",
    "security-vulnerability",
    "concurrent-computing",
    "process-computing",
    "file-system",
    "pseudocode",
    "unix",
    "posix",
    "database",
    "database-transaction",
    "access-control",
    "distributed-computing",
    "atomic-operation",
    "mutex",
    "synchronization-computing",
    "critical-section",
    "operating-system",
    "least-privilege",
    "code-review",
    "formal-verification",
    "model-checking"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}