Files
Kelx/utils/svg-sanitizer.js
2026-11-30 16:32:37 +00:00

690 lines
24 KiB
JavaScript

/**
* utils/svg-sanitizer.js
*
* Enterprise-grade SVG Sanitizer and Security Validator.
* Designed according to OWASP SVG Security Guidelines & Defense-in-Depth principles.
*
* Architecture: PARSE -> VALIDATE -> REBUILD.
*
* The document is parsed with a vetted XML parser (@xmldom/xmldom, XML mode,
* strict error collection) instead of being filtered in place. Every node of
* the resulting DOM is checked against a whitelist and the output is then
* RE-SERIALIZED from validated names, values and text — the emitted bytes are
* generated, never echoed input. This closes the whole class of regex
* tokenizer bypasses (comment splitting, attribute-boundary confusion,
* mangled/markup smuggling, CDATA tricks): any input the parser cannot parse
* as well-formed XML is rejected outright, and any construct that survives
* parsing is re-emitted with attacker-controlled bytes escaped or dropped.
*
* Threat Vectors Neutralized:
* 1. Stored XSS via <script>, <foreignObject>, <iframe>, <embed>, <object>, etc.
* (dangerous tags are removed together with their entire subtree).
* 2. Stored XSS via inline DOM & SMIL event handlers (onload, onclick,
* onmouseover, onbegin, etc.) — on local name as well as prefixed name.
* 3. Pseudo-protocol attacks (javascript:, vbscript:, data:text/html) in
* href/xlink:href/src/style — checked against parser-decoded values, and
* re-checked after a second decode pass to defeat double encoding.
* 4. XXE (XML External Entity) attacks (<!DOCTYPE ... SYSTEM ...>, <!ENTITY ...>).
* 5. Denial-of-Service / XML bombs (Billion Laughs / quadratic entity expansion),
* plus node-count and nesting-depth caps on the rebuilt document.
* 6. External resource injection via <use href="http://..."> — <use> and
* friends are restricted to local "#fragment" references; <image> to safe
* raster data URIs or relative paths.
* 7. CSS injection via @import, expression(), -moz-binding, behavior:, or
* style-content breakouts (style text is XML-escaped on output, so no
* `</style>` sequence from CSS can ever terminate the element early).
* 8. Namespace confusion — xmlns declarations are re-emitted by the rebuild
* itself; xml:base (relative-URI rebasing) is stripped.
*
* Serving contract (defense-in-depth, enforced in index.js): SVG responses
* must be served as image/svg+xml with `Content-Security-Policy: default-src
* 'none'; sandbox` and `X-Content-Type-Options: nosniff`. A response-header
* guard wraps res.setHeader so EVERY serving path — current or future — gets
* those headers by construction.
*/
"use strict";
const MAX_SVG_SIZE_BYTES = 5 * 1024 * 1024; // 5MB maximum for brand logo
// DoS bounds for the rebuilt document. A brand logo never comes close; a
// pathological input (hundreds of thousands of elements, or nesting deeper
// than these caps) is rejected instead of grinding the rebuild.
const MAX_ELEMENT_COUNT = 50000;
const MAX_TREE_DEPTH = 128;
// Strict whitelist of safe graphical SVG elements.
// Active elements (script, foreignObject, animate, set, iframe, audio, video, etc.) are strictly excluded.
const ALLOWED_TAGS = new Set([
"svg",
"g",
"path",
"rect",
"circle",
"ellipse",
"line",
"polyline",
"polygon",
"text",
"tspan",
"textpath",
"defs",
"lineargradient",
"radialgradient",
"stop",
"mask",
"clippath",
"pattern",
"symbol",
"use",
"image",
"style",
"title",
"desc",
"filter",
"feblend",
"fecolormatrix",
"fecomponenttransfer",
"fecomposite",
"feconvolvematrix",
"fediffuselighting",
"fedisplacementmap",
"fedistantlight",
"feflood",
"fefunca",
"fefuncb",
"fefuncg",
"fefuncr",
"fegaussianblur",
"femerge",
"femergenode",
"femorphology",
"feoffset",
"fepointlight",
"fespecularlighting",
"fespotlight",
"fetile",
"feturbulence"
]);
// Tags whose entire subtree (content + children) must be discarded if encountered
const DANGEROUS_BLOCK_TAGS = new Set([
"script",
"foreignobject",
"iframe",
"frame",
"frameset",
"object",
"embed",
"applet",
"animate",
"set",
"animatetransform",
"animatemotion",
"animatecolor",
"handler",
"listener",
"audio",
"video",
"source",
"track",
"canvas",
"form",
"input",
"button",
"select",
"textarea",
"option",
"meta",
"link",
"base",
"template"
]);
// Standard allowed namespaces
const ALLOWED_NAMESPACES = new Set([
"http://www.w3.org/2000/svg",
"http://www.w3.org/1999/xlink",
"http://www.w3.org/2000/xmlns/",
"http://www.w3.org/XML/1998/namespace"
]);
const SVG_NAMESPACE = "http://www.w3.org/2000/svg";
const XLINK_NAMESPACE = "http://www.w3.org/1999/xlink";
/**
* Decodes HTML/XML entities in attribute values to prevent encoding-based filter evasion.
* Handles hex (&#x6a;), decimal (&#106;), and common named entities (&quot;, &amp;, &apos;, &lt;, &gt;).
*
* The XML parser already decodes well-formed references once; this second pass
* is deliberate defense-in-depth for double-encoded payloads such as
* `&amp;#x6a;avascript:` and mirrors the pre-parser behavior for consumers of
* the raw rules.
*/
function decodeEntities(str) {
if (!str || typeof str !== "string") return "";
return str
.replace(/&#x([0-9a-fA-F]+);?/g, (_, hex) => {
try { return String.fromCharCode(parseInt(hex, 16)); } catch { return ""; }
})
.replace(/&#([0-9]+);?/g, (_, dec) => {
try { return String.fromCharCode(parseInt(dec, 10)); } catch { return ""; }
})
.replace(/&quot;/gi, '"')
.replace(/&apos;/gi, "'")
.replace(/&amp;/gi, "&")
.replace(/&lt;/gi, "<")
.replace(/&gt;/gi, ">");
}
/**
* Normalizes CSS text and removes dangerous directives:
* - @import
* - expression(...)
* - -moz-binding
* - behavior:
* - url(javascript:...)
* - url(data:text/html...)
*/
function sanitizeCss(cssText) {
if (!cssText || typeof cssText !== "string") return "";
let cleaned = cssText;
// Remove CDATA markers if present
cleaned = cleaned.replace(/<!\[CDATA\[|\]\]>/g, "");
// Remove CSS comments to prevent comment-splitting evasion
cleaned = cleaned.replace(/\/\*[\s\S]*?\*\//g, "");
// Remove @import statements completely
cleaned = cleaned.replace(/@import\s+[^;]+;?/gi, "");
// Remove expression() (IE dynamic CSS execution)
cleaned = cleaned.replace(/expression\s*\([^)]*\)/gi, "none");
// Remove -moz-binding (XBL script execution)
cleaned = cleaned.replace(/-moz-binding\s*:[^;]+;?/gi, "");
// Remove behavior: url(...) (HTC script execution)
cleaned = cleaned.replace(/behavior\s*:[^;]+;?/gi, "");
// Check all url(...) declarations: only allow safe data images or relative paths, never javascript: or data:text/html
cleaned = cleaned.replace(/url\s*\(\s*(['"]?)(.*?)\1\s*\)/gi, (match, quote, url) => {
const decodedUrl = decodeEntities(url).replace(/[\s\t\r\n]+/g, "").toLowerCase();
if (
decodedUrl.startsWith("javascript:") ||
decodedUrl.startsWith("vbscript:") ||
decodedUrl.startsWith("data:text") ||
decodedUrl.startsWith("data:application") ||
decodedUrl.includes("<") ||
decodedUrl.includes(">")
) {
return "none";
}
return match;
});
return cleaned;
}
/**
* Validates and sanitizes a single attribute.
* Returns { keep: boolean, name: string, value: string }
*
* The emitted name preserves the source attribute's case (SVG attribute
* names are case-sensitive: lowercasing turned viewBox into viewbox and
* preserveAspectRatio into preserveaspectratio, which browsers then ignore,
* mis-scaling every sanitized logo). Comparisons and danger checks run on
* the lowercased name; prefixed names (xlink:/xml:) are emitted lowercase so
* the rebuilt document only ever references the two prefixes the rebuild
* itself declares.
*/
function sanitizeAttribute(elementName, attrName, attrValue) {
const rawName = String(attrName || "");
const lowerName = rawName.toLowerCase();
const rawValue = String(attrValue || "");
// Attribute names are re-emitted, so pin them to a strict shape before
// anything else can quote or punctuate its way into the output.
if (!/^[a-zA-Z0-9_\-:.]+$/.test(lowerName)) {
return { keep: false };
}
// Emit lowercase for prefixed attributes (their prefix must match the
// declaration the rebuild emits), original case otherwise.
const emittedName = rawName.includes(":") ? lowerName : rawName;
// Strip ANY event handler attribute: /^[oO][nN]/
// Examples: onload, onclick, onmouseover, onfocus, onbegin, onend, onerror, onactivate, etc.
// Checked on the full (possibly prefixed) name and its local part, so
// prefixed variants cannot smuggle an event handler past a prefix check.
if (/^on[a-z0-9_\-]/i.test(lowerName) || /(^|:|_)on[a-z0-9_\-]/i.test(lowerName)) {
return { keep: false };
}
// xml:base rebases relative URI resolution — never needed by a brand logo
// and dangerous next to the relative-path allowances below.
if (lowerName === "xml:base") {
return { keep: false };
}
// Decode entities and collapse whitespace to inspect true URI content
const decodedValue = decodeEntities(rawValue).replace(/[\u0000-\u001F\u007F-\u009F\s\t\r\n]+/g, "").toLowerCase();
// Strip dangerous pseudo-protocols anywhere in attribute values
if (
decodedValue.startsWith("javascript:") ||
decodedValue.startsWith("vbscript:") ||
decodedValue.startsWith("data:text/html") ||
decodedValue.startsWith("data:application/") ||
decodedValue.includes("javascript:") ||
decodedValue.includes("vbscript:")
) {
return { keep: false };
}
// Check href and xlink:href
if (lowerName === "href" || lowerName === "xlink:href") {
if (elementName === "use") {
// <use> is strictly limited to local symbol/element fragment references (e.g., "#logo-icon")
// External URLs like href="http://evil.com/payload.svg#x" are rejected to prevent SSRF and leakage
if (!/^\s*#[a-zA-Z0-9_\-:\.]+\s*$/.test(rawValue)) {
return { keep: false };
}
} else if (elementName === "image") {
// <image> permits safe raster data URIs or safe relative paths, never external or active URLs
const trimmed = rawValue.trim();
const isSafeRasterDataUri = /^data:image\/(png|jpeg|jpg|webp|gif|avif);base64,[a-zA-Z0-9+/=]+$/i.test(trimmed);
const isSafeRelative = !trimmed.includes(":") && !trimmed.startsWith("//") && !trimmed.includes("..");
if (!isSafeRasterDataUri && !isSafeRelative) {
return { keep: false };
}
} else if (elementName === "textpath" || elementName === "clippath" || elementName === "mask" || elementName === "pattern") {
// Only local references allowed
if (!/^\s*#[a-zA-Z0-9_\-:\.]+\s*$/.test(rawValue)) {
return { keep: false };
}
} else {
// href on any other element is disallowed in brand logos
return { keep: false };
}
}
// Validate xmlns namespaces
if (lowerName.startsWith("xmlns")) {
const nsVal = rawValue.trim();
if (nsVal && !ALLOWED_NAMESPACES.has(nsVal)) {
// If namespace is not standard SVG/XLink (e.g. XHTML namespace), drop it
return { keep: false };
}
}
// Sanitize inline style attribute
if (lowerName === "style") {
const cleanStyle = sanitizeCss(rawValue);
return { keep: true, name: emittedName, value: cleanStyle };
}
return { keep: true, name: emittedName, value: rawValue };
}
/**
* Escapes XML attribute values.
*/
function escapeXmlAttr(value) {
return String(value)
.replace(/&/g, "&amp;")
.replace(/"/g, "&quot;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;");
}
/**
* Escapes XML character data (text and style content). Escaping style content
* is correct as well as safe: an XML parser decodes `&lt;`/`&gt;` back to
* `<`/`>` before the CSS engine sees them, while a literal `</style>` can
* never appear in the output to terminate the element early.
*/
function escapeXmlText(value) {
return String(value)
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;");
}
// The parser is lazy-required and created per call (its onError collector is
// per-parse). If the dependency is missing, every SVG is REJECTED with an
// actionable error — the panel still boots and serves, and there is no regex
// fallback that would silently reopen the mangled-input bypass class.
function parseSvgDocument(svgText) {
let DOMParser;
try {
({ DOMParser } = require("@xmldom/xmldom"));
} catch (err) {
return { fatal: "SVG sanitizer dependency @xmldom/xmldom is not installed — run `npm install` and retry" };
}
const parseErrors = [];
const parser = new DOMParser({
onError: (severity, message) => {
parseErrors.push(`${severity}: ${message}`);
},
});
let doc;
try {
doc = parser.parseFromString(svgText, "image/svg+xml");
} catch (err) {
const message = String(err && err.message || "");
if (/NamespaceError|prefix/i.test(message)) {
return { fatal: "Malformed SVG: undeclared namespace prefix" };
}
return { fatal: "Malformed SVG: not well-formed XML" };
}
// Strict well-formedness: ANY parser diagnostic (including recoverable
// warnings and undefined-entity errors) rejects the document. Clean SVG
// logos from design tools are well-formed XML; mangled input is exactly the
// shape a sanitizer bypass attempt takes, so nothing is "recovered".
if (parseErrors.length > 0) {
return { fatal: "Malformed SVG: XML parse errors detected" };
}
const root = doc && doc.documentElement;
if (!root) {
return { fatal: "Invalid SVG: missing root <svg> tag" };
}
return { root };
}
const XLINK_NS_DECL = ' xmlns:xlink="http://www.w3.org/1999/xlink"';
// Real-world SVGs frequently use the xlink: prefix without declaring
// xmlns:xlink (HTML-context parsing is lenient about it; strict XML — and
// therefore the parser — is not). Before parsing, add the missing declaration
// to the root opening tag. This is namespace REPAIR, not sanitization: the
// injected string is a compile-time constant, so no untrusted bytes are
// involved, and a misplaced insertion can only make a document fail the
// subsequent strict parse, never pass it.
function ensureXlinkDeclaration(svgText) {
if (/xmlns:xlink\s*=/i.test(svgText)) return svgText;
if (!/\sxlink:[a-zA-Z0-9_\-]+\s*=/.test(svgText)) return svgText;
const rootMatch = /<(?:[a-zA-Z0-9_.\-]+:)?svg(?=[\s/>])/i.exec(svgText);
if (!rootMatch) return svgText;
// Quote-aware scan for the end of the root opening tag (a raw indexOf('>')
// could land inside an attribute value).
let inQuote = null;
for (let i = rootMatch.index; i < svgText.length; i++) {
const ch = svgText[i];
if (inQuote) {
if (ch === inQuote) inQuote = null;
continue;
}
if (ch === '"' || ch === "'") {
inQuote = ch;
continue;
}
if (ch === ">") {
const insertAt = svgText[i - 1] === "/" ? i - 1 : i;
return svgText.slice(0, insertAt) + XLINK_NS_DECL + svgText.slice(insertAt);
}
}
return svgText;
}
// Qualified names ("svg:use", "xlink:href") are reduced to their local part,
// lowercased — matching how the SVG elements are ultimately interpreted.
function localPart(qualifiedName) {
const name = String(qualifiedName || "");
return (name.includes(":") ? name.slice(name.lastIndexOf(":") + 1) : name).toLowerCase();
}
/**
* The rebuild walker. Emits sanitized XML for the validated subtree; the
* output is constructed exclusively from whitelisted names and escaped values,
* never from raw input slices.
*/
function rebuildNode(node, depth, state) {
if (depth > MAX_TREE_DEPTH) {
throw new Error("SVG nesting too deep");
}
const nodeType = node.nodeType;
// Text and CDATA sections both become escaped character data.
if (nodeType === 3 || nodeType === 4) {
state.textNodes += 1;
if (state.textNodes > MAX_ELEMENT_COUNT) throw new Error("SVG too complex");
return escapeXmlText(node.nodeValue || "");
}
// Comments, processing instructions, the doctype and anything else
// non-element are simply not carried over.
if (nodeType !== 1) {
return "";
}
const tag = localPart(node.nodeName);
state.elementCount += 1;
if (state.elementCount > MAX_ELEMENT_COUNT) throw new Error("SVG too complex");
// Dangerous active content: drop the tag AND its entire subtree.
if (DANGEROUS_BLOCK_TAGS.has(tag)) {
return "";
}
// Unknown element: drop the tag but keep its (individually validated)
// children — same permissive-but-validated behavior for benign wrappers.
if (!ALLOWED_TAGS.has(tag)) {
return rebuildChildren(node, depth, state);
}
if (tag === "style") {
// Only character data is meaningful inside <style>; rebuild it from the
// concatenated text, scrubbed, then XML-escaped on output (see
// escapeXmlText) so the emitted markup cannot be broken out of.
let cssText = "";
for (const child of Array.from(node.childNodes || [])) {
if (child.nodeType === 3 || child.nodeType === 4) {
cssText += String(child.nodeValue || "");
}
}
return `<style>${escapeXmlText(sanitizeCss(cssText))}</style>`;
}
// Parse and sanitize attributes through the whitelist rules.
const cleanAttrs = [];
for (const attr of Array.from(node.attributes || [])) {
const rawName = String(attr.nodeName || "");
// Namespace declarations ARE exposed as attributes by the parser; the
// rebuild owns namespace emission (SVG namespace below, XLink when the
// pre-scan saw a kept xlink attribute), so declarations are never echoed.
if (/^xmlns(:|$)/i.test(rawName)) {
continue;
}
// Prefixed attributes are only re-emitted for the prefixes this module
// controls: `xlink` (declared on the root, see preScanXlink) and `xml`
// (implicitly bound in XML). Design-tool metadata attributes in unknown
// namespaces (Inkscape/CorelDraw's `serif:*`, `sodipodi:*`, ...) are
// dropped — their declaration is never carried over, and emitting them
// would produce output that is not well-formed XML.
if (rawName.includes(":")) {
const prefix = rawName.slice(0, rawName.indexOf(":")).toLowerCase();
if (prefix !== "xlink" && prefix !== "xml") {
continue;
}
}
const sanitized = sanitizeAttribute(tag, rawName, attr.value);
if (sanitized && sanitized.keep) {
cleanAttrs.push(`${sanitized.name}="${escapeXmlAttr(sanitized.value)}"`);
}
}
// Re-emit the SVG namespace on every <svg> element (which also repairs
// roots that arrived without one), and the XLink namespace when the
// pre-scan found a kept xlink attribute — the output must be well-formed
// XML with every prefix it uses declared.
if (tag === "svg") {
cleanAttrs.push(`xmlns="${SVG_NAMESPACE}"`);
if (state.usesXlink) {
cleanAttrs.push(`xmlns:xlink="${XLINK_NAMESPACE}"`);
}
}
const attrStr = cleanAttrs.length > 0 ? " " + cleanAttrs.join(" ") : "";
const isSelfClosing = !node.childNodes || node.childNodes.length === 0;
if (isSelfClosing) {
return `<${tag}${attrStr}/>`;
}
return `<${tag}${attrStr}>${rebuildChildren(node, depth, state)}</${tag}>`;
}
function rebuildChildren(node, depth, state) {
let out = "";
for (const child of Array.from(node.childNodes || [])) {
out += rebuildNode(child, depth + 1, state);
}
return out;
}
// Runs before the rebuild because the root element is serialized before its
// children are walked: whether xmlns:xlink must be declared on the root is
// only knowable from a full pass over every element's attributes.
function preScanXlink(root) {
const stack = [root];
while (stack.length > 0) {
const node = stack.pop();
if (!node || node.nodeType !== 1) continue;
for (const attr of Array.from(node.attributes || [])) {
if (String(attr.nodeName || "").toLowerCase().startsWith("xlink:")) {
return true;
}
}
for (const child of Array.from(node.childNodes || [])) {
stack.push(child);
}
}
return false;
}
/**
* Main SVG Sanitizer function.
*
* @param {Buffer|string} input - Raw SVG buffer or string
* @returns {{ valid: boolean, sanitized?: Buffer, error?: string }}
*/
function sanitizeSvg(input) {
if (!input) {
return { valid: false, error: "Empty SVG input" };
}
let svgText = "";
if (Buffer.isBuffer(input)) {
if (input.length < 8) {
return { valid: false, error: "SVG file too small" };
}
if (input.length > MAX_SVG_SIZE_BYTES) {
return { valid: false, error: `SVG exceeds maximum size (${MAX_SVG_SIZE_BYTES / 1024 / 1024}MB)` };
}
svgText = input.toString("utf8");
} else if (typeof input === "string") {
if (input.length > MAX_SVG_SIZE_BYTES) {
return { valid: false, error: `SVG exceeds maximum size (${MAX_SVG_SIZE_BYTES / 1024 / 1024}MB)` };
}
svgText = input;
} else {
return { valid: false, error: "Invalid SVG input type" };
}
// 1. Check for null bytes (used in truncation and filter evasion attacks)
if (svgText.includes("\0")) {
return { valid: false, error: "Malformed SVG: illegal null bytes detected" };
}
// 2. Reject XML entity declarations and DOCTYPE completely (Anti-XXE & Anti-Billion-Laughs).
// Clean SVG logos never need DTDs or entity expansions. Rejecting them
// upfront means the parser's entity handling is never even exercised.
if (/<!ENTITY/i.test(svgText)) {
return { valid: false, error: "Security violation: XML entity declarations (XXE) are strictly prohibited" };
}
if (/<!DOCTYPE/i.test(svgText)) {
return { valid: false, error: "Security violation: DOCTYPE declarations are strictly prohibited" };
}
// 3. Parse with the vetted XML parser under strict well-formedness.
const parsed = parseSvgDocument(ensureXlinkDeclaration(svgText));
if (parsed.fatal) {
return { valid: false, error: parsed.fatal };
}
// 4. The root element must be <svg> (any prefix, case-insensitive).
if (localPart(parsed.root.nodeName) !== "svg") {
return { valid: false, error: "Invalid SVG: missing root <svg> tag" };
}
// 5. Rebuild the document from the validated DOM.
let output;
try {
output = rebuildNode(parsed.root, 0, {
elementCount: 0,
textNodes: 0,
usesXlink: preScanXlink(parsed.root),
});
} catch (err) {
return { valid: false, error: `Invalid SVG: ${err.message}` };
}
output = output.trim();
if (!/^<svg[\s>]/i.test(output)) {
return { valid: false, error: "Invalid SVG: no valid <svg> root element found after sanitization" };
}
// 6. Final validation pass on the GENERATED output. Every check here should
// be unreachable by construction; a hit means a rebuild bug — fail closed.
if (
/<script[\s>]/i.test(output) ||
/<foreignobject[\s>]/i.test(output) ||
/<iframe[\s>]/i.test(output) ||
/<animate[\s>]/i.test(output) ||
/<set[\s>]/i.test(output) ||
/<!doctype/i.test(output) ||
/<\?/.test(output) ||
/<!\[cdata\[/i.test(output) ||
/\son[a-z0-9_\-]+\s*=/i.test(output) ||
/javascript\s*:/i.test(output)
) {
return { valid: false, error: "Sanitization failure: prohibited tokens detected in final output" };
}
const cleanBuffer = Buffer.from(output, "utf8");
return { valid: true, sanitized: cleanBuffer };
}
/**
* Validates an SVG Buffer and returns { valid: boolean, data?: Buffer, error?: string }
*/
function validateSvgBuffer(buffer) {
if (!Buffer.isBuffer(buffer)) {
return { valid: false, error: "Invalid buffer provided" };
}
const result = sanitizeSvg(buffer);
if (!result.valid) {
return { valid: false, error: result.error || "Invalid or malicious SVG content" };
}
return { valid: true, data: result.sanitized };
}
module.exports = {
sanitizeSvg,
validateSvgBuffer,
ALLOWED_TAGS,
DANGEROUS_BLOCK_TAGS
};