From a67b1b8bb5dcff5e6e3151844d96bf882ae4a976 Mon Sep 17 00:00:00 2001 From: "jeremy@jermolene.com" Date: Sat, 28 Aug 2021 13:16:54 +0100 Subject: [PATCH] Fileserver: Check for valid file paths --- core/modules/server/routes/get-file.js | 35 +++++++++++++++----------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/core/modules/server/routes/get-file.js b/core/modules/server/routes/get-file.js index 2588e48f7..44c79329e 100644 --- a/core/modules/server/routes/get-file.js +++ b/core/modules/server/routes/get-file.js @@ -21,21 +21,28 @@ exports.handler = function(request,response,state) { fs = require("fs"), util = require("util"), suppliedFilename = decodeURIComponent(state.params[0]), - filename = path.resolve(state.boot.wikiPath,"files",suppliedFilename), + baseFilename = path.resolve(state.boot.wikiPath,"files"), + filename = path.resolve(baseFilename,suppliedFilename), extension = path.extname(filename); - fs.readFile(filename,function(err,content) { - var status,content,type = "text/plain"; - if(err) { - console.log("Error accessing file " + filename + ": " + err.toString()); - status = 404; - content = "File '" + suppliedFilename + "' not found"; - } else { - status = 200; - content = content; - type = ($tw.config.fileExtensionInfo[extension] ? $tw.config.fileExtensionInfo[extension].type : "application/octet-stream"); - } - state.sendResponse(status,{"Content-Type": type},content); - }); + // Check that the filename is inside the wiki files folder + if(path.relative(baseFilename,filename).indexOf("..") !== 0) { + // Send the file + fs.readFile(filename,function(err,content) { + var status,content,type = "text/plain"; + if(err) { + console.log("Error accessing file " + filename + ": " + err.toString()); + status = 404; + content = "File '" + suppliedFilename + "' not found"; + } else { + status = 200; + content = content; + type = ($tw.config.fileExtensionInfo[extension] ? $tw.config.fileExtensionInfo[extension].type : "application/octet-stream"); + } + state.sendResponse(status,{"Content-Type": type},content); + }); + } else { + state.sendResponse(404,{"Content-Type": "text/plain"},"File '" + suppliedFilename + "' not found"); + } }; }());