← Java / Spring · Contents

JAVA-013 / Beginner

Path traversal in file downloads

A01:2021 Broken Access Control · CWE-22 Path Traversal

Why is this a problem?

An arbitrary file can be read using ../../etc/passwd.

How to fix it

java
Path base = Path.of("/data/files").toRealPath();
Path file = base.resolve(name).toRealPath();
if (!file.startsWith(base) || !Files.isRegularFile(file)) {
    throw new SecurityException();
}

Further reading