Skip to content
javahacks.dev
Security

How to Prevent Path Traversal in Java File Handling

Stop path traversal by resolving user-supplied names against a base directory, normalizing and checking the result, and avoiding user input in paths.

6 min read
Summarize in AI
Flat illustration of a security filter chain guarding a request, with the Spring Security, OWASP, Okta and JSON Web Tokens logos.

A download endpoint takes a file name and returns the file:

java
@GetMapping("/files")
byte[] download(@RequestParam String name) throws IOException {
    return Files.readAllBytes(Path.of("/var/app/uploads/" + name));
}

A request with name=../../../etc/passwd reads a file outside the uploads directory. The operating system resolves the .. segments, and nothing in the code limits where the path ends up. Path traversal (also called directory traversal) reaches configuration, keys and source code, and in writes it can overwrite files. It is a short list of fixes. It is one of the injection family discussed in Java security basics.

Best fix: do not use user input as a path

Store files under names you generate and keep the user's name as metadata:

java
String storedName = UUID.randomUUID().toString();
Files.copy(upload, baseDir.resolve(storedName));
files.save(new FileRecord(storedName, originalName));    // originalName only for display

Downloads look up the record by id and open the stored name. No user-controlled string ever reaches a path, which removes the whole bug class. The file upload side is in uploading files in Struts 2 safely.

When a name must be a path: resolve, normalize, check

java
static Path safeResolve(Path base, String userName) throws IOException {
    Path baseReal = base.toRealPath();
    Path target = baseReal.resolve(userName).normalize();
    if (!target.startsWith(baseReal)) {
        throw new SecurityException("Path escapes the base directory: " + userName);
    }
    return target;
}

Three steps matter. resolve joins the name to the base (and if userName is absolute, resolve returns it unchanged, which is why the check follows). normalize collapses . and .. segments, so base/../../etc/passwd becomes /etc/passwd. startsWith compares path components, not characters, so /var/app/uploads-evil does not pass for base /var/app/uploads, a bug that string startsWith has. Use the Path version.

Check results for different inputs:

InputResolved pathAllowed
report.pdf/var/app/uploads/report.pdfyes
a/b.txt/var/app/uploads/a/b.txtyes
../secrets.txt/var/app/secrets.txtno
/etc/passwd/etc/passwdno
a/../../x/var/app/xno

normalize works on the path text, not on the file system. A symlink inside the base that points outside passes the check and reads the target. If users can create links (an archive upload, a shared directory), check the real path of the target too:

java
if (Files.exists(target) && !target.toRealPath().startsWith(baseReal)) {
    throw new SecurityException("Link escapes the base directory");
}

toRealPath resolves links and requires that the file exist. Better, do not let untrusted users create links, and reject archive entries that are links.

Zip slip

Extracting an archive writes entries by the names inside it, so an entry named ../../app/config.yml overwrites a file outside the target. Apply the same check to each entry:

java
try (ZipInputStream zip = new ZipInputStream(input)) {
    ZipEntry entry;
    while ((entry = zip.getNextEntry()) != null) {
        Path target = safeResolve(destination, entry.getName());
        if (entry.isDirectory()) {
            Files.createDirectories(target);
        } else {
            Files.createDirectories(target.getParent());
            Files.copy(zip, target, StandardCopyOption.REPLACE_EXISTING);
        }
    }
}

Also limit the total size and entry count, because a zip bomb exhausts disk.

Other places the bug hides

  • Template names and include paths built from request parameters (return "pages/" + page).
  • getResourceAsStream with a user-controlled name.
  • Spring's ResourceLoader with a file: prefix from input.
  • A filename in a Content-Disposition header or a log, which is a different issue (header injection) but starts the same way.

Encoding tricks

Filters that block the literal ../ fail against %2e%2e%2f, double encoding and different separators (a backslash form on Windows). Decode input once, then validate the resulting path with normalize and startsWith, never the raw string. The Path check does not depend on spelling.

Defense in depth

Run the process as a user that can read only the directories it needs, keep secrets out of the web server's reach and avoid serving files straight from application code when the web server or object storage can do it with signed URLs.

A download endpoint that holds up

Putting the pieces together, here is a Spring MVC controller that serves files from one directory. It resolves the name safely, refuses anything that is not a regular file, and never echoes the path back to the caller:

java
@RestController
class DownloadController {

    private final Path base;

    DownloadController(@Value("${app.upload-dir}") Path base) throws IOException {
        this.base = base.toRealPath();
    }

    @GetMapping("/files/{name}")
    ResponseEntity<Resource> download(@PathVariable String name) throws IOException {
        Path target = base.resolve(name).normalize();
        if (!target.startsWith(base) || !Files.isRegularFile(target, LinkOption.NOFOLLOW_LINKS)) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok()
            .header(HttpHeaders.CONTENT_DISPOSITION,
                ContentDisposition.attachment().filename(target.getFileName().toString()).build().toString())
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .body(new FileSystemResource(target));
    }
}

Three details are deliberate. The base is turned into a real path once at startup, so the comparison does not depend on how the configuration spelled it. A rejected name and a missing file give the same 404, so a caller cannot use the response to probe which paths exist outside the base. And NOFOLLOW_LINKS makes isRegularFile return false for a symbolic link, which closes the link escape without a second toRealPath call.

A test that attacks the check

A security check without a hostile test is a guess. The helper from earlier is a pure function, so the test needs no server:

java
class SafeResolveTest {

    @TempDir
    Path base;

    @ParameterizedTest
    @ValueSource(strings = {
        "../secret.txt",
        "a/../../secret.txt",
        "/etc/passwd",
        "..",
        "a/./../../b"
    })
    void rejectsNamesThatLeaveTheBase(String name) {
        assertThrows(SecurityException.class, () -> safeResolve(base, name));
    }

    @Test
    void acceptsNestedNames() throws IOException {
        Path resolved = safeResolve(base, "reports/2025/q1.pdf");
        assertTrue(resolved.startsWith(base.toRealPath()));
    }

    @Test
    void rejectsSiblingDirectoryWithSamePrefix() throws IOException {
        Path sibling = Files.createDirectory(base.resolveSibling(base.getFileName() + "-evil"));
        String name = "../" + sibling.getFileName() + "/x";
        assertThrows(SecurityException.class, () -> safeResolve(base, name));
    }
}

The last test is the one that catches the string startsWith bug: a directory called uploads-evil shares a prefix with uploads and passes a character comparison. Add a test for every bypass you read about, and the list stays honest.

What changes on Windows

Windows adds cases a Linux-only check never sees. A backslash is a separator as well as a slash, so a name built from .. segments joined with backslashes traverses just like the slash form. A name that starts with a drive letter is an absolute path, and resolve returns it unchanged. Device names such as CON and NUL are reserved, and an alternate data stream suffix (file.txt:hidden) names something other than the file. Path.of on Windows rejects some of these with InvalidPathException, which is the correct outcome, so catch it and answer with the same 404 as any other bad name. Run the parameterized test on a Windows agent if you ship there, because a Linux build proves nothing about those inputs.

Null bytes and old APIs

The java.nio.file API rejects a path containing a NUL character with InvalidPathException. Older java.io.File code did not always, and some code paths truncated the name at the NUL, so evil.php%00.jpg passed an extension check and was saved as evil.php. If a legacy library still takes a File, convert the validated Path with toFile() after the check, never before it, and do not run extension checks on the raw string.

Where this does not apply

If you only read files from locations the code chooses, there is no traversal. Frameworks that serve static resources (Spring's resource handler) include this protection, and custom controllers need their own. The OWASP Path Traversal page and the [java.nio.file.Path documentation](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/Path.html) are the primary sources. Input handling more broadly is covered in Java security basics and OWASP Top Ten for Java developers.

Also inJava Core
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.