Node.js based forum software built for the modern web
refactor: add file.isPathInside to replace .startsWith checks (#14509)
Barış Uşaklıb1e8721acfba
diff --git a/src/controllers/admin/uploads.js b/src/controllers/admin/uploads.jsindex abec2e1c79..14b17d83d5 100644--- a/src/controllers/admin/uploads.js+++ b/src/controllers/admin/uploads.js@@ -20,7 +20,7 @@ const uploadsController = module.exports;uploadsController.get = async function (req, res, next) {const currentFolder = path.join(nconf.get('upload_path'), req.query.dir || '');- if (!currentFolder.startsWith(nconf.get('upload_path'))) {+ if (!file.isPathInside(nconf.get('upload_path'), currentFolder)) {return next(new Error('[[error:invalid-path]]'));}const itemsPerPage = 20;diff --git a/src/file.js b/src/file.jsindex ec19617e2a..9c75f768fd 100644--- a/src/file.js+++ b/src/file.js@@ -23,7 +23,7 @@ file.saveFileToLocal = async function (filename, folder, tempPath) {filename = filename.split('.').map(name => slugify(name)).join('.');const uploadPath = path.join(nconf.get('upload_path'), folder, filename);- if (!uploadPath.startsWith(nconf.get('upload_path'))) {+ if (!file.isPathInside(nconf.get('upload_path'), uploadPath)) {throw new Error('[[error:invalid-path]]');}@@ -43,6 +43,12 @@ file.saveFileToLocal = async function (filename, folder, tempPath) {};};+file.isPathInside = function (base, targetPath) {+ const resolvedBase = path.resolve(base);+ const resolvedTarget = path.resolve(base, targetPath);+ return resolvedTarget === resolvedBase || resolvedTarget.startsWith(resolvedBase + path.sep);+};+file.base64ToLocal = async function (imageData, uploadPath) {const buffer = Buffer.from(imageData.slice(imageData.indexOf('base64') + 7), 'base64');uploadPath = path.join(nconf.get('upload_path'), uploadPath);diff --git a/src/meta/themes.js b/src/meta/themes.jsindex 6cce964832..198b02b267 100644--- a/src/meta/themes.js+++ b/src/meta/themes.js@@ -94,8 +94,9 @@ Themes.set = async (data) => {await db.sortedSetAdd('plugins:active', score || 0, data.id);if (current !== data.id) {- const pathToThemeJson = path.join(nconf.get('themes_path'), data.id, 'theme.json');- if (!pathToThemeJson.startsWith(nconf.get('themes_path'))) {+ const themesPath = nconf.get('themes_path');+ const pathToThemeJson = path.join(themesPath, data.id, 'theme.json');+ if (!file.isPathInside(themesPath, pathToThemeJson)) {throw new Error('[[error:invalid-theme-id]]');}diff --git a/src/middleware/assert.js b/src/middleware/assert.jsindex 2d920dfd29..db896fda15 100644--- a/src/middleware/assert.js+++ b/src/middleware/assert.js@@ -102,7 +102,7 @@ Assert.path = helpers.try(async (req, res, next) => {res.locals.cleanedPath = pathToFile;// Guard against path traversal- if (!pathToFile.startsWith(nconf.get('upload_path'))) {+ if (!file.isPathInside(nconf.get('upload_path'), pathToFile)) {return controllerHelpers.formatApiResponse(403, res, new Error('[[error:invalid-path]]'));}diff --git a/src/middleware/index.js b/src/middleware/index.jsindex dda66d403a..91af064ae6 100644--- a/src/middleware/index.js+++ b/src/middleware/index.js@@ -16,6 +16,7 @@ const privileges = require('../privileges');const cacheCreate = require('../cache/lru');const helpers = require('./helpers');const api = require('../api');+const file = require('../file');const controllers = {api: require('../controllers/api'),@@ -154,7 +155,7 @@ middleware.routeTouchIcon = function routeTouchIcon(req, res) {if (brandTouchIcon) {const uploadPath = nconf.get('upload_path');iconPath = path.join(uploadPath, brandTouchIcon.replace(/assets\/uploads/, ''));- if (!iconPath.startsWith(uploadPath)) {+ if (!file.isPathInside(uploadPath, iconPath)) {return res.status(404).send('Not found');}} else {diff --git a/src/topics/thumbs.js b/src/topics/thumbs.jsindex 30d168f0ae..cd9c4268e1 100644--- a/src/topics/thumbs.js+++ b/src/topics/thumbs.js@@ -8,6 +8,7 @@ const mime = require('mime').default;const plugins = require('../plugins');const posts = require('../posts');const meta = require('../meta');+const file = require('../file');const topics = module.parent.exports;const Thumbs = module.exports;@@ -176,7 +177,7 @@ Thumbs.filterThumbs = function (thumbs) {}// ensure it is in upload pathconst fullPath = path.join(upload_path, thumb);- return fullPath.startsWith(upload_path);+ return file.isPathInside(upload_path, fullPath);});return thumbs;};diff --git a/src/user/uploads.js b/src/user/uploads.jsindex 7d004fdc37..b8f81c5cd1 100644--- a/src/user/uploads.js+++ b/src/user/uploads.js@@ -11,9 +11,9 @@ const batch = require('../batch');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 _getFullPath = relativePath => path.join(pathPrefix, relativePath);+const _getFullPath = relativePath => path.join(upload_path, relativePath);const _validatePath = async (relativePaths) => {if (typeof relativePaths === 'string') {@@ -22,10 +22,10 @@ const _validatePath = async (relativePaths) => {throw new Error(`[[error:wrong-parameter-type, relativePaths, ${typeof relativePaths}, array]]`);}- const fullPaths = relativePaths.map(path => _getFullPath(path));- const exists = await Promise.all(fullPaths.map(async fullPath => file.exists(fullPath)));+ const fullPaths = relativePaths.map(_getFullPath);+ const exists = await Promise.all(fullPaths.map(file.exists));- if (!fullPaths.every(fullPath => fullPath.startsWith(nconf.get('upload_path'))) || !exists.every(Boolean)) {+ if (!fullPaths.every(fullPath => file.isPathInside(upload_path, fullPath)) || !exists.every(Boolean)) {throw new Error('[[error:invalid-path]]');}};diff --git a/src/webserver.js b/src/webserver.jsindex 6458498732..f16d2b35eb 100644--- a/src/webserver.js+++ b/src/webserver.js@@ -253,7 +253,7 @@ function setupHelmet(app) {function setupFavicon(app) {let faviconPath = meta.config['brand:favicon'] || 'favicon.ico';faviconPath = path.join(nconf.get('base_dir'), 'public', faviconPath.replace(/assets\/uploads/, 'uploads'));- if (!faviconPath.startsWith(nconf.get('upload_path'))) {+ if (!file.isPathInside(nconf.get('upload_path'), faviconPath)) {faviconPath = path.join(nconf.get('base_dir'), 'public', 'favicon.ico');}if (file.existsSync(faviconPath)) {diff --git a/test/file.js b/test/file.jsindex becd7b44d6..28cc8b6499 100644--- a/test/file.js+++ b/test/file.js@@ -1,5 +1,6 @@'use strict';+const db = require('./mocks/databasemock');const assert = require('assert');const fs = require('fs');const path = require('path');@@ -119,4 +120,61 @@ describe('file', () => {assert.equal(file.typeToExtension(''), '');done();});++ describe('file.isPathInside', () => {+ const uploadPath = nconf.get('upload_path');++ it('should return true for valid paths inside the base directory', () => {+ const validPaths = [+ // Standard absolute paths+ path.join(uploadPath, 'test.png'),+ path.join(uploadPath, 'files/test.png'),++ // Standard relative paths+ 'test.png',+ 'files/test.png',++ // Current directory edge cases+ '',+ '.',++ // Paths with redundant dot-segments that still resolve inside+ 'files/../test.png',+ path.join(uploadPath, 'files/../test.png'),+ ];++ for (const p of validPaths) {+ assert.strictEqual(file.isPathInside(uploadPath, p), true, `Failed on valid path: ${p}`);+ }+ });++ it('should return false for traversal attempts and paths outside the base directory', () => {+ const invalidPaths = [+ // The Sibling Directory Bypass+ '../uploads-secret',+ '../uploads-secret/test.png',+ `${uploadPath}-secret`,++ // Standard Path Traversal+ '../',+ '..',+ '../../etc/passwd',++ // Sneaky Traversal (redundant slashes)+ '..//..//etc/passwd',+ 'files/../../etc/passwd',++ // Absolute Path Injection (escaping the base entirely)+ '/etc/passwd',+ '/root/secret.txt',++ // Absolute path guaranteed to work on current OS (Windows/Linux)+ path.resolve('/etc/passwd'),+ ];++ for (const p of invalidPaths) {+ assert.strictEqual(file.isPathInside(uploadPath, p), false, `Failed on invalid path: ${p}`);+ }+ });+ });});