Using publicly writable directories such as /tmp to store temporary files exposes an application to race condition vulnerabilities.

Why is this an issue?

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:

It also raises an issue when it detects reads of environment variables that point to publicly writable directories: TMP, TMPDIR, and TEMP.

What is the potential impact?

Information disclosure

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.

Data tampering

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.

How to fix it in Python Standard Library

Use the tempfile module, which creates temporary files with unpredictable names in a secure location.

Code examples

Noncompliant code example

file = open("/tmp/temporary_file","w+") # Noncompliant
tmp_dir = os.environ.get('TMPDIR') # Noncompliant
file = open(tmp_dir+"/temporary_file","w+")

Compliant solution

import tempfile

file = tempfile.TemporaryFile(dir="/tmp/my_subdirectory", mode="w+") # Compliant
import tempfile

file = tempfile.TemporaryFile()

Resources

Documentation

Articles & blog posts

Standards