A time-of-check to time-of-use (TOCTTOU) error is a concurrency issue where control is given to another process between an access control check and the access operation it guards, letting the checked condition change before it is used.
int openfile(char *path) {
struct stat s;
if (stat(path, &s) < 0)
return -1;
if (!S_ISREG(s.st_mode)) {
error("only allowed to regular files");
return -1;
}
return open(path, O_RDONLY);
}
stat checks that path is a regular file. Between that check and open, an attacker can change what path refers to, so the file actually opened is not the one checked.
Attack Mechanism
openfile runs in the kernel. At user level, an adversary-controlled program P defines a shared path variable and launches 2 threads T1 and T2 that both see updates to it.
T1callsopenfilewithpathset to a regular file.T2concurrently setspathto point to a directory.- If
T2’s write lands betweenT1’sstatandopen,openfileopens the directory despite having checked a regular file.
Prevention
- Ensure critical parameters are not exposed during pre-emption
openfileownspathexclusively for the duration of the call. - Ensure serial integrity
Makeopenfileatomic, so no pre-emption occurs during its execution. - Validate critical parameters
Compute a checksum ofpathbefore pre-emption and compare it to a checksum taken after.