The Risk
A time of check to time of use race, or TOCTOU, happens when a program checks a condition and then acts on it as two separate steps. Between the check and the use, the state can change. An attacker who controls timing swaps the resource in that window. A classic case checks that a file is safe, then opens it, while the attacker repoints the name to a sensitive target in between.
The flaw is assuming the world stays still between a check and the action that relies on it.
The Defense
- Operate on a stable handle. Open the resource once and perform checks and use on that same handle rather than re looking up a name.
- Use atomic operations that check and act in one indivisible step.
- Hold a lock that covers the whole check then act sequence for shared state.
- Prefer fail safe creation flags that refuse to follow links or to clobber existing targets.
Key idea
Bind the check and the use to the same handle or an atomic operation so no attacker can swap the resource in the gap between them.