-
Notifications
You must be signed in to change notification settings - Fork 335
fix(message): render received external SVG images #13142
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
Open
joeldj-nl
wants to merge
8
commits into
nextcloud:main
Choose a base branch
from
joeldj-nl:fix/render-received-svg-images
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+519
−4
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
ccb4252
fix(message): render received external SVG images
joeldj-nl f9279d6
fix(proxy): close SVG sanitizer security gaps
joeldj-nl 23b68c9
Merge branch 'main' into fix/render-received-svg-images
joeldj-nl 80a7a9e
fix(proxy): handle blocked image read failures
joeldj-nl 3bef3c7
Merge branch 'fix/render-received-svg-images' of https://github.com/j…
joeldj-nl a47fda5
fixup! fix(message): render received external SVG images
joeldj-nl 431b9bf
fixup! fix(message): render received external SVG images
joeldj-nl c637d51
fixup! fix(proxy): close SVG sanitizer security gaps
joeldj-nl File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,163 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| /* | ||
| * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors | ||
| * SPDX-License-Identifier: AGPL-3.0-or-later | ||
| */ | ||
|
|
||
| namespace OCA\Mail\Service; | ||
|
|
||
| use DOMAttr; | ||
| use DOMDocument; | ||
| use DOMElement; | ||
| use DOMXPath; | ||
|
|
||
| /** | ||
| * Removes active content from SVG markup before it is embedded into or sent | ||
| * with a message. SVGs are rendered in an <img>/CID context where scripts do | ||
| * not execute, but they are still sanitised as defence in depth: any document | ||
| * that cannot be parsed safely is dropped entirely. | ||
| */ | ||
| class SvgSanitizer { | ||
| /** Elements that can carry or execute active content. */ | ||
| private const FORBIDDEN_ELEMENTS = [ | ||
| 'script', | ||
| 'foreignObject', | ||
| 'handler', | ||
| 'listener', | ||
| 'set', | ||
| ]; | ||
|
joeldj-nl marked this conversation as resolved.
|
||
|
|
||
| /** Attributes that carry URL references and must not point off-document. */ | ||
| private const URL_ATTRIBUTES = ['href', 'xlink:href', 'src', 'action', 'formaction']; | ||
|
|
||
| /** Reject payloads larger than this to prevent DoS via oversized documents. */ | ||
| private const MAX_SVG_BYTES = 2 * 1024 * 1024; | ||
|
|
||
| /** | ||
| * @param string $svg The raw (decoded) SVG markup | ||
| * @return string The sanitised markup, or an empty string if it cannot be | ||
| * parsed safely | ||
| */ | ||
| public function sanitize(string $svg): string { | ||
| if (trim($svg) === '' || strlen($svg) > self::MAX_SVG_BYTES) { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please take a look at nextcloud/server#62162 and check if we have those cases covered. |
||
| return ''; | ||
| } | ||
|
|
||
| // A DOCTYPE or entity declaration is not needed for plain SVG graphics | ||
| // and is a common XXE / entity-expansion vector. Reject such documents. | ||
| if (preg_match('/<!DOCTYPE|<!ENTITY/i', $svg) === 1) { | ||
| return ''; | ||
| } | ||
|
|
||
| // An XSL/Transform namespace signals a client-side transformation | ||
| // stylesheet that can execute JavaScript in some browsers. Reject the | ||
| // document outright, matching server-side hardening in nextcloud/server. | ||
| if (str_contains($svg, 'http://www.w3.org/1999/XSL/Transform')) { | ||
| return ''; | ||
| } | ||
|
|
||
| $dom = new DOMDocument(); | ||
| $previousErrors = libxml_use_internal_errors(true); | ||
| // LIBXML_NONET forbids any network access while parsing. | ||
| $loaded = $dom->loadXML($svg, LIBXML_NONET); | ||
|
joeldj-nl marked this conversation as resolved.
|
||
| libxml_clear_errors(); | ||
| libxml_use_internal_errors($previousErrors); | ||
|
|
||
| if (!$loaded || $dom->documentElement === null) { | ||
| return ''; | ||
| } | ||
|
|
||
| $xpath = new DOMXPath($dom); | ||
|
|
||
| // Remove processing instructions (e.g. <?xml-stylesheet type="text/xsl"?>). | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The |
||
| // Document-level PIs are already excluded by saveXML($dom->documentElement), | ||
| // but PIs nested inside the root element are handled here. | ||
| $pis = $xpath->query('//processing-instruction()'); | ||
| if ($pis !== false) { | ||
| foreach (iterator_to_array($pis) as $pi) { | ||
| $pi->parentNode?->removeChild($pi); | ||
| } | ||
| } | ||
|
|
||
| // Remove dangerous elements. Matching on the local name catches them | ||
| // regardless of any namespace prefix (e.g. <x:script>). | ||
| foreach (self::FORBIDDEN_ELEMENTS as $tag) { | ||
| $nodes = $xpath->query('//*[local-name() = "' . $tag . '"]'); | ||
| if ($nodes !== false) { | ||
| foreach (iterator_to_array($nodes) as $node) { | ||
| $node->parentNode?->removeChild($node); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Sanitise <style> element content: strip external CSS url() references. | ||
| $styleNodes = $xpath->query('//*[local-name() = "style"]'); | ||
| if ($styleNodes !== false) { | ||
| foreach ($styleNodes as $node) { | ||
| $node->textContent = $this->stripCssUrls($node->textContent); | ||
| } | ||
| } | ||
|
|
||
| $elements = $xpath->query('//*'); | ||
| if ($elements !== false) { | ||
| foreach ($elements as $element) { | ||
| if ($element instanceof DOMElement) { | ||
| $this->stripDangerousAttributes($element); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| $result = $dom->saveXML($dom->documentElement); | ||
| return $result === false ? '' : $result; | ||
| } | ||
|
|
||
| /** | ||
| * Heuristically decide whether the given bytes are an SVG document. | ||
| */ | ||
| public function looksLikeSvg(string $content): bool { | ||
| $start = ltrim($content); | ||
| if (str_starts_with($start, "\xEF\xBB\xBF")) { | ||
| $start = ltrim(substr($start, 3)); | ||
| } | ||
| $hasSvgPrologue = str_starts_with($start, '<?xml') | ||
| || stripos($start, '<svg') === 0; | ||
| return $hasSvgPrologue && stripos($content, '<svg') !== false; | ||
| } | ||
|
|
||
| private function stripDangerousAttributes(DOMElement $element): void { | ||
| /** @var DOMAttr $attribute */ | ||
| foreach (iterator_to_array($element->attributes) as $attribute) { | ||
| $name = strtolower($attribute->nodeName); | ||
| $value = trim($attribute->nodeValue ?? ''); | ||
|
|
||
| // Inline event handlers (onload, onclick, …). | ||
| if (str_starts_with($name, 'on')) { | ||
| $element->removeAttributeNode($attribute); | ||
| continue; | ||
| } | ||
|
|
||
| // Only allow same-document references; strip javascript:, external | ||
| // and data: URLs from links and resource references. | ||
| if (in_array($name, self::URL_ATTRIBUTES, true) && !str_starts_with($value, '#')) { | ||
| $element->removeAttributeNode($attribute); | ||
| continue; | ||
| } | ||
|
|
||
| // Strip external CSS url() references from inline style attributes. | ||
| if ($name === 'style') { | ||
| $element->setAttribute('style', $this->stripCssUrls($value)); | ||
| } | ||
| } | ||
| } | ||
|
joeldj-nl marked this conversation as resolved.
|
||
|
|
||
| /** | ||
| * Replace CSS url() references that point outside the document with 'none'. | ||
| * Fragment references (url(#…)) are preserved for gradients and masks. | ||
| */ | ||
| private function stripCssUrls(string $css): string { | ||
| return preg_replace('/url\s*\((?!\s*[\'"]?#)[^)]*\)/i', 'none', $css) ?? $css; | ||
| } | ||
|
Comment on lines
+160
to
+162
|
||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
$content is only a resource with a call like
$client->get($src, ['stream' => true]). The actual return for the current request is string.Please drop is_resource fallback.
To make static code analysis happy add: