Node.js based forum software built for the modern web
fix: sanitize xml files in uploads
Barış Soner Uşaklı2bde875f7b4d
diff --git a/install/package.json b/install/package.jsonindex 3b7608cb76..e7075f7e0c 100644--- a/install/package.json+++ b/install/package.json@@ -39,6 +39,7 @@"@textcomplete/contenteditable": "0.1.13","@textcomplete/core": "0.1.13","@textcomplete/textarea": "0.1.13",+ "@xmldom/xmldom": "^0.9.10","ace-builds": "1.43.6","archiver": "7.0.1","async": "3.2.6",diff --git a/src/file.js b/src/file.jsindex 7bfc957a94..45a7f7089e 100644--- a/src/file.js+++ b/src/file.js@@ -8,6 +8,7 @@ const { mkdirp } = require('mkdirp');const mime = require('mime');const graceful = require('graceful-fs');const sanitizeHtml = require('sanitize-html');+const { DOMParser, XMLSerializer } = require('@xmldom/xmldom');const slugify = require('./slugify');@@ -28,8 +29,11 @@ file.saveFileToLocal = async function (filename, folder, tempPath) {winston.verbose(`Saving file ${filename} to : ${uploadPath}`);await mkdirp(path.dirname(uploadPath));- if (filename.endsWith('.svg')) {+ const extension = path.extname(filename).toLowerCase();+ if (extension === '.svg') {await sanitizeSvg(tempPath);+ } else if (extension === '.xml') {+ await sanitizeXml(tempPath);}await fs.promises.copyFile(tempPath, uploadPath);@@ -195,4 +199,54 @@ async function sanitizeSvg(filePath) {await fs.promises.writeFile(filePath, clean);}+const FORBIDDEN = new Set([+ 'script',+ 'iframe',+ 'object',+ 'embed',+ 'svg',+]);++async function sanitizeXml(filePath) {+ const dirty = await fs.promises.readFile(filePath, 'utf8');+ if (dirty.includes('<!DOCTYPE') || dirty.includes('<!ENTITY')) {+ throw new Error('DTD not allowed');+ }+ console.log('dirty', dirty);+ const doc = new DOMParser().parseFromString(dirty, 'text/xml');++ function walk(node) {+ if (node.nodeType === 1) {+ const tag = node.tagName.toLowerCase();++ if (FORBIDDEN.has(tag)) {+ node.parentNode.removeChild(node);+ return;+ }++ for (const attr of [...node.attributes]) {+ const name = attr.name.toLowerCase();+ const value = attr.value.toLowerCase();++ if (+ name.startsWith('on') ||+ value.startsWith('javascript:')+ ) {+ node.removeAttribute(attr.name);+ }+ }+ }++ for (const child of [...node.childNodes]) {+ walk(child);+ }+ }++ walk(doc.documentElement);++ const clean = new XMLSerializer().serializeToString(doc);+ console.log('clean', clean);+ await fs.promises.writeFile(filePath, clean);+}+require('./promisify')(file);diff --git a/test/files/xss-dirty.xml b/test/files/xss-dirty.xmlnew file mode 100644index 0000000000..7dcc39dc9f--- /dev/null+++ b/test/files/xss-dirty.xml@@ -0,0 +1,10 @@+<?xml version="1.0" encoding="UTF-8"?>+<a xmlns:a="http://www.w3.org/1999/xhtml">+ <a:body onload="alert('XSS')">+ <a:entry>+ <a:title>Test Entry</a:title>+ <a:content>This is a test entry.</a:content>+ <script>alert('XSS');</script>+ </a:entry>+ </a:body>+</a>diff --git a/test/files/xss-valid.xml b/test/files/xss-valid.xmlnew file mode 100644index 0000000000..dbf7bcd9b6--- /dev/null+++ b/test/files/xss-valid.xml@@ -0,0 +1,17 @@+<?xml version="1.0" encoding="UTF-8"?>+<bookstore>+ <book>+ <title>Book 1</title>+ <author>John Smith</author>+ <year>2026</year>+ <price>29.99</price>+ <description>Book 1 Description.</description>+ </book>+ <book>+ <title>Book 2</title>+ <author>Sam Smith</author>+ <year>2025</year>+ <price>39.99</price>+ <description>Book 2 Description.</description>+ </book>+</bookstore>\ No newline at end of filediff --git a/test/uploads.js b/test/uploads.jsindex e5ac2bfb4a..8c53d86e37 100644--- a/test/uploads.js+++ b/test/uploads.js@@ -469,6 +469,41 @@ describe('Upload Controllers', () => {assert(file.existsSync(path.join(nconf.get('upload_path'), 'system', 'test.png')));});+ it('should sanitize xss payload in uploaded xml files', async () => {+ const { response, body } = await helpers.uploadFile(`${nconf.get('url')}/api/admin/upload/file`, path.join(__dirname, '../test/files/xss-dirty.xml'), {+ params: JSON.stringify({+ folder: 'files',+ }),+ }, jar, csrf_token);++ assert.equal(response.statusCode, 200);+ assert(Array.isArray(body));+ assert.equal(body[0].url, '/assets/uploads/files/xss-dirty.xml');++ const { response: fileResponse, body: uploadedBody } = await request.get(`${nconf.get('url')}${body[0].url}`);+ assert.equal(fileResponse.statusCode, 200);+ assert.strictEqual(uploadedBody.includes('<script>'), false);+ assert.strictEqual(uploadedBody.includes('onload="alert(\'XSS\')"'), false);+ });++ it('should keep valid xml file unchanged', async () => {+ const validXmlPath = path.join(__dirname, '../test/files/xss-valid.xml');+ const validXmlContent = await fs.readFile(validXmlPath, 'utf-8');+ const { response, body } = await helpers.uploadFile(`${nconf.get('url')}/api/admin/upload/file`, validXmlPath, {+ params: JSON.stringify({+ folder: 'files',+ }),+ }, jar, csrf_token);++ assert.equal(response.statusCode, 200);+ assert(Array.isArray(body));+ assert.equal(body[0].url, '/assets/uploads/files/xss-valid.xml');++ const { response: fileResponse, body: uploadedBody } = await request.get(`${nconf.get('url')}${body[0].url}`);+ assert.equal(fileResponse.statusCode, 200);+ assert.strictEqual(uploadedBody, validXmlContent);+ });+it('should fail to upload regular file in wrong directory', async () => {const { response, body } = await helpers.uploadFile(`${nconf.get('url')}/api/admin/upload/file`, path.join(__dirname, '../test/files/test.png'), {params: JSON.stringify({