Skip to content

Time-of-check time-of-use (TOCTOU) race condition

Description

Usage of the `readlink` function call hints at a potential Time Of Check Time Of Use (TOCTOU) vulnerability. An attacker may be able to modify the file being specified by the `readlink` function prior to the `readlink` function being called. Additionally, care must be taken that the buffer provided is large enough to hold the contents of the file.

Examples

Insecure Code

c
readlink(path, buffer, sizeof(buffer))

Secure Code

c
if (lstat(path, &stat_buf) == 0) { fd = open(path, O_RDONLY); if (fd != -1) { if (fstat(fd, &stat_buf_fd) == 0 && stat_buf.st_dev == stat_buf_fd.st_dev && stat_buf.st_ino == stat_buf_fd.st_ino) { // safe to read and operate on the file's contents } } }

Remediation

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.

Rule Details

FieldValue
IDCODE-0609
CategoryGeneric
SeverityMEDIUM
CWECWE-367
ConfidenceHIGH
ImpactMEDIUM
LikelihoodMEDIUM
ExploitabilityMODERATE
TagsTOCTOU, race condition
OWASPA5:2017-Broken Access Control, A01:2021-Broken Access Control