Node.js based forum software built for the modern web
fix: directory traversal in post uploads
Barış Soner Uşaklı9970c9f1ff17
diff --git a/src/posts/uploads.js b/src/posts/uploads.jsindex b85b1734f0..bfb46d46bc 100644--- a/src/posts/uploads.js+++ b/src/posts/uploads.js@@ -21,14 +21,17 @@ module.exports = function (Posts) {Posts.uploads = {};const md5 = filename => crypto.createHash('md5').update(filename).digest('hex');- const pathPrefix = path.join(nconf.get('upload_path'));+ const upload_path = nconf.get('upload_path');const searchRegex = /\/assets\/uploads(\/files\/[^\s")]+\.?[\w]*)/g;- const _getFullPath = relativePath => path.join(pathPrefix, relativePath);- const _filterValidPaths = async filePaths => (await Promise.all(filePaths.map(async (filePath) => {- const fullPath = _getFullPath(filePath);- return fullPath.startsWith(pathPrefix) && await file.exists(fullPath) ? filePath : false;- }))).filter(Boolean);+ const _getFullPath = relativePath => path.join(upload_path, relativePath);+ const _filterValidPaths = async function (filePaths) {+ return (await Promise.all(filePaths.map(async (filePath) => {+ const fullPath = _getFullPath(filePath);+ const valid = file.isPathInside(upload_path, fullPath) && await file.exists(fullPath);+ return valid ? filePath : false;+ }))).filter(Boolean);+ };Posts.uploads.startJobs = async function () {const runJobs = nconf.get('runJobs');diff --git a/test/posts/uploads.js b/test/posts/uploads.jsindex 45ea10411f..eb3e33d71d 100644--- a/test/posts/uploads.js+++ b/test/posts/uploads.js@@ -246,6 +246,45 @@ describe('upload methods', () => {await posts.purge(secondPost.pid, uid);assert.strictEqual(await file.exists(path.resolve(nconf.get('upload_path'), 'files', 'abracadabra.png')), true);});++ it('should fail to delete from sibling uploads folder', async () => {+ const siblingFolderPath = path.resolve(nconf.get('upload_path'), '../uploads-sibling');+ const siblingFilePath = path.join(siblingFolderPath, 'dummy.txt');+ let createdPost;++ try {+ await fs.promises.mkdir(siblingFolderPath, { recursive: true });+ await fs.promises.writeFile(siblingFilePath, 'dummy');++ createdPost = await topics.post({+ uid,+ cid,+ title: 'Traversal to sibling upload folder',+ content: '/assets/uploads/files/../../uploads-sibling/dummy.txt',+ });++ const mainPid = createdPost.postData.pid;+ const uploads = await posts.uploads.list(mainPid);++ assert.deepStrictEqual(uploads, []);++ await posts.edit({+ pid: mainPid,+ uid,+ content: 'post removed',+ });++ assert.strictEqual(await file.exists(siblingFilePath), true);+ } finally {+ if (await file.exists(siblingFilePath)) {+ await file.delete(siblingFilePath);+ }++ if (await file.exists(siblingFolderPath)) {+ await fs.promises.rm(siblingFolderPath, { recursive: true, force: true });+ }+ }+ });});describe('.deleteFromDisk()', () => {