test_security_tools_lesson.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. """The toy lab on the security tools lesson runs, and does what the page says it does.
  2. docs/wiki/Security-Tools-Basics-Nmap-OpenVAS-Burp-Metasploit.md teaches with three Python
  3. scripts the learner saves from the page: a toy three-part system, a toy scan detector and a toy
  4. intercepting proxy. These tests pull each script out of the page, run it on loopback only, and
  5. compare it with the page's claims. Nothing leaves the machine; the only addresses used are
  6. 127.x.x.x. Nmap is used only if it is installed, against that same loopback lab.
  7. """
  8. import errno
  9. import random
  10. import re
  11. import shutil
  12. import socket
  13. import subprocess
  14. import sys
  15. import time
  16. import urllib.error
  17. import urllib.request
  18. from pathlib import Path
  19. import pytest
  20. WIKI = Path(__file__).resolve().parent.parent / "docs" / "wiki"
  21. PAGE = WIKI / "Security-Tools-Basics-Nmap-OpenVAS-Burp-Metasploit.md"
  22. FENCE = re.compile(r"^```(\w*)\n(.*?)^```$", re.MULTILINE | re.DOTALL)
  23. IPV4 = re.compile(r"\b(\d{1,3}(?:\.\d{1,3}){3})\b")
  24. def one_block(marker: str) -> str:
  25. found = [b for tag, b in FENCE.findall(PAGE.read_text(encoding="utf-8")) if tag == "python" and marker in b]
  26. assert len(found) == 1, f"expected one python block with {marker!r}, found {len(found)}"
  27. return found[0]
  28. def free_base() -> int:
  29. """A random base port whose next two ports are free on 127.0.0.1 (and 127.0.0.2/3 where they exist).
  30. Regression note (issue #241): this used to scan upward from a fixed 20100, so every parallel copy
  31. of the file, and every other agent running the suite, chose the same ports; the loser's lab died
  32. with "address in use" (or the proxy test talked to someone else's listener). A random start spreads
  33. the choices; launch_lab() and launch_proxy() below still retry, because a probe can never be
  34. atomic with the bind that follows it.
  35. """
  36. rng = random.SystemRandom()
  37. for _ in range(200):
  38. base = rng.randrange(21000, 31990)
  39. socks = []
  40. try:
  41. for host in ("127.0.0.1", "127.0.0.2", "127.0.0.3"):
  42. for off in range(3):
  43. s = socket.socket()
  44. socks.append(s)
  45. try:
  46. s.bind((host, base + off))
  47. except OSError as exc:
  48. if exc.errno == errno.EADDRNOTAVAIL and host != "127.0.0.1":
  49. continue # this system has no 127.0.0.2/3: fine
  50. raise
  51. return base
  52. except OSError:
  53. continue
  54. finally:
  55. for s in socks:
  56. s.close()
  57. pytest.skip("no free loopback ports")
  58. def wait_for(host: str, port: int) -> None:
  59. for _ in range(100):
  60. try:
  61. socket.create_connection((host, port), timeout=0.2).close()
  62. return
  63. except OSError:
  64. time.sleep(0.1)
  65. raise AssertionError(f"{host}:{port} never came up")
  66. @pytest.fixture()
  67. def scripts(tmp_path):
  68. (tmp_path / "lab.py").write_text(one_block("a toy three-part system"))
  69. (tmp_path / "scan_detect.py").write_text(one_block("toy detector"))
  70. (tmp_path / "proxy.py").write_text(one_block("toy intercepting proxy"))
  71. return tmp_path
  72. def stop(proc: subprocess.Popen) -> None:
  73. proc.terminate()
  74. try:
  75. proc.wait(timeout=10)
  76. except subprocess.TimeoutExpired:
  77. proc.kill()
  78. proc.wait(timeout=10)
  79. def launch_lab(folder: Path, *extra: str) -> tuple[subprocess.Popen, int]:
  80. """Start lab.py on a free base port; if it dies at startup (a port was taken meanwhile), pick again."""
  81. for _ in range(10):
  82. base = free_base()
  83. proc = subprocess.Popen(
  84. [sys.executable, "-I", "lab.py", "--base-port", str(base), *extra],
  85. cwd=folder, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
  86. )
  87. lines = [proc.stdout.readline() for _ in range(3)]
  88. if all("listening on" in x for x in lines):
  89. return proc, base
  90. stop(proc)
  91. raise AssertionError("lab.py could not start on any port tried")
  92. def launch_proxy(folder: Path) -> tuple[subprocess.Popen, int]:
  93. """Start proxy.py and prove it is OUR proxy answering (a refused target gives its 403), not a stranger."""
  94. for _ in range(10):
  95. pbase = free_base()
  96. proc = subprocess.Popen([sys.executable, "-I", "proxy.py", str(pbase)], cwd=folder,
  97. stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
  98. for _ in range(100):
  99. if proc.poll() is not None:
  100. break
  101. try:
  102. with socket.create_connection(("127.0.0.1", pbase), timeout=0.5) as raw:
  103. raw.sendall(b"GET http://203.0.113.9/ HTTP/1.0\r\n\r\n")
  104. if b" 403 " in raw.recv(200).split(b"\r\n")[0] and proc.poll() is None:
  105. return proc, pbase
  106. except OSError:
  107. pass
  108. time.sleep(0.1)
  109. stop(proc)
  110. raise AssertionError("proxy.py could not start on any port tried")
  111. def get(url: str):
  112. try:
  113. with urllib.request.urlopen(url, timeout=5) as r:
  114. return r.status, dict(r.headers), r.read()
  115. except urllib.error.HTTPError as e:
  116. return e.code, dict(e.headers), e.read()
  117. def can_connect(host: str, port: int) -> bool:
  118. try:
  119. socket.create_connection((host, port), timeout=0.5).close()
  120. return True
  121. except OSError:
  122. return False
  123. @pytest.fixture()
  124. def lab(scripts):
  125. proc, base = launch_lab(scripts)
  126. try: # setup and yield share one try, so a failed wait still stops the process
  127. wait_for("127.0.0.1", base + 2)
  128. # Regression note (issue #226): wait_for() itself connects to the db port, and lab.py logs that
  129. # CONN line from its own server thread, a moment AFTER the connect returns. A test that emptied
  130. # lab.log right away could have the fixture's late line land after the truncation and count it as
  131. # a scan connection (one extra dport=<base+2>; about 1 run in 15 alone, about half under load).
  132. # So the fixture does not hand over until that line exists, and tests then clear the log safely.
  133. deadline = time.time() + 10
  134. log = scripts / "lab.log"
  135. while time.time() < deadline:
  136. if log.exists() and f"CONN db src=127.0.0.1 dport={base + 2}" in log.read_text():
  137. break
  138. time.sleep(0.05)
  139. else:
  140. raise AssertionError("the fixture's own probe was never logged")
  141. yield scripts, base
  142. finally:
  143. stop(proc)
  144. def test_default_build_is_flat_leaky_and_loopback_only(lab):
  145. _folder, base = lab
  146. assert all(can_connect("127.0.0.1", base + i) for i in range(3)) # one address: no segmentation
  147. status, headers, _body = get(f"http://127.0.0.1:{base}/")
  148. assert status == 200 and headers["Server"].startswith("LabHTTP/1.0 build-")
  149. assert get(f"http://127.0.0.1:{base}/admin/")[0] == 200 # the debug page the page tells you to find
  150. assert get(f"http://127.0.0.1:{base}/nope")[0] == 404
  151. with socket.create_connection(("127.0.0.1", base + 2), timeout=2) as s:
  152. assert s.recv(100).startswith(b"LABDB 5.5.0")
  153. listen = subprocess.run(["ss", "-ltn"], capture_output=True, text=True, check=False).stdout if shutil.which("ss") else ""
  154. for line in listen.splitlines():
  155. if f":{base}" in line or f":{base + 1}" in line or f":{base + 2}" in line:
  156. assert "127.0.0.1:" in line and "0.0.0.0:" not in line.split()[3], line
  157. def test_the_log_has_the_fields_the_page_and_the_detector_read(lab):
  158. folder, base = lab
  159. get(f"http://127.0.0.1:{base}/.env")
  160. time.sleep(0.3)
  161. lines = (folder / "lab.log").read_text().splitlines()
  162. req = [x for x in lines if " REQ " in x]
  163. assert re.fullmatch(
  164. rf'\d{{4}}-\d\d-\d\dT\d\d:\d\d:\d\dZ REQ web src=127\.0\.0\.1 dport={base} GET /\.env 404 ua="[^"]*"', req[-1]
  165. ), req[-1]
  166. assert any(re.fullmatch(rf"\S+Z CONN web src=127\.0\.0\.1 dport={base}", x) for x in lines)
  167. def test_fixed_build_segments_and_says_less(scripts):
  168. proc, base = launch_lab(scripts, "--fixed")
  169. try:
  170. wait_for("127.0.0.1", base)
  171. if not can_connect("127.0.0.1", base):
  172. pytest.skip("loopback not available")
  173. try:
  174. wait_for("127.0.0.2", base + 1)
  175. wait_for("127.0.0.3", base + 2)
  176. except AssertionError:
  177. pytest.skip("this system does not answer on 127.0.0.2 / 127.0.0.3")
  178. # the outside view (the front end's address) sees only the web port
  179. assert can_connect("127.0.0.1", base)
  180. assert not can_connect("127.0.0.1", base + 1) and not can_connect("127.0.0.1", base + 2)
  181. status, headers, _ = get(f"http://127.0.0.1:{base}/")
  182. assert status == 200 and headers["Server"] == "web"
  183. assert get(f"http://127.0.0.1:{base}/admin/")[0] == 404
  184. assert get(f"http://127.0.0.2:{base + 1}/")[0] == 200 # the app tier still works
  185. finally:
  186. stop(proc)
  187. def run_detect(folder: Path, text: str, window: int, need: int):
  188. (folder / "t.log").write_text(text)
  189. return subprocess.run(
  190. [sys.executable, "-I", "scan_detect.py", "t.log", str(window), str(need)],
  191. cwd=folder, capture_output=True, text=True, timeout=20, check=False,
  192. )
  193. def conn(sec: int, port: int, src: str = "198.51.100.5") -> str:
  194. return f"2026-01-01T00:00:{sec:02d}Z CONN web src={src} dport={port}\n"
  195. def test_detector_fires_on_a_fast_scan_and_not_on_a_slow_one(scripts):
  196. fast = conn(0, 1) + conn(1, 2) + conn(2, 3)
  197. slow = conn(0, 1) + conn(20, 2) + conn(40, 3)
  198. assert "ALERT port_scan src=198.51.100.5 ports=3 window=10s" in run_detect(scripts, fast, 10, 3).stdout
  199. assert run_detect(scripts, slow, 10, 3).stdout == ""
  200. assert "ALERT port_scan" in run_detect(scripts, slow, 60, 3).stdout # the "defend" step
  201. def test_detector_needs_distinct_ports_and_groups_by_source(scripts):
  202. same_port = conn(0, 1) + conn(1, 1) + conn(2, 1) + conn(3, 1)
  203. assert run_detect(scripts, same_port, 10, 3).stdout == ""
  204. split = conn(0, 1) + conn(1, 2, "198.51.100.6") + conn(2, 3, "198.51.100.7")
  205. assert run_detect(scripts, split, 10, 3).stdout == "" # three sources, one port each
  206. def test_detector_treats_hostile_lines_as_data(scripts):
  207. hostile = (
  208. "garbage\n\n$(touch pwned) CONN x src=$(touch pwned) dport=1\n"
  209. "2026-01-01T00:00:00Z CONN web src=198.51.100.5 dport=notanumber\n"
  210. "2026-13-45T99:00:00Z CONN web src=198.51.100.5 dport=1\n"
  211. + conn(0, 1) + conn(1, 2) + conn(2, 3)
  212. )
  213. proc = run_detect(scripts, hostile, 10, 3)
  214. assert proc.returncode == 0, proc.stderr
  215. assert "ALERT port_scan" in proc.stdout and "skipped 2 unparseable lines" in proc.stderr
  216. assert not (scripts / "pwned").exists()
  217. def test_proxy_forwards_loopback_and_refuses_everything_else(lab):
  218. folder, base = lab
  219. proc, pbase = launch_proxy(folder)
  220. try:
  221. opener = urllib.request.build_opener(urllib.request.ProxyHandler({"http": f"http://127.0.0.1:{pbase}"}))
  222. with opener.open(f"http://127.0.0.1:{base}/admin/", timeout=5) as r:
  223. assert r.status == 200 and b"debug page" in r.read()
  224. for target in ("http://203.0.113.9/", "http://example.com/"):
  225. with pytest.raises(urllib.error.HTTPError) as err:
  226. opener.open(target, timeout=5)
  227. assert err.value.code == 403, target
  228. with socket.create_connection(("127.0.0.1", pbase), timeout=5) as raw: # a non-http scheme, sent by hand
  229. raw.sendall(b"GET https://127.0.0.1/ HTTP/1.0\r\n\r\n")
  230. assert b" 403 " in raw.recv(200).split(b"\r\n")[0]
  231. for bad in (b"http://127.0.0.1:notaport/", b"http://127.0.0.1:99999/"): # bad ports are refused, not a crash
  232. with socket.create_connection(("127.0.0.1", pbase), timeout=5) as raw:
  233. raw.sendall(b"GET " + bad + b" HTTP/1.0\r\n\r\n")
  234. assert b" 403 " in raw.recv(200).split(b"\r\n")[0], bad
  235. finally:
  236. stop(proc)
  237. out = proc.stdout.read()
  238. assert ">>> GET http://127.0.0.1:" in out and "<<< 200 OK" in out and "<<< Server: LabHTTP/1.0" in out
  239. assert "203.0.113.9" not in out # refused before anything was printed or sent
  240. @pytest.mark.skipif(shutil.which("nmap") is None, reason="nmap is not installed")
  241. def test_a_connect_scan_leaves_one_connection_line_per_open_port(lab):
  242. folder, base = lab
  243. (folder / "lab.log").write_text("") # safe now: the fixture's probe is already logged
  244. subprocess.run(["nmap", "-sT", "-p", f"{base}-{base + 2}", "127.0.0.1"], capture_output=True, timeout=60, check=True)
  245. ports: list[str] = []
  246. for _ in range(100): # the server logs from its own threads: wait for the lines, not a fixed time
  247. ports = [x.split()[-1] for x in (folder / "lab.log").read_text().splitlines() if " CONN " in x]
  248. if len(ports) >= 3:
  249. break
  250. time.sleep(0.05)
  251. time.sleep(0.2) # a short grace so a spurious extra line would still be caught
  252. ports = [x.split()[-1] for x in (folder / "lab.log").read_text().splitlines() if " CONN " in x]
  253. assert sorted(ports) == [f"dport={base + i}" for i in range(3)] # order-independent
  254. # --- the page itself --------------------------------------------------------------
  255. def page_text() -> str:
  256. return PAGE.read_text(encoding="utf-8")
  257. def test_only_loopback_and_documentation_addresses_appear():
  258. allowed = ("127.", "192.0.2.", "198.51.100.", "203.0.113.", "0.0.0.0")
  259. version_like = {"3.13.5", "8.21.0", "7.98", "5.5.0"}
  260. bad = [ip for ip in IPV4.findall(page_text()) if not ip.startswith(allowed) and ip not in version_like]
  261. assert not bad, bad
  262. def test_the_companion_link_is_present_and_kept_out_of_the_next_line():
  263. text = page_text()
  264. assert "Red-and-Blue-Yin-and-Yang-and-Your-Lab-OS.md" in text
  265. # The companion page is in the wiki, so the old 'may not resolve until it merges' caveat is gone (issue #444).
  266. assert "may not resolve until" not in text
  267. for line in text.splitlines():
  268. if "Next:" in line:
  269. assert "Red-and-Blue-Yin-and-Yang" not in line
  270. def test_every_exercise_has_predict_do_check_undo_and_unrun_things_are_marked():
  271. text = page_text()
  272. exercises = re.split(r"^### Exercise ", text, flags=re.MULTILINE)[1:]
  273. assert len(exercises) >= 8
  274. for ex in exercises:
  275. head = ex.splitlines()[0]
  276. for word in ("**Predict", "**Do", "**Undo"):
  277. assert word in ex, f"Exercise {head}: missing {word}"
  278. if "not run" not in head:
  279. assert "**Check" in ex, f"Exercise {head}: missing **Check"
  280. assert "est." in text and "PowerShell" in text