flawopen.com/path-traversal/Javascript
How naive path.join allows directory traversal in Express/Node.js, and how to enforce directory boundary checks with path.resolve and path.sep.
एक होटल के कमरे के कार्ड रीडर की कल्पना करें जिसे केवल दूसरी मंजिल के कमरे खोलने चाहिए। यदि कोई मेहमान कीपैड पर '../../master-safe' टाइप करता है, तो असुरक्षित ताला हॉलवे से बाहर निकलकर प्रबंधक की तिजोरी खोल देता है।
Web Application SecurityCWE-918.CWE-918CWE-918): Standard Common Weakness Enumeration classification for path-traversal-javascript.Defense-in-Depthएंडपॉइंट HTTP पैरामीटर के माध्यम से उपयोगकर्ता द्वारा प्रदान किया गया फ़ाइल नाम स्वीकार करता है।
हमलावर फ़ाइल नाम में '../' या '..%2f' जैसे रिलेटिव डायरेक्टरी ट्रैवर्सल सीक्वेंस डालता है।
बैकएंड कैनोनिकल पाथ को सत्यापित किए बिना बेस डायरेक्टरी के साथ पाथ को जोड़ देता है।
सर्वर सिस्टम की संवेदनशील फ़ाइलें (/etc/passwd, पासवर्ड या कुंजियाँ) पढ़कर हमलावर को भेज देता है।
// VULNERABLE: path.join allows directory breakout
const express = require('express');
const path = require('path');
const fs = require('fs');
const app = express();
const PUBLIC_DIR = path.join(__dirname, 'public');
app.get('/download', (req, res) => {
// Attacker input: "../../etc/passwd"
const targetFile = path.join(PUBLIC_DIR, req.query.file);
// Directly pipes arbitrary system file to response!
res.sendFile(targetFile);
});
// HARDENED: Canonicalize path and assert prefix with directory separator
const express = require('express');
const path = require('path');
const fs = require('fs');
const app = express();
const PUBLIC_DIR = path.resolve(__dirname, 'public');
app.get('/download', (req, res) => {
const userInput = req.query.file;
if (!userInput || typeof userInput !== 'string') {
return res.status(400).send('Invalid file parameter');
}
// 1. Resolve to absolute path
const safePath = path.resolve(PUBLIC_DIR, userInput);
// 2. Strict boundary check: must start with base folder + separator
if (!safePath.startsWith(PUBLIC_DIR + path.sep)) {
return res.status(403).send('Forbidden: Path Traversal detected');
}
// 3. Verify file exists and is a regular file
fs.stat(safePath, (err, stats) => {
if (err || !stats.isFile()) return res.status(404).send('File not found');
res.sendFile(safePath);
});
});
path.resolve()।express.static() with dotfiles: 'ignore' for static file serving का उपयोग करें।