diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 4b3a34f5..9fc2f6d2 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -64,9 +64,9 @@ "problemMatcher": [] }, { - "label": "Check: CSP Scripts", + "label": "Check: CSP", "type": "process", - "command": "checks/check-csp-scripts.py", + "command": "checks/check-csp.py", "args": [ "public" ], @@ -82,7 +82,7 @@ "Lint: Shell", "Lint: Shell Format", "Check: URL Parity", - "Check: CSP Scripts" + "Check: CSP" ], "problemMatcher": [] } diff --git a/CONTENT.md b/CONTENT.md index 1db8eb19..5e043e0f 100644 --- a/CONTENT.md +++ b/CONTENT.md @@ -192,7 +192,7 @@ This is the reason this file exists, so it is worth stating plainly. | --- | --- | | `hugo --gc --minify --panicOnWarning` | yes, it must build | | [`checks/check-url-parity.py`][parity] | yes, for URLs, asset references, and the orphan count | -| [`checks/check-csp-scripts.py`][csp-scripts] | yes, for a script, inline handler, `javascript:` URL, frame, media file, or object a post's raw HTML adds | +| [`checks/check-csp.py`][csp] | yes, for an inline handler or `javascript:` URL a post's raw HTML adds, and for a script, image, stylesheet, font, frame, media file, or object it loads from another host | | `checks/check-live-urls.sh` | yes, against a running server | | markdownlint | no, `content/.markdownlint-cli2.jsonc` ignores the tree | | CSpell | no, `cspell.json` ignores the tree | @@ -211,7 +211,7 @@ A fact in a published post that proves wrong is corrected in the post. It is not [checks]: ./checks/ [codestyle]: ./CODESTYLE.md -[csp-scripts]: ./checks/check-csp-scripts.py +[csp]: ./checks/check-csp.py [operations]: ./OPERATIONS.md [metadata]: ./checks/check-media-metadata.py [normalize]: ./scripts/normalize-media.py diff --git a/README.md b/README.md index 682ca5e9..2ddb3066 100644 --- a/README.md +++ b/README.md @@ -189,12 +189,12 @@ For a defect in the site or the tooling, such as a broken link, a missing redire The required tools and their install commands are listed in [deploy/README.md][deploy-readme]. Hugo must be the extended build. -Build the site and verify it against the URL contract and the blog's Content-Security-Policy: +Build the site and verify it against the URL contract and both sites' Content-Security-Policies: ```sh hugo --gc --minify --panicOnWarning checks/check-url-parity.py public -checks/check-csp-scripts.py public +checks/check-csp.py public ``` Build a release and verify it against a running server: diff --git a/checks/README.md b/checks/README.md index 0dcd0663..1546482b 100644 --- a/checks/README.md +++ b/checks/README.md @@ -7,7 +7,7 @@ This README covers the URL contract alone. The other checks in this directory ea | Check | Fails when | | --- | --- | | [`check-csp-browser.py`][check-csp-browser] | a page on a running mirror makes the browser block something that `csp-browser-allow.txt` does not list | -| [`check-csp-scripts.py`][check-csp-scripts] | the scripts, frames, media, or objects the built site loads and the blog's policy disagree | +| [`check-csp.py`][check-csp] | a page or stylesheet on either site fetches something its site's policy does not allow, or a policy names another host | | [`check-env-docs.py`][check-env-docs] | a configuration value is declared without a description in `ENVIRONMENT.md`, or described there and declared nowhere | | [`check-github-env.py`][check-github-env] | the variables and secrets GitHub holds differ from the ones `ENVIRONMENT.md` lists | | [`check-media-metadata.py`][check-media-metadata] | carried media is not in a form the gate can vouch for | @@ -190,7 +190,7 @@ Three traps in that adjudication, each of which produced a wrong answer first an [caddy-dockerfile]: ./caddy/Dockerfile [capture-readme]: ../capture/README.md [check-csp-browser]: ./check-csp-browser.py -[check-csp-scripts]: ./check-csp-scripts.py +[check-csp]: ./check-csp.py [check-env-docs]: ./check-env-docs.py [check-github-env]: ./check-github-env.py [check-live-urls]: ./check-live-urls.sh diff --git a/checks/check-csp-browser.py b/checks/check-csp-browser.py index cc3fb038..6af97fae 100755 --- a/checks/check-csp-browser.py +++ b/checks/check-csp-browser.py @@ -1,8 +1,9 @@ #!/usr/bin/env python3 """Load a running site in headless Chromium and report what its Content-Security-Policy blocks. -`check-csp-scripts.py` proves the built scripts match the policy's hashes. It cannot see what a -browser blocks at run time: a style, a font, a fetch, an image, or a script a proxy injects. This +`check-csp.py` proves the built scripts match the policy's hashes and that every fetch the pages +and stylesheets name is one the policy allows. It cannot see what a browser blocks at run time: a +fetch a script makes, or a script a proxy injects. This check loads each page in a URL list against a mirror. It records every `securitypolicyviolation` event in the page and in each frame it holds, as it fires. The event fires for an enforcing policy and a Report-Only one alike. Each page is scrolled to its end so lazy images load, and its diff --git a/checks/check-csp-scripts.py b/checks/check-csp-scripts.py deleted file mode 100755 index f83261db..00000000 --- a/checks/check-csp-scripts.py +++ /dev/null @@ -1,239 +0,0 @@ -#!/usr/bin/env python3 -"""Verify that the blog's Content-Security-Policy allows every script and embed the built site loads. - -The policy is read from `checks/security-headers.txt`, and `deploy/Caddyfile`, which ships, must -send the same value. Without `script-src` the browser applies `default-src`, and so does this -check. Every inline script must carry a hash the policy lists. Every hash the policy lists -must match an inline script. A Hugo or theme update that changes a script's bytes then fails -here rather than in a reader's browser. A script loaded by URL must come from a host or a -scheme the policy names. An inline event handler or a `javascript:` URL fails outright, since a hash allows -neither without `'unsafe-hashes'`, which the blog policy does not carry. A script whose type the -browser runs is checked, an import map and a speculation rules block included. Any other type is -a data block that never runs, and the browser never checks an empty script, so neither needs a -hash. - -A frame, a media file, or an object loads under its own directive. A post may carry raw HTML, -so it can add one from a host the policy does not name. Each such load must come from a host or a -scheme its directive names. The browser's fallbacks apply: `child-src` then `default-src` for a -frame, and `default-src` for the others. An `about:` URL fetches nothing, so no directive applies. -""" - -import argparse -import base64 -import collections -import hashlib -import pathlib -import sys -from html.parser import HTMLParser -from urllib.parse import urlsplit - -CHECKS = pathlib.Path(__file__).resolve().parent -HEADERS = CHECKS / "security-headers.txt" -CADDYFILE = CHECKS.parent / "deploy" / "Caddyfile" -CSP = "Content-Security-Policy" - -SCRIPT_TYPES = { - "", - "module", - "importmap", - "speculationrules", - "application/ecmascript", - "application/javascript", - "application/x-ecmascript", - "application/x-javascript", - "text/ecmascript", - "text/javascript", - *(f"text/javascript1.{minor}" for minor in range(6)), - "text/jscript", - "text/livescript", - "text/x-ecmascript", - "text/x-javascript", -} - - -def blog_policy(headers_text): - """The blog's policy as security-headers.txt holds it, or None where the blog sends none.""" - for line in headers_text.splitlines(): - site, _, header = line.partition("\t") - name, _, value = header.partition(": ") - if site == "blog" and name == CSP: - return value - return None - - -FALLBACKS = { - "script-src": ("script-src", "default-src"), - "frame-src": ("frame-src", "child-src", "default-src"), - "media-src": ("media-src", "default-src"), - "object-src": ("object-src", "default-src"), -} - -EMBEDS = { - ("iframe", "src"): "frame-src", - ("frame", "src"): "frame-src", - ("audio", "src"): "media-src", - ("video", "src"): "media-src", - ("source", "src"): "media-src", - ("track", "src"): "media-src", - ("embed", "src"): "object-src", - ("object", "data"): "object-src", -} - - -def directive_sources(policy, directive): - """The sources the browser applies to a directive, its fallbacks included.""" - directives = {} - for part in policy.split(";"): - tokens = part.split() - if tokens: - directives.setdefault(tokens[0], tokens[1:]) - for name in FALLBACKS[directive]: - if name in directives: - return directives[name] - return [] - - -def script_sources(policy): - return directive_sources(policy, "script-src") - - -def digest(body): - return ( - "'sha256-" - + base64.b64encode(hashlib.sha256(body.encode()).digest()).decode() - + "'" - ) - - -class ScriptScan(HTMLParser): - def __init__(self): - super().__init__(convert_charrefs=False) - self.inline = [] - self.loaded = [] - self.embeds = [] - self.findings = [] - self.body = None - - def handle_starttag(self, tag, attrs): - for name, value in attrs: - url = (value or "").strip() - if name.startswith("on"): - self.findings.append(f"<{tag} {name}> is an inline event handler") - elif name in ("href", "src", "action") and url.lower().startswith( - "javascript:" - ): - self.findings.append(f"<{tag} {name}> is a javascript: URL") - elif (tag, name) in EMBEDS and url and not url.lower().startswith("about:"): - self.embeds.append((tag, name, url, EMBEDS[tag, name])) - if tag != "script": - return - attr = dict(attrs) - if (attr.get("type") or "").strip().lower() not in SCRIPT_TYPES: - return - if "src" not in attr: - self.body = [] - return - src = attr["src"] or "" - if not src.strip().lower().startswith("javascript:"): - self.loaded.append(src) - - def handle_data(self, data): - if self.body is not None: - self.body.append(data) - - def handle_endtag(self, tag): - if tag == "script" and self.body is not None: - self.inline.append("".join(self.body)) - self.body = None - - -def allowed(src, sources): - parts = urlsplit(src if not src.startswith("//") else "https:" + src) - if parts.netloc: - return f"{parts.scheme}://{parts.netloc}" in sources - if parts.scheme: - return f"{parts.scheme}:" in sources - return "'self'" in sources - - -def check(public, policy): - sources = script_sources(policy) - embed_sources = { - name: directive_sources(policy, name) for name in set(EMBEDS.values()) - } - used = collections.defaultdict(list) - findings = [] - for path in sorted(public.rglob("*.html")): - rel = path.relative_to(public).as_posix() - scan = ScriptScan() - scan.feed(path.read_text(encoding="utf-8")) - scan.close() - findings += [f"{rel}: {finding}" for finding in scan.findings] - findings += [ - f"{rel}: " +ORIGIN = "https://site.example.test" +OTHER = "https://cdn.example.test" def policy(*sources): @@ -33,7 +33,7 @@ def run_gate(self, pages, sources, csp=None): path.parent.mkdir(parents=True, exist_ok=True) path.write_text(html, encoding="utf-8") with contextlib.redirect_stdout(io.StringIO()): - return gate.check(public, csp or policy(*sources)) + return gate.check(public, csp or policy(*sources), ORIGIN) def test_a_listed_hash_for_every_inline_script_passes(self) -> None: sources = ["'self'", gate.digest(THEME)] @@ -95,8 +95,12 @@ def test_a_script_url_needs_its_origin_named(self) -> None: findings = self.run_gate({"index.html": html}, ["'self'"]) self.assertEqual(len(findings), 1) self.assertIn("does not name", findings[0]) - named = ["'self'", "https://cdn.example.test"] - self.assertEqual(self.run_gate({"index.html": other}, named), []) + named = ["'self'", OTHER] + findings = self.run_gate({"index.html": other}, named) + self.assertEqual( + findings, + [f"the policy names {OTHER} under script-src, which allows another host"], + ) def test_a_valueless_src_body_is_not_hashed(self) -> None: html = f"" @@ -149,15 +153,14 @@ def test_an_embed_from_the_site_itself_passes_under_default_src(self) -> None: html = '' self.assertEqual(self.run_gate({"index.html": html}, ["'self'"]), []) - def test_a_named_host_passes_and_the_fallback_order_holds(self) -> None: - html = '' - host = "https://maps.example.test" + def test_the_fallback_order_holds(self) -> None: + html = '' for csp, findings in ( - (f"default-src 'self'; frame-src {host}", 0), - (f"default-src 'self'; child-src {host}", 0), - (f"default-src {host}", 0), - (f"default-src {host}; frame-src 'self'", 1), - (f"default-src {host}; child-src 'self'", 1), + ("default-src 'self'; frame-src data:", 0), + ("default-src 'self'; child-src data:", 0), + ("default-src data:", 0), + ("default-src data:; frame-src 'self'", 1), + ("default-src data:; child-src 'self'", 1), ): with self.subTest(csp): found = self.run_gate({"index.html": html}, [], csp) @@ -183,9 +186,90 @@ def test_a_javascript_embed_is_reported_once(self) -> None: self.assertEqual(len(findings), 1) self.assertIn("javascript: URL", findings[0]) + def test_every_fetch_from_another_host_fails_under_its_directive(self) -> None: + for html, directive in ( + (f'', "img-src"), + (f'', "img-src"), + (f'', "img-src"), + (f'', "img-src"), + (f'', "img-src"), + (f'', "style-src"), + (f'', "img-src"), + (f'', "font-src"), + (f'', "default-src"), + (f'', "script-src"), + (f'', "manifest-src"), + (f'', "default-src"), + ('', "default-src"), + (f'

x

', "img-src"), + (f"", "style-src"), + (f'', "style-src"), + ( + f'', + "connect-src", + ), + ): + with self.subTest(html): + findings = self.run_gate({"index.html": html}, []) + self.assertEqual(len(findings), 1, findings) + self.assertIn(f"{directive} does not name", findings[0]) + + def test_a_link_that_loads_nothing_is_not_checked(self) -> None: + html = ( + f'' + f'' + '' + ) + self.assertEqual(self.run_gate({"index.html": html}, []), []) + + def test_the_site_itself_passes_by_path_and_by_its_own_origin(self) -> None: + html = ( + '' + f'' + '' + ) + self.assertEqual(self.run_gate({"index.html": html}, []), []) + elsewhere = html.replace(ORIGIN, ORIGIN + ":8443") + self.assertEqual(len(self.run_gate({"index.html": elsewhere}, [])), 1) + + def test_a_stylesheet_is_read_by_where_each_url_sits(self) -> None: + css = ( + "/* url(https://comment.example.test/a.png) */" + f'@import url("{OTHER}/a.css");' + f"@font-face {{ font-family: A; src: url('{OTHER}/a.woff2') format('woff2'); }}" + f"body {{ background: url({OTHER}/b.png), url(#grain); }}" + ) + findings = self.run_gate({"assets/site.css": css}, []) + self.assertEqual( + [f.split(" does not name")[0].rsplit(" ", 1)[1] for f in findings], + ["style-src", "font-src", "img-src"], + ) + self.assertTrue(all(f.startswith("assets/site.css: url(") for f in findings)) + + def test_a_listed_scheme_passes_in_a_stylesheet(self) -> None: + css = "html { background: url(\"data:image/svg+xml,%3Csvg filter='url(%23n)'/%3E\"); }" + csp = "default-src 'self'; img-src 'self' data:" + self.assertEqual(self.run_gate({"site.css": css}, [], csp), []) + self.assertEqual(len(self.run_gate({"site.css": css}, [])), 1) + + def test_a_style_block_and_a_font_face_in_it_are_read(self) -> None: + html = f"" + findings = self.run_gate({"index.html": html}, []) + self.assertEqual(len(findings), 1) + self.assertIn("