Race Condition

A race condition is a bug whose outcome depends on the order or timing of two concurrent operations.

Definition

A race condition is a defect in which the correctness of a program depends on the precise order or timing of two or more concurrent operations. In single-threaded code, a race typically arises between a signal handler and the main flow, or between a user-space program and a kernel that updates shared state asynchronously. In multithreaded code, it arises between threads sharing memory without sufficient synchronisation. In distributed systems, it arises between two clients reaching a shared resource through different code paths.

Security-relevant races usually take the form of a TOCTOU (time-of-check-to-time-of-use) flaw: the program checks a property of a resource, then operates on the resource, and the resource's state changes between the two steps. The attacker arranges that change.

How it works

Classic file-system TOCTOU: a setuid program checks that the path the user named is a regular file the user owns, then opens the path for writing. Between the `stat()` and the `open()`, the attacker swaps the path for a symlink to `/etc/passwd`. The program now writes to `/etc/passwd` with root privilege.

Web variants: an "atomic" balance-transfer endpoint that reads the balance, checks if it's sufficient, and decrements — but each step is its own SQL statement. Two concurrent transfers both observe the original balance and both succeed, leaving the balance negative.

Impact

Privilege escalation, financial loss, data integrity loss, race-condition denial of service. The double-spend variant is the canonical exploit against centralised wallets and gift-card systems.

Mitigation

Replace check-then-use with atomic primitives (open-with-O_NOFOLLOW, `flock`, database row locks, `SELECT ... FOR UPDATE`, optimistic-concurrency tokens). Avoid filesystem paths in privileged code — operate on file descriptors. For HTTP endpoints, use idempotency keys and database transactions with appropriate isolation.

Examples

  • CVE-2016-5195 — Dirty COW; Linux kernel race in copy-on-write.
  • CVE-2022-0847 — Dirty Pipe; Linux pipe race for arbitrary file write.

See also

References