fix: sanitize <script> in __FRSH_STATE state (#739)

This commit escapes `<` `>` and related characters in the serialized state that is encoded into the `<script id=__FRSH_STATE>` tag. This prevents XSS attack occuring through injection of a `</script>` string in island props.
This commit is contained in:
OkadaGenya
2022-09-12 17:33:02 +02:00
committed by GitHub
parent b75509526d
commit 9d13f6ff26
7 changed files with 142 additions and 37 deletions
+15
View File
@@ -0,0 +1,15 @@
// This utility is based on https://github.com/zertosh/htmlescape
// License: https://github.com/zertosh/htmlescape/blob/0527ca7156a524d256101bb310a9f970f63078ad/LICENSE
const ESCAPE_LOOKUP: { [match: string]: string } = {
">": "\\u003e",
"<": "\\u003c",
"\u2028": "\\u2028",
"\u2029": "\\u2029",
};
const ESCAPE_REGEX = /[><\u2028\u2029]/g;
export function htmlEscapeJsonString(str: string): string {
return str.replace(ESCAPE_REGEX, (match) => ESCAPE_LOOKUP[match]);
}
+18
View File
@@ -0,0 +1,18 @@
import { htmlEscapeJsonString } from "./htmlescape.ts";
import { assertEquals } from "../../tests/deps.ts";
Deno.test("with angle brackets should escape", () => {
const evilObj = { evil: "<script></script>" };
assertEquals(
htmlEscapeJsonString(JSON.stringify(evilObj)),
'{"evil":"\\u003cscript\\u003e\\u003c/script\\u003e"}',
);
});
Deno.test("with angle brackets should parse back", () => {
const evilObj = { evil: "<script></script>" };
assertEquals(
JSON.parse(htmlEscapeJsonString(JSON.stringify(evilObj))),
evilObj,
);
});
+2 -1
View File
@@ -17,6 +17,7 @@ import { CSP_CONTEXT, nonce, NONE, UNSAFE_INLINE } from "../runtime/csp.ts";
import { ContentSecurityPolicy } from "../runtime/csp.ts";
import { bundleAssetUrl } from "./constants.ts";
import { assetHashingHook } from "../runtime/utils.ts";
import { htmlEscapeJsonString } from "./htmlescape.ts";
export interface RenderOptions<Data> {
route: Route<Data> | UnknownPage | ErrorPage;
@@ -276,7 +277,7 @@ export async function render<Data>(
if (state[0].length > 0 || state[1].length > 0) {
// Append state to the body
bodyHtml += `<script id="__FRSH_STATE" type="application/json">${
JSON.stringify(state)
htmlEscapeJsonString(JSON.stringify(state))
}</script>`;
// Append the inline script to the body