...
| Code Block | ||
|---|---|---|
| ||
char *file namefilename; struct stat lstat_info; int fd; /* ... */ if (lstat(file namefilename, &lstat_info) == -1) { /* handle error */ } if (!S_ISLNK(lstat_info.st_mode)) { if ((fd = open(file namefilename, O_RDWR)) == -1) { /* handle error */ } } write(fd, userbuf, userlen); |
...
This compliant solution eliminates the race condition by:
- calling
lstat()on the file namefilename. - calling
open()to open the file. - calling
fstat()on the file descriptor returned byopen(). - comparing the file information returned by the calls to
lstat()andfstat()to ensure that the files are the same.
| Code Block | ||
|---|---|---|
| ||
char *file namefilename; struct stat lstat_info struct stat fstat_info; int fd; /* ... */ if (lstat(file namefilename, &lstat_info) == -1) { /* handle error */ } if ((fd = open(file namefilename, O_RDWR)) == -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) { write(fd, userbuf, userlen); } |
...
| 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 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 05|AA. C References#Seacord 05]\] Chapter 7, "File I/O" |
...