Skip to content

Commit

Permalink
Merge commit '9c9389b30caa43c3e2c6f64d5adcad47780b2cde'
Browse files Browse the repository at this point in the history
* commit '9c9389b30caa43c3e2c6f64d5adcad47780b2cde':
  Protect fs.stats calls from bad path arguments

# Conflicts:
#	lib/node-static.js
#	test/integration/node-static-test.js
  • Loading branch information
brettz9 committed Mar 29, 2021
2 parents 83aac2e + 9c9389b commit 78879dc
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
16 changes: 12 additions & 4 deletions lib/node-static.js
Expand Up @@ -12,6 +12,14 @@ const fs = require('fs')
// Current version
const version = [0, 7, 9];

function tryStat(p, callback) {
try {
fs.stat(p, callback);
} catch (e) {
callback(e);
}
}

const Server = function (root, options) {
if (root && (typeof(root) === 'object')) { options = root; root = null }

Expand Down Expand Up @@ -57,7 +65,7 @@ Server.prototype.serveDir = function (pathname, req, res, finish) {
const htmlIndex = path.join(pathname, this.options.indexFile),
that = this;

fs.stat(htmlIndex, function (e, stat) {
tryStat(htmlIndex, function (e, stat) {
if (!e) {
const status = 200;
const headers = {};
Expand Down Expand Up @@ -90,7 +98,7 @@ Server.prototype.serveFile = function (pathname, status, headers, req, res) {

pathname = this.resolve(pathname);

fs.stat(pathname, function (e, stat) {
tryStat(pathname, function (e, stat) {
if (e) {
return promise.emit('error', e);
}
Expand Down Expand Up @@ -145,7 +153,7 @@ Server.prototype.servePath = function (pathname, status, headers, req, res, fini
// Make sure we're not trying to access a
// file outside of the root.
if (pathname.startsWith(that.root)) {
fs.stat(pathname, function (e, stat) {
tryStat(pathname, function (e, stat) {
if (e) {
finish(404, {});
} else if (stat.isFile()) { // Stream a single file.
Expand Down Expand Up @@ -216,7 +224,7 @@ Server.prototype.respondGzip = function (pathname, status, contentType, _headers
const that = this;
if (files.length == 1 && this.gzipOk(req, contentType)) {
const gzFile = files[0] + ".gz";
fs.stat(gzFile, function (e, gzStat) {
tryStat(gzFile, function (e, gzStat) {
if (!e && gzStat.isFile()) {
const vary = _headers['Vary'];
_headers['Vary'] = (vary && vary != 'Accept-Encoding' ? vary + ', ' : '') + 'Accept-Encoding';
Expand Down
9 changes: 9 additions & 0 deletions test/integration/node-static-test.js
Expand Up @@ -460,4 +460,13 @@ suite.addBatch({
assert.equal(body, 'hello world');
}
}
}).addBatch({
'handling malicious urls': {
topic : function(){
request.get(TEST_SERVER + '/%00', this.callback);
},
'should respond with 404' : function(error, response, body){
assert.equal(response.statusCode, 404);
}
}
}).export(module);

0 comments on commit 78879dc

Please sign in to comment.