From 4877231629fc58bb6fd8e0121fa2912d7c41a9be Mon Sep 17 00:00:00 2001 From: Gilad Oren Date: Tue, 29 May 2012 12:30:48 +0300 Subject: [PATCH] Fix security issue when going up the directories hierarchy --- lib/staticGzip.js | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/lib/staticGzip.js b/lib/staticGzip.js index 5044928..89ae1db 100644 --- a/lib/staticGzip.js +++ b/lib/staticGzip.js @@ -96,6 +96,8 @@ exports = module.exports = function staticGzip(dirPath, options){ if (!dirPath) throw new Error('You need to provide the directory to your static content.'); if (!contentTypeMatch.test) throw new Error('contentTypeMatch: must be a regular expression.'); + dirPath = path.normalize(dirPath); + return function staticGzip(req, res, next){ var url, filename, contentType, acceptEncoding, charset; @@ -134,6 +136,14 @@ exports = module.exports = function staticGzip(dirPath, options){ }); } + function forbidden(res) { + var body = 'Forbidden'; + res.setHeader('Content-Type', 'text/plain'); + res.setHeader('Content-Length', body.length); + res.statusCode = 403; + res.end(body); + }; + if (req.method !== 'GET' && req.method !== 'HEAD') { return next(); } @@ -145,7 +155,11 @@ exports = module.exports = function staticGzip(dirPath, options){ return next(); } - filename = path.join(dirPath, url.pathname.substring(prefix.length)); + filename = path.normalize(path.join(dirPath, url.pathname.substring(prefix.length))); + // malicious path + if (0 != filename.indexOf(dirPath)){ + return forbidden(res); + } contentType = mime.lookup(filename); charset = mime.charsets.lookup(contentType, 'UTF-8');