...
The POSIX lstat() function collects information about a symbolic link rather than its target. This noncompliant code example uses the lstat() function to collect information about the file, checks the st_mode field to determine if the file is a symbolic link, and then opens the file if it is not a symbolic link.:
| 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 compliant solution eliminates the race condition by
- calling Calling
lstat()on the file name. - calling Calling
open()to open the file. - calling Calling
fstat()on the file descriptor returned byopen(). - comparing Comparing the file information returned by the calls to
lstat()andfstat()to ensure that the files are the same.
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
ISO/IEC 9899:2011 Section 7.21, "Input/output <stdio.h>"
...
...
| Race condition enabling link following CWE-365, |
...
| Race |
...
| condition in |
...
| switch |
...
Bibliography
| [Dowd 2006] | Chapter 9, "UNIX 1: Privileges and Files" |
| [ISO/IEC 9899:2011] | Section 7.21, "Input/output <stdio.h>" |
| [Open Group 2004] | lstat() |
...
...
...
| 2013] | Chapter |
...
| 8, "File I/O" |
...