test_cryptography_fundamentals_lesson.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. # SPDX-License-Identifier: Apache-2.0
  2. """The cryptography fundamentals lesson: its drill runs, its citations exist, it is registered and honest about what was run.
  3. docs/wiki/Cryptography-Fundamentals-Symmetric-Asymmetric-Hashing-Certificates-and-Keys.md teaches symmetric and
  4. asymmetric encryption, MACs, signatures, PKI, the three data states, key custody, the NIST defaults and the post-quantum
  5. plan, with a table of where this project uses each. A drill whose output differs from the page, a cited file that does
  6. not exist, a sample that contradicts itself, a missing registration or a real address would each teach the wrong thing.
  7. """
  8. import hashlib
  9. import math
  10. import os
  11. import re
  12. import shutil
  13. import subprocess
  14. import tempfile
  15. import textwrap
  16. from pathlib import Path
  17. from wikitext import glossary_text, nav_text, page_text
  18. ROOT = Path(__file__).resolve().parent.parent
  19. WIKI = ROOT / "docs" / "wiki"
  20. NAME = "Cryptography-Fundamentals-Symmetric-Asymmetric-Hashing-Certificates-and-Keys"
  21. PAGE = WIKI / f"{NAME}.md"
  22. FENCE = re.compile(r"^[ ]*```(\w*)\n(.*?)^[ ]*```$", re.MULTILINE | re.DOTALL)
  23. LINK = re.compile(r"\]\(([A-Za-z0-9_-]+)\.md(?:#([^)]*))?\)")
  24. ADDR = re.compile(r"\b(?:\d{1,3}\.){3}\d{1,3}\b")
  25. PATH_TOKEN = re.compile(r"`((?:modules|stacks|scripts|docs|\.github|\.spacelift|tests)/[A-Za-z0-9_./-]+|board\.yaml|\.gitignore)`")
  26. STATUS_WORDS = ("Read", "Run", "Listing read", "Title and header read", "**est.**", "General knowledge", "**Not run**", "Not run")
  27. TOPICS = (
  28. "## What encryption is and is not",
  29. "## Symmetric and asymmetric: what each is good for",
  30. "### How they combine: a key exchange, then a symmetric cipher",
  31. "## Hashing is not encryption: salts, passwords and message authentication",
  32. "## Digital signatures",
  33. "## Certificates and PKI in plain words",
  34. "## Data at rest, in transit and in use",
  35. "## Where this shows up in this project",
  36. "## Key management and custody: the hard part",
  37. "## Common mistakes",
  38. "## Modern defaults per NIST",
  39. "## Post-quantum planning, as far as NIST publishes it",
  40. "## Free path: run the drill, then read a real certificate chain",
  41. "## Claims register",
  42. )
  43. def text() -> str:
  44. return page_text(PAGE) # without the generated navigation blocks (issue #417)
  45. def section(body: str, start: str, end: str) -> str:
  46. return body.split(start)[1].split(end)[0]
  47. def table_rows(block: str) -> list[list[str]]:
  48. rows = [line for line in block.splitlines() if line.startswith("|") and not line.startswith("|---")]
  49. return [[c.strip() for c in r.strip("|").split("|")] for r in rows[1:]]
  50. def cited_paths(cell: str) -> list[str]:
  51. return PATH_TOKEN.findall(cell)
  52. def rows_missing_citation(rows: list[list[str]]) -> list[str]:
  53. """A project row must cite files that exist, or start with None in its file column and say None in its status."""
  54. bad = []
  55. for r in rows:
  56. files, status = r[2], r[3]
  57. paths = cited_paths(files)
  58. if any(not (ROOT / p).exists() for p in paths):
  59. bad.append(r[0])
  60. elif files.startswith("None"):
  61. if "None" not in status:
  62. bad.append(r[0])
  63. elif not paths:
  64. bad.append(r[0])
  65. return bad
  66. def project_rows(body: str) -> list[list[str]]:
  67. return table_rows(section(body, "## Where this shows up in this project", "Three honest observations"))
  68. def register_rows(body: str) -> list[list[str]]:
  69. return table_rows(body.split("## Claims register")[1])
  70. def rows_missing_status(rows: list[list[str]]) -> list[str]:
  71. return [r[0] for r in rows if not any(w in r[-1] for w in STATUS_WORDS)]
  72. def slug(heading: str) -> str:
  73. return re.sub(r"[^a-z0-9-]", "", heading.lower().replace(" ", "-"))
  74. def headings(body: str) -> set[str]:
  75. return {slug(h) for h in re.findall(r"^#+ (.+)$", body, re.MULTILINE)}
  76. def broken_chain(lines: list[str]) -> list[int]:
  77. """In an s_client chain listing, the issuer of each certificate must be the subject of the next one."""
  78. subjects = [m.group(1) for line in lines if (m := re.match(r"^ *\d s:(.*)$", line))]
  79. issuers = [m.group(1) for line in lines if (m := re.match(r"^ *i:(.*)$", line))]
  80. return [n for n in range(len(subjects) - 1) if issuers[n] != subjects[n + 1]]
  81. def test_the_banner_says_what_was_and_was_not_run():
  82. body = text()
  83. assert body.startswith("# Cryptography fundamentals")
  84. assert "Status: unverified draft" in body
  85. assert "**Not run:**" in body and "2026-10-31" in body
  86. assert "sample from that date" in body
  87. def test_every_topic_the_issue_asked_for_has_a_section():
  88. body = text()
  89. missing = [t for t in TOPICS if f"\n{t}\n" not in body]
  90. assert not missing, missing
  91. def test_every_linked_wiki_page_exists_and_every_anchor_resolves():
  92. links = LINK.findall(text())
  93. assert len({t for t, _ in links}) >= 10, "the guard collected too few links"
  94. problems = []
  95. for target, anchor in links:
  96. path = WIKI / f"{target}.md"
  97. if not path.exists():
  98. problems.append(target)
  99. elif anchor and anchor not in headings(path.read_text(encoding="utf-8")):
  100. problems.append(f"{target}#{anchor}")
  101. assert not problems, problems
  102. named = {t for t, _ in links}
  103. for needed in ("Hashing-Encryption-and-Keys", "The-CIA-Triad-Confidentiality-Integrity-Availability"):
  104. assert needed in named, needed
  105. def test_the_tor_and_i2p_lesson_is_linked_now_that_it_exists():
  106. # That lesson (issue 358) is in the wiki, so it is linked, and the old 'not written yet' statement is gone.
  107. body = text()
  108. assert "Tor and I2P" in body
  109. targets = [t for t, _ in LINK.findall(body) if re.fullmatch(r"Tor[-A-Za-z0-9]*I2P[-A-Za-z0-9]*", t)]
  110. assert targets, "the Tor and I2P lesson exists and must be linked"
  111. assert all((WIKI / f"{t}.md").is_file() for t in targets), targets
  112. assert "not written yet" not in body and "named here in plain text" not in body
  113. assert "Plan-for-Failure-Blast-Radius" not in body, "tests/test_blast_radius_lesson.py caps links to that lesson"
  114. def test_the_lesson_is_registered_in_contents_and_reading_order_not_the_sidebar():
  115. nav = nav_text(WIKI)
  116. entry = nav.split(f"page: {NAME},")[1].split("\n")[0]
  117. assert 'status: "draft"' in entry
  118. assert "sidebar" not in entry, "new lessons are reached from Contents and Reading Order, not the sidebar"
  119. for special in ("Contents.md", "Reading-Order.md"):
  120. assert f"{NAME}.md" in (WIKI / special).read_text(encoding="utf-8"), special
  121. rows = [line for line in glossary_text(WIKI).splitlines() if f"{NAME}.md" in line]
  122. assert len(rows) >= 5, "expected glossary rows for the new terms"
  123. def test_glossary_rows_point_at_real_headings():
  124. anchors = set()
  125. for line in glossary_text(WIKI).splitlines():
  126. anchors.update(re.findall(rf"{NAME}\.md#([a-z0-9-]+)", line))
  127. assert anchors, "the guard collected nothing"
  128. assert anchors <= headings(text()), sorted(anchors - headings(text()))
  129. def test_the_hashing_page_links_the_lesson():
  130. assert f"{NAME}.md" in (WIKI / "Hashing-Encryption-and-Keys.md").read_text(encoding="utf-8")
  131. def test_no_addresses_and_no_em_dashes():
  132. body = text()
  133. assert not ADDR.findall(body)
  134. assert "—" not in body
  135. assert "Connecting to" not in body, "openssl prints the server address on stderr; the exercise discards stderr"
  136. def test_the_address_guard_bites():
  137. assert ADDR.findall("ping 192.0.2.7")
  138. def test_every_project_row_cites_an_existing_file_or_says_none():
  139. rows = project_rows(text())
  140. assert len(rows) >= 12, "the guard collected too few rows"
  141. assert not rows_missing_citation(rows)
  142. assert sum(r[2].startswith("None") for r in rows) >= 4, "the table should say None where nothing exists"
  143. wanted = ("Disk", "Droplet backups", "bucket", "OpenTofu state", "Doppler", "Twingate", "SSH", "Data in use", "post-quantum", "key custody")
  144. joined = " ".join(r[0] for r in rows)
  145. assert all(w in joined for w in wanted), [w for w in wanted if w not in joined]
  146. def test_the_citation_guard_bites():
  147. rows = [
  148. ["a", "x", "`scripts/does_not_exist.py`", "Built"],
  149. ["b", "x", "`scripts/secret_rule.py`", "Built"],
  150. ["c", "x", "None here", "Built"],
  151. ["d", "x", "None; the design is in `docs/does/not/exist.md`", "None"],
  152. ["e", "x", "no path at all", "Built"],
  153. ]
  154. assert rows_missing_citation(rows) == ["a", "c", "d", "e"]
  155. def test_every_repository_path_the_page_names_exists():
  156. paths = set(cited_paths(text()))
  157. assert len(paths) >= 8, "the guard collected too few paths"
  158. assert not [p for p in sorted(paths) if not (ROOT / p).exists()]
  159. def test_project_claims_hold_in_the_files():
  160. # The table says these things; the files must still say them.
  161. def read(p: str) -> str:
  162. return (ROOT / p).read_text(encoding="utf-8")
  163. assert "backups = false" in read("modules/twingate-connector/main.tf")
  164. doppler = read("scripts/spacelift/doppler-env.sh")
  165. assert "--proto '=https' --tlsv1.2" in doppler and "sha256sum -c" in doppler
  166. cloud_init = read("modules/twingate-bootstrap/cloud-init.yaml.tftpl")
  167. assert "PasswordAuthentication no" in cloud_init and "fingerprint" in cloud_init
  168. assert re.search(r'condition\s*=\s*var\.acl == "private"', read("modules/spaces-bucket/variables.tf"))
  169. assert "*.tfstate" in read(".gitignore")
  170. unencrypted = [p for p in ROOT.rglob("*.tf") if ".claude" not in p.parts and re.search(r"^\s*encryption\s*\{", p.read_text(encoding="utf-8"), re.MULTILINE)]
  171. assert not unencrypted, f"the page says no encryption block exists in any .tf file: {unencrypted}"
  172. def test_the_nist_facts_are_stated_with_their_dates_and_sources():
  173. body = text()
  174. for needle in (
  175. "doi.org/10.6028/NIST.IR.8547",
  176. "FIPS 203",
  177. "FIPS 204",
  178. "FIPS 205",
  179. "ML-KEM",
  180. "ML-DSA",
  181. "SLH-DSA",
  182. "2024-08-13",
  183. "after 2030",
  184. "after 2035",
  185. "harvest now, decrypt later",
  186. "SP 800-57 Part 1 Rev. 5",
  187. "SP 800-131A Rev. 2",
  188. "SP 800-38D",
  189. "SP 800-52 Rev. 2",
  190. "RFC 8446",
  191. "RFC 5280",
  192. "RFC 9106",
  193. "OWASP",
  194. ):
  195. assert needle in body, needle
  196. def test_every_claims_register_row_has_a_status():
  197. rows = register_rows(text())
  198. assert len(rows) >= 20, "the guard collected too few rows"
  199. assert not rows_missing_status(rows)
  200. joined = " ".join(r[1] for r in rows)
  201. assert "csrc.nist.gov" in joined and "rfc-editor.org" in joined and "doi.org/10.6028" in joined
  202. assert sum("2026-10-31" in r[-1] or "Read" in r[-1] for r in rows) >= 15
  203. assert any("Run" in r[-1] for r in rows) and any("Not run" in r[-1] for r in rows)
  204. def test_the_register_guard_bites():
  205. assert rows_missing_status([["X", "y", "maybe"]]) == ["X"]
  206. def test_the_tls_sample_is_dated_and_marked_a_sample():
  207. body = text()
  208. block = section(body, "### Exercise 2: read a real TLS certificate chain", "**Safe-use rules")
  209. assert "sample read on 2026-10-31" in block and "your output will differ" in block
  210. assert "2> /dev/null > s_client.txt" in block, "stderr must be discarded: it carries the server address"
  211. commands = next(b for t, b in FENCE.findall(block) if t == "bash")
  212. assert "openssl s_client -connect example.com:443" in commands
  213. def test_the_sample_chain_is_consistent_with_itself():
  214. block = section(text(), "### Exercise 2: read a real TLS certificate chain", "**Safe-use rules")
  215. chain = next(b for t, b in FENCE.findall(block) if t == "text" and b.lstrip().startswith("0 s:"))
  216. lines = chain.splitlines()
  217. assert sum(1 for line in lines if re.match(r"^ *\d s:", line)) >= 3, "the guard collected too few certificates"
  218. assert not broken_chain(lines)
  219. def test_the_chain_guard_bites():
  220. bad = [" 0 s:CN=a", " i:CN=b", " 1 s:CN=z", " i:CN=c"]
  221. assert broken_chain(bad) == [0]
  222. def script() -> str:
  223. found = [textwrap.dedent(b) for t, b in FENCE.findall(text()) if t == "bash" and "# crypto_drill.sh - " in b]
  224. assert len(found) == 1, f"expected one crypto_drill.sh block, found {len(found)}"
  225. return found[0]
  226. def shown_output() -> str:
  227. found = [b for t, b in FENCE.findall(text()) if t == "text" and b.startswith("== 1. Hashing")]
  228. assert len(found) == 1
  229. return found[0]
  230. NEEDED = ("bash", "openssl", "gpg", "gpgconf", "sha256sum", "cmp", "od", "tr", "awk", "python3")
  231. def test_every_tool_the_drill_needs_is_installed():
  232. # No skip: a runner without these must fail loudly, not quietly stop checking the page.
  233. missing = [t for t in NEEDED if shutil.which(t) is None]
  234. assert not missing, missing
  235. version = subprocess.run(["openssl", "version"], capture_output=True, text=True, check=True).stdout
  236. assert re.search(r"OpenSSL 3\.", version), f"the drill needs OpenSSL 3.x (kdf, mac, pkeyutl -rawin): {version}"
  237. def run_drill() -> subprocess.CompletedProcess:
  238. # A short directory name: gpg-agent sockets live under the lab folder and have a path length limit.
  239. base = Path(tempfile.mkdtemp(prefix="cf"))
  240. try:
  241. path = base / "crypto_drill.sh"
  242. path.write_text(script())
  243. done = subprocess.run(["bash", str(path)], capture_output=True, text=True, timeout=180, check=False, env={**os.environ, "TMPDIR": str(base)})
  244. leftovers = [p.name for p in base.glob("tmp*")]
  245. assert not leftovers, f"the script must delete its own lab folder: {leftovers}"
  246. return done
  247. finally:
  248. shutil.rmtree(base, ignore_errors=True)
  249. def test_the_drill_runs_and_its_output_matches_the_page():
  250. done = run_drill()
  251. assert done.returncode == 0, done.stderr
  252. got = [line.rstrip() for line in done.stdout.strip().splitlines()]
  253. want = [line.rstrip() for line in shown_output().strip().splitlines()]
  254. assert got == want
  255. def test_the_drill_prints_only_version_independent_labels():
  256. shown = shown_output()
  257. for label in ("CHECK-OK", "CHECK-FAIL", "GPG-REFUSED", "VERIFY-OK", "VERIFY-FAIL"):
  258. assert label in shown, label
  259. # raw tool wording differs between OpenSSL, GnuPG and coreutils versions and must stay out of the compared text
  260. for raw in ("error 20", "error 62", "hostname mismatch", "verification failed", "Bad session key", "manipulated", "WARNING", "Verified Successfully", "FAILED"):
  261. assert raw not in shown, raw
  262. assert not any(line.startswith("gpg:") for line in shown.splitlines())
  263. def test_the_prose_numbers_match_the_printed_output():
  264. body = text()
  265. shown = shown_output()
  266. same = re.search(r"same hex digit in the same place: (\d+) of 64", shown).group(1)
  267. assert f"{same} happen to line up by chance" in body
  268. assert "pay Alice 900 dollars" in shown and "the safe code is 4417" in shown
  269. GENERIC_KEY = re.compile(
  270. r"""(?i)[\w.-]{0,50}?(?:access|auth|(?-i:[Aa]pi|API)|credential|creds|key|passw(?:or)?d|secret|token)(?:[ \t\w.-]{0,20})[\s'"]{0,3}"""
  271. r"""(?:=|>|:{1,3}=|\|\|:|<=|=>|:|\?=)(?:'|"|\s|=|`){0,5}([\w.=-]{10,150}|[a-z0-9][a-z0-9+/]{11,}={0,3})(?:['"\n\r\s`;]|$)"""
  272. )
  273. def entropy(s: str) -> float:
  274. return -sum(s.count(c) / len(s) * math.log2(s.count(c) / len(s)) for c in set(s))
  275. def secret_looking(body: str) -> list[str]:
  276. """An approximation of gitleaks' generic-api-key rule: a keyword, an assignment, then a long high-entropy value."""
  277. return [m.group(1) for line in body.splitlines() for m in GENERIC_KEY.finditer(line) if entropy(m.group(1)) >= 3.5]
  278. def test_no_long_random_looking_value_sits_next_to_a_secret_keyword():
  279. for name, body in (("page", text()), ("drill", script()), ("test", Path(__file__).read_text(encoding="utf-8"))):
  280. found = secret_looking(body)
  281. assert not found, f"{name}: {found}"
  282. def test_the_secret_guard_bites():
  283. random_looking = hashlib.sha256(b"guard").hexdigest() # built at run time so no literal sits in this file
  284. assert secret_looking(f"hmac, right key: {random_looking}")
  285. assert secret_looking(f'API_TOKEN="{random_looking[:40]}"')
  286. assert not secret_looking('AES_K="$(derive demo-seed-one 32)"')
  287. assert not secret_looking("hmac, same key and same message twice: tags equal")
  288. KEYWORD_NEAR_RUN = re.compile(
  289. r"(?i)(?:key|salt|secret|token|password|passphrase|nonce|iv).{0,40}?(?<![A-Za-z0-9+/])(?:[0-9A-Fa-f]{20,}|[A-Za-z0-9+/]{20,}={0,2})"
  290. )
  291. BARE_HEX = re.compile(r"(?<![0-9A-Fa-f])[0-9A-Fa-f]{32,}(?![0-9A-Fa-f])")
  292. def long_runs(body: str) -> list[str]:
  293. """Lines with a bare run of 32 or more hex digits, or 20 or more hex or base64 characters near a secret-sounding word."""
  294. return [line.strip() for line in body.splitlines() if BARE_HEX.search(line) or KEYWORD_NEAR_RUN.search(line)]
  295. def test_no_long_hex_or_base64_run_appears_anywhere_in_the_page_the_drill_or_the_test():
  296. for name, body in (("page", text()), ("drill", script()), ("test", Path(__file__).read_text(encoding="utf-8"))):
  297. found = long_runs(body)
  298. assert not found, f"{name}: {found}"
  299. def test_the_long_run_guard_bites():
  300. digest = hashlib.sha256(b"guard").hexdigest()
  301. assert long_runs(f"{digest}")
  302. assert long_runs(f"salt 1: {digest[:32]}")
  303. assert long_runs(f"the nonce is {digest[:24]}")
  304. assert not long_runs("first 8 hex digits: cbcc2a3b...")
  305. assert not long_runs("same password and different salts: derived keys differ")
  306. def test_the_drill_never_touches_anything_outside_its_own_folder():
  307. body = script()
  308. assert "mktemp -d" in body and 'export GNUPGHOME="$lab/gnupg"' in body
  309. rm_lines = [line for line in body.splitlines() if re.search(r"\brm\b", line)]
  310. assert len(rm_lines) == 1 and 'rm -rf "$lab"' in rm_lines[0], rm_lines
  311. assert not re.search(r"\bsudo\b|\bcurl\b|\bwget\b|\bs_client\b|\bssh\b|\bchattr\b|~/|\$HOME", body)
  312. assert not re.search(r"\bgpg\b[^\n]*--(?:import|export|gen-key|full-generate-key|recv-keys|send-keys)", body)