The gap
A time of check to time of use bug, or TOCTOU, is a race where a program checks a condition and then acts on it, but the state changes in the window between the two steps. The decision was valid when made and wrong by the time it is used.
Common examples
- File systems — checking that a path is safe to open, then opening it, while an attacker swaps the path for a symlink in between.
- Balances — verifying an account has enough funds, then withdrawing, while a concurrent withdrawal drains it.
- Capacity — testing that a queue has room, then enqueuing, after another producer fills it.
Closing the window
- Make check and act atomic under a single lock or transaction.
- Prefer operate then validate primitives, such as opening a file by handle and checking the handle, or a compare and swap that fails if state moved.
- Use database conditional updates rather than read then write.
Key idea
TOCTOU bugs live in the gap between check and use. Close the gap by making the two atomic or by validating the exact thing you operate on.