SecPrep logoSecPrep

What vulnerability does this diff address?

javascript diff
-const filePath = './uploads/' + req.params.filename;-res.sendFile(filePath);+const UPLOAD_DIR = path.resolve('./uploads');+const filePath = path.resolve(UPLOAD_DIR, req.params.filename);+if (!filePath.startsWith(UPLOAD_DIR + path.sep)) return res.sendStatus(400);+res.sendFile(filePath);

Path traversal vulnerability. The original code naively concatenates a user-supplied filename onto './uploads/'. An attacker can supply ../../etc/passwd as the filename: the resulting path ./uploads/../../etc/passwd resolves to /etc/passwd, completely outside the intended directory.

The fix uses path.resolve() to compute the absolute, normalised path (this collapses .. sequences), then checks whether the result still starts with UPLOAD_DIR + path.sep. If the resolved path escapes the uploads directory for any reason, the request is rejected with a 400 before sendFile is called.

Practice this in the app →