910
if(is_link($filename)){
$filename = readlink($filename);
}
if(fileowner($filename) == $user){
echo file_get_contents($realFile);
return;
}
else{
echo 'Access denied';
return false;
}
}
This code attempts to resolve symbolic links before checking the file and printing its contents.
However, an attacker may be able to change the file from a real file to a symbolic link between the
calls to is_link() and file_get_contents(), allowing the reading of arbitrary files. Note that this code
fails to log the attempted access (CWE-778).
Example 4:
This example is adapted from [REF-18]. Assume that this code block is invoked from multiple
threads. The switch statement will execute different code depending on the time when MYFILE.txt
was last changed.
Example Language: C (Bad)
#include <sys/types.h>
#include <sys/stat.h>
...
struct stat sb;
stat("MYFILE.txt",&sb);
printf("file change time: %d\n",sb->st_ctime);
switch(sb->st_ctime % 2){
case 0: printf("Option 1\n"); break;
case 1: printf("Option 2\n"); break;
default: printf("this should be unreachable?\n"); break;
}
If this code block were executed within multiple threads, and MYFILE.txt changed between the
operation of one thread and another, then the switch could produce different, possibly unexpected
results.
Observed Examples
Reference Description
CVE-2015-1743 TOCTOU in sandbox process allows installation of untrusted browser add-ons
by replacing a file after it has been verified, but before it is executed
https://www.cve.org/CVERecord?id=CVE-2015-1743
CVE-2003-0813 A multi-threaded race condition allows remote attackers to cause a denial of
service (crash or reboot) by causing two threads to process the same RPC
request, which causes one thread to use memory after it has been freed.
https://www.cve.org/CVERecord?id=CVE-2003-0813
CVE-2004-0594 PHP flaw allows remote attackers to execute arbitrary code by aborting
execution before the initialization of key data structures is complete.
https://www.cve.org/CVERecord?id=CVE-2004-0594
CVE-2008-2958 chain: time-of-check time-of-use (TOCTOU) race condition in program allows
bypass of protection mechanism that was designed to prevent symlink attacks.
https://www.cve.org/CVERecord?id=CVE-2008-2958
CVE-2008-1570 chain: time-of-check time-of-use (TOCTOU) race condition in program allows
bypass of protection mechanism that was designed to prevent symlink attacks.
https://www.cve.org/CVERecord?id=CVE-2008-1570
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