A TOCTOU (time-of-check, time-of-use) race condition is possible when two or more concurrent processes are operating on a shared file system [Seacord 2013b]. Typically, the first access is a check to verify some attribute of the file, followed by a call to use the file. An attacker can alter the file between the two accesses, or replace the file with a symbolic or hard link to a different file. These TOCTOU conditions can be exploited when a program performs two or more file operations on the same file name or path name.
...
This compliant solution invokes fopen()
at a single location and uses the x
mode of fopen()
, which was added in C11. This mode causes fopen()
to fail if the file exists. This check and subsequent open is performed without creating a race window. Note that the x
mode provides exclusive access to the file only if the host environment provides this support.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdio.h> void open_some_file(const char *file) { FILE *f = fopen(file, "wx") if (NULL == f) { /* Handle error */ } /* Write to file */ if (fclose(f) == EOF) { /* Handle error */ } } |
...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
void open_some_file(const char *file) {
int fd = open(file, O_CREAT | O_EXCL | O_WRONLY);
if (-1 != fd) {
FILE *f = fdopen(fd, "w");
if (NULL != f) {
/* Write to file */
if (fclose(f) == EOF) {
/* Handle error */
}
}
else {
if (close(fd) == -1) {
/* Handle error */
}
}
}
} |
...