Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion .vscode/tasks.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -71,7 +81,8 @@
"Lint: Spelling",
"Lint: Shell",
"Lint: Shell Format",
"Check: URL Parity"
"Check: URL Parity",
"Check: CSP Scripts"
],
"problemMatcher": []
}
Expand Down
2 changes: 2 additions & 0 deletions CONTENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand All @@ -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
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 2 additions & 0 deletions checks/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -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
Expand Down
190 changes: 190 additions & 0 deletions checks/check-csp-scripts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
#!/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 an origin 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 attr.get("src") is not None:
self.loaded.append(attr["src"] or "")
else:
self.body = []

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 not parts.netloc:
return "'self'" in sources
return f"{parts.scheme}://{parts.netloc}" 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}: <script src={src}> is from an origin script-src does not name"
for src in scan.loaded
if not allowed(src, sources)
]
for body in scan.inline:
if body:
used[digest(body)].append(rel)
listed = {token for token in sources if token.startswith("'sha256-")}
for token, pages in sorted(used.items()):
if token not in listed:
findings.append(
f"{pages[0]}: inline script {token} is not in script-src, on {len(pages)} page(s)"
)
findings += [
f"script-src lists {token}, which no inline script matches"
for token in sorted(listed - used.keys())
]
print(
f"csp: {len(used)} distinct inline scripts, {len(listed)} hashes in script-src"
)
return findings


def load_policy(headers, caddyfile):
"""The blog's policy, or a refusal naming why it cannot be checked."""
policy = blog_policy(headers.read_text(encoding="utf-8"))
if policy is None:
return None, f"{headers.name} holds no {CSP} for the blog"
if f'{CSP} "{policy}"' not in caddyfile.read_text(encoding="utf-8"):
return (
None,
f"{caddyfile.name} does not send the blog {CSP} {headers.name} holds",
)
return policy, None


def main(argv=None):
parser = argparse.ArgumentParser(description=(__doc__ or "").partition("\n")[0])
parser.add_argument(
"public", type=pathlib.Path, help="the built site, as hugo wrote it"
)
args = parser.parse_args(argv)
if not args.public.is_dir():
sys.exit(f"FAIL: {args.public} is not a directory - run hugo first")
policy, refusal = load_policy(HEADERS, CADDYFILE)
if policy is None:
sys.exit(f"FAIL: {refusal}")

findings = check(args.public, script_sources(policy))
if not findings:
print("PASS - the blog's script-src allows every script the site runs")
return 0
print(f"FAIL csp: {len(findings)} problem{'' if len(findings) == 1 else 's'}")
for item in findings[:20]:
print(f" {item}")
if len(findings) > 20:
print(f" ... and {len(findings) - 20} more")
return 1


if __name__ == "__main__":
sys.exit(main())
1 change: 1 addition & 0 deletions checks/security-headers.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
blog Strict-Transport-Security: max-age=31536000
blog X-Content-Type-Options: nosniff
blog Referrer-Policy: strict-origin-when-cross-origin
blog 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'
family Strict-Transport-Security: max-age=31536000
family X-Content-Type-Options: nosniff
family Referrer-Policy: strict-origin-when-cross-origin
Expand Down
Loading
Loading