Unrestricted File Download in NodeJS
Express.js
Vulnerable Example
The following example is of an Express.js route that serves files from a directory in an unsecure way:
app.use('/', function (req, res) {
const path = req.path;
const filename = __dirname + "/public" + path;
fs.readFile(filename, function (err, data) {
if (err) {
res.writeHead(500);
return res.end(err.toString());
}
res.writeHead(200);
res.end(data);
});
});
An attacker could request the following URL to fetch files anywhere in the file system:
http://example.com/../../../../../etc/passwd
Prevention
Express.js provides facilities to serve static files in a secure way using the express.static
middleware:
app.use(express.static('public'));