-
Notifications
You must be signed in to change notification settings - Fork 4
/
path_transversal_ok.js
48 lines (40 loc) · 1.27 KB
/
path_transversal_ok.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
var express = require('express');
var fs = require('fs');
var app = express();
var path = require('path');
var root = path.join(__dirname, '/files');
//For avoid path transversal
//You simply need to construct the absolute path and check that it
//Limiting public file access to specific controlled folders or files and always
//constructing and validating absolute paths before actual file access allows
//you to make sure that you’re safe against being overly open with your data.
//starts with the absolute path of your expected public folders.
//Construct absolute path
function getPath(filename) {
return path.join(root, filename);
}
//Validate path
function validate(filePath) {
// Expect the filepath to start with
// our public root path
return filePath.indexOf(root) === 0;
}
app.get('/', function (req, res) {
if(!req.query.file) {
res.sendStatus(404);
return;
}
var filePath = getPath(req.query.file);
if(!validate(filePath)) {
res.sendStatus(404);
return;
}
var stream = fs.createReadStream(filePath);
//Handle errors
stream.on('error', function (err) {
var status = err.code === 'ENOENT' ? 404 : 500;
res.sendStatus(status);
});
stream.pipe(res);
});
app.listen(3000);