test_deception_lessons.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  1. """The code on the deception lesson pages runs, and says what the pages say it does.
  2. docs/wiki/Deception-and-Honeypots-*.md teach with scripts the learner pastes into
  3. files. A lesson whose script is broken, or whose printed output has drifted from
  4. what the script prints, teaches the wrong thing. These tests pull each script out
  5. of the page text, run it in a temporary folder, and compare against the page.
  6. Everything runs on localhost with invented data. The checks collect loosely (any
  7. fenced block) and assert strictly (exactly one block per marker, and the output
  8. matches), and each has a negative case showing the guard bites.
  9. """
  10. import configparser
  11. import ipaddress
  12. import json
  13. import os
  14. import re
  15. import shutil
  16. import socket
  17. import subprocess
  18. import sys
  19. import time
  20. import xml.etree.ElementTree as ET
  21. from pathlib import Path
  22. import pytest
  23. WIKI = Path(__file__).resolve().parent.parent / "docs" / "wiki"
  24. SIEM = WIKI / "Deception-and-Honeypots-Alerts-in-the-SIEM.md"
  25. CANARY = WIKI / "Deception-and-Honeypots-Plant-a-Canary.md"
  26. HONEY = WIKI / "Deception-and-Honeypots-Honeyfiles-on-Your-Host.md"
  27. ANATOMY = WIKI / "Deception-and-Honeypots-Cloud-Sensor-Anatomy.md"
  28. WEEKEND = WIKI / "Deception-and-Honeypots-Cloud-Cowrie-Weekend.md"
  29. LOGS = WIKI / "Deception-and-Honeypots-Read-the-Sensor-Logs.md"
  30. TRACK2 = (ANATOMY, WEEKEND, LOGS)
  31. COST_PRICES = WIKI.parent / "cost-prices.json"
  32. COST_MD = WIKI.parent / "cost.md"
  33. DESIGN = WIKI / "Deception-and-Honeypots-Design-a-Honeynet.md"
  34. TPOT = WIKI / "Deception-and-Honeypots-T-Pot-at-Home.md"
  35. FENCE = re.compile(r"^```(\w*)\n(.*?)^```$", re.MULTILINE | re.DOTALL)
  36. def blocks(path: Path, lang: str) -> list[str]:
  37. return [body for tag, body in FENCE.findall(path.read_text(encoding="utf-8")) if tag == lang]
  38. def one_block(path: Path, lang: str, marker: str) -> str:
  39. found = [b for b in blocks(path, lang) if marker in b]
  40. assert len(found) == 1, f"{path.name}: expected one {lang} block with {marker!r}, found {len(found)}"
  41. return found[0]
  42. def run_py(folder: Path, script: str, *args: str, env=None) -> subprocess.CompletedProcess:
  43. return subprocess.run(
  44. [sys.executable, "-I", script, *args],
  45. cwd=folder, capture_output=True, text=True, timeout=30, env=env, check=False,
  46. )
  47. # --- lesson 5: the generator, the detector and the draft rules -------------------
  48. @pytest.fixture()
  49. def siem_lab(tmp_path):
  50. (tmp_path / "make_events.py").write_text(one_block(SIEM, "python", "Builds SYNTHETIC honeypot events"))
  51. (tmp_path / "detect.py").write_text(one_block(SIEM, "python", "A toy detector"))
  52. made = run_py(tmp_path, "make_events.py")
  53. assert made.returncode == 0, made.stderr
  54. (tmp_path / "events.jsonl").write_text(made.stdout)
  55. return tmp_path
  56. def alerts(proc) -> list[dict]:
  57. return [json.loads(line) for line in proc.stdout.splitlines()]
  58. def test_the_generator_makes_eighteen_lines_with_documentation_addresses_only(siem_lab):
  59. lines = (siem_lab / "events.jsonl").read_text().splitlines()
  60. assert len(lines) == 18
  61. docs = [ipaddress.ip_network(n) for n in ("192.0.2.0/24", "198.51.100.0/24", "203.0.113.0/24")]
  62. parsed = []
  63. for line in lines:
  64. try:
  65. parsed.append(json.loads(line))
  66. except ValueError:
  67. pass # the deliberately invalid line
  68. assert len(parsed) == 17
  69. for event in parsed:
  70. assert any(ipaddress.ip_address(event["src_ip"]) in net for net in docs), event["src_ip"]
  71. def test_the_detector_alerts_on_source_a_only_and_drops_the_bad_lines(siem_lab):
  72. proc = run_py(siem_lab, "detect.py", "events.jsonl")
  73. assert proc.returncode == 0, proc.stderr
  74. got = alerts(proc)
  75. assert [(a["rule"], a["src_ip"]) for a in got] == [
  76. ("brute_force", "203.0.113.7"),
  77. ("success_after_brute_force", "203.0.113.7"),
  78. ("brute_force", "192.0.2.66"),
  79. ]
  80. assert 'dropped: {"not_json": 1, "too_long": 1, "bad_shape": 0}' in proc.stderr
  81. def test_the_output_shown_on_the_page_is_what_the_detector_prints(siem_lab):
  82. shown = one_block(SIEM, "text", '"rule": "brute_force"')
  83. shown_alerts = [json.loads(x) for x in shown.splitlines() if x.startswith("{")]
  84. assert shown_alerts == alerts(run_py(siem_lab, "detect.py", "events.jsonl"))
  85. assert 'dropped: {"not_json": 1, "too_long": 1, "bad_shape": 0}' in shown
  86. def test_hostile_lines_stay_data_and_a_text_search_is_fooled(siem_lab):
  87. text = (siem_lab / "events.jsonl").read_text()
  88. assert text.count("cowrie.login.success") == 4 # the page says a text search counts 4 ...
  89. got = alerts(run_py(siem_lab, "detect.py", "events.jsonl"))
  90. successes = [a for a in got if a["rule"] == "success_after_brute_force"]
  91. assert [a["src_ip"] for a in successes] == ["203.0.113.7"] # ... the parsed field finds one chain alert
  92. # source D tripped the brute-force rule, so a substring check would have fired a second, false chain alert
  93. assert [a["rule"] for a in got if a["src_ip"] == "192.0.2.66"] == ["brute_force"]
  94. assert not (siem_lab / "pwned").exists()
  95. def test_negative_cases_the_rule_stays_quiet_below_the_threshold(siem_lab):
  96. lines = (siem_lab / "events.jsonl").read_text().splitlines(keepends=True)
  97. def alerts_without(*banned: str) -> list[dict]:
  98. (siem_lab / "cut.jsonl").write_text("".join(x for x in lines if not any(b in x for b in banned)))
  99. return alerts(run_py(siem_lab, "detect.py", "cut.jsonl"))
  100. d = "192.0.2.66" # the page's commands also remove source D
  101. assert alerts_without("203.0.113.7", d) == [] # no source A at all
  102. assert alerts_without('"guess4"', '"guess5"', d) == [] # four failures: one short
  103. assert len(alerts_without('"guess5"', d)) == 2 # five failures: both rules fire
  104. assert len(alerts_without()) == 3 # control: nothing removed
  105. def test_the_detector_survives_odd_shapes(siem_lab):
  106. odd = [
  107. "[]", "5", "null", "{}", '{"eventid": 5}', '{"eventid": "cowrie.login.failed"}',
  108. '{"eventid": "cowrie.login.failed", "src_ip": "x", "timestamp": "not a time"}',
  109. '{"eventid": "cowrie.login.failed", "src_ip": 5, "timestamp": "2026-01-01T00:00:00Z"}',
  110. ]
  111. (siem_lab / "odd.jsonl").write_text("\n".join(odd) + "\n")
  112. proc = run_py(siem_lab, "detect.py", "odd.jsonl")
  113. assert proc.returncode == 0, proc.stderr
  114. assert alerts(proc) == []
  115. assert '"not_json": 0' in proc.stderr and '"bad_shape": 8' in proc.stderr
  116. def test_a_success_stamped_before_the_alert_does_not_match(siem_lab):
  117. early = json.dumps({"eventid": "cowrie.login.success", "src_ip": "203.0.113.7", "session": "z",
  118. "timestamp": "2026-01-01T11:59:00.000000Z"})
  119. late = json.dumps({"eventid": "cowrie.login.success", "src_ip": "203.0.113.7", "session": "z",
  120. "timestamp": "2026-01-01T12:05:00.000000Z"})
  121. base = (siem_lab / "events.jsonl").read_text()
  122. (siem_lab / "early.jsonl").write_text(base + early + "\n" + late + "\n")
  123. got = alerts(run_py(siem_lab, "detect.py", "early.jsonl"))
  124. # only the original success (8 s after the alert) matches; 60 s before and 288 s after do not
  125. assert [a["at"] for a in got if a["rule"] == "success_after_brute_force"] == ["2026-01-01T12:00:20.000000Z"]
  126. def test_long_lines_are_counted_in_bytes_and_never_read_whole(siem_lab):
  127. ok = json.dumps({"eventid": "x", "src_ip": "192.0.2.1", "timestamp": "2026-01-01T00:00:00Z", "pad": ""})
  128. pad = "é" * ((4096 - len(ok.encode())) // 2) # 2 bytes each: under 4,096 characters, near the byte limit
  129. just_under = ok.replace('"pad": ""', f'"pad": "{pad}"')
  130. assert len(just_under.encode()) <= 4096
  131. over = ok.replace('"pad": ""', f'"pad": "{pad}éé"') # 4 bytes more: over the byte limit
  132. assert len(over.encode()) > 4096 and len(over) < 4096 # fewer than 4,096 characters, too many bytes
  133. huge = "A" * 5_000_000 # one 5 MB line, no newline until the end
  134. (siem_lab / "long.jsonl").write_bytes(
  135. (just_under + "\n" + over + "\n" + huge + "\n" + just_under + "\n").encode()
  136. )
  137. proc = run_py(siem_lab, "detect.py", "long.jsonl")
  138. assert proc.returncode == 0, proc.stderr
  139. assert '"too_long": 2' in proc.stderr and '"bad_shape": 0' in proc.stderr and '"not_json": 0' in proc.stderr
  140. def test_the_draft_rules_are_well_formed_and_reference_only_their_own_ids():
  141. xml = one_block(SIEM, "xml", "<group")
  142. root = ET.fromstring(xml)
  143. rules = {r.get("id"): r for r in root.iter("rule")}
  144. assert len(rules) == len(list(root.iter("rule"))) >= 4, "duplicate or missing rule ids"
  145. for rule in rules.values():
  146. for tag in ("if_sid", "if_matched_sid"):
  147. for ref in rule.findall(tag):
  148. assert ref.text.strip() in rules, f"{tag} names an unknown rule: {ref.text}"
  149. assert rules["100902"].get("frequency") == "5" and rules["100902"].get("timeframe") == "60"
  150. # the lesson says the draft is unverified; the banner must keep saying it
  151. assert "never loaded" in SIEM.read_text(encoding="utf-8").lower()
  152. # --- lesson 3: the local tripwire -------------------------------------------------
  153. def free_port() -> int:
  154. with socket.socket() as s:
  155. s.bind(("127.0.0.1", 0))
  156. return s.getsockname()[1]
  157. def raw_request(port: int, request: bytes) -> bytes:
  158. with socket.create_connection(("127.0.0.1", port), timeout=5) as s:
  159. s.sendall(request)
  160. s.shutdown(socket.SHUT_WR)
  161. data = b""
  162. while chunk := s.recv(4096):
  163. data += chunk
  164. return data
  165. @pytest.fixture()
  166. def tripwire(tmp_path):
  167. (tmp_path / "build_bait.py").write_text(one_block(CANARY, "python", "Builds the decoy document"))
  168. (tmp_path / "tripwire.py").write_text(one_block(CANARY, "python", "A local tripwire"))
  169. port = free_port()
  170. env = {**os.environ, "TRIPWIRE_PORT": str(port)}
  171. built = run_py(tmp_path, "build_bait.py", env=env)
  172. assert built.returncode == 0, built.stderr
  173. server = subprocess.Popen(
  174. [sys.executable, "-I", "tripwire.py"], cwd=tmp_path,
  175. stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
  176. )
  177. try:
  178. for _ in range(100):
  179. try:
  180. socket.create_connection(("127.0.0.1", port), timeout=0.2).close()
  181. break
  182. except OSError:
  183. time.sleep(0.05)
  184. else:
  185. raise AssertionError("the tripwire did not start")
  186. yield tmp_path, port
  187. finally:
  188. server.terminate()
  189. server.wait(timeout=5)
  190. def bait_fields(folder: Path) -> dict:
  191. out = {}
  192. for line in (folder / "bait" / "vpn-notes-OLD.txt").read_text().splitlines():
  193. key, _, value = line.partition(": ")
  194. out[key] = value
  195. return out
  196. def test_only_the_token_and_the_decoy_user_raise_an_alert(tripwire):
  197. folder, port = tripwire
  198. bait = bait_fields(folder)
  199. token_path = bait["details"].split(f":{port}", 1)[1]
  200. log = folder / "alerts.jsonl"
  201. raw_request(port, b"GET /index.html HTTP/1.0\r\n\r\n") # noise
  202. body = b"user=admin&password=x"
  203. raw_request(port, b"POST /login HTTP/1.0\r\nContent-Length: %d\r\n\r\n%s" % (len(body), body))
  204. assert not log.exists(), "noise must not alert"
  205. hostile = b'evil"\x1b[2J{{x}}'
  206. raw_request(port, b"GET %s HTTP/1.0\r\nUser-Agent: %s\r\n\r\n" % (token_path.encode(), hostile))
  207. pwd = bait["password"]
  208. body = f"user={bait['user']}&password={pwd}".encode()
  209. raw_request(port, b"POST /login HTTP/1.0\r\nContent-Length: %d\r\n\r\n%s" % (len(body), body))
  210. for _ in range(100):
  211. if log.exists() and len(log.read_text().splitlines()) >= 2:
  212. break
  213. time.sleep(0.05)
  214. records = [json.loads(x) for x in log.read_text().splitlines()]
  215. assert [r["eventid"] for r in records] == ["decoy.token.hit", "decoy.credential.used"]
  216. assert records[0]["user_agent"] == hostile.decode() # intact, as data
  217. assert records[1]["username"] == bait["user"]
  218. assert pwd not in log.read_text(), "the password must never be logged"
  219. def post(port: int, length: str, body: bytes) -> bytes:
  220. return raw_request(port, b"POST /login HTTP/1.0\r\nContent-Length: %s\r\n\r\n%s" % (length.encode(), body))
  221. def wait_for_lines(log: Path, n: int) -> list[dict]:
  222. for _ in range(100):
  223. if log.exists() and len(log.read_text().splitlines()) >= n:
  224. break
  225. time.sleep(0.05)
  226. return [json.loads(x) for x in log.read_text().splitlines()] if log.exists() else []
  227. def test_a_bad_content_length_is_refused_or_clamped_and_the_server_lives(tripwire):
  228. folder, port = tripwire
  229. bait = bait_fields(folder)
  230. log = folder / "alerts.jsonl"
  231. decoy = f"user={bait['user']}&password=x".encode()
  232. assert b" 400 " in post(port, "abc", decoy).split(b"\r\n")[0] + b" " # not a number: refused
  233. assert b" 400 " in post(port, "", decoy).split(b"\r\n")[0] + b" " # empty: refused
  234. assert b" 401 " in post(port, "-5", decoy).split(b"\r\n")[0] + b" " # negative: clamped to 0
  235. assert not log.exists(), "none of those may alert"
  236. padding = b"a=" + b"x" * 1100 + b"&"
  237. post(port, "99999", padding + decoy) # the decoy user sits past the 1,024-byte clamp
  238. assert not log.exists(), "bytes past the clamp must not be read"
  239. post(port, "99999999999999999999", decoy) # huge length, short body: read what is there
  240. records = wait_for_lines(log, 1)
  241. assert [r["eventid"] for r in records] == ["decoy.credential.used"]
  242. assert b" 401 " in post(port, "5", b"user=").split(b"\r\n")[0] + b" " # still serving
  243. def test_the_bait_is_built_at_run_time_and_differs_each_time(tmp_path):
  244. script = one_block(CANARY, "python", "Builds the decoy document")
  245. seen = set()
  246. for n in range(2):
  247. folder = tmp_path / str(n)
  248. folder.mkdir()
  249. (folder / "build_bait.py").write_text(script)
  250. assert run_py(folder, "build_bait.py").returncode == 0
  251. seen.add(bait_fields(folder)["password"])
  252. assert len(seen) == 2
  253. # --- lesson 4: the watcher's guard against forged lines ----------------------------
  254. FAKE_TOOL = """#!/usr/bin/env bash
  255. # stands in for inotifywait --csv: one CSV record per event; a name with a newline is quoted
  256. printf 'bait/,OPEN,bait.txt\\n'
  257. printf 'bait/,CREATE,"line1\\nbait/,DELETE,forged"\\n'
  258. printf 'bait/,"OPEN,ISDIR",\\n'
  259. printf 'bait/,DELETE,"a|b""c,d"\\n'
  260. """
  261. def run_watch(tmp_path: Path, script: str) -> str:
  262. bindir = tmp_path / "bin"
  263. bindir.mkdir(exist_ok=True)
  264. tool = bindir / "inotifywait"
  265. tool.write_text(FAKE_TOOL)
  266. tool.chmod(0o755)
  267. watch = tmp_path / "watch.sh"
  268. watch.write_text(script)
  269. watch.chmod(0o755)
  270. env = {"PATH": f"{bindir}:/usr/bin:/bin", "HOME": str(tmp_path)}
  271. proc = subprocess.run(
  272. ["bash", str(watch), "bait", str(tmp_path / "alerts.log")],
  273. cwd=tmp_path, capture_output=True, text=True, timeout=30, env=env, check=False,
  274. )
  275. assert proc.returncode == 0, proc.stderr
  276. return (tmp_path / "alerts.log").read_text()
  277. def test_the_watcher_keeps_a_hostile_name_on_one_line_and_forges_nothing(tmp_path):
  278. script = one_block(HONEY, "bash", "inotifywait -m")
  279. log = run_watch(tmp_path, script)
  280. lines = log.splitlines()
  281. assert len(lines) == 3, log # OPEN, CREATE, DELETE; the folder event is skipped
  282. assert all(line.startswith("ALERT time=") for line in lines)
  283. assert 'file="line1\\nbait/,DELETE,forged"' in lines[1] # the newline is escaped, still one event
  284. assert sum("event=DELETE" in line for line in lines) == 1 # the forged DELETE is not an event
  285. assert 'file="a|b\\"c,d"' in lines[2]
  286. assert "ISDIR" not in log
  287. def test_a_line_by_line_reader_is_forged_by_the_same_input(tmp_path):
  288. naive = FAKE_TOOL.split("\n", 1)[0] + "\n" # keep the shebang only
  289. script = (
  290. "#!/usr/bin/env bash\n"
  291. "inotifywait -m -q --csv \"$1\" | while IFS=, read -r d events name; do\n"
  292. " printf 'ALERT event=%s file=%s\\n' \"$events\" \"$name\" >> \"$2\"\n"
  293. "done\n"
  294. )
  295. assert naive.startswith("#!")
  296. log = run_watch(tmp_path, script)
  297. assert log.count("event=DELETE") == 2, log # one real, one forged out of a hostile name
  298. @pytest.mark.parametrize("marker", ["Register-ObjectEvent", "ConvertTo-Json"])
  299. def test_the_powershell_watcher_escapes_names(marker):
  300. assert marker in one_block(HONEY, "powershell", "FileSystemWatcher")
  301. # --- track 2: the cloud sensor lessons (lessons 7 to 9) ------------------------------
  302. #
  303. # Nothing here touches a cloud, a real honeypot or the network. The lure script, the
  304. # invented sensor log, the jq reads, the lesson 5 detector on that log, the host firewall
  305. # file (syntax only, in a throwaway namespace) and the configuration snippet are pulled
  306. # out of the page text and run, and the pages' prose is held to the repository's rules.
  307. DOC_NETS = [ipaddress.ip_network(n) for n in ("192.0.2.0/24", "198.51.100.0/24", "203.0.113.0/24")]
  308. ALLOWED_LITERALS = {"0.0.0.0", "127.0.0.1"}
  309. IPV4 = re.compile(r"\b\d{1,3}(?:\.\d{1,3}){3}\b")
  310. MONEY = re.compile(r"\$\d+(?:\.\d+)?")
  311. def ip_problems(text: str) -> list[str]:
  312. """Every IPv4 literal that is neither a documentation address nor a loopback or wildcard one."""
  313. bad = []
  314. for m in IPV4.findall(text):
  315. if m in ALLOWED_LITERALS:
  316. continue
  317. try:
  318. addr = ipaddress.ip_address(m)
  319. except ValueError:
  320. bad.append(m)
  321. continue
  322. if not any(addr in net for net in DOC_NETS):
  323. bad.append(m)
  324. return bad
  325. def test_track2_pages_use_documentation_addresses_only_and_the_guard_bites():
  326. for page in TRACK2:
  327. assert ip_problems(page.read_text(encoding="utf-8")) == [], page.name
  328. assert ip_problems("connect to 8.8.8.8 and 203.0.113.7 and 10.0.0.1") == ["8.8.8.8", "10.0.0.1"]
  329. def test_track2_cost_figures_come_from_the_repository_price_files():
  330. prices = json.loads(COST_PRICES.read_text(encoding="utf-8"))
  331. droplet = prices["droplets"]["s-1vcpu-1gb"]
  332. assert droplet == 6, "the pages say $6; update them if the price file changes"
  333. assert "$5" in COST_MD.read_text(encoding="utf-8") # the log bucket the pages mention only as the design's option
  334. # $0.43 is the pages' own estimate (6 x 48 / 672), $11 is the design's option A, $0.01 and $0.00 are quoted provider rules
  335. allowed = {f"${droplet}", "$5", "$11", "$0.43", "$0.01", "$0.00"}
  336. assert round(droplet * 48 / 672, 2) == 0.43
  337. for page in TRACK2:
  338. figures = set(MONEY.findall(page.read_text(encoding="utf-8")))
  339. assert figures <= allowed, f"{page.name}: figures not in the price files: {sorted(figures - allowed)}"
  340. def test_track2_pages_keep_the_wording_rules():
  341. for page in TRACK2:
  342. text = page.read_text(encoding="utf-8")
  343. assert not re.search(r"\b(?:un)?paid\b", text, re.IGNORECASE), f"{page.name}: say 'your own bill', not 'paid'"
  344. assert "Unfamiliar word or acronym?" in text
  345. assert "## Claims register" in text and "Not verified, plainly" in text
  346. # the status banners say what was not run
  347. assert "never run" in WEEKEND.read_text(encoding="utf-8")
  348. assert "nothing built, nothing run" in ANATOMY.read_text(encoding="utf-8")
  349. assert "no real sensor log was read" in LOGS.read_text(encoding="utf-8")
  350. def test_the_hands_on_exercises_have_predict_do_check_and_undo():
  351. for page in (WEEKEND, LOGS):
  352. text = page.read_text(encoding="utf-8")
  353. for word in ("Predict", "Do", "Check", "Undo"):
  354. assert text.count(f"**{word}.**") >= 5, f"{page.name}: too few {word} steps"
  355. for marker in ("ConvertFrom-Json", "ConvertTo-Json -Compress", "Group-Object"):
  356. assert marker in LOGS.read_text(encoding="utf-8")
  357. def test_a_teardown_is_written_before_anything_is_built():
  358. text = WEEKEND.read_text(encoding="utf-8")
  359. assert text.index("## Teardown first") < text.index("## Exercise 2: create the firewalls and the server")
  360. assert "doctl compute droplet delete cowrie-lab --force" in text
  361. assert "not a spending cap" in text and "powered-off droplet is still billed" in text
  362. # the lure and the invented sensor log
  363. @pytest.fixture()
  364. def sensor_lab(tmp_path):
  365. (tmp_path / "make_lure.py").write_text(one_block(WEEKEND, "python", "Builds the lure file"))
  366. (tmp_path / "make_session.py").write_text(one_block(LOGS, "python", "Builds SYNTHETIC sensor events"))
  367. (tmp_path / "detect.py").write_text(one_block(SIEM, "python", "A toy detector"))
  368. assert run_py(tmp_path, "make_lure.py").returncode == 0
  369. made = run_py(tmp_path, "make_session.py")
  370. assert made.returncode == 0, made.stderr
  371. (tmp_path / "cowrie.json").write_text(made.stdout)
  372. return tmp_path
  373. def test_the_lure_is_invented_at_run_time_and_differs_each_time(tmp_path):
  374. script = one_block(WEEKEND, "python", "Builds the lure file")
  375. seen = set()
  376. for n in range(2):
  377. folder = tmp_path / str(n)
  378. folder.mkdir()
  379. (folder / "make_lure.py").write_text(script)
  380. assert run_py(folder, "make_lure.py").returncode == 0
  381. lines = (folder / "lure" / "deploy-notes-OLD.txt").read_text().splitlines()
  382. assert lines[0] == "old backup login, do not use"
  383. assert lines[1].startswith("user: svc-backup-") and lines[2].startswith("password: ")
  384. seen.add(lines[2])
  385. assert len(seen) == 2
  386. # no secret-shaped literal sits in the page: the password never appears there
  387. for pw in seen:
  388. assert pw.removeprefix("password: ") not in WEEKEND.read_text(encoding="utf-8")
  389. def test_the_sensor_log_has_28_lines_documentation_addresses_and_one_broken_line(sensor_lab):
  390. lines = (sensor_lab / "cowrie.json").read_text().splitlines()
  391. assert len(lines) == 28
  392. parsed = []
  393. for line in lines:
  394. try:
  395. parsed.append(json.loads(line))
  396. except ValueError:
  397. pass
  398. assert len(parsed) == 27
  399. for ev in parsed:
  400. assert any(ipaddress.ip_address(ev["src_ip"]) in net for net in DOC_NETS), ev["src_ip"]
  401. assert {"eventid", "session", "src_ip", "timestamp"} <= set(ev) # the shared attributes the Cowrie docs list
  402. def bash(folder: Path, script: str) -> subprocess.CompletedProcess:
  403. return subprocess.run(
  404. ["bash", "-c", script], cwd=folder, capture_output=True, text=True, timeout=60, check=False,
  405. env={"PATH": os.environ["PATH"], "HOME": str(folder)},
  406. )
  407. needs_jq = pytest.mark.skipif(shutil.which("jq") is None, reason="jq is not installed")
  408. @needs_jq
  409. def test_the_plain_jq_read_stops_at_the_broken_line_and_the_line_by_line_read_does_not(sensor_lab):
  410. naive = bash(sensor_lab, "jq . cowrie.json > /dev/null")
  411. assert naive.returncode != 0 and "parse error" in naive.stderr
  412. safe = bash(sensor_lab, "jq -rR 'fromjson? | objects | .eventid' cowrie.json | wc -l")
  413. assert safe.stdout.strip() == "27"
  414. @needs_jq
  415. def test_the_jq_reads_print_what_the_page_says(sensor_lab):
  416. by_type = bash(sensor_lab, one_block(LOGS, "bash", "# events by type"))
  417. assert by_type.returncode == 0, by_type.stderr
  418. counts = {line.split()[1]: int(line.split()[0]) for line in by_type.stdout.splitlines()}
  419. assert counts == {
  420. "cowrie.command.input": 8, "cowrie.login.failed": 7, "cowrie.session.connect": 4,
  421. "cowrie.session.closed": 4, "cowrie.login.success": 2,
  422. "cowrie.session.file_download.failed": 1, "cowrie.client.version": 1,
  423. }
  424. page_counts = {}
  425. for line in one_block(LOGS, "text", "cowrie.command.input").splitlines():
  426. n, name = line.split()
  427. page_counts[name] = int(n)
  428. assert page_counts == counts
  429. guesses = bash(sensor_lab, one_block(LOGS, "bash", "# failed logins per source"))
  430. assert guesses.returncode == 0, guesses.stderr
  431. per_source = {l.split()[1]: int(l.split()[0]) for l in guesses.stdout.splitlines() if re.fullmatch(r"\s*\d+ \d+\.\d+\.\d+\.\d+", l)}
  432. assert per_source == {"203.0.113.7": 5, "198.51.100.23": 1, "192.0.2.66": 1}
  433. @needs_jq
  434. def test_hostile_text_is_printed_inert_and_nothing_runs(sensor_lab):
  435. trap = sensor_lab / "pwned" # a unique path under the test folder, so a stray file elsewhere cannot hide a run
  436. log = sensor_lab / "cowrie.json"
  437. log.write_text(log.read_text().replace("/tmp/pwned", str(trap)))
  438. shown = bash(sensor_lab, one_block(LOGS, "bash", "# commands per session, made safe to print"))
  439. assert shown.returncode == 0, shown.stderr
  440. out = shown.stdout.splitlines()
  441. assert len(out) == 8 + 1 # eight commands, then the one raw line made visible by cat -v
  442. assert out[7] == f'd4d4d4d4 "x\\"; $(touch {trap}) \\u001b[2J {{\\"eventid\\": \\"cowrie.login.success\\"}}"'
  443. assert "\x1b" not in shown.stdout # no raw escape reached the output
  444. assert out[8] == f'x"; $(touch {trap}) ^[[2J {{"eventid": "cowrie.login.success"}}'
  445. assert not trap.exists() # the substitution in the field was never run
  446. @needs_jq
  447. def test_the_lure_touches_are_found_and_only_those(sensor_lab):
  448. hits = bash(sensor_lab, one_block(LOGS, "bash", "# lure file read"))
  449. assert hits.returncode == 0, hits.stderr
  450. rows = [json.loads(x) for x in hits.stdout.splitlines()]
  451. assert [(r.get("src_ip"), r.get("session")) for r in rows if "input" in r] == [("203.0.113.7", "a1a1a1a1")]
  452. cred = [r for r in rows if "eventid" in r]
  453. assert [(r["eventid"], r["src_ip"]) for r in cred] == [("cowrie.login.failed", "192.0.2.66")]
  454. # negative case: with no lure user in the log, the credential filter is silent
  455. (sensor_lab / "lure" / "deploy-notes-OLD.txt").write_text("user: svc-backup-nobody\npassword: x\n")
  456. quiet = bash(sensor_lab, one_block(LOGS, "bash", "# lure file read"))
  457. assert [json.loads(x) for x in quiet.stdout.splitlines() if '"eventid"' in x] == []
  458. def test_the_lesson_5_detector_alerts_on_the_sensor_log_as_the_page_shows(sensor_lab):
  459. proc = run_py(sensor_lab, "detect.py", "cowrie.json")
  460. assert proc.returncode == 0, proc.stderr
  461. got = alerts(proc)
  462. assert [(a["rule"], a["src_ip"]) for a in got] == [
  463. ("brute_force", "203.0.113.7"), ("success_after_brute_force", "203.0.113.7"),
  464. ]
  465. shown = one_block(LOGS, "text", '"rule": "brute_force"')
  466. assert [json.loads(x) for x in shown.splitlines() if x.startswith("{")] == got
  467. assert 'dropped: {"not_json": 1, "too_long": 0, "bad_shape": 0}' in shown
  468. assert 'dropped: {"not_json": 1, "too_long": 0, "bad_shape": 0}' in proc.stderr
  469. # the host firewall file and the Cowrie configuration snippet
  470. def firewall_text(addr: str = "203.0.113.10", port: str = "49152") -> str:
  471. return one_block(WEEKEND, "nft", "Host firewall for the sensor").replace("LEARNER_ADDR", addr).replace("MGMT_PORT", port)
  472. def chain(text: str, name: str) -> str:
  473. return re.search(rf"chain {name} \{{(.*?)^ \}}", text, re.MULTILINE | re.DOTALL).group(1)
  474. def test_the_host_firewall_drops_outgoing_traffic_and_allows_management_from_one_address_only():
  475. text = firewall_text()
  476. out = chain(text, "output")
  477. assert "policy drop" in out
  478. accepts = [l.strip() for l in out.splitlines() if "accept" in l]
  479. assert accepts == ['oif "lo" accept', "ct state established,related accept"] # nothing else leaves
  480. inp = chain(text, "input")
  481. assert "policy drop" in inp
  482. assert "ip saddr 203.0.113.10 tcp dport 49152 accept" in inp # one address, one port
  483. assert "tcp dport { 2222, 2223 } accept" in inp
  484. assert "redirect to :2222" in text and "redirect to :2223" in text
  485. assert "policy drop" in chain(text, "forward")
  486. @pytest.mark.skipif(shutil.which("nft") is None or shutil.which("unshare") is None, reason="nft or unshare missing")
  487. def test_the_host_firewall_file_is_valid_nft_syntax(tmp_path):
  488. (tmp_path / "run.nft").write_text(firewall_text())
  489. try:
  490. proc = subprocess.run(["unshare", "-rn", "nft", "-c", "-f", "run.nft"], cwd=tmp_path,
  491. capture_output=True, text=True, timeout=30, check=False)
  492. except OSError as exc:
  493. pytest.skip(f"cannot start a namespace: {exc}")
  494. if proc.returncode != 0 and ("Operation not permitted" in proc.stderr or "unshare" in proc.stderr):
  495. pytest.skip("user namespaces are not available here")
  496. assert proc.returncode == 0, proc.stderr
  497. # the check bites: a broken rule fails
  498. (tmp_path / "bad.nft").write_text(firewall_text().replace("policy drop", "polcy drop", 1))
  499. bad = subprocess.run(["unshare", "-rn", "nft", "-c", "-f", "bad.nft"], cwd=tmp_path,
  500. capture_output=True, text=True, timeout=30, check=False)
  501. assert bad.returncode != 0
  502. def test_the_cowrie_configuration_snippet_closes_what_the_lesson_says_it_closes():
  503. cfg = configparser.ConfigParser()
  504. cfg.read_string(one_block(WEEKEND, "ini", "forwarding = false"))
  505. assert cfg["ssh"]["forwarding"] == "false" # the default is true (direct-tcpip forwarding)
  506. assert cfg["telnet"]["enabled"] == "true" # the default is false; the lesson turns it on
  507. assert int(cfg["honeypot"]["download_limit_size"]) == 1048576
  508. assert "honeypot" not in cfg["honeypot"]["hostname"].lower()
  509. def test_the_page_commands_use_the_documented_cowrie_and_doctl_forms():
  510. weekend = WEEKEND.read_text(encoding="utf-8")
  511. for needle in (
  512. 'python -m pip install "cowrie==3.1.3"', "cowrie init", "cowrie start",
  513. "fsctl var/lib/cowrie/fs.pickle", "-o PubkeyAuthentication=no",
  514. "doctl compute firewall create --name cowrie-lab-core", "--tag-names cowrie-lab-core,cowrie-lab-build",
  515. "doctl compute firewall add-rules", "Port 49152", "PermitRootLogin no", "PasswordAuthentication no",
  516. ):
  517. assert needle in weekend, needle
  518. # the version pin is the one the pages say they read, and no unpinned install is shown
  519. assert "pip install cowrie\n" not in weekend and 'pip install cowrie"' not in weekend
  520. # --- track 3, lesson 10: the rule checker on the honeynet design page -----------------
  521. @pytest.fixture()
  522. def policy_lab(tmp_path):
  523. (tmp_path / "policy_check.py").write_text(one_block(DESIGN, "python", "Checks a firewall rule file"))
  524. (tmp_path / "rules.txt").write_text(one_block(DESIGN, "text", "# Internal-only honeynet rules"))
  525. (tmp_path / "expect.txt").write_text(one_block(DESIGN, "text", "# what must be true"))
  526. # the page's own commands make the three broken copies
  527. made = subprocess.run(
  528. ["bash", "-c", one_block(DESIGN, "bash", "broken1.txt")],
  529. cwd=tmp_path, capture_output=True, text=True, timeout=30, check=False,
  530. )
  531. assert made.returncode == 0, made.stderr
  532. return tmp_path
  533. def check(folder: Path, rules: str) -> subprocess.CompletedProcess:
  534. return run_py(folder, "policy_check.py", rules, "expect.txt")
  535. def verdicts(proc) -> list[str]:
  536. return [line.split()[0] for line in proc.stdout.splitlines()[:-1]]
  537. def test_the_designed_rules_satisfy_every_expectation(policy_lab):
  538. proc = check(policy_lab, "rules.txt")
  539. assert proc.returncode == 0, proc.stdout + proc.stderr
  540. assert proc.stdout.splitlines()[-1] == "11 of 11 expectations hold"
  541. # the page shows this run; the printed lines must be what the program prints
  542. shown = one_block(DESIGN, "text", "11 of 11 expectations hold").splitlines()
  543. assert shown[:-1] == proc.stdout.splitlines()
  544. assert shown[-1] == "exit=0"
  545. def test_each_broken_copy_fails_where_the_page_says(policy_lab):
  546. shown = one_block(DESIGN, "text", "== broken1")
  547. expected: list[str] = []
  548. for name in ("broken1", "broken2", "broken3"):
  549. proc = check(policy_lab, f"{name}.txt")
  550. assert proc.returncode == 1, name
  551. expected.append(f"== {name}")
  552. expected += [x for x in proc.stdout.splitlines() if x.startswith("FAIL") or " of 11 " in x]
  553. assert shown.splitlines() == expected
  554. # and the three fail for three different reasons, so they are not one test three times
  555. assert verdicts(check(policy_lab, "broken1.txt")).count("FAIL") == 4
  556. assert verdicts(check(policy_lab, "broken2.txt")).count("FAIL") == 2
  557. assert verdicts(check(policy_lab, "broken3.txt")).count("FAIL") == 1
  558. def test_order_matters_the_same_rules_in_the_wrong_order_fail(policy_lab):
  559. rules = (policy_lab / "rules.txt").read_text().splitlines()
  560. block = next(i for i, r in enumerate(rules) if r.split()[:3] == ["block", "lan", "honeynet"])
  561. allow = next(i for i, r in enumerate(rules) if r.split()[:3] == ["pass", "lan", "honeynet"])
  562. assert block < allow
  563. rules[block], rules[allow] = rules[allow], rules[block]
  564. (policy_lab / "swapped.txt").write_text("\n".join(rules) + "\n")
  565. assert check(policy_lab, "swapped.txt").returncode == 1
  566. def test_the_checker_has_no_default_allow_an_empty_rule_file_denies_everything(policy_lab):
  567. (policy_lab / "empty.txt").write_text("# nothing\n")
  568. proc = check(policy_lab, "empty.txt")
  569. assert proc.returncode == 1 # the three allow expectations fail
  570. assert [line.split()[0] for line in proc.stdout.splitlines()[:-1]].count("FAIL") == 3
  571. assert all("[default deny]" in line for line in proc.stdout.splitlines()[:-1])
  572. @pytest.mark.parametrize(
  573. "rule",
  574. [
  575. "pass lan honeynet tcp", # too few fields
  576. "allow lan honeynet tcp 22", # not pass or block
  577. "pass lan nowhere tcp 22", # unknown network name
  578. "pass lan honeynet icmp 22", # unsupported protocol
  579. "pass lan honeynet tcp 70000", # port out of range
  580. "pass lan honeynet tcp 9-2", # reversed range
  581. "pass lan honeynet tcp 22,x", # not a number
  582. "pass lan honeynet tcp 22 extra", # too many fields
  583. ],
  584. )
  585. def test_malformed_rules_are_refused_with_a_message_and_no_traceback(policy_lab, rule):
  586. (policy_lab / "bad.txt").write_text(rule + "\n")
  587. proc = check(policy_lab, "bad.txt")
  588. assert proc.returncode != 0
  589. assert "bad.txt:1" in proc.stderr and "Traceback" not in proc.stderr
  590. def test_malformed_expectations_and_oversized_files_are_refused(policy_lab):
  591. for line in ("allow 192.0.2.1 203.0.113.5 tcp 22", "maybe 192.0.2.1 203.0.113.5 tcp 22 x",
  592. "allow not-an-ip 203.0.113.5 tcp 22 x", "allow 192.0.2.1 203.0.113.5 icmp 22 x",
  593. "allow 192.0.2.1 203.0.113.5 tcp 99999 x"):
  594. (policy_lab / "e.txt").write_text(line + "\n")
  595. proc = run_py(policy_lab, "policy_check.py", "rules.txt", "e.txt")
  596. assert proc.returncode != 0 and "Traceback" not in proc.stderr, line
  597. (policy_lab / "big.txt").write_text("# x\n" * 40000) # 160,000 bytes
  598. proc = check(policy_lab, "big.txt")
  599. assert proc.returncode != 0 and "larger than" in proc.stderr
  600. (policy_lab / "many.txt").write_text("#\n" * 501)
  601. proc = check(policy_lab, "many.txt")
  602. assert proc.returncode != 0 and "more than 500 lines" in proc.stderr
  603. (policy_lab / "bin.txt").write_bytes(b"\xff\xfe\x00 pass lan honeynet tcp 22\n")
  604. assert "Traceback" not in check(policy_lab, "bin.txt").stderr
  605. def test_the_checker_names_only_documentation_addresses(policy_lab):
  606. names = re.search(r"NAMES = \{(.*?)\n\}", (policy_lab / "policy_check.py").read_text(), re.DOTALL).group(1)
  607. for cidr in re.findall(r'"(\d+\.\d+\.\d+\.\d+/\d+)"', names):
  608. net = ipaddress.ip_network(cidr)
  609. assert net == ipaddress.ip_network("0.0.0.0/0") or any(net.subnet_of(d) for d in DOC_NETS), cidr
  610. for line in (policy_lab / "expect.txt").read_text().splitlines():
  611. if line and not line.startswith("#"):
  612. for addr in line.split()[1:3]:
  613. assert any(ipaddress.ip_address(addr) in d for d in DOC_NETS), addr
  614. # --- track 3, lessons 10 and 11: the claims the pages make about T-Pot ----------------
  615. def page_addresses(path: Path) -> set[str]:
  616. text = re.sub(r"https?://\S+", "", path.read_text(encoding="utf-8")) # drop URLs and their version-like parts
  617. return set(re.findall(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", text))
  618. @pytest.mark.parametrize("page", [DESIGN, TPOT])
  619. def test_the_track_3_pages_use_documentation_addresses_only(page):
  620. for addr in page_addresses(page):
  621. assert addr == "0.0.0.0" or any(ipaddress.ip_address(addr) in d for d in DOC_NETS), f"{page.name}: {addr}"
  622. def test_the_pages_agree_on_the_management_ports_and_the_opt_out():
  623. design, tpot = DESIGN.read_text(encoding="utf-8"), TPOT.read_text(encoding="utf-8")
  624. for port in ("64294", "64295", "64297"):
  625. assert port in design and port in tpot
  626. # the rule table, the checker's rule file and the expectations all use the same ports
  627. assert "64294-64297" in one_block(DESIGN, "text", "# Internal-only honeynet rules")
  628. assert "# Ewsposter service" in tpot and "ewsposter" in tpot.lower()
  629. assert "mercilessly" in tpot # updates can undo the opt-out; the page must keep saying so
  630. def test_the_t_pot_page_keeps_its_unverified_banner_and_names_no_version_it_did_not_read():
  631. text = TPOT.read_text(encoding="utf-8")
  632. assert "T-Pot was not installed, run or tested" in text
  633. versions = set(re.findall(r"\b\d{2}\.\d{2}\.\d\b", text)) # the project's year.month.patch tags
  634. assert versions == {"24.04.1"}, versions
  635. assert "DMZ host" in DESIGN.read_text(encoding="utf-8") and "port forward" in DESIGN.read_text(encoding="utf-8").lower()
  636. def test_an_empty_expectation_list_cannot_pass_vacuously(policy_lab):
  637. (policy_lab / "none.txt").write_text("# only a comment\n")
  638. proc = run_py(policy_lab, "policy_check.py", "rules.txt", "none.txt")
  639. assert proc.returncode != 0 and "no expectations" in proc.stderr
  640. assert "0 of 0" not in proc.stdout
  641. def test_the_t_pot_install_command_pins_the_release_and_ssh_checks_host_keys():
  642. text = TPOT.read_text(encoding="utf-8")
  643. assert "git clone --branch 24.04.1" in text and "--exact-match" in text
  644. assert "StrictHostKeyChecking=no" not in text
  645. def test_a_missing_expectation_file_is_a_clean_error(policy_lab):
  646. proc = run_py(policy_lab, "policy_check.py", "rules.txt", "absent.txt")
  647. assert proc.returncode != 0 and "cannot read" in proc.stderr and "Traceback" not in proc.stderr