...
A program that performs a file operation on a filename or path twice creates a race window between the two file operations. This race window comes from the assumption that the filename refers to the same file both times. If an attacker can modify the file, remove it, or replace it with a different file, then this assumption will not hold.
Noncompliant Code Example (
...
write)
If an existing file is opened for writing, the file's previous contents are destroyed. This noncompliant code example tries to prevent an existing file from being overwritten by first ensuring that a file does not exist trying to open it for reading before opening it for writing. An attacker can exploit the race window between the access and the open to cause two calls to fopen()
to overwrite an existing file.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdio.h> #include <unistd.h> void open_some_file(const char *file) { FILE *f; if (access(file, R_OK | W_OK) ==(f = fopen(file, "r")) != NULL) { /* File exists, handle error */ } else { if (fclose(f) != 0) { /* handle error */ printf("access granted.\n"); } if ((f = fopen(file, "wb+w"); if (NULL ) == fNULL) { /* Handle error */ } /* write to file */ if (fclose(f); != 0) { /* handle error */ } } } |
Compliant Solution (C11 write)
...