While developing Web Apps we may ignore security in favor of adding new features. One of these vulnerabilities is path traversal. We know that appending an ‘../’ to a path and solving it will result in the parent directory. If an web app uses http path to determine which file to show, then it can be vulnerable to path traversal attacks. Let’s take an example using express.js
const express = require('express');
const path = require('path');
const app = express();
app.get('*', (req, res) => {
res.sendFile(path.join(process.cwd(), req.path));
})
app.listen(3000, () => {
console.log('Listening on port 3000');
})
If our app is located in the ‘C:/Projects/js/’ folder, then if we join it with ’../../Windows/System32’ (just an example, could be any important folder), the hacker can have access to the System32 dir.
A simple way to prevent this is to restrict access to just a few public directories(like /public
, /app
etc.), or, if need to access a dir with sensible data, use an authentication method.