Skip to content

ActivityPub-federated video streaming platform using P2P directly in your web browser

Sanitize SVG

Chocobozzz90302d0a5b1e
diff --git a/packages/core-utils/src/renderer/html.ts b/packages/core-utils/src/renderer/html.ts
index 6a72547cd5..af845cf60c 100644
--- a/packages/core-utils/src/renderer/html.ts
+++ b/packages/core-utils/src/renderer/html.ts
@@ -10,8 +10,6 @@ export function getDefaultSanitizedHrefAttributes () {
return [ 'href', 'class', 'target', 'rel' ]
}
-// ---------------------------------------------------------------------------
-
// ---------------------------------------------------------------------------
// sanitize-html
// ---------------------------------------------------------------------------
@@ -58,6 +56,229 @@ export function getTextOnlySanitizeOptions () {
}
}
+// Sanitize options for user uploaded SVG files, to prevent XSS
+export function getSanitizeSVGOptions () {
+ return {
+ allowedTags: [
+ 'svg',
+ 'g',
+ 'defs',
+ 'symbol',
+ 'use',
+ 'switch',
+ 'title',
+ 'desc',
+ 'metadata',
+ 'path',
+ 'rect',
+ 'circle',
+ 'ellipse',
+ 'line',
+ 'polyline',
+ 'polygon',
+ 'text',
+ 'tspan',
+ 'textPath',
+ 'linearGradient',
+ 'radialGradient',
+ 'stop',
+ 'clipPath',
+ 'mask',
+ 'pattern',
+ 'marker',
+ 'image',
+ 'filter',
+ 'feBlend',
+ 'feColorMatrix',
+ 'feComponentTransfer',
+ 'feComposite',
+ 'feConvolveMatrix',
+ 'feDiffuseLighting',
+ 'feDisplacementMap',
+ 'feDistantLight',
+ 'feDropShadow',
+ 'feFlood',
+ 'feFuncA',
+ 'feFuncB',
+ 'feFuncG',
+ 'feFuncR',
+ 'feGaussianBlur',
+ 'feImage',
+ 'feMerge',
+ 'feMergeNode',
+ 'feMorphology',
+ 'feOffset',
+ 'fePointLight',
+ 'feSpecularLighting',
+ 'feSpotLight',
+ 'feTile',
+ 'feTurbulence'
+ ],
+ allowedAttributes: {
+ '*': [
+ // Core
+ 'id',
+ 'class',
+ 'style',
+ 'lang',
+ // References
+ 'href',
+ 'xlink:href',
+ 'xlink:title',
+ // Namespaces/versioning
+ 'xmlns',
+ 'xmlns:xlink',
+ 'version',
+ 'xml:space',
+ 'xml:lang',
+ 'baseProfile',
+ // Geometry
+ 'x',
+ 'y',
+ 'x1',
+ 'y1',
+ 'x2',
+ 'y2',
+ 'cx',
+ 'cy',
+ 'r',
+ 'rx',
+ 'ry',
+ 'd',
+ 'points',
+ 'width',
+ 'height',
+ 'dx',
+ 'dy',
+ 'rotate',
+ 'pathLength',
+ 'transform',
+ 'gradientTransform',
+ 'patternTransform',
+ 'viewBox',
+ 'preserveAspectRatio',
+ 'offset',
+ // Presentation
+ 'fill',
+ 'fill-opacity',
+ 'fill-rule',
+ 'clip-path',
+ 'clip-rule',
+ 'mask',
+ 'filter',
+ 'stroke',
+ 'stroke-width',
+ 'stroke-linecap',
+ 'stroke-linejoin',
+ 'stroke-dasharray',
+ 'stroke-dashoffset',
+ 'stroke-opacity',
+ 'stroke-miterlimit',
+ 'opacity',
+ 'color',
+ 'display',
+ 'visibility',
+ 'overflow',
+ 'vector-effect',
+ 'stop-color',
+ 'stop-opacity',
+ 'paint-order',
+ 'shape-rendering',
+ 'image-rendering',
+ 'color-interpolation',
+ 'color-interpolation-filters',
+ // Text
+ 'font-family',
+ 'font-size',
+ 'font-weight',
+ 'font-style',
+ 'text-anchor',
+ 'text-decoration',
+ 'letter-spacing',
+ 'word-spacing',
+ 'dominant-baseline',
+ 'alignment-baseline',
+ 'baseline-shift',
+ 'direction',
+ 'writing-mode',
+ // Units
+ 'gradientUnits',
+ 'patternUnits',
+ 'patternContentUnits',
+ 'clipPathUnits',
+ 'maskUnits',
+ 'maskContentUnits',
+ 'markerUnits',
+ 'filterUnits',
+ 'primitiveUnits',
+ 'spreadMethod',
+ 'markerWidth',
+ 'markerHeight',
+ 'refX',
+ 'refY',
+ 'orient',
+ // Filters
+ 'in',
+ 'in2',
+ 'result',
+ 'stdDeviation',
+ 'mode',
+ 'type',
+ 'values',
+ 'operator',
+ 'k1',
+ 'k2',
+ 'k3',
+ 'k4',
+ 'radius',
+ 'flood-color',
+ 'flood-opacity',
+ 'edgeMode',
+ 'tableValues',
+ 'slope',
+ 'intercept',
+ 'amplitude',
+ 'exponent',
+ 'baseFrequency',
+ 'numOctaves',
+ 'seed',
+ 'stitchTiles',
+ 'scale',
+ 'xChannelSelector',
+ 'yChannelSelector',
+ 'order',
+ 'kernelMatrix',
+ 'divisor',
+ 'bias',
+ 'targetX',
+ 'targetY',
+ 'preserveAlpha',
+ 'surfaceScale',
+ 'diffuseConstant',
+ 'specularConstant',
+ 'specularExponent',
+ 'azimuth',
+ 'elevation',
+ 'limitingConeAngle',
+ 'pointsAtX',
+ 'pointsAtY',
+ 'pointsAtZ',
+ 'z'
+ ]
+ },
+ // Prevent javascript: and data: URLs
+ allowedSchemes: getDefaultSanitizedSchemes(),
+ allowedSchemesAppliedToAttributes: [ 'href', 'xlink:href' ],
+
+ // SVG tags and attributes are case sensitive (e.g. viewBox, linearGradient) and use self-closing tags
+ parser: {
+ lowerCaseTags: false,
+ lowerCaseAttributeNames: false,
+ recognizeSelfClosing: true
+ }
+ }
+}
+
// ---------------------------------------------------------------------------
// Manual escapes
// ---------------------------------------------------------------------------
diff --git a/packages/tests/src/server-helpers/image.ts b/packages/tests/src/server-helpers/image.ts
index 42bbb05e7e..54b3b8546c 100644
--- a/packages/tests/src/server-helpers/image.ts
+++ b/packages/tests/src/server-helpers/image.ts
@@ -2,10 +2,10 @@
import { buildAbsoluteFixturePath, root } from '@peertube/peertube-node-utils'
import { execPromise } from '@peertube/peertube-server/core/helpers/core-utils.js'
-import { processImage } from '@peertube/peertube-server/core/helpers/image-utils.js'
+import { processImage, processSVG } from '@peertube/peertube-server/core/helpers/image-utils.js'
import { expect } from 'chai'
-import { remove } from 'fs-extra/esm'
-import { readFile } from 'fs/promises'
+import { ensureDir, remove } from 'fs-extra/esm'
+import { readFile, writeFile } from 'fs/promises'
import { join } from 'path'
import sharp from 'sharp'
@@ -121,3 +121,100 @@ describe('Image helpers', function () {
await remove(imageDestDir)
})
})
+
+describe('SVG sanitization', function () {
+ const svgDir = join(root(), 'test-svg')
+ const svgSrc = join(svgDir, 'input.svg')
+ const svgDest = join(svgDir, 'output.svg')
+
+ async function sanitize (content: string) {
+ await ensureDir(svgDir)
+ await writeFile(svgSrc, content)
+
+ await processSVG({ path: svgSrc, destination: svgDest })
+
+ return readFile(svgDest, 'utf-8')
+ }
+
+ it('Should remove script tags', async function () {
+ const result = await sanitize(
+ '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script><circle cx="5" cy="5" r="5"/></svg>'
+ )
+
+ expect(result).to.not.contain('script')
+ expect(result).to.not.contain('alert')
+ expect(result).to.contain('circle')
+ })
+
+ it('Should remove event handler attributes', async function () {
+ const result = await sanitize(
+ '<svg xmlns="http://www.w3.org/2000/svg" onload="alert(1)"><rect width="10" height="10" onclick="alert(2)"/></svg>'
+ )
+
+ expect(result).to.not.contain('onload')
+ expect(result).to.not.contain('onclick')
+ expect(result).to.not.contain('alert')
+ expect(result).to.contain('rect')
+ })
+
+ it('Should remove foreignObject that can embed arbitrary HTML', async function () {
+ const result = await sanitize(
+ '<svg xmlns="http://www.w3.org/2000/svg">' +
+ '<foreignObject width="100" height="100"><body xmlns="http://www.w3.org/1999/xhtml"><img src=x onerror="alert(1)"></body></foreignObject>' +
+ '</svg>'
+ )
+
+ expect(result).to.not.contain('foreignObject')
+ expect(result).to.not.contain('onerror')
+ expect(result).to.not.contain('alert')
+ })
+
+ it('Should remove javascript: hrefs', async function () {
+ const result = await sanitize(
+ '<svg xmlns="http://www.w3.org/2000/svg">' +
+ '<a href="javascript:alert(1)"><text x="0" y="0">click</text></a>' +
+ '<use xlink:href="javascript:alert(2)"/>' +
+ '</svg>'
+ )
+
+ // oxlint-disable-next-line no-script-url
+ expect(result).to.not.contain('javascript:')
+ expect(result).to.not.contain('alert')
+ })
+
+ it('Should remove animation elements that can inject event handlers', async function () {
+ const result = await sanitize(
+ '<svg xmlns="http://www.w3.org/2000/svg">' +
+ '<rect width="10" height="10"><set attributeName="onload" to="alert(1)"/></rect>' +
+ '<animate attributeName="href" to="javascript:alert(2)"/>' +
+ '</svg>'
+ )
+
+ expect(result).to.not.contain('animate')
+ expect(result.toLowerCase()).to.not.contain('<set')
+ expect(result).to.not.contain('alert')
+ // oxlint-disable-next-line no-script-url
+ expect(result).to.not.contain('javascript:')
+ })
+
+ it('Should keep valid SVG content and case sensitive attributes', async function () {
+ const input = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">' +
+ '<defs><linearGradient id="g" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#fff"/></linearGradient></defs>' +
+ '<path d="M10 10 H 90 V 90 H 10 Z" fill="url(#g)" stroke="#000"/>' +
+ '<circle cx="50" cy="50" r="40"/>' +
+ '</svg>'
+
+ const result = await sanitize(input)
+
+ expect(result).to.contain('viewBox="0 0 100 100"')
+ expect(result).to.contain('linearGradient')
+ expect(result).to.contain('gradientUnits="userSpaceOnUse"')
+ expect(result).to.contain('d="M10 10 H 90 V 90 H 10 Z"')
+ expect(result).to.contain('fill="url(#g)"')
+ expect(result).to.contain('circle')
+ })
+
+ after(async function () {
+ await remove(svgDir)
+ })
+})
diff --git a/server/core/helpers/image-utils.ts b/server/core/helpers/image-utils.ts
index 6e19bd9740..756468c8ed 100644
--- a/server/core/helpers/image-utils.ts
+++ b/server/core/helpers/image-utils.ts
@@ -1,6 +1,8 @@
+import { getSanitizeSVGOptions } from '@peertube/peertube-core-utils'
import { buildUUID, getLowercaseExtension } from '@peertube/peertube-node-utils'
import { copy, remove } from 'fs-extra/esm'
-import { readFile } from 'fs/promises'
+import { readFile, writeFile } from 'fs/promises'
+import sanitizeHtml from 'sanitize-html'
import sharp, { type Metadata, type Sharp } from 'sharp'
import { logger } from './logger.js'
@@ -8,6 +10,27 @@ export function generateImageFilename (extension = '.jpg') {
return buildUUID() + extension
}
+// ---------------------------------------------------------------------------
+
+const svgSanitizeOptions = getSanitizeSVGOptions()
+
+// Sanitize a SVG to strip potential XSS
+// It only allows a safe subset of SVG tags and attributes
+// Would be better to use dompurify, but it's very heavy in NodeJS so prefer using the already imported sanitize-html module
+export async function processSVG (options: {
+ path: string
+ destination: string
+}) {
+ const { path, destination } = options
+
+ logger.debug('Sanitizing SVG %s to %s.', path, destination)
+
+ const svg = await readFile(path, 'utf-8')
+ const sanitized = sanitizeHtml(svg, svgSanitizeOptions)
+
+ await writeFile(destination, sanitized, 'utf-8')
+}
+
export async function processImage (options: {
path: string
destination: string
diff --git a/server/core/lib/upload-image.ts b/server/core/lib/upload-image.ts
index c316912840..c424a9b3dc 100644
--- a/server/core/lib/upload-image.ts
+++ b/server/core/lib/upload-image.ts
@@ -1,8 +1,8 @@
import { LogoType, UploadImageType, UploadImageType_Type } from '@peertube/peertube-models'
import { buildUUID, getLowercaseExtension } from '@peertube/peertube-node-utils'
-import { buildImageSize, processImage } from '@server/helpers/image-utils.js'
+import { buildImageSize, processImage, processSVG } from '@server/helpers/image-utils.js'
import { UploadImageModel } from '@server/models/application/upload-image.js'
-import { copy, remove } from 'fs-extra/esm'
+import { remove } from 'fs-extra/esm'
import { retryTransactionWrapper } from '../helpers/database-utils.js'
import { UPLOAD_IMAGES_SIZE } from '../initializers/constants.js'
import { sequelizeTypescript } from '../initializers/database.js'
@@ -50,7 +50,7 @@ async function generateImageSizes (imagePath: string, type: UploadImageType_Type
const imageName = buildUUID() + extension
const destination = UploadImageModel.getFSPathOf(imageName)
- await copy(imagePath, destination)
+ await processSVG({ path: imagePath, destination })
return [ { imageName, imageSize: { width: null, height: null } } ]
}