diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 074b96da..4b3a34f5 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -63,6 +63,16 @@ "dependsOn": "Build: Site", "problemMatcher": [] }, + { + "label": "Check: CSP Scripts", + "type": "process", + "command": "checks/check-csp-scripts.py", + "args": [ + "public" + ], + "dependsOn": "Build: Site", + "problemMatcher": [] + }, { "label": "Clean Compile", "dependsOrder": "sequence", @@ -71,7 +81,8 @@ "Lint: Spelling", "Lint: Shell", "Lint: Shell Format", - "Check: URL Parity" + "Check: URL Parity", + "Check: CSP Scripts" ], "problemMatcher": [] } diff --git a/CONTENT.md b/CONTENT.md index 4ead3e5e..02c4d456 100644 --- a/CONTENT.md +++ b/CONTENT.md @@ -192,6 +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, or `javascript:` URL a post's raw HTML adds | | `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 | @@ -210,6 +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 [operations]: ./OPERATIONS.md [metadata]: ./checks/check-media-metadata.py [normalize]: ./scripts/normalize-media.py diff --git a/README.md b/README.md index d9d34a9b..4e017191 100644 --- a/README.md +++ b/README.md @@ -189,11 +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: +Build the site and verify it against the URL contract and the blog's script policy: ```sh hugo --gc --minify --panicOnWarning checks/check-url-parity.py public +checks/check-csp-scripts.py public ``` Build a release and verify it against a running server: diff --git a/checks/README.md b/checks/README.md index 6560797c..cb3d98ab 100644 --- a/checks/README.md +++ b/checks/README.md @@ -6,6 +6,7 @@ This README covers the URL contract alone. The other checks in this directory ea | Check | Fails when | | --- | --- | +| [`check-csp-scripts.py`][check-csp-scripts] | the scripts the built site runs and the blog's `script-src` disagree | | [`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 | @@ -187,6 +188,7 @@ Three traps in that adjudication, each of which produced a wrong answer first an [capture-build-redirects]: ../capture/build-redirects.py [caddy-dockerfile]: ./caddy/Dockerfile [capture-readme]: ../capture/README.md +[check-csp-scripts]: ./check-csp-scripts.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-scripts.py b/checks/check-csp-scripts.py new file mode 100755 index 00000000..2ecf177d --- /dev/null +++ b/checks/check-csp-scripts.py @@ -0,0 +1,194 @@ +#!/usr/bin/env python3 +"""Verify that the blog's Content-Security-Policy allows every script the built site runs. + +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. +""" + +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 + + +def script_sources(policy): + directives = {} + for directive in policy.split(";"): + tokens = directive.split() + if tokens: + directives.setdefault(tokens[0], tokens[1:]) + return directives.get("script-src", directives.get("default-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.findings = [] + self.body = None + + def handle_starttag(self, tag, attrs): + for name, value in attrs: + if name.startswith("on"): + self.findings.append(f"<{tag} {name}> is an inline event handler") + elif name in ("href", "src", "action") and ( + value or "" + ).strip().lower().startswith("javascript:"): + self.findings.append(f"<{tag} {name}> is a javascript: URL") + 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, sources): + 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}: " + + +def policy(*sources): + return f"default-src 'self'; script-src {' '.join(sources)}; img-src 'self'" + + +class CheckTest(unittest.TestCase): + def run_gate(self, pages, sources): + with tempfile.TemporaryDirectory() as tmp: + public = pathlib.Path(tmp) + for rel, html in pages.items(): + path = public / rel + 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, sources) + + def test_a_listed_hash_for_every_inline_script_passes(self) -> None: + sources = ["'self'", gate.digest(THEME)] + pages = {"index.html": PAGE, "a/index.html": PAGE} + self.assertEqual(self.run_gate(pages, sources), []) + + def test_an_unlisted_inline_script_fails_with_its_hash(self) -> None: + findings = self.run_gate({"index.html": PAGE}, ["'self'"]) + self.assertEqual(len(findings), 1) + self.assertIn(gate.digest(THEME), findings[0]) + self.assertIn("not in script-src", findings[0]) + + def test_a_hash_no_script_matches_fails(self) -> None: + stale = gate.digest("retired()") + sources = ["'self'", gate.digest(THEME), stale] + findings = self.run_gate({"index.html": PAGE}, sources) + self.assertEqual( + findings, [f"script-src lists {stale}, which no inline script matches"] + ) + + def test_a_changed_byte_is_a_different_script(self) -> None: + sources = ["'self'", gate.digest(THEME)] + changed = PAGE.replace(THEME, THEME + ";") + findings = self.run_gate({"index.html": changed}, sources) + self.assertEqual(len(findings), 2) + + def test_the_hash_covers_the_raw_text_without_decoding_references(self) -> None: + body = "if (a && b) {}" + html = f"" + findings = self.run_gate({"index.html": html}, ["'self'", gate.digest(body)]) + self.assertEqual(findings, []) + + def test_data_blocks_and_empty_scripts_are_not_checked(self) -> None: + html = ( + '' + "" + ) + self.assertEqual(self.run_gate({"index.html": html}, ["'self'"]), []) + + def test_every_type_the_browser_runs_is_checked(self) -> None: + for kind in ( + "module", + "importmap", + "speculationrules", + "Application/X-JavaScript", + ): + with self.subTest(kind): + html = f'' + findings = self.run_gate({"index.html": html}, ["'self'"]) + self.assertEqual(len(findings), 1) + + def test_a_script_url_needs_its_origin_named(self) -> None: + own = '' + other = '' + relative = '' + self.assertEqual(self.run_gate({"index.html": own}, ["'self'"]), []) + for html in (other, relative): + with self.subTest(html): + 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), []) + + def test_a_valueless_src_body_is_not_hashed(self) -> None: + html = f"" + self.assertEqual(self.run_gate({"index.html": html}, ["'self'"]), []) + + def test_a_scheme_url_needs_its_scheme_named(self) -> None: + for scheme in ("data", "blob"): + with self.subTest(scheme): + html = f'' + findings = self.run_gate({"index.html": html}, ["'self'"]) + self.assertEqual(len(findings), 1) + self.assertIn("does not name", findings[0]) + named = ["'self'", f"{scheme}:"] + self.assertEqual(self.run_gate({"index.html": html}, named), []) + + def test_handlers_and_javascript_urls_fail(self) -> None: + for html, expected in ( + ('', "inline event handler"), + ('Go', "javascript: URL"), + ('', "javascript: URL"), + ): + with self.subTest(html): + findings = self.run_gate({"index.html": html}, ["'self'"]) + self.assertEqual(len(findings), 1) + self.assertIn(expected, findings[0]) + + +class PolicyTest(unittest.TestCase): + def test_the_blog_policy_is_read(self) -> None: + blog = policy("'self'", "'sha256-AAAA'") + family = policy("'none'") + text = ( + "blog\tReferrer-Policy: no-referrer\n" + f"blog\tContent-Security-Policy: {blog}\n" + f"family\tContent-Security-Policy: {family}\n" + ) + self.assertEqual(gate.blog_policy(text), blog) + + def test_a_blog_without_a_policy_reads_as_none(self) -> None: + family = policy("'self'") + text = f"family\tContent-Security-Policy: {family}\n" + self.assertIsNone(gate.blog_policy(text)) + + def test_script_src_is_read_and_default_src_stands_in_for_it(self) -> None: + sources = gate.script_sources(policy("'self'", "'sha256-AAAA'")) + self.assertEqual(sources, ["'self'", "'sha256-AAAA'"]) + fallback = gate.script_sources("default-src 'self'; img-src 'self'") + self.assertEqual(fallback, ["'self'"]) + self.assertEqual(gate.script_sources("img-src 'self'"), []) + + def load(self, headers, caddyfile): + with tempfile.TemporaryDirectory() as tmp: + root = pathlib.Path(tmp) + (root / "security-headers.txt").write_text(headers, encoding="utf-8") + (root / "Caddyfile").write_text(caddyfile, encoding="utf-8") + return gate.load_policy(root / "security-headers.txt", root / "Caddyfile") + + def test_a_policy_the_caddyfile_sends_loads(self) -> None: + blog = policy("'self'") + sent = f'header {{\n\tContent-Security-Policy "{blog}"\n}}\n' + held = f"blog\tContent-Security-Policy: {blog}\n" + self.assertEqual(self.load(held, sent), (blog, None)) + + def test_a_caddyfile_sending_another_value_refuses(self) -> None: + sent_policy = policy("'self'") + held_policy = policy("'self'", "'sha256-AAAA'") + sent = f'header {{\n\tContent-Security-Policy "{sent_policy}"\n}}\n' + held = f"blog\tContent-Security-Policy: {held_policy}\n" + loaded, refusal = self.load(held, sent) + self.assertIsNone(loaded) + self.assertIn("Caddyfile does not send", refusal or "") + + def test_a_header_file_without_a_blog_policy_refuses(self) -> None: + loaded, refusal = self.load("blog\tReferrer-Policy: no-referrer\n", "") + self.assertIsNone(loaded) + self.assertIn("holds no Content-Security-Policy", refusal or "") + + +if __name__ == "__main__": + unittest.main() diff --git a/deploy/Caddyfile b/deploy/Caddyfile index 9042a3a2..a344c435 100644 --- a/deploy/Caddyfile +++ b/deploy/Caddyfile @@ -37,6 +37,7 @@ Strict-Transport-Security "max-age=31536000" X-Content-Type-Options "nosniff" Referrer-Policy "strict-origin-when-cross-origin" + Content-Security-Policy "default-src 'self'; script-src 'self' 'sha256-5ilQRTfItUB+Etsk1onTDCqBA1OpUBIKfJhdMlZ61Co=' 'sha256-QOwTHff6BrH8cmnR7hf10tIuyQ09hKSkEevZzo+G8WE=' 'sha256-UBD9lfFHKxagKGHh9S8B2hytN1cmDsFK1Tl1uedsZ0Q=' 'sha256-eyUVosQAviXm2qeOTG819D1n0kSst2gY8VmfgVsZlag='; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src https://fonts.gstatic.com; img-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'" } # One map serves four classes because their key spaces are disjoint. diff --git a/deploy/README.md b/deploy/README.md index 5beb4f3a..2bf12835 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -7,7 +7,7 @@ How the site is built, released, and served. The release is a **self-contained b | Tool | Used by | Needed for | Install | | --- | --- | --- | --- | | `hugo` (extended) | `make-release.sh` | building the site | see below | -| `python3` (3.10+) | `check-url-parity.py`, `capture/build-redirects.py` | the build-time gate, regenerating maps | `apt install python3` | +| `python3` (3.10+) | `check-url-parity.py`, `check-csp-scripts.py`, `capture/build-redirects.py` | the build-time gates, regenerating maps | `apt install python3` | | PyYAML | `capture/clean-content.py` | reading front matter during a conversion | `apt install python3-yaml` | | `rsync` | `make-release.sh` | installing a release, hard-linking unchanged files | `apt install rsync` | | `gzip` | `make-release.sh` | precompression | coreutils, already present | @@ -302,7 +302,11 @@ The sites send the same security headers on every response, redirects and the `4 The HSTS value carries neither `includeSubDomains` nor `preload`. `includeSubDomains` would extend the policy to every subdomain of the site's hostname, and this bundle serves none of them. `preload` asks for the whole domain to be built into browsers, where a removal takes months to reach readers. HSTS at the edge is the host side's setting, and it stays off because Cloudflare applies it to every name in the zone. -**Only the family site sends a `Content-Security-Policy`.** Its page loads few resources, so its policy names each kind: its own files, Google Fonts, inline styles, and `data:` images. Blog posts embed third-party content, so a blog policy waits on a survey of what the posts load. +**Each site sends its own `Content-Security-Policy`.** The family page loads few resources, so its policy names each kind: its own files, Google Fonts, inline styles, and `data:` images. The blog policy allows its own files, Google Fonts, and inline styles, which the theme and some archived posts carry. No post loads a script, frame, or object from another host. An embed from another host, such as a video or a map, needs that host in the policy first, or the browser blocks it. Write a script's host as `https://` and a scheme as `data:`, the forms the gate reads. Images load only from the site itself. That blocks the hotlinked images a few archived posts still reference, and each of those is already gone. Its `script-src` lists a hash for each inline script the theme writes, rather than allowing every inline script. + +**A Hugo update, a theme update, or a theme setting in `hugo.yaml` can change those scripts.** [`checks/check-csp-scripts.py`][checks-csp-scripts] runs in the release build and fails when the hashes and the built scripts differ. The fix is to copy each hash it reports into both the Caddyfile and `security-headers.txt`, and to drop each hash it reports as unused. + +**The policy also blocks a script the proxy injects into a page.** Cloudflare's Rocket Loader, Email Address Obfuscation, and Web Analytics each inject one, so each stays off. They are the host side's to set, and the gate cannot see them, since it reads only what Hugo builds. **A change to any of these values changes [`checks/security-headers.txt`][checks-security-headers] with it.** The live check asserts each value exactly, and a unit case fails while the two differ. @@ -429,6 +433,7 @@ Two orderings are load-bearing. `@post_child_feed` precedes `@post_child` becaus Each of these fails silently when it fails, which is why it is checked rather than assumed: - **The URL contract**, via `check-url-parity.py`, before anything is installed. +- **The blog's script hashes**, via `check-csp-scripts.py`, before anything is installed. - **World-readability of the finished release.** `--chmod` and `--no-g` apply only to files rsync newly transfers. A file supplied by `--link-dest` is a hard link to the previous release's inode and keeps that inode's mode and ownership, so a badly moded file rides the @@ -445,6 +450,7 @@ Each of these fails silently when it fails, which is why it is checked rather th [caddyfile]: ./Caddyfile [capture-build-redirects]: ../capture/build-redirects.py [capture-readme]: ../capture/README.md +[checks-csp-scripts]: ../checks/check-csp-scripts.py [checks-redirect-urls]: ../checks/redirect-urls.txt [checks-security-headers]: ../checks/security-headers.txt [example-env]: ../.secrets/example.env diff --git a/deploy/make-release.sh b/deploy/make-release.sh index 21ff4797..5bf53b75 100755 --- a/deploy/make-release.sh +++ b/deploy/make-release.sh @@ -204,6 +204,9 @@ hugo --gc --minify --panicOnWarning echo "==> verifying the URL contract" checks/check-url-parity.py public +echo "==> verifying the Content-Security-Policy" +checks/check-csp-scripts.py public + echo "==> precompressing" # Text only, because JPEG, PNG, and MP4 are already compressed. # A compressed sibling larger than the original is worse than none. diff --git a/layouts/shortcodes/googlemaps.html b/layouts/shortcodes/googlemaps.html deleted file mode 100644 index c37c434a..00000000 --- a/layouts/shortcodes/googlemaps.html +++ /dev/null @@ -1,5 +0,0 @@ - diff --git a/themes/README.md b/themes/README.md index bee84e99..c058fe66 100644 --- a/themes/README.md +++ b/themes/README.md @@ -73,7 +73,7 @@ The content width is unchanged from the theme default, deliberately. 720px at th ## Updating -Nothing is carried, so an update is a replace. Delete `PaperMod/`, drop the new upstream tree in its place, and update the upstream table at the top of the PaperMod section. Then confirm the site still builds under `--panicOnWarning`, which is the gate the theme has failed before. Run the `diff -r` above afterwards, so the next reader inherits the same guarantee. +Nothing is carried, so an update is a replace. Delete `PaperMod/`, drop the new upstream tree in its place, and update the upstream table at the top of the PaperMod section. Then confirm the site still builds under `--panicOnWarning`, which is the gate the theme has failed before. The release build's `checks/check-csp-scripts.py` also fails where an update changes the theme's inline scripts, and `deploy/README.md` "Security headers" says how to update the policy's hashes. Run the `diff -r` above afterwards, so the next reader inherits the same guarantee. Re-check the customization table before the replace, while the upstream table still names the old commit. Each theme hook it names is a comment-only file upstream today. If upstream adds content to one, the local override hides it without any build failure. The exception is `blank.css`, which the head partial bundles beside `custom.css` rather than shadowing. Added rules there still ship, ahead of `custom.css`. A rule duplicating one in `custom.css` needs no change, since the `custom.css` copy keeps the rule if upstream drops it. A conflicting upstream rule wins wherever its selector is more specific or its declaration is `!important`. Restate the site's value in `custom.css` with a selector at least as specific, since `custom.css` comes later, marked `!important` only where the upstream declaration is. Once `blank.css` carries any rule, correct each place calling it comment-only or rule-free: this paragraph, the customization table, and the `custom.css` header comment. Use the clone from the `diff -r` check above, or make a fresh one. Diff each row's theme hook between the recorded commit and the new commit. A comment-only diff needs no action. For a partial, added content means porting it into the override, or deciding it is unwanted.