-
Notifications
You must be signed in to change notification settings - Fork 12
Prevent potential malicious code injection by whitelisting head html insertion #3937
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
jurgenwerk
wants to merge
4
commits into
main
Choose a base branch
from
cs-9876-consider-xss-vulnerability-of-head-insertion-implementation
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.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
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
Some comments aren't visible on the classic Files Changed page.
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,139 @@ | ||
| const ALLOWED_HEAD_TAGS = new Set(['meta', 'title', 'link']); | ||
| const ALLOWED_META_ATTRS = new Set(['name', 'property', 'content']); | ||
| const ALLOWED_TITLE_ATTRS = new Set<string>([]); | ||
| const ALLOWED_LINK_ATTRS = new Set([ | ||
| 'rel', | ||
| 'href', | ||
| 'type', | ||
| 'sizes', | ||
| 'media', | ||
| 'crossorigin', | ||
| 'integrity', | ||
| 'referrerpolicy', | ||
| 'fetchpriority', | ||
| ]); | ||
| const SAFE_LINK_REL_TOKENS = new Set([ | ||
| 'canonical', | ||
| 'icon', | ||
| 'shortcut', | ||
| 'apple-touch-icon', | ||
| 'mask-icon', | ||
| 'manifest', | ||
| ]); | ||
|
|
||
| export function sanitizeHeadHTML( | ||
| headHTML: string, | ||
| doc: Document, | ||
| ): DocumentFragment | null { | ||
| if (typeof headHTML !== 'string') { | ||
| return null; | ||
| } | ||
|
|
||
| let template = doc.createElement('template'); | ||
| template.innerHTML = headHTML; | ||
|
|
||
| let fragment = doc.createDocumentFragment(); | ||
| for (let node of Array.from(template.content.childNodes)) { | ||
| let sanitized = sanitizeHeadNode(node, doc); | ||
| if (sanitized) { | ||
| fragment.appendChild(sanitized); | ||
| } | ||
| } | ||
|
|
||
| return fragment.childNodes.length > 0 ? fragment : null; | ||
| } | ||
|
|
||
| // Reject any non-element nodes (text nodes, comments, document fragments, etc.) | ||
| // so that only explicit, allowlisted <head> elements are inserted | ||
| function sanitizeHeadNode(node: Node, doc: Document): Node | null { | ||
| if (node.nodeType !== Node.ELEMENT_NODE) { | ||
| return null; | ||
| } | ||
|
|
||
| let element = node as Element; | ||
| let tagName = element.tagName.toLowerCase(); | ||
| if (!ALLOWED_HEAD_TAGS.has(tagName)) { | ||
| return null; | ||
| } | ||
|
|
||
| switch (tagName) { | ||
| case 'meta': | ||
| return sanitizeMetaElement(element, doc); | ||
| case 'title': | ||
| return sanitizeTitleElement(element, doc); | ||
| case 'link': | ||
| return sanitizeLinkElement(element, doc); | ||
| } | ||
|
|
||
| return null; | ||
| } | ||
|
|
||
| function sanitizeMetaElement(element: Element, doc: Document): HTMLMetaElement { | ||
| let meta = doc.createElement('meta'); | ||
| copyAllowedAttributes(element, meta, ALLOWED_META_ATTRS); | ||
| return meta; | ||
| } | ||
|
|
||
| function sanitizeTitleElement( | ||
| element: Element, | ||
| doc: Document, | ||
| ): HTMLTitleElement { | ||
| let title = doc.createElement('title'); | ||
| copyAllowedAttributes(element, title, ALLOWED_TITLE_ATTRS); | ||
| title.textContent = element.textContent ?? ''; | ||
| return title; | ||
| } | ||
|
|
||
| function sanitizeLinkElement( | ||
| element: Element, | ||
| doc: Document, | ||
| ): HTMLLinkElement | null { | ||
| let relValue = element.getAttribute('rel') ?? ''; | ||
| if (!isSafeLinkRel(relValue)) { | ||
| return null; | ||
| } | ||
|
|
||
| let href = element.getAttribute('href'); | ||
| if (href && !isSafeLinkHref(href, doc)) { | ||
| return null; | ||
| } | ||
|
|
||
| let link = doc.createElement('link'); | ||
| copyAllowedAttributes(element, link, ALLOWED_LINK_ATTRS); | ||
| return link; | ||
| } | ||
|
|
||
| function isSafeLinkRel(relValue: string): boolean { | ||
| let tokens = relValue.toLowerCase().split(/\s+/).filter(Boolean); | ||
| if (tokens.length === 0) { | ||
| return false; | ||
| } | ||
| return tokens.every((token) => SAFE_LINK_REL_TOKENS.has(token)); | ||
| } | ||
|
|
||
| function isSafeLinkHref(href: string, doc: Document): boolean { | ||
| let trimmed = href.trim(); | ||
| if (!trimmed) { | ||
| return false; | ||
| } | ||
|
|
||
| try { | ||
| let url = new URL(trimmed, doc.baseURI ?? window.location.origin); | ||
| return url.protocol === 'http:' || url.protocol === 'https:'; | ||
| } catch { | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| function copyAllowedAttributes( | ||
| source: Element, | ||
| target: Element, | ||
| allowed: Set<string>, | ||
| ) { | ||
| for (let attribute of Array.from(source.attributes)) { | ||
| let name = attribute.name.toLowerCase(); | ||
| if (allowed.has(name)) { | ||
| target.setAttribute(attribute.name, attribute.value); | ||
| } | ||
| } | ||
| } | ||
jurgenwerk marked this conversation as resolved.
Show resolved
Hide resolved
|
||
159 changes: 159 additions & 0 deletions
159
packages/host/tests/unit/utils/sanitize-head-html-test.ts
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,159 @@ | ||
| import { module, test } from 'qunit'; | ||
|
|
||
| import { sanitizeHeadHTML } from '@cardstack/host/utils/sanitize-head-html'; | ||
|
|
||
| module('Unit | Utils | sanitizeHeadHTML', function () { | ||
| test('filters head markup to allowed elements and attributes', function (assert) { | ||
| let input = ` | ||
| <title data-test-title="ok" onclick="alert(1)">Hello</title> | ||
| <meta name="description" content="desc" charset="utf-8" onload="bad"> | ||
| <meta property="og:title" content="OG Title"> | ||
| <link rel="canonical" href="https://example.com" onclick="bad" data-test-link="ok"> | ||
| <link rel="preload" href="https://example.com/app.js" as="script"> | ||
| <link rel="icon" href="javascript:alert(1)"> | ||
| <script>alert(1)</script> | ||
| <style>.x{}</style> | ||
| <div>nope</div> | ||
| `; | ||
|
|
||
| let fragment = sanitizeHeadHTML(input, document); | ||
| assert.ok(fragment, 'returns a fragment when allowed elements exist'); | ||
|
|
||
| let container = document.createElement('div'); | ||
| if (fragment) { | ||
| container.appendChild(fragment); | ||
| } | ||
|
|
||
| let elements = Array.from(container.children); | ||
| assert.strictEqual(elements.length, 4, 'only allowed elements remain'); | ||
|
|
||
| let title = container.querySelector('title'); | ||
| assert.ok(title, 'title is preserved'); | ||
| assert.strictEqual(title?.textContent, 'Hello'); | ||
| assert.false( | ||
| Boolean(title?.hasAttribute('data-test-title')), | ||
| 'data attributes are removed', | ||
| ); | ||
| assert.false( | ||
| Boolean(title?.hasAttribute('onclick')), | ||
| 'event handler attributes are removed', | ||
| ); | ||
|
|
||
| let meta = container.querySelector('meta[name="description"]'); | ||
| assert.ok(meta, 'meta element is preserved'); | ||
| assert.strictEqual(meta?.getAttribute('content'), 'desc'); | ||
| assert.false( | ||
| Boolean(meta?.hasAttribute('charset')), | ||
| 'disallowed meta attributes are removed', | ||
| ); | ||
| assert.false( | ||
| Boolean(meta?.hasAttribute('onload')), | ||
| 'disallowed meta attributes are removed', | ||
| ); | ||
jurgenwerk marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| let ogMeta = container.querySelector('meta[property="og:title"]'); | ||
| assert.ok(ogMeta, 'meta property is preserved'); | ||
| assert.strictEqual(ogMeta?.getAttribute('content'), 'OG Title'); | ||
|
|
||
| let link = container.querySelector('link[rel="canonical"]'); | ||
| assert.ok(link, 'safe link rel is preserved'); | ||
| assert.strictEqual(link?.getAttribute('href'), 'https://example.com'); | ||
| assert.false( | ||
| Boolean(link?.hasAttribute('data-test-link')), | ||
| 'data attributes are removed', | ||
| ); | ||
| assert.false( | ||
| Boolean(link?.hasAttribute('onclick')), | ||
| 'disallowed link attributes are removed', | ||
| ); | ||
| assert.strictEqual( | ||
| container.querySelector('link[rel="preload"]'), | ||
| null, | ||
| 'unsafe link rel is removed', | ||
| ); | ||
| assert.strictEqual( | ||
| container.querySelector('link[rel="icon"]'), | ||
| null, | ||
| 'unsafe link href is removed', | ||
| ); | ||
| assert.strictEqual( | ||
| container.querySelector('script'), | ||
| null, | ||
| 'script tags are removed', | ||
| ); | ||
| assert.strictEqual( | ||
| container.querySelector('style'), | ||
| null, | ||
| 'style tags are removed', | ||
| ); | ||
| assert.strictEqual( | ||
| container.querySelector('div'), | ||
| null, | ||
| 'disallowed tags are removed', | ||
| ); | ||
| }); | ||
|
|
||
| test('returns null when no allowed head elements remain', function (assert) { | ||
| let fragment = sanitizeHeadHTML('<script>alert(1)</script>', document); | ||
| assert.strictEqual(fragment, null); | ||
| }); | ||
|
|
||
| test('ignores text nodes, comments, and whitespace-only input', function (assert) { | ||
| let fragment = sanitizeHeadHTML( | ||
| ' \n<!-- comment --><title>Ok</title>\nText node\n', | ||
| document, | ||
| ); | ||
| assert.ok(fragment, 'fragment is returned when allowed elements exist'); | ||
|
|
||
| let container = document.createElement('div'); | ||
| if (fragment) { | ||
| container.appendChild(fragment); | ||
| } | ||
|
|
||
| assert.strictEqual( | ||
| container.querySelectorAll('title').length, | ||
| 1, | ||
| 'title element preserved', | ||
| ); | ||
| assert.strictEqual( | ||
| container.childNodes.length, | ||
| 1, | ||
| 'non-element nodes are filtered out', | ||
| ); | ||
|
|
||
| let empty = sanitizeHeadHTML(' \n\t', document); | ||
| assert.strictEqual(empty, null, 'whitespace-only input returns null'); | ||
| }); | ||
|
|
||
| test('preserves multiple title tags and filters nested disallowed elements', function (assert) { | ||
| let fragment = sanitizeHeadHTML( | ||
| '<title>First</title><title>Second</title><div><meta name="a" content="b"></div>', | ||
| document, | ||
| ); | ||
| assert.ok(fragment, 'fragment is returned when allowed elements exist'); | ||
|
|
||
| let container = document.createElement('div'); | ||
| if (fragment) { | ||
| container.appendChild(fragment); | ||
| } | ||
|
|
||
| assert.strictEqual( | ||
| container.querySelectorAll('title').length, | ||
| 2, | ||
| 'multiple title tags are preserved', | ||
| ); | ||
| assert.strictEqual( | ||
| container.querySelectorAll('meta').length, | ||
| 0, | ||
| 'nested disallowed elements are removed', | ||
| ); | ||
| }); | ||
|
|
||
| test('drops encoded javascript in link hrefs', function (assert) { | ||
| let fragment = sanitizeHeadHTML( | ||
| '<link rel="icon" href="javascript:alert(1)">', | ||
| document, | ||
| ); | ||
| assert.strictEqual(fragment, null, 'encoded javascript href is rejected'); | ||
| }); | ||
| }); | ||
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.
Uh oh!
There was an error while loading. Please reload this page.