blog.plugpollution

TOCTOU race conditions

Hello

One thing to be careful about is temporary files—to ensure they aren’t misused. Yes, there is a special function that handles this properly in a single, uninterrupted program step. In multitasking and object-oriented environments, no program runs in isolation.

It’s not necessarily risky to reimplement functions for creating temp files. But did you know? The following approach is actually wrong:


File userTempFile = new File("/tmp/unsafe_temp.txt");  
if (!userTempFile.exists()) {  
    userTempFile.createNewFile();  
    System.out.println("Temporary file created at: " + userTempFile.getAbsolutePath());  
}                
            

Okay, that’s Java, but whatever. Where’s the mistake?

An attacker could swap the file between those two function calls. Instead, it’s better to perform this in a single, uninterruptible program step. There’s a special function that creates temp files safely:


File safeTempFile = File.createTempFile("secure_", ".tmp");
safeTempFile.deleteOnExit();
System.out.println("Secure temporary file created at: " + safeTempFile.getAbsolutePath());                
            

File.createTempFile vs. new File("/tmp/tempfile.txt")
Less code, less hassle.

The programming language doesn’t really matter; if such an “atomic” (i.e., uninterruptible) function exists, it’s always advisable to use it. :)

This also applies to many things related to timers and time-based operations.

This is crucial in multithreaded and object-oriented setups. Consider a virus running on the machine—you can’t see it, but it might steal a tiny fraction of CPU time, just a few thousand clock cycles, enough to exploit the bug. And that time slice happens to fall exactly between two function calls in our shiny software. Bingo.

In Python, you should use:


import sys, os, tempfile  

with tempfile.TemporaryFile() as safe_file:  
    safe_file.write(b"Secure data written here")  
            

See the Python Docs: Generating temporary files and directories.