fix(editor): sanitize user-imported SVGs before DOM insertion

SvgEditorRoute.loadSVG inserted dropped SVG files with no stripping;
pathology-editor stripped descendants but missed the root element's
on* attributes and javascript: hrefs. Both now remove script/
foreignObject nodes, on* handlers (root included) and javascript:
hrefs before appendChild. Impact bounded (no auth/backend), MEDIUM.
This commit is contained in:
Bastien Chanot committed 2026-07-12 03:32:50 +02:00
1 parent 18865def06
commit 3f91a45660
2 files changed
+21 -3

No files matched your search

+5 -2
View File
@@ -1125,9 +1125,12 @@
clearChildren(canvasInner);
var imported = document.importNode(svg, true);
imported.querySelectorAll('script, foreignObject').forEach(function (e) { e.remove(); });
imported.querySelectorAll('*').forEach(function (e) {
[imported].concat(Array.prototype.slice.call(imported.querySelectorAll('*'))).forEach(function (e) {
for (var i = e.attributes.length - 1; i >= 0; i--) {
if (e.attributes[i].name.match(/^on/i)) e.removeAttribute(e.attributes[i].name);
var a = e.attributes[i];
var isHandler = a.name.match(/^on/i);
var isJsHref = a.name.match(/href$/i) && a.value.match(/^\s*javascript:/i);
if (isHandler || isJsHref) e.removeAttribute(a.name);
}
});
canvasInner.appendChild(imported);
+16 -1
View File
@@ -495,6 +495,19 @@ function initSvgEditor(
}, sig)
}
/** Strip active content from an untrusted SVG: scripts, foreignObject,
* event-handler attributes (root included) and javascript: hrefs. */
function sanitizeSvg(root: Element) {
root.querySelectorAll('script, foreignObject').forEach((el) => el.remove())
for (const el of [root, ...root.querySelectorAll('*')]) {
for (const attr of [...el.attributes]) {
const isHandler = /^on/i.test(attr.name)
const isJsHref = /href$/i.test(attr.name) && /^\s*javascript:/i.test(attr.value)
if (isHandler || isJsHref) el.removeAttribute(attr.name)
}
}
}
function loadSVG(svgText: string) {
const parser = new DOMParser()
const doc = parser.parseFromString(svgText, 'image/svg+xml')
@@ -505,8 +518,10 @@ function initSvgEditor(
return
}
const imported = document.importNode(parsedSvg, true)
sanitizeSvg(imported)
canvasInner.textContent = ''
canvasInner.appendChild(document.importNode(parsedSvg, true))
canvasInner.appendChild(imported)
svgRoot = canvasInner.querySelector('svg')
if (!svgRoot) {
alert(t('svg_editor.alert_invalid_svg'))