...
This code contains a time-of-check, time-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.)
Compliant Solution (POSIX.1-2008 or newer)
This compliant solution eliminates the race condition by using O_NOFOLLOW to cause open() to fail if passed a symbolic link, avoiding the TOCTOU by not having a separate "check" and "use":
| Code Block | ||
|---|---|---|
| ||
char *filename = /* file name */;
char *userbuf = /* user data */;
unsigned int userlen = /* length of userbuf string */;
int fd = open(filename, O_RDWR|O_NOFOLLOW);
if (fd == -1) {
/* Handle error */
}
if (write(fd, userbuf, userlen) < userlen) {
/* Handle error */
} |
Compliant Solution (POSIX.1-2001 or older)
This compliant solution eliminates the race condition by
...