...
| Code Block | ||
|---|---|---|
| ||
char *filename = /* file name */; char *userbuf = /* user data */; unsigned int userlen = /* length of userbuf string */; struct stat lstat_info; int fd; /* ... */ if (lstat(filename, &lstat_info) == -1) { /* handle error */ } if (!S_ISLNK(lstat_info.st_mode)) { fd = open(filename, O_RDWR); if (fd == -1) { /* handle error */ } } if (write(fd, userbuf, userlen) < userlen) { /* Handle Error */ } |
This code contains a time-of-creation-of-use (TOCTOU) race condition between the call to lstat() and the subsequent call to open() because both functions operate on a file name that can be manipulated asynchronously to the execution of the program (see FIO01-C. Be careful using functions that use file names for identification).
...
| Code Block | ||
|---|---|---|
| ||
char *filename = /* file name */; char *userbuf = /* user data */; unsigned int userlen = /* length of userbuf string */; struct stat lstat_info; struct stat fstat_info; int fd; /* ... */ if (lstat(filename, &lstat_info) == -1) { /* handle error */ } fd = open(filename, O_RDWR); if (fd == -1) { /* handle error */ } if (fstat(fd, &fstat_info) == -1) { /* handle error */ } if (lstat_info.st_mode == fstat_info.st_mode && lstat_info.st_ino == fstat_info.st_ino && lstat_info.st_dev == fstat_info.st_dev) { if (write(fd, userbuf, userlen) < userlen) { /* Handle Error */ } } |
...
Comparing i-nodes using the st_ino fields and devices using the st_dev fields ensures that the file passed to lstat() is the same as the file passed to fstat() (see FIO05-C. Identify files using multiple file attributes).
Risk Assessment
Time-of-creation-to-time-of-use (TOCTOU ) race condition vulnerabilities can be exploited to gain elevated privileges.
...
| Wiki Markup |
|---|
\[[Dowd 06|AA. C References#Dowd 06]\] Chapter 9, "UNIX 1: Privileges and Files"
\[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] Section 7.19, "Input/output <stdio.h>"
\[[MITRE 07|AA. C References#MITRE 07]\] [CWE ID 363|http://cwe.mitre.org/data/definitions/363.html], "Race Condition Enabling Link Following", and [CWE ID 365|http://cwe.mitre.org/data/definitions/365.html] "Race Condition in Switch"
\[[Open Group 04|AA. C References#Open Group 04]\] [lstat()|http://www.opengroup.org/onlinepubs/000095399/functions/lstat.html], [fstat()|http://www.opengroup.org/onlinepubs/009695399/functions/fstat.html], [open()|http://www.opengroup.org/onlinepubs/009695399/functions/open.html]
\[[Seacord 05a|AA. C References#Seacord 05]\] Chapter 7, "File I/O" |
...