Potential Time Of Check Time Of Use Vulnerability
Description
Usage of the `open` family of functions may hint at a potential Time Of Check Time Of Use (TOCTOU) vulnerability. An attacker may be able to modify the file being specified by the `open` function prior to the `open` function being called. To avoid this, use `lstat` to check the file attributes before calling `open`, and then use `fstat` on the file descriptor to confirm that `st_dev` and `st_ino` are equal.
Examples
Insecure Code
c
file = fopen("example.txt", "r");Secure Code
c
struct stat file_stat; lstat("example.txt", &file_stat); file = open("example.txt", O_RDONLY); struct stat file_stat_fd; fstat(file, &file_stat_fd); if (file_stat.st_dev == file_stat_fd.st_dev && file_stat.st_ino == file_stat_fd.st_ino) { /* safe to read and operate on the file's contents */ }Remediation
Use `lstat` to check the file attributes before calling `open`, and then use `fstat` on the file descriptor to confirm that `st_dev` and `st_ino` are equal.
Rule Details
| Field | Value |
|---|---|
| ID | CODE-0600 |
| Category | Injection |
| Severity | MEDIUM |
| CWE | CWE-362 |
| Confidence | HIGH |
| Impact | MEDIUM |
| Likelihood | MEDIUM |
| Exploitability | MODERATE |
| Tags | TOCTOU, race condition |
| OWASP | A5:2017-Broken Access Control, A01:2021-Broken Access Control |