909
Phase: Implementation
Ensure that locking occurs before the check, as opposed to afterwards, such that the resource,
as checked, is the same as it is when in use.
Demonstrative Examples
Example 1:
The following code checks a file, then updates its contents.
Example Language: C (Bad)
struct stat *sb;
...
lstat("...",sb); // it has not been updated since the last time it was read
printf("stated file\n");
if (sb->st_mtimespec==...){
print("Now updating things\n");
updateThings();
}
Potentially the file could have been updated between the time of the check and the lstat, especially
since the printf has latency.
Example 2:
The following code is from a program installed setuid root. The program performs certain file
operations on behalf of non-privileged users, and uses access checks to ensure that it does not
use its root privileges to perform operations that should otherwise be unavailable the current
user. The program uses the access() system call to check if the person running the program
has permission to access the specified file before it opens the file and performs the necessary
operations.
Example Language: C (Bad)
if(!access(file,W_OK)) {
f = fopen(file,"w+");
operate(f);
...
}
else {
fprintf(stderr,"Unable to open file %s.\n",file);
}
The call to access() behaves as expected, and returns 0 if the user running the program has the
necessary permissions to write to the file, and -1 otherwise. However, because both access() and
fopen() operate on filenames rather than on file handles, there is no guarantee that the file variable
still refers to the same file on disk when it is passed to fopen() that it did when it was passed to
access(). If an attacker replaces file after the call to access() with a symbolic link to a different file,
the program will use its root privileges to operate on the file even if it is a file that the attacker would
otherwise be unable to modify. By tricking the program into performing an operation that would
otherwise be impermissible, the attacker has gained elevated privileges. This type of vulnerability is
not limited to programs with root privileges. If the application is capable of performing any operation
that the attacker would not otherwise be allowed perform, then it is a possible target.
Example 3:
This code prints the contents of a file if a user has permission.
Example Language: PHP (Bad)
function readFile($filename){
$user = getCurrentUser();
//resolve file if its a symbolic link
CWE Version 4.14
CWE-367: Time-of-check Time-of-use (TOCTOU) Race Condition
CWE-367: Time-of-check Time-of-use (TOCTOU) Race Condition