test_ids_ips_lesson.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. """The scripts on the IDS and IPS lesson run, and the page keeps the promises it makes.
  2. docs/wiki/IDS-and-IPS-Snort-and-Suricata.md teaches with a capture builder, two rules, a small
  3. summarizer and a container wrapper. These tests pull each file out of the page, build the
  4. capture in a temporary folder, parse it with the standard library, and check the summarizer
  5. against output files made up at run time. Suricata itself is run only if it is installed
  6. (the lesson runs it in a container; a test run does not pull images or touch a network).
  7. Everything is invented data on documentation addresses.
  8. """
  9. import hashlib
  10. import ipaddress
  11. import json
  12. import re
  13. import shutil
  14. import struct
  15. import subprocess
  16. import sys
  17. from pathlib import Path
  18. import pytest
  19. from wikitext import glossary_text, page_text
  20. WIKI = Path(__file__).resolve().parent.parent / "docs" / "wiki"
  21. PAGE = WIKI / "IDS-and-IPS-Snort-and-Suricata.md"
  22. # The lesson is a hub and four parts (issue #562): the checks read the hub and every part, as one text.
  23. PARTS = sorted(WIKI.glob("IDS-and-IPS-Snort-and-Suricata-Part-*.md"))
  24. FENCE = re.compile(r"^```(\w*)\n(.*?)^```$", re.MULTILINE | re.DOTALL)
  25. DOC_NETS = [ipaddress.ip_network(n) for n in ("192.0.2.0/24", "198.51.100.0/24", "203.0.113.0/24")]
  26. def hub_text() -> str:
  27. return page_text(PAGE)
  28. def text() -> str:
  29. assert len(PARTS) == 4, "the lesson has lost a part"
  30. return "\n".join(page_text(p) for p in (PAGE, *PARTS))
  31. def one_block(lang: str, marker: str) -> str:
  32. found = [b for tag, b in FENCE.findall(text()) if tag == lang and marker in b]
  33. assert len(found) == 1, f"expected one {lang} block with {marker!r}, found {len(found)}"
  34. return found[0]
  35. @pytest.fixture()
  36. def lab(tmp_path):
  37. (tmp_path / "make_pcap.py").write_text(one_block("python", "make_pcap.py - writes lab.pcap"))
  38. (tmp_path / "summarize.py").write_text(one_block("python", "summarize.py OUT_DIR"))
  39. (tmp_path / "local.rules").write_text(one_block("text", "local.rules - our own rules"))
  40. return tmp_path
  41. def run_py(folder: Path, script: str, *args: str):
  42. return subprocess.run([sys.executable, "-I", script, *args], cwd=folder, capture_output=True, text=True, check=False)
  43. def read_pcap(path: Path):
  44. data = path.read_bytes()
  45. magic, vmaj, vmin, _tz, _sig, _snap, link = struct.unpack("<IHHiIII", data[:24])
  46. assert (magic, vmaj, vmin, link) == (0xA1B2C3D4, 2, 4, 1)
  47. pos, frames = 24, []
  48. while pos < len(data):
  49. _s, _us, caplen, origlen = struct.unpack("<IIII", data[pos:pos + 16])
  50. assert caplen == origlen
  51. frames.append(data[pos + 16:pos + 16 + caplen])
  52. pos += 16 + caplen
  53. assert pos == len(data)
  54. return frames
  55. def csum(b: bytes) -> int:
  56. if len(b) % 2:
  57. b += b"\x00"
  58. total = sum(struct.unpack(f"!{len(b) // 2}H", b))
  59. while total >> 16:
  60. total = (total & 0xFFFF) + (total >> 16)
  61. return (~total) & 0xFFFF
  62. def dissect(frame: bytes):
  63. assert frame[12:14] == b"\x08\x00"
  64. ip = frame[14:]
  65. ihl = (ip[0] & 0x0F) * 4
  66. assert csum(ip[:ihl]) == 0, "bad IP header checksum"
  67. src, dst = ipaddress.ip_address(ip[12:16]), ipaddress.ip_address(ip[16:20])
  68. tcp = ip[ihl:]
  69. pseudo = ip[12:20] + struct.pack("!BBH", 0, 6, len(tcp))
  70. assert csum(pseudo + tcp) == 0, "bad TCP checksum"
  71. sport, dport = struct.unpack("!HH", tcp[:4])
  72. return src, dst, sport, dport, tcp[(tcp[12] >> 4) * 4:]
  73. # --- the capture ------------------------------------------------------------------------
  74. def test_the_capture_is_what_the_page_says(lab):
  75. done = run_py(lab, "make_pcap.py")
  76. assert done.returncode == 0 and "wrote lab.pcap with 140 packets" in done.stdout
  77. frames = read_pcap(lab / "lab.pcap")
  78. assert len(frames) == 140
  79. requests = []
  80. for f in frames:
  81. src, dst, _sp, _dp, payload = dissect(f)
  82. for ip in (src, dst):
  83. assert any(ip in net for net in DOC_NETS), ip
  84. if payload.startswith(b"GET "):
  85. requests.append((str(src), payload.split(b" ")[1].decode()))
  86. assert sorted(requests) == sorted(
  87. [("192.0.2.10", "/index.html"), ("192.0.2.10", "/cah-lab/probe?id=1")] + [("192.0.2.50", "/healthcheck")] * 12
  88. )
  89. def test_the_capture_is_reproducible(lab):
  90. run_py(lab, "make_pcap.py")
  91. first = hashlib.sha256((lab / "lab.pcap").read_bytes()).hexdigest()
  92. (lab / "lab.pcap").unlink()
  93. run_py(lab, "make_pcap.py")
  94. assert hashlib.sha256((lab / "lab.pcap").read_bytes()).hexdigest() == first
  95. def test_the_case_variant_holds_only_the_capital_letter_request(lab):
  96. done = run_py(lab, "make_pcap.py", "case")
  97. assert done.returncode == 0 and "wrote lab-case.pcap with 10 packets" in done.stdout
  98. paths = [dissect(f)[4].split(b" ")[1] for f in read_pcap(lab / "lab-case.pcap") if dissect(f)[4].startswith(b"GET ")]
  99. assert paths == [b"/CAH-LAB/PROBE?id=1"]
  100. # --- the rules --------------------------------------------------------------------------
  101. def test_the_rules_use_the_local_sid_range_and_are_well_formed(lab):
  102. rules = [r for r in (lab / "local.rules").read_text().splitlines() if r and not r.startswith("#")]
  103. assert len(rules) == 2
  104. sids = []
  105. for rule in rules:
  106. assert re.match(r"^alert http any any -> any any \(.*\)$", rule)
  107. sid = int(re.search(r"\bsid:(\d+);", rule).group(1))
  108. assert 1000000 <= sid <= 1999999
  109. assert re.search(r"\brev:\d+;", rule) and re.search(r'msg:"[^";\\]+";', rule)
  110. sids.append(sid)
  111. assert len(set(sids)) == len(sids)
  112. def test_the_page_uses_only_documentation_and_loopback_addresses():
  113. # the lesson shows a few illustrative lines from Suricata's documentation; none may hold a real-looking host
  114. for m in re.finditer(r"\b(\d{1,3}(?:\.\d{1,3}){3})(?:/\d+)?\b", text()):
  115. ip = ipaddress.ip_address(m.group(1))
  116. ok = ip.is_loopback or any(ip in net for net in DOC_NETS) or m.group(1) in {"0.0.0.0", "3.12.4.0"} # 3.12.4.0 is a Snort version
  117. assert ok, f"{m.group(0)} is not a documentation or loopback address"
  118. # --- the summarizer ----------------------------------------------------------------------
  119. def fake_run(folder: Path, alerts: list[tuple[int, str, str]], rules_failed: int = 0, junk: bool = False) -> Path:
  120. out = folder / "fake_out"
  121. out.mkdir(exist_ok=True)
  122. lines = []
  123. for sid, msg, src in alerts:
  124. lines.append(json.dumps({"event_type": "alert", "src_ip": src, "alert": {"signature_id": sid, "signature": msg}}))
  125. lines.append(json.dumps({"event_type": "stats", "stats": {"detect": {"engines": [
  126. {"rules_loaded": 2 - rules_failed, "rules_failed": rules_failed}]}}}))
  127. if junk:
  128. lines.append("{not json; $(touch pwned)")
  129. (out / "eve.json").write_text("\n".join(lines) + "\n")
  130. (out / "stats.log").write_text(
  131. f"Counter | TM Name | Value\ndecoder.pkts | Total | 140\ndetect.alert | Total | {len(alerts)}\n")
  132. return out
  133. def test_the_summary_counts_by_rule_and_source(lab):
  134. out = fake_run(lab, [(1000001, "probe", "192.0.2.10")] + [(1000002, "health", "192.0.2.50")] * 3)
  135. done = run_py(lab, "summarize.py", str(out))
  136. assert done.returncode == 0
  137. assert "rules loaded: 2 rules FAILED to load: 0" in done.stdout
  138. assert "sid 1000001 1 probe" in done.stdout and "sid 1000002 3 health" in done.stdout
  139. assert "decoder.pkts" in done.stdout and "(not present)" in done.stdout
  140. def test_the_canary_fails_when_an_expected_rule_is_silent(lab):
  141. out = fake_run(lab, [(1000002, "health", "192.0.2.50")])
  142. done = run_py(lab, "summarize.py", str(out), "--expect", "1000001", "1000002")
  143. assert done.returncode == 1 and "MISSING: rule 1000001 did not alert" in done.stdout and "canary: FAILED" in done.stdout
  144. ok = run_py(lab, "summarize.py", str(out), "--expect", "1000002")
  145. assert ok.returncode == 0 and "canary: ok" in ok.stdout
  146. def test_a_failed_rule_load_is_reported_even_when_alerts_look_fine(lab):
  147. out = fake_run(lab, [(1000002, "health", "192.0.2.50")], rules_failed=1)
  148. assert "rules FAILED to load: 1" in run_py(lab, "summarize.py", str(out)).stdout
  149. def test_a_hostile_line_stays_data(lab):
  150. out = fake_run(lab, [(1000001, "probe", "192.0.2.10")], junk=True)
  151. done = run_py(lab, "summarize.py", str(out))
  152. assert done.returncode == 0 and "unparseable lines skipped: 1" in done.stdout
  153. assert not (lab / "pwned").exists()
  154. # --- the wrapper ---------------------------------------------------------------------------
  155. def test_the_wrapper_keeps_the_container_small():
  156. for lang, marker in (("bash", "run.sh RULES_FILE"), ("powershell", "run.ps1 RULES_FILE")):
  157. body = one_block(lang, marker)
  158. assert "--network none" in body and "--cap-drop all" in body
  159. assert "docker.sock" not in body and "podman.sock" not in body and "--privileged" not in body
  160. assert "jasonish/suricata:8.0.7" in body and ":latest" not in body
  161. assert "RUNTIME" in body and "IMAGE" in body
  162. assert "sudo" not in body
  163. assert not re.search(r"-v\s+\S*(\$HOME|~|/home|/:)", one_block("bash", "run.sh RULES_FILE").replace("$PWD", ""))
  164. @pytest.mark.skipif(
  165. not (shutil.which("suricata") and Path("/etc/suricata/suricata.yaml").is_file()),
  166. reason="no suricata with /etc/suricata/suricata.yaml on this machine",
  167. )
  168. def test_suricata_alerts_on_the_capture_as_the_page_says(lab):
  169. run_py(lab, "make_pcap.py")
  170. out = lab / "out"
  171. out.mkdir()
  172. done = subprocess.run(
  173. ["suricata", "-c", "/etc/suricata/suricata.yaml", "-r", "lab.pcap", "-S", "local.rules", "-l", "out", "-k", "none"],
  174. cwd=lab, capture_output=True, text=True, check=False)
  175. assert done.returncode == 0, done.stderr
  176. summary = run_py(lab, "summarize.py", "out", "--expect", "1000001", "1000002")
  177. assert summary.returncode == 0 and "sid 1000002 12" in summary.stdout
  178. # --- the page keeps its promises -----------------------------------------------------------
  179. def test_the_banner_says_what_was_not_run():
  180. banner = text().split("> **Status:", 1)[1].split("\n", 1)[0]
  181. for word in ("PowerShell", "Snort", "not run", "Docker", "Wazuh", "pfSense", "OPNsense"):
  182. assert word in banner or word.lower() in banner.lower(), word
  183. def test_the_lesson_has_the_loop_and_the_flip_and_the_threat_model():
  184. page = text()
  185. for word in ("**Build.**", "**Break.**", "**Detect.**", "**Evade.**", "**Defend.**", "### Flip the board",
  186. "## Threat model of the IDS itself", "## Claims register"):
  187. assert word in page, word
  188. def test_every_exercise_has_predict_do_check_and_undo():
  189. sections = re.split(r"^### Exercise \d+[^\n]*\n", text(), flags=re.MULTILINE)[1:]
  190. assert len(sections) == 8
  191. for number, body in enumerate(sections, 1):
  192. body = re.split(r"\n## |\n### ", body, maxsplit=1)[0]
  193. for part in ("**Predict.**", "**Do", "**Check.**", "**Undo.**"):
  194. assert part in body, f"exercise {number} lacks {part}"
  195. def test_sibling_lessons_are_linked_by_exact_name_but_not_from_the_next_line():
  196. page = text()
  197. for name in ("Packet-Filters-Compared-iptables-nftables-ufw-pf", "File-Integrity-and-Alerting-Tripwire-AIDE-Wazuh",
  198. "Rate-Limiting-at-Every-Layer"):
  199. assert f"]({name}.md" in page, name
  200. nxt = [line for line in hub_text().splitlines() if line.startswith("Next:")]
  201. assert len(nxt) == 1 and "Packet-Filters" not in nxt[0] and "File-Integrity" not in nxt[0] and "Rate-Limiting" not in nxt[0]
  202. # The sibling lessons are in the wiki, so the old 'may not resolve until it merges' caveat is gone (issue #444).
  203. assert "may not resolve until" not in page
  204. def test_the_lesson_is_linked_from_the_navigation_and_the_glossary_has_the_new_terms():
  205. assert "IDS-and-IPS-Snort-and-Suricata.md" in (WIKI / "_Sidebar.md").read_text()
  206. assert "IDS-and-IPS-Snort-and-Suricata.md" in (WIKI / "Reading-Order.md").read_text()
  207. glossary = glossary_text(WIKI)
  208. for term in ("EVE JSON", "NFQUEUE", "Network tap", "Signature (IDS)", "Snort", "SPAN port", "Suricata"):
  209. assert f"| **{term}** |" in glossary, term