Using publicly writable directories such as /tmp to store temporary files exposes an application to race condition
vulnerabilities.
Operating systems provide globally writable directories—such as /tmp on Linux or \Windows\Temp on Windows—where any user
can create, read, and modify files. When an application creates files in these directories with predictable names, it becomes vulnerable to race
conditions: an attacker can create a file with the same name before the application does, potentially causing the application to read or write
attacker-controlled content.
This rule raises an issue when it detects hard-coded paths to publicly writable directories, such as:
/tmp/var/tmp/usr/tmp/dev/shm/dev/mqueue/run/lock/var/run/lock/Library/Caches/Users/Shared/private/tmp/private/var/tmp\Windows\Temp\Temp\TMP%USERPROFILE%\AppData\Local\TempIt also raises an issue when it detects reads of environment variables that point to publicly writable directories: TMP,
TMPDIR, and TEMP.
By winning the race condition, an attacker can access files written by the application to a publicly writable directory. If those files contain sensitive data—credentials, session tokens, or personal information—the attacker can read them before the application removes them.
An attacker can replace or modify a file before the application reads it, causing the application to process attacker-controlled content. This can result in data corruption, unexpected behavior, or indirect code execution. The risk is significantly higher when the application runs with elevated privileges.
Use the tempfile module, which creates temporary files with unpredictable names in a secure location.
file = open("/tmp/temporary_file","w+") # Noncompliant
tmp_dir = os.environ.get('TMPDIR') # Noncompliant
file = open(tmp_dir+"/temporary_file","w+")
import tempfile file = tempfile.TemporaryFile(dir="/tmp/my_subdirectory", mode="w+") # Compliant
import tempfile file = tempfile.TemporaryFile()