test_ids_ips_lesson.py 12 KB

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