-
Notifications
You must be signed in to change notification settings - Fork 13
Sanitise project instructions before rendering them #1615
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
jamiebenstead
wants to merge
2
commits into
main
Choose a base branch
from
1738-sanitise-instructions-to-prevent-xss
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 1 commit
Commits
Show all changes
2 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
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
11 changes: 7 additions & 4 deletions
11
src/components/Menus/Sidebar/InstructionsPanel/InstructionsStep/InstructionsStep.jsx
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
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,52 @@ | ||
| import DOMPurify from "dompurify"; | ||
|
|
||
| // Some project steps embed the editor's own project viewer to show a worked | ||
| // example. Frames from anywhere else are removed | ||
| const EMBED_ORIGINS = [ | ||
| "https://editor.raspberrypi.org", | ||
| "https://staging-editor.raspberrypi.org", | ||
| ]; | ||
|
|
||
| const isProjectViewer = (src) => { | ||
| try { | ||
| return EMBED_ORIGINS.includes(new URL(src, window.location.href).origin); | ||
| } catch { | ||
| return false; | ||
| } | ||
| }; | ||
|
|
||
| const sanitiseConfig = { | ||
| // `use` draws the icons inside a scratchblocks SVG, such as the green flag | ||
| ADD_TAGS: ["iframe", "use"], | ||
| ADD_ATTR: [ | ||
| "allowfullscreen", | ||
| "frameborder", | ||
| "marginheight", | ||
| "marginwidth", | ||
| "target", | ||
| ], | ||
| }; | ||
|
|
||
| const purifier = DOMPurify(window); | ||
|
|
||
| const remove = (node) => node.parentNode?.removeChild(node); | ||
|
|
||
| purifier.addHook("uponSanitizeElement", (node, { tagName }) => { | ||
| if (tagName === "iframe" && !isProjectViewer(node.getAttribute("src"))) { | ||
| return remove(node); | ||
| } | ||
|
|
||
| // A stylesheet anywhere else would restyle the rest of the editor | ||
| if (tagName === "style" && !node.closest("svg")) { | ||
| return remove(node); | ||
| } | ||
|
|
||
| // Same document references only, so a `use` cannot pull in outside markup | ||
| if (tagName === "use" && !node.getAttribute("href")?.startsWith("#")) { | ||
| return remove(node); | ||
| } | ||
| }); | ||
|
|
||
| const sanitiseInstructions = (html) => purifier.sanitize(html, sanitiseConfig); | ||
|
|
||
| export default sanitiseInstructions; | ||
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,210 @@ | ||
| import { processEditorProject } from "@raspberrypifoundation/rpf-markdown-core"; | ||
| import sanitiseInstructions from "./sanitiseInstructions"; | ||
|
|
||
| const parse = (html) => { | ||
| const container = document.createElement("div"); | ||
| container.innerHTML = sanitiseInstructions(html); | ||
| return container; | ||
| }; | ||
|
|
||
| const eventHandlerAttributes = (container) => | ||
| Array.from(container.querySelectorAll("*")).flatMap((element) => | ||
| Array.from(element.attributes) | ||
| .map((attribute) => attribute.name) | ||
| .filter((name) => name.startsWith("on")), | ||
| ); | ||
|
|
||
| describe("Scriptable payloads", () => { | ||
| const payloads = { | ||
| "script element": "<script>window.hacked = true</script>", | ||
| "script src": '<script src="https://evil.example/x.js"></script>', | ||
| "img onerror": '<img src="x" onerror="window.hacked = true">', | ||
| "svg onload": '<svg onload="window.hacked = true"></svg>', | ||
| "body onload": '<body onload="window.hacked = true">text</body>', | ||
| "details ontoggle": | ||
| '<details open ontoggle="window.hacked = true">x</details>', | ||
| "unknown element with handler": | ||
| '<xss id="x" tabindex="1" onfocus="window.hacked = true"></xss>', | ||
| "javascript href": '<a href="javascript:window.hacked = true">click</a>', | ||
| "javascript href with entities": | ||
| '<a href="javascript:window.hacked = true">click</a>', | ||
| "data url href": | ||
| '<a href="data:text/html;base64,PHNjcmlwdD53aW5kb3cuaGFja2VkPXRydWU8L3NjcmlwdD4=">click</a>', | ||
| "form action": | ||
| '<form action="javascript:window.hacked = true"><button>go</button></form>', | ||
| "formaction button": | ||
| '<button formaction="javascript:window.hacked = true">go</button>', | ||
| "third party iframe": '<iframe src="https://evil.example/x"></iframe>', | ||
| "iframe srcdoc": | ||
| '<iframe srcdoc="<script>window.hacked = true</script>"></iframe>', | ||
| "allowed origin iframe with srcdoc": | ||
| '<iframe src="https://editor.raspberrypi.org/en/embed/viewer/x" srcdoc="<script>window.hacked = true</script>"></iframe>', | ||
| object: '<object data="javascript:window.hacked = true"></object>', | ||
| embed: '<embed src="https://evil.example/x.swf">', | ||
| "meta refresh": | ||
| '<meta http-equiv="refresh" content="0;url=https://evil.example">', | ||
| base: '<base href="https://evil.example/">', | ||
| "link stylesheet": | ||
| '<link rel="stylesheet" href="https://evil.example/x.css">', | ||
| "style element": "<style>.project-instructions { display: none }</style>", | ||
| "style import": "<style>@import url(https://evil.example/x.css)</style>", | ||
| "external svg use": | ||
| '<svg><use href="https://evil.example/x.svg#y" /></svg>', | ||
| template: "<template><script>window.hacked = true</script></template>", | ||
| noscript: | ||
| '<noscript><p title="</noscript><img src=x onerror=window.hacked=true>">', | ||
| "mutation xss": | ||
| '<math><mtext><table><mglyph><style><!--</style><img title="--><textarea onfocus=window.hacked=true autofocus>"></mglyph></table></mtext></math>', | ||
| }; | ||
|
|
||
| test.each(Object.entries(payloads))("%s renders inert", (_name, payload) => { | ||
| const container = parse(payload); | ||
| const html = container.innerHTML; | ||
|
|
||
| expect(container.querySelector("script")).toBeNull(); | ||
| expect(container.querySelector("style")).toBeNull(); | ||
| expect(container.querySelector("iframe[srcdoc]")).toBeNull(); | ||
| expect( | ||
| container.querySelector("object, embed, link, base, meta"), | ||
| ).toBeNull(); | ||
| expect(eventHandlerAttributes(container)).toEqual([]); | ||
| expect(html).not.toMatch(/javascript:/i); | ||
| expect(html).not.toMatch(/data:text\/html/i); | ||
| expect(html).not.toMatch(/evil\.example/i); | ||
| }); | ||
|
|
||
| test("Strips scriptable payloads written as markdown", () => { | ||
| const container = parse( | ||
| processEditorProject( | ||
| "[click](javascript:alert)\n\n<script>window.hacked = true</script>\n", | ||
| ), | ||
| ); | ||
|
|
||
| expect(container.querySelector("script")).toBeNull(); | ||
| expect(container.querySelector("a")).not.toBeNull(); | ||
| expect(container.querySelector('a[href^="javascript:"]')).toBeNull(); | ||
| }); | ||
| }); | ||
|
|
||
| describe("Embedded project viewers", () => { | ||
| const embed = (src) => | ||
| `<iframe src="${src}" width="600" height="600" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>`; | ||
|
|
||
| test.each([ | ||
| "https://editor.raspberrypi.org/en/embed/viewer/editor-mapping-data-step-2", | ||
| "https://staging-editor.raspberrypi.org/embed/viewer/fruit-face-example?show_visual_tab=true", | ||
| ])("Keeps the embed at %s", (src) => { | ||
| const iframe = parse(embed(src)).querySelector("iframe"); | ||
|
|
||
| expect(iframe).not.toBeNull(); | ||
| expect(iframe.getAttribute("src")).toEqual(src); | ||
| expect(iframe.getAttribute("width")).toEqual("600"); | ||
| expect(iframe.getAttribute("allowfullscreen")).not.toBeNull(); | ||
| }); | ||
|
|
||
| test.each([ | ||
| "https://evil.example/x", | ||
| "https://editor.raspberrypi.org.evil.example/x", | ||
| "//evil.example/x", | ||
| "/en/embed/viewer/x", | ||
| ])("Removes the embed at %s", (src) => { | ||
| expect(parse(embed(src)).querySelector("iframe")).toBeNull(); | ||
| }); | ||
| }); | ||
|
|
||
| describe("Project site content", () => { | ||
| test("Keeps callouts, task checkboxes and headings", () => { | ||
| const container = parse( | ||
| '<h2 class="c-project-heading--task" id="step-1">Step 1</h2>' + | ||
| '<div class="c-project-callout c-project-callout--tip" style="font-size: 1.1em">' + | ||
| '<h3 id="tip">Tip</h3></div>' + | ||
| '<div class="c-project-task">' + | ||
| '<input class="c-project-task__checkbox" type="checkbox" aria-label="Mark this task as complete" />' + | ||
| "</div>", | ||
| ); | ||
|
|
||
| expect(container.querySelector("h2.c-project-heading--task").id).toEqual( | ||
| "step-1", | ||
| ); | ||
| expect( | ||
| container.querySelector(".c-project-callout--tip").getAttribute("style"), | ||
| ).toEqual("font-size: 1.1em"); | ||
| expect(container.querySelector("h3#tip")).not.toBeNull(); | ||
| expect( | ||
| container | ||
| .querySelector('input[type="checkbox"]') | ||
| .getAttribute("aria-label"), | ||
| ).toEqual("Mark this task as complete"); | ||
| }); | ||
|
|
||
| test("Keeps the attributes the syntax highlighter relies on", () => { | ||
| const container = parse( | ||
| '<pre dir="ltr" class="line-numbers" data-start="10" data-line-offset="10" data-line="11">' + | ||
| '<code class="language-python" dir="ltr">print('Hello')</code></pre>', | ||
| ); | ||
|
|
||
| const pre = container.querySelector("pre"); | ||
| expect(pre.getAttribute("data-line")).toEqual("11"); | ||
| expect(pre.getAttribute("data-start")).toEqual("10"); | ||
| expect(pre.getAttribute("data-line-offset")).toEqual("10"); | ||
| expect(pre.getAttribute("dir")).toEqual("ltr"); | ||
| expect(container.querySelector("code.language-python").textContent).toEqual( | ||
| "print('Hello')", | ||
| ); | ||
| }); | ||
|
|
||
| test("Keeps images and links", () => { | ||
| const container = parse( | ||
| '<p><img src="https://projects-static.raspberrypi.org/projects/x/images/y.png" alt="A screenshot" width="300" /></p>' + | ||
| '<a href="https://projects.raspberrypi.org/en/projects/x" target="_blank">Link</a>', | ||
| ); | ||
|
|
||
| expect(container.querySelector("img").alt).toEqual("A screenshot"); | ||
| expect(container.querySelector("a").getAttribute("target")).toEqual( | ||
| "_blank", | ||
| ); | ||
| }); | ||
|
|
||
| test("Keeps code samples that contain HTML", () => { | ||
| const container = parse( | ||
| '<pre><code class="language-html"><script>alert(1)</script></code></pre>', | ||
| ); | ||
|
|
||
| expect(container.querySelector("script")).toBeNull(); | ||
| expect(container.querySelector("code").textContent).toEqual( | ||
| "<script>alert(1)</script>", | ||
| ); | ||
| }); | ||
| }); | ||
|
|
||
| describe("Scratch blocks", () => { | ||
| const scratchblocksHtml = processEditorProject( | ||
| "```blocks\nwhen green flag clicked\nsay [Hello] for (2) seconds\n```\n", | ||
| ); | ||
|
|
||
| test("Keeps the rendered SVG, its stylesheet and its icons", () => { | ||
| const container = parse(scratchblocksHtml); | ||
|
|
||
| const svg = container.querySelector("svg"); | ||
| expect(svg).not.toBeNull(); | ||
| expect(svg.querySelector("style")).not.toBeNull(); | ||
| expect(svg.querySelectorAll("use").length).toBeGreaterThan(0); | ||
| expect(svg.querySelector("use").getAttribute("href")).toMatch(/^#/); | ||
| }); | ||
|
|
||
| test("Keeps the block markup the editor renders client side", () => { | ||
| const container = parse( | ||
| '<pre><code class="language-blocks">when green flag clicked</code></pre>', | ||
| ); | ||
|
|
||
| expect(container.querySelector("code.language-blocks").textContent).toEqual( | ||
| "when green flag clicked", | ||
| ); | ||
| }); | ||
| }); | ||
|
|
||
| describe("When there is nothing to sanitise", () => { | ||
| test.each([undefined, null, ""])("Returns an empty string for %s", (html) => { | ||
| expect(sanitiseInstructions(html)).toEqual(""); | ||
| }); | ||
| }); |
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.
Uh oh!
There was an error while loading. Please reload this page.