Time of Check to Time of Use

2. Examples

In Unix, the following C code, when used in a setuid program, has a TOCTTOU bug

if (access(“file”, W_OK) != 0) { exit(1); } fd=  open(“file”,  O_WRONLY);  write(fd,  buffer,sizeof(buffer));

Here, access is intended to check whether the real user who executed the setuid program would normally be allowed to write the file (i.e., access checks the real user id rather than effective user id).

This race condition is vulnerable to an attack: 

In this example, an attacker can exploit the race condition between the access and open to trick the setuid victim into overwriting an entry in the system password database. TOCTTOU races can be used for privilege escalation, to get administrative access to a machine.

Although this sequence of events requires precise timing,it is possible for an attacker to arrange such conditions without too much difficulty.The implication is that applications cannot assume the state managed by the operating system (in this case the file system namespace) will not change between system calls.