Description
Check whether input selects a file or supplies content for a file already chosen. Using a request value as the path to fs.readFile lets the caller select other files on the server.
Potential impact
Reads may expose another user’s files. If callers can select write or delete targets, they may corrupt data or interrupt the service.
Remediation
- For a filename, validate a single component and join it to a server-controlled base. Check that the normalized path and the real destination after resolving links both stay inside it. Prevent file or link replacement between checking and reading.
- In
fs.writeFile(path, data), thepathargument selects the target.fs.write(fd, data)writes to an already-open descriptor.
Examples
Before
javascript
const fs = require('fs');
const express = require('express');
const app = express();
app.get('/download', (req, res) => {
// Before: use input directly in a filesystem call.
const fileName = req.query.file;
fs.readFile(fileName, (err, data) => {
if (err) return res.status(404).send('File not found');
res.send(data);
});
});
After
javascript
const fs = require('fs');
const path = require('path');
const express = require('express');
const app = express();
// Only the server may write here, preventing link replacement between checking and reading.
const BASE_DIR = fs.realpathSync(path.join(__dirname, 'files'));
function isInside(baseDir, targetPath) {
const relative = path.relative(baseDir, targetPath);
return (
relative !== '' &&
relative !== '..' &&
!relative.startsWith('..' + path.sep) &&
!path.isAbsolute(relative)
);
}
app.get('/download', (req, res) => {
const rawName = req.query.file;
if (typeof rawName !== 'string') {
return res.status(400).send('Invalid file path');
}
// Allow filenames only; reject directory components instead of stripping them.
const fileName = path.basename(rawName);
if (fileName !== rawName || !/^[a-zA-Z0-9._-]+$/.test(fileName)) {
return res.status(400).send('Invalid file path');
}
const candidate = path.resolve(BASE_DIR, fileName);
if (!isInside(BASE_DIR, candidate)) {
return res.status(400).send('Invalid file path');
}
let requestedPath;
try {
requestedPath = fs.realpathSync(candidate);
} catch {
return res.status(404).send('File not found');
}
if (!isInside(BASE_DIR, requestedPath)) {
return res.status(400).send('Invalid file path');
}
fs.readFile(requestedPath, (err, data) => {
if (err) return res.status(404).send('File not found');
res.send(data);
});
});
app.post('/message', (req, res) => {
// The server fixes the path; input supplies file contents only.
fs.writeFile(path.join(BASE_DIR, 'message.txt'), req.body.message, (err) => {
if (err) return res.status(500).send('write failed');
res.send('saved');
});
});
The download checks path.basename() and the filename format, then reads the checked real path. The POST handler writes req.body.message to the fixed message.txt file and requires body-parsing middleware.