CERT-FIO45-C
Synopsis
Avoid TOCTOU race conditions while accessing files.
Enabled by default
Yes
Severity/Certainty
High/Medium

Full description
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. A program that performs two or more file operations on a single file name or path name creates a race window between the two file operations. This race window comes from the assumption that the file name or path name refers to the same resource both times. If an attacker can modify the file, remove it, or replace it with a different file, then this assumption will not hold.
Coding standards
- CERT FIO45-C
Avoid TOCTOU race conditions while accessing files
Code examples
The following code example fails the check and will give a warning:
#include <stdio.h>
void open_some_file(const char *file) {
FILE *f = fopen(file, "r");
if (NULL != f) {
return;
} else {
if (fclose(f) == EOF) {
/* Handle error */
}
f = fopen(file, "w");
if (NULL == f) {
return;
}
/* Write to file */
if (fclose(f) == EOF) {
/* Handle error */
}
}
}
The following code example passes the check and will not give a warning about this issue:
#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 */
}
}