Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

svgs: sanitization #5342

Merged
merged 1 commit into from
Jan 26, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
25 changes: 24 additions & 1 deletion src/components/svg/SvgImage.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,24 @@
justifyContent: 'center',
});

const sanitizeSVG = svgContent => {
// Regular expression to find all event handler attributes
const eventHandlerRegex = /\son\w+="[^"]*"/gi;

// Regular expression to remove script tags
const scriptTagRegex = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi;
Dismissed Show dismissed Hide dismissed

// Regular expression to sanitize href and xlink:href attributes
const hrefRegex = /(href|xlink:href)="javascript:[^"]*"/gi;

// Remove the event handlers, script tags, and sanitize hrefs
let sanitizedContent = svgContent.replace(eventHandlerRegex, '');
Dismissed Show dismissed Hide dismissed
sanitizedContent = sanitizedContent.replace(scriptTagRegex, '');
Dismissed Show dismissed Hide dismissed
sanitizedContent = sanitizedContent.replace(hrefRegex, '');

return sanitizedContent;
};

const getHTML = (svgContent, style) =>
`
<html data-key="key-${style.height}-${style.width}">
Expand All @@ -22,9 +40,12 @@
window.alert = () => false;
window.prompt = () => false;
window.confirm = () => false;
window.open = () => {return null};
}
overLoadFunctions();
window.onload = overLoadFunctions();
document.addEventListener('DOMContentLoaded', overLoadFunctions);

</script>
<style>
html, body {
Expand Down Expand Up @@ -129,7 +150,9 @@
if (svgContent) {
const flattenedStyle = StyleSheet.flatten(props.style) || {};
if (svgContent.includes('viewBox')) {
html = getHTML(svgContent, flattenedStyle);
// Sanitize SVG content
const sanitizedContent = sanitizeSVG(svgContent);
html = getHTML(sanitizedContent, flattenedStyle);
} else {
const svgRegex = RegExp('(<svg)([^<]*|[^>]*)');
const svg = svgRegex.exec(svgContent)[0];
Expand Down