test_logs_siem_lesson.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. """The scripts on the logs, SIEM and detection lesson run, and print what the page says they print.
  2. docs/wiki/Logs-SIEM-and-Detection-Basics.md teaches with Bash scripts the learner pastes into
  3. files and with PowerShell twins of them. A lesson whose script is broken, or whose printed
  4. output has drifted from what the script prints, teaches the wrong thing. These tests pull each
  5. script out of the page, run the Bash ones in a temporary folder, and compare with the page.
  6. The PowerShell twins are not run for their output; a parity test checks that their invented
  7. data is the same data, and a parse check runs wherever pwsh exists.
  8. Everything is invented data on localhost. The checks collect loosely (any fenced block) and
  9. assert strictly (exactly one block per marker), and each has a negative case.
  10. """
  11. import ipaddress
  12. import re
  13. import shutil
  14. import subprocess
  15. from pathlib import Path
  16. import pytest
  17. PAGE = Path(__file__).resolve().parent.parent / "docs" / "wiki" / "Logs-SIEM-and-Detection-Basics.md"
  18. FENCE = re.compile(r"^```(\w*)\n(.*?)^```$", re.MULTILINE | re.DOTALL)
  19. DOC_NETS = [ipaddress.ip_network(n) for n in ("192.0.2.0/24", "198.51.100.0/24", "203.0.113.0/24")]
  20. def text() -> str:
  21. return PAGE.read_text(encoding="utf-8")
  22. def blocks(lang: str) -> list[str]:
  23. return [body for tag, body in FENCE.findall(text()) if tag == lang]
  24. def one_block(lang: str, marker: str) -> str:
  25. found = [b for b in blocks(lang) if marker in b]
  26. assert len(found) == 1, f"expected one {lang} block with {marker!r}, found {len(found)}"
  27. return found[0]
  28. def sh(folder: Path, command: str, stdin: str | None = None) -> subprocess.CompletedProcess:
  29. return subprocess.run(
  30. ["bash", "-c", command], cwd=folder, input=stdin, capture_output=True, text=True, timeout=60, check=False
  31. )
  32. @pytest.fixture()
  33. def lab(tmp_path):
  34. for name, marker in (
  35. ("mklogs.sh", "mklogs.sh - builds"),
  36. ("normalize.sh", "normalize.sh [WEB_CLOCK"),
  37. ("detect.sh", "detect.sh THRESHOLD"),
  38. ("mkbaseline.sh", "mkbaseline.sh - builds"),
  39. ):
  40. (tmp_path / name).write_text(one_block("bash", marker))
  41. made = sh(tmp_path, "bash mklogs.sh")
  42. assert made.returncode == 0, made.stderr
  43. return tmp_path
  44. def run(lab: Path, command: str) -> str:
  45. done = sh(lab, command)
  46. assert done.returncode == 0, done.stderr
  47. return done.stdout
  48. def on_page(output: str) -> None:
  49. assert output.strip() in text(), f"the page does not show this output:\n{output}"
  50. # --- the data ---------------------------------------------------------------------------
  51. def test_the_setup_output_is_what_the_page_shows(lab):
  52. on_page("wrote auth.log (17 lines) and access.log (6 lines)")
  53. assert (lab / "auth.log").read_text().count("\n") == 17
  54. assert (lab / "access.log").read_text().count("\n") == 6
  55. def test_every_address_in_the_fake_logs_is_a_documentation_address(lab):
  56. found = 0
  57. for name in ("auth.log", "access.log"):
  58. for addr in re.findall(r"\b\d{1,3}(?:\.\d{1,3}){3}\b", (lab / name).read_text()):
  59. found += 1
  60. assert any(ipaddress.ip_address(addr) in net for net in DOC_NETS), addr
  61. assert found > 20
  62. def test_the_powershell_twin_builds_the_same_data_as_the_bash_script(lab):
  63. ps = one_block("powershell", "mklogs.ps1 - builds")
  64. here = re.findall(r"= @'\n(.*?)\n'@", ps, re.DOTALL)
  65. assert len(here) == 2
  66. assert here[0] == (lab / "auth.log").read_text().rstrip("\n")
  67. assert here[1] == (lab / "access.log").read_text().rstrip("\n")
  68. def test_the_baseline_twin_uses_the_same_arithmetic():
  69. sh_text = one_block("bash", "mkbaseline.sh - builds")
  70. ps_text = one_block("powershell", "mkbaseline.ps1 - SYNTHETIC")
  71. assert "8 + (d * 5) % 9" in sh_text and "d * 7 % 60" in sh_text
  72. assert "8 + ($d * 5) % 9" in ps_text and "$d * 7 % 60" in ps_text
  73. # --- reading and finding (exercises 1 to 4) ----------------------------------------------
  74. def test_the_failed_login_counts_on_the_page_are_right(lab):
  75. loose = run(lab, "grep -cE 'Failed password for [^ ]+ from' auth.log").strip()
  76. wide = run(lab, "grep -cE 'Failed password for (invalid user )?[^ ]+ from [0-9.]+' auth.log").strip()
  77. per_source = run(
  78. lab, "grep -oE 'Failed password.* from [0-9.]+' auth.log | awk '{print $NF}' | sort | uniq -c | sort -rn"
  79. )
  80. assert (loose, wide) == ("8", "12") # the first pattern misses the invalid-user lines
  81. on_page(f"{loose}\n{wide}\n{per_source.rstrip()}")
  82. def test_normalized_lines_interleave_the_two_sources_and_skip_the_cron_line(lab):
  83. out = run(lab, "bash normalize.sh")
  84. assert "CRON" not in out and "cron" not in out
  85. mine = [ln for ln in out.splitlines() if "src=203.0.113.9 " in ln]
  86. assert len(mine) == 9
  87. assert [ln.split(" ")[2] for ln in mine[:3]] == ["source=sshd", "source=web", "source=sshd"]
  88. on_page("\n".join(out.splitlines()[:4]))
  89. on_page("\n".join(" ".join([ln.split(" ")[0], ln.split(" ")[2]]) for ln in mine))
  90. assert "auth.log:6\naccess.log:3" in text()
  91. def test_a_skewed_web_clock_reorders_the_story(lab):
  92. out = run(lab, "bash normalize.sh 420 | head -9 | cut -d' ' -f1,3,4")
  93. on_page(out)
  94. assert out.splitlines()[6].startswith("ts=2026-10-22T03:21:10Z source=web")
  95. # a large negative offset must wrap inside the day instead of printing a negative time
  96. early = run(lab, "bash normalize.sh -4000 | grep source=web | head -1")
  97. assert re.search(r"ts=2026-10-22T\d\d:\d\d:\d\dZ", early) and "T-" not in early
  98. # --- the rule (exercises 5 to 7) ---------------------------------------------------------
  99. def test_the_rule_fires_for_the_guesser_and_for_bob(lab):
  100. out = run(lab, "bash normalize.sh | bash detect.sh 5 60")
  101. assert out.count("ALERT brute_force") == 2
  102. assert "src=203.0.113.9 failures=5 window=60s at=2026-10-22T03:14:33Z" in out
  103. assert "src=192.0.2.10 failures=5" in out
  104. assert "198.51.100.23" not in out # one failure is not five
  105. on_page(out + "exit=0")
  106. def test_the_threshold_table_on_the_page_is_what_the_rule_does(lab):
  107. out = run(
  108. lab,
  109. 'for n in 3 4 5 6 7; do echo "threshold=$n alerts=$(bash normalize.sh | bash detect.sh $n 60 | wc -l)"; done',
  110. )
  111. on_page(out)
  112. def test_the_boundary_four_stays_quiet_and_five_fires(lab):
  113. def alerts(count: int) -> int:
  114. stdin = "".join(
  115. f"ts=2026-10-22T10:00:{i:02d}Z src=198.51.100.1 source=sshd action=login_failed user=x\n"
  116. for i in range(count)
  117. )
  118. done = sh(lab, "bash detect.sh 5 60", stdin)
  119. assert done.returncode == 0, done.stderr
  120. return done.stdout.count("ALERT")
  121. assert alerts(4) == 0
  122. assert alerts(5) == 1
  123. assert alerts(12) == 1 # the quiet period stops a repeat inside the window
  124. def test_failures_older_than_the_window_do_not_count(lab):
  125. stdin = "".join(
  126. f"ts=2026-10-22T10:{m:02d}:00Z src=198.51.100.1 source=sshd action=login_failed user=x\n" for m in range(5)
  127. )
  128. assert sh(lab, "bash detect.sh 5 60", stdin).stdout == "" # one a minute: never five inside 60 s
  129. assert sh(lab, "bash detect.sh 5 600", stdin).stdout.count("ALERT") == 1
  130. def test_break_evade_and_defend_do_what_the_page_says(lab):
  131. break_cmd = one_block("bash", "198.51.100.88")
  132. evade_cmd = one_block("bash", "203.0.113.77")
  133. out = run(lab, break_cmd) # the page block appends the lines, then runs the rule
  134. assert "198.51.100.88" not in out and out.count("ALERT") == 2
  135. assert "198.51.100.88" in run(lab, "bash normalize.sh | bash detect.sh 4 60")
  136. out = run(lab, evade_cmd)
  137. assert "203.0.113.77" not in out and out.count("ALERT") == 2
  138. wide = run(lab, "bash normalize.sh | bash detect.sh 5 7200")
  139. assert "src=203.0.113.77 failures=5 window=7200s at=2026-10-22T03:20:00Z" in wide
  140. assert "198.51.100.88" not in wide # four guesses still slip under five
  141. on_page(wide)
  142. def test_the_baseline_is_learned_and_the_off_hours_rule_fires(lab):
  143. learned = run(lab, "bash mkbaseline.sh")
  144. assert (lab / "hours.txt").read_text() == "alice 8 17\n"
  145. out = run(lab, "bash normalize.sh | bash detect.sh 5 60 hours.txt")
  146. assert out.count("off_hours") == 1 and "src=203.0.113.50" in out
  147. assert "198.51.100.7" not in out and "user=bob" not in out
  148. on_page(learned.rstrip() + "\n" + out.rstrip())
  149. # --- hostile and odd input ----------------------------------------------------------------
  150. def test_a_hostile_username_stays_data(lab):
  151. evil = "$(touch_pwned)_`touch_pwned2`_;touch_pwned3"
  152. (lab / "auth.log").write_text(
  153. f"Oct 22 03:00:00 demo-host sshd[1]: Failed password for {evil} from 203.0.113.1 port 1 ssh2\n"
  154. )
  155. (lab / "access.log").write_text("")
  156. out = run(lab, "bash normalize.sh | bash detect.sh 1 60")
  157. assert "ALERT brute_force" in out
  158. assert not list(lab.glob("pwned*"))
  159. def test_input_spanning_two_days_is_refused_not_miscounted(lab):
  160. stdin = (
  161. "ts=2026-10-22T23:59:00Z src=198.51.100.1 source=sshd action=login_failed user=x\n"
  162. "ts=2026-10-23T00:00:30Z src=198.51.100.1 source=sshd action=login_failed user=x\n"
  163. )
  164. done = sh(lab, "bash detect.sh 2 60", stdin)
  165. assert done.returncode == 2 and "more than one day" in done.stderr
  166. def test_lines_the_normalizer_does_not_understand_are_dropped_not_fatal(lab):
  167. (lab / "auth.log").write_text("garbage\n\nOct 22 03:00:00 demo-host sshd[1]: something else\n")
  168. (lab / "access.log").write_text("not a web line\n")
  169. done = sh(lab, "bash normalize.sh")
  170. assert done.returncode == 0 and done.stdout == ""
  171. # --- the page keeps its promises ----------------------------------------------------------
  172. def test_the_banner_says_what_was_not_run():
  173. banner = text().split("> **Status:", 1)[1].split("\n", 1)[0]
  174. assert "PowerShell" in banner and "not run" in banner.lower()
  175. assert "Wazuh" in banner and "applied" in banner
  176. def test_the_powershell_detector_is_an_advanced_script_that_takes_pipeline_input():
  177. ps = one_block("powershell", "detect.ps1 [-Threshold")
  178. assert re.search(r"\[CmdletBinding\(\)\]\s*param\(", ps) and "ValueFromPipeline" in ps
  179. def test_the_lesson_has_the_loop_and_the_flip():
  180. page = text()
  181. for word in ("**Build.**", "**Break.**", "**Detect.**", "**Evade.**", "**Defend.**", "### Flip the board"):
  182. assert word in page, word
  183. def test_every_exercise_has_predict_do_check_and_undo():
  184. sections = re.split(r"^### Exercise \d+:", text(), flags=re.MULTILINE)[1:]
  185. assert len(sections) == 8
  186. for number, body in enumerate(sections, 1):
  187. body = body.split("\n## ", 1)[0]
  188. for part in ("**Predict.**", "**Do (Bash", "**Check.**", "**Undo.**"):
  189. assert part in body, f"exercise {number} lacks {part}"
  190. @pytest.mark.skipif(not shutil.which("pwsh"), reason="no PowerShell on this machine")
  191. def test_the_powershell_scripts_parse(tmp_path):
  192. for marker in ("mklogs.ps1 - builds", "normalize.ps1 [-WebOffset", "detect.ps1 [-Threshold", "mkbaseline.ps1 - SYNTHETIC"):
  193. path = tmp_path / marker.split(" ")[0]
  194. path.write_text(one_block("powershell", marker))
  195. cmd = (
  196. "$e=$null;[void][System.Management.Automation.Language.Parser]::ParseFile("
  197. f"'{path}',[ref]$null,[ref]$e);if($e){{$e;exit 1}}"
  198. )
  199. done = subprocess.run(["pwsh", "-NoProfile", "-Command", cmd], capture_output=True, text=True, check=False)
  200. assert done.returncode == 0, done.stdout + done.stderr