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 Java SE

Use the secure-by-design APIs from java.io and java.nio that create temporary files with unpredictable names and appropriate permissions.

Code examples

Noncompliant code example

new File("/tmp/myfile.txt"); // Noncompliant
Paths.get("/tmp/myfile.txt"); // Noncompliant

java.io.File.createTempFile("prefix", "suffix"); // Noncompliant: will be in the default temporary-file directory.
java.nio.file.Files.createTempDirectory("prefix"); // Noncompliant: will be in the default temporary-file directory.
Map<String, String> env = System.getenv();
env.get("TMP"); // Noncompliant

Compliant solution

new File("/myDirectory/myfile.txt");  // Compliant

File.createTempFile("prefix", "suffix", new File("/mySecureDirectory"));  // Compliant

if(SystemUtils.IS_OS_UNIX) {
  FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------"));
  Files.createTempFile("prefix", "suffix", attr); // Compliant
}
else {
  File f = Files.createTempFile("prefix", "suffix").toFile();  // Compliant
  f.setReadable(true, true);
  f.setWritable(true, true);
  f.setExecutable(true, true);
}
File.createTempFile("prefix", "suffix", new File("/mySecureDirectory"));  // Compliant

Resources

Articles & blog posts

Standards