Skip to main content

Path traversal in file downloads and uploads: Node, Python, Go and Java

A download endpoint takes a filename and returns the file. An upload endpoint takes a file and saves it under the name the browser sent. Both look too simple to get wrong, and both are classic ways for an attacker to read /etc/passwd, your .env, or cloud credentials, or to write a file where it will be executed.

This is path traversal, CWE-22: user input chooses part of a filesystem path, and ../ sequences or an absolute path walk it out of the intended folder. This post shows the vulnerable and fixed shapes in Node.js, Python, Go and Java, the normalization mistakes that make "fixed" code still vulnerable, and how to handle uploads and archives.

Why path.join does not protect you

The most common belief behind this bug is that a path-joining function sanitizes. It does the opposite: it normalizes .. segments, which is exactly how the attacker escapes.

path.join('/srv/files', '../../etc/passwd'); // '/etc/passwd'

Python's os.path.join is worse in one respect. If a later segment is absolute, it discards everything before it, as the os.path docs state:

os.path.join('/srv/files', '/etc/passwd')  # '/etc/passwd'

Go's filepath.Join and Java's Path.resolve behave the same way for ... Joining is not validation.

File downloads

Node.js and Express

// Vulnerable
app.get('/download', (req, res) => {
  res.sendFile(path.join(__dirname, 'files', req.query.name));
});

Query and route parameters are URL-decoded before your handler sees them, so ..%2F..%2F.env arrives as ../../.env. Two fixes. The simplest is to let Express contain the path with the root option. The Express response docs say that when root is set, Express validates that the relative path resolves within it:

app.get('/download', (req, res) => {
  res.sendFile(String(req.query.name), { root: path.join(__dirname, 'files') });
});

When you read files with fs directly, resolve and check containment yourself:

const BASE = path.resolve(__dirname, 'files');

function safePath(name) {
  const target = path.resolve(BASE, name);
  if (!target.startsWith(BASE + path.sep)) throw new Error('Path outside the files folder');
  return target;
}

Note the + path.sep. Without it, /srv/files-private/secret passes a startsWith('/srv/files') check.

Python

# Vulnerable (Flask)
@app.get("/download")
def download():
    return send_file(os.path.join(BASE_DIR, request.args["name"]))

In Flask, send_from_directory(BASE_DIR, name) joins safely and returns a 404 for paths that escape. For plain file access, resolve both sides and compare whole path components:

BASE = os.path.realpath("/srv/files")

def safe_path(name: str) -> str:
    target = os.path.realpath(os.path.join(BASE, name))
    if os.path.commonpath([BASE, target]) != BASE:
        raise ValueError("Path outside the files folder")
    return target

realpath also resolves symlinks, so a link inside the folder that points outside it is caught. Avoid os.path.commonprefix here: it compares character by character and has the same prefix bug as a naive startsWith.

Go

// Vulnerable
func download(w http.ResponseWriter, r *http.Request) {
    p := filepath.Join("/srv/files", r.URL.Query().Get("name"))
    http.ServeFile(w, r, p)
}

Go 1.24 added os.Root, which the Go blog describes as disallowing operations that escape the root through .. or symlinks. Open the folder once and do all file access through it:

var root *os.Root // opened once at startup: root, err = os.OpenRoot("/srv/files")

func download(w http.ResponseWriter, r *http.Request) {
    f, err := root.Open(r.URL.Query().Get("name"))
    if err != nil { http.Error(w, "File not found", http.StatusNotFound); return }
    defer f.Close()
    io.Copy(w, f)
}

On older versions, filepath.IsLocal (Go 1.20) reports whether a path is lexically local: no .. escape, not absolute, not empty. It does not follow symlinks.

Java

// Vulnerable
@GetMapping("/download")
public Resource download(@RequestParam String name) {
    return new FileSystemResource(new File("/srv/files", name));
}
// Fixed
private static final Path BASE = Path.of("/srv/files").toAbsolutePath().normalize();

@GetMapping("/download")
public Resource download(@RequestParam String name) {
    Path target = BASE.resolve(name).normalize();
    if (!target.startsWith(BASE)) {
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Path outside the files folder");
    }
    return new FileSystemResource(target);
}

Path.startsWith compares whole name elements, so it does not have the string-prefix bug. Use toRealPath() on both sides if the folder can contain symlinks.

Normalization pitfalls

Most broken fixes fail in one of these ways:

  • Checking before decoding. Rejecting the string ../ and then URL-decoding lets %2e%2e%2f through. Double encoding (%252e) defeats code that decodes twice. Validate the final value that reaches the filesystem call.
  • Stripping instead of rejecting. Removing ../ once turns ....// into ../. Reject, do not repair.
  • Forgetting other separators. On Windows, ..\ is a traversal too, and so is an absolute path like C:\Windows.
  • String prefix checks. startsWith(base) without a trailing separator, as above.
  • Ignoring symlinks. A lexical check passes, then the OS follows a link out. Resolve real paths or use an API like os.Root.

The strongest fix sidesteps all of them: do not take a path at all. Store files under generated IDs and look the path up in the database, checking that the caller is allowed to see that record.

File uploads

The filename in a multipart upload is chosen by the client. file.originalname in multer, getOriginalFilename() in Spring and FileStorage.filename in Flask can all contain ../ or an absolute path.

// Vulnerable: client picks where the file lands
fs.writeFileSync(path.join(UPLOAD_DIR, req.file.originalname), req.file.buffer);

// Fixed: the server picks the name
const id = crypto.randomUUID();
fs.writeFileSync(path.join(UPLOAD_DIR, id), req.file.buffer);
await db.files.insert({ id, displayName: req.file.originalname.slice(0, 255), owner: req.user.id });

Keep the original name only as display metadata. Store uploads outside the web root so an uploaded .php or .jsp file is never served as code, and decide content type from what you allow, not from the extension the client sent. If you must keep a user-facing name on disk, Werkzeug's secure_filename reduces it to a safe ASCII form.

Archives: zip slip

Extracting an uploaded archive is path traversal at scale: each entry name is attacker-controlled. Apply the same resolve-and-contain check to every entry before writing it. In Python, tarfile extraction filters arrived in 3.12, and 3.14 made the data filter the default, which refuses links to absolute paths or outside the destination (tarfile docs). On earlier versions, pass filter="data" explicitly.

What Vulkro checks

Vulkro follows request data into filesystem calls in JavaScript, TypeScript, Python, Go and Java. Rules include py-taint-path-001, go-taint-path-001 and JAVA-PATH-001, each finding carrying the hops from the route to the file call, plus GO-ZIPSLIP-001 for archive extraction in Go and PHP-UPLOAD-001 for PHP uploads. vulkro fix prints a path traversal remedy per finding, and if you expected a finding that did not appear, vulkro why-not --family path-traversal explains the silence at a file and line.

FAQ

Does path.join prevent path traversal?

No. path.join resolves .. segments, which is how ../../etc/passwd escapes the base folder. Resolve the path, then check it is still inside the base folder, or use an API that enforces a root.

What is the best way to prevent path traversal?

Do not build paths from user input. Map user-facing IDs to stored paths on the server. When you must accept a name, resolve it to a real path and check containment by whole path components, and reject rather than strip bad input.

How do I prevent path traversal in file uploads?

Ignore the client's filename for storage: generate a random name on the server, keep the original only as metadata, store outside the web root, and check every entry path when extracting archives.

Start a 14-day trial at /start/. Related reading: IDOR prevention in Express and NestJS and Attack paths, not findings lists.