Skip to content

Commit

Permalink
Fix an XSS in Server Islands. (#11508)
Browse files Browse the repository at this point in the history
* Fix an XSS in Server Islands.

Discussed with @FredKSchott that this is OK to disclose since Server Islands are still experimental.

It's generally not safe to use `JSON.stringify` to interpolate potentially attacker controlled data into `<script>` tags as JSON doesn't escape `<>"'` and so one can use it to break out of the script tag and e.g. make a new one with controlled content.

See https://pragmaticwebsecurity.com/articles/spasecurity/json-stringify-xss

* Format

* Create smart-snakes-promise.md

* Switch to manual encoding

---------

Co-authored-by: Matt Kane <[email protected]>
  • Loading branch information
cramforce and ascorbic authored Jul 19, 2024
1 parent 026e8ba commit ca335e1
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
5 changes: 5 additions & 0 deletions .changeset/smart-snakes-promise.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"astro": patch
---

Escapes HTML in serialized props
17 changes: 13 additions & 4 deletions packages/astro/src/runtime/server/render/server-islands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,15 @@ export function containsServerDirective(props: Record<string | number, any>) {
return 'server:component-directive' in props;
}

function safeJsonStringify(obj: any) {
return JSON.stringify(obj)
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029')
.replace(/</g, '\\u003c')
.replace(/>/g, '\\u003e')
.replace(/\//g, '\\u002f');
}

export function renderServerIsland(
result: SSRResult,
_displayName: string,
Expand Down Expand Up @@ -53,13 +62,13 @@ export function renderServerIsland(
const hostId = crypto.randomUUID();

destination.write(`<script async type="module" data-island-id="${hostId}">
let componentId = ${JSON.stringify(componentId)};
let componentExport = ${JSON.stringify(componentExport)};
let componentId = ${safeJsonStringify(componentId)};
let componentExport = ${safeJsonStringify(componentExport)};
let script = document.querySelector('script[data-island-id="${hostId}"]');
let data = {
componentExport,
props: ${JSON.stringify(props)},
slots: ${JSON.stringify(renderedSlots)},
props: ${safeJsonStringify(props)},
slots: ${safeJsonStringify(renderedSlots)},
};
let response = await fetch('/_server-islands/${componentId}', {
Expand Down

0 comments on commit ca335e1

Please sign in to comment.