Time-of-Check-to-Time-of-Use (TOCTOU) race conditions occur when a program checks a condition and then uses the result of that check, but the condition might have changed between the check and use. This pattern creates security vulnerabilities, particularly in file system operations, but can affect any multi-step operation where state might change.
Time-of-Check-to-Time-of-Use (TOCTOU) race conditions occur when a program checks a condition and then uses the result of that check, but the condition might have changed between the check and use. This pattern creates security vulnerabilities, particularly in file system operations, but can affect any multi-step operation where state might change.
To prevent TOCTOU vulnerabilities:
// VULNERABLE TO TOCTOU:
if !Path::new("file.txt").exists() {
File::create("file.txt")?; // Race condition: file might be created here by another process
}
// SAFER APPROACH:
let file = File::options().create_new(true).open("file.txt"); // Atomic operation
// Keep the file open while working with it rather than reopening based on metadata checks
let mut file = File::open("data.txt")?;
// Continue using the same file handle for subsequent operations
Be skeptical of metadata obtained from previous checks, as it may be stale
For security-critical operations, verify that operations succeeded with their intended effect rather than assuming success
Remember that even file locks may be insufficient protection against malicious actors, as they’re often advisory and can potentially be bypassed.
Enter the URL of a public GitHub repository