Potential Time Of Check Time Of Use (TOCTOU) vulnerability
Description
Usage of the `access` function call hints at a potential Time Of Check Time Of Use (TOCTOU) vulnerability. Using the `access` function to check if a file exists and is readable before opening it, an attacker can create a race condition between the `access` call and opening the file. The attacker could replace the file with a different one or modify its content between the time the `access` function is called and the file is opened, thus bypassing the permission check.
Examples
Insecure Code
if (access("file.txt", R_OK) == 0) { /* open and read file */ }Secure Code
if ((fd = open("file.txt", O_RDONLY)) != -1) { struct stat sb; if (fstat(fd, &sb) == 0 && lstat("file.txt", &sb) == 0 && sb.st_dev == sb.st_ino) { /* read and operate on file contents */ } }Remediation
Call `setuid` to drop privileges on the process prior to opening any files. Instead of using `access`, use `lstat` prior to opening the file and confirm the attributes are correct. Then use `open` to get a file descriptor to this file. Call `fstat` on the `open` file descriptor to confirm that `st_dev` and `st_ino` are equal between the two. If they are, it is safe to read and operate on the file's contents.
Rule Details
| Field | Value |
|---|---|
| ID | CODE-0606 |
| Category | AccessControl |
| 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 |