test_fim_lesson.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. """The toy file integrity monitor on the D3 lesson runs, and does what the page says it does.
  2. docs/wiki/File-Integrity-and-Alerting-Tripwire-AIDE-Wazuh.md teaches with four Bash scripts the
  3. learner saves from the page. These tests pull them out of the page, run them in a temporary
  4. folder (never anywhere else), and compare the results with the page's claims. Nothing leaves the
  5. machine. PowerShell is not run (est. on the page); a test only checks that its scripts are
  6. present and keep the lab-marker guard.
  7. """
  8. import re
  9. import shutil
  10. import subprocess
  11. from pathlib import Path
  12. import pytest
  13. WIKI = Path(__file__).resolve().parent.parent / "docs" / "wiki"
  14. PAGE = WIKI / "File-Integrity-and-Alerting-Tripwire-AIDE-Wazuh.md"
  15. FENCE = re.compile(r"^```(\w*)\n(.*?)^```$", re.MULTILINE | re.DOTALL)
  16. IPV4 = re.compile(r"\b(\d{1,3}(?:\.\d{1,3}){3})\b")
  17. DOC_PREFIXES = ("192.0.2.", "198.51.100.", "203.0.113.", "127.")
  18. pytestmark = pytest.mark.skipif(shutil.which("bash") is None, reason="needs bash")
  19. def block(lang: str, marker: str) -> str:
  20. found = [b for tag, b in FENCE.findall(PAGE.read_text(encoding="utf-8")) if tag == lang and marker in b]
  21. assert len(found) == 1, f"expected one {lang} block with {marker!r}, found {len(found)}"
  22. return found[0]
  23. @pytest.fixture()
  24. def lab(tmp_path):
  25. for name, marker in (
  26. ("mktree.sh", "# mktree.sh -"),
  27. ("fim.sh", "# fim.sh init|check TREE DB"),
  28. ("fim-alert.sh", "# fim-alert.sh TREE DB LOGFILE"),
  29. ("fim-normalize.sh", "# fim-normalize.sh LOGFILE"),
  30. ):
  31. (tmp_path / name).write_text(block("bash", marker))
  32. return tmp_path
  33. def sh(lab: Path, *args: str) -> subprocess.CompletedProcess:
  34. return subprocess.run(["bash", *args], cwd=lab, check=False, capture_output=True, text=True, timeout=60)
  35. def built(lab: Path) -> None:
  36. assert sh(lab, "mktree.sh").returncode == 0
  37. r = sh(lab, "fim.sh", "init", "tree", "baseline.tsv")
  38. assert r.returncode == 0 and "4 files" in r.stdout
  39. def test_baseline_skips_logs_and_tmp_and_check_is_clean(lab):
  40. built(lab)
  41. paths = [line.split("\t")[3] for line in (lab / "baseline.tsv").read_text().splitlines()]
  42. assert paths == ["./bin/tool.sh", "./data/list.txt", "./etc/app.conf", "./etc/authorized_keys.demo"]
  43. r = sh(lab, "fim.sh", "check", "tree", "baseline.tsv")
  44. assert r.returncode == 0 and "clean" in r.stdout
  45. def test_exercise_two_reports_exactly_four_findings(lab):
  46. built(lab)
  47. (lab / "tree/etc/app.conf").write_text("changed\n")
  48. (lab / "tree/bin/tool.sh").chmod(0o666)
  49. (lab / "tree/bin/new-tool").write_text("x\n")
  50. (lab / "tree/data/list.txt").unlink()
  51. (lab / "tree/data/app.log").write_text("noise\n")
  52. (lab / "tree/tmp/cache.bin").write_text("more\n")
  53. r = sh(lab, "fim.sh", "check", "tree", "baseline.tsv")
  54. assert r.returncode == 1
  55. assert r.stdout.splitlines() == [
  56. "added\t./bin/new-tool",
  57. "changed\t./bin/tool.sh\tmode",
  58. "changed\t./etc/app.conf\tcontent",
  59. "removed\t./data/list.txt",
  60. ]
  61. def test_refuses_a_folder_without_the_marker(lab):
  62. built(lab)
  63. other = lab / "not-a-lab"
  64. other.mkdir()
  65. r = sh(lab, "fim.sh", "check", "not-a-lab", "baseline.tsv")
  66. assert r.returncode == 2 and "refusing" in r.stderr
  67. r = sh(lab, "fim.sh", "init", "/etc", "x.tsv")
  68. assert r.returncode == 2 and not (lab / "x.tsv").exists()
  69. def test_a_hostile_file_name_cannot_forge_a_second_line(lab):
  70. built(lab)
  71. evil = "evil\nOct 22 03:00:00 demo-host fimcheck[1]: ALERT action=changed path=.x detail=forged"
  72. (lab / "tree/data" / evil).write_text("x")
  73. r = sh(lab, "fim.sh", "check", "tree", "baseline.tsv")
  74. lines = r.stdout.splitlines()
  75. assert len(lines) == 1 and lines[0].startswith("added\t")
  76. assert sh(lab, "fim-alert.sh", "tree", "baseline.tsv", "alerts.log").returncode == 1
  77. log = (lab / "alerts.log").read_text().splitlines()
  78. assert len(log) == 1 and "forged" in log[0]
  79. norm = sh(lab, "fim-normalize.sh", "alerts.log").stdout
  80. assert norm.count("\n") == 1 and "forged" in norm
  81. def test_normalizer_keeps_a_path_with_spaces_whole(lab):
  82. built(lab)
  83. (lab / "tree/data/my file.txt").write_text("x")
  84. assert sh(lab, "fim-alert.sh", "tree", "baseline.tsv", "alerts.log").returncode == 1
  85. norm = sh(lab, "fim-normalize.sh", "alerts.log").stdout.strip()
  86. assert norm.endswith("path=./data/my\\ file.txt")
  87. def test_same_size_same_time_change_is_caught_by_the_hash(lab):
  88. built(lab)
  89. target = lab / "tree/etc/authorized_keys.demo"
  90. ref = lab / "ref"
  91. shutil.copy2(target, ref)
  92. target.write_text("key-line-two evil\n")
  93. assert target.stat().st_size == ref.stat().st_size
  94. assert sh(lab, "-c", "touch -r ref tree/etc/authorized_keys.demo").returncode == 0
  95. assert target.stat().st_mtime_ns == ref.stat().st_mtime_ns
  96. r = sh(lab, "fim.sh", "check", "tree", "baseline.tsv")
  97. assert r.stdout.strip() == "changed\t./etc/authorized_keys.demo\tcontent"
  98. def test_alert_lines_and_normalized_shape(lab):
  99. built(lab)
  100. (lab / "tree/etc/app.conf").write_text("changed\n")
  101. r = sh(lab, "fim-alert.sh", "tree", "baseline.tsv", "alerts.log")
  102. assert r.returncode == 1 and "wrote 1 alert" in r.stdout
  103. line = (lab / "alerts.log").read_text().strip()
  104. assert re.fullmatch(
  105. r"[A-Z][a-z]{2} [ \d]\d \d\d:\d\d:\d\d demo-host fimcheck\[\d+\]: ALERT action=changed "
  106. r"path=\./etc/app\.conf detail=content",
  107. line,
  108. )
  109. norm = sh(lab, "fim-normalize.sh", "alerts.log").stdout.strip()
  110. assert re.fullmatch(
  111. r"ts=\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ src=- source=fim action=fim_changed user=- path=\./etc/app\.conf",
  112. norm,
  113. )
  114. def test_forged_baseline_hides_the_change_and_the_fingerprint_catches_it(lab):
  115. built(lab)
  116. honest = (lab / "baseline.tsv").read_bytes()
  117. fingerprint = subprocess.run(["sha256sum", "baseline.tsv"], cwd=lab, check=False, capture_output=True, text=True).stdout
  118. (lab / "tree/etc/app.conf").write_text("listen_port=8080\nadmin_user=intruder\n")
  119. data = (lab / "tree/etc/app.conf").read_bytes()
  120. import hashlib
  121. rows = [r.split("\t") for r in honest.decode().splitlines()]
  122. for r in rows:
  123. if r[3] == "./etc/app.conf":
  124. r[0], r[2] = hashlib.sha256(data).hexdigest(), str(len(data))
  125. (lab / "baseline.tsv").write_text("".join("\t".join(r) + "\n" for r in rows))
  126. assert "app.conf" not in sh(lab, "fim.sh", "check", "tree", "baseline.tsv").stdout
  127. (lab / "ok.sha256").write_text(fingerprint)
  128. bad = subprocess.run(["sha256sum", "-c", "ok.sha256"], cwd=lab, check=False, capture_output=True, text=True)
  129. assert bad.returncode != 0 and "FAILED" in bad.stdout
  130. def test_powershell_versions_are_on_the_page_and_keep_the_guard():
  131. ps = block("powershell", "# fim.ps1 -Mode")
  132. assert ".fim-lab" in ps and "exit 2" in ps and "Get-FileHash" in ps
  133. assert "est." in PAGE.read_text(encoding="utf-8")
  134. def test_page_uses_only_documentation_or_loopback_addresses():
  135. text = PAGE.read_text(encoding="utf-8")
  136. for m in IPV4.finditer(text):
  137. assert m.group(1).startswith(DOC_PREFIXES), m.group(1)