find-sec-bugs / find-sec-bugs

The SpotBugs plugin for security audits of Java web applications and Android applications. (Also work with Kotlin, Groovy and Scala projects)

Home Page:https://find-sec-bugs.github.io/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Path Traversal sink incorrect

jcopenhop opened this issue · comments

Problem

I believe the inclusion of Files.createTempFile(String, String, FileAttributes) in path-traversal-in.txt is a false positive.

This version of createTempFile takes two strings for a suffix and prefix for a filename. Using the below test code any inclusion of a path separator results in an exception being thrown.

import java.nio.file.Files;
import java.nio.file.Path;
import java.io.IOException;


class TestCreateTempFile {
    public static void main(String[] args) {
        try {
          Path p = Files.createTempFile("/a","b");
          System.out.println(p.toString()); 
        } catch(IOException e) {
          System.out.println(e);
        }
    }
}
Exception in thread "main" java.lang.IllegalArgumentException: Invalid prefix or suffix
	at java.base/java.nio.file.TempFileHelper.generatePath(TempFileHelper.java:62)
	at java.base/java.nio.file.TempFileHelper.create(TempFileHelper.java:126)
	at java.base/java.nio.file.TempFileHelper.createTempFile(TempFileHelper.java:160)
	at java.base/java.nio.file.Files.createTempFile(Files.java:913)
	at TestCreateTempFile.main(TestCreateTempFile.java:10)

Looking at the implementation of java.nio.file.TempFileHelper.generatePath you can see that it explicitly checks to ensure that the filename generated is a simple filename and contains no path components.

   private static Path generatePath(String prefix, String suffix, Path dir) {
        long n = random.nextLong();
        n = (n == Long.MIN_VALUE) ? 0 : Math.abs(n);
        Path name = dir.getFileSystem().getPath(prefix + Long.toString(n) + suffix);
        // the generated name should be a simple file name
        if (name.getParent() != null)
            throw new IllegalArgumentException("Invalid prefix or suffix");
        return dir.resolve(name);
    }

createTempDirectory has the same behavior and root cause (both createTempDirectory and createTempFile leverage generatePath under the hood)