test_host_firewall_script.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. """Hermetic tests for the host-firewall script in the connector cloud-init.
  2. The script is extracted from modules/twingate-bootstrap/cloud-init.yaml.tftpl
  3. (undoing the template's `$$` escaping and the YAML block indentation, and
  4. filling the two template variables) and run with fake `nft` and `ss` binaries
  5. on a PATH that holds nothing else, inside a temporary directory. The real nft
  6. is never invoked for a change: the one optional syntax check runs `nft -c`
  7. (check only) in a throwaway user and network namespace and skips when that is
  8. not possible. Nothing here touches this machine's firewall or any service.
  9. """
  10. import re
  11. import shutil
  12. import stat
  13. import subprocess
  14. from pathlib import Path
  15. import pytest
  16. ROOT = Path(__file__).resolve().parent.parent
  17. TEMPLATE = ROOT / "modules/twingate-bootstrap/cloud-init.yaml.tftpl"
  18. SCRIPT_PATH = "/usr/local/sbin/cah-host-firewall"
  19. UNIT_PATH = "/etc/systemd/system/cah-host-firewall.service"
  20. BASH = shutil.which("bash")
  21. DEFAULT_SOURCES = "10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16"
  22. pytestmark = pytest.mark.skipif(BASH is None, reason="bash is not available")
  23. def _run(args, **kwargs):
  24. """subprocess.run that reports the exit code instead of raising."""
  25. return subprocess.run(args, check=False, **kwargs)
  26. def extract_file(
  27. template_text: str,
  28. path: str,
  29. subs: dict[str, str] | None = None,
  30. node_exporter: bool = False,
  31. ) -> str:
  32. """The write_files content for `path`, as it lands on the machine.
  33. `%{ if node_exporter ~}` ... `%{ endif ~}` lines INSIDE a script (followed by
  34. an indented line) are evaluated with `node_exporter`; any other directive at
  35. column 0 ends the block scalar, as before.
  36. """
  37. lines = template_text.splitlines()
  38. start = next(
  39. (i for i, line in enumerate(lines) if line.strip() == f"- path: {path}"), None
  40. )
  41. assert start is not None, f"{path} is not written by the template"
  42. body: list[str] = []
  43. in_content = False
  44. inline_if = False # inside an inline node_exporter conditional
  45. for idx in range(start + 1, len(lines)):
  46. line = lines[idx]
  47. if not in_content:
  48. if line.strip() == "content: |":
  49. in_content = True
  50. continue
  51. if line == "%{ if node_exporter ~}" and lines[idx + 1].startswith(" "):
  52. inline_if = True
  53. continue
  54. if line == "%{ endif ~}" and inline_if:
  55. inline_if = False
  56. continue
  57. if inline_if and not node_exporter:
  58. continue
  59. # The block scalar ends at the first line indented less than 6 spaces
  60. # that is not blank (the next " - path:" entry or a %{ directive).
  61. if line.strip() and not line.startswith(" "):
  62. break
  63. body.append(line[6:] if line.startswith(" ") else "")
  64. assert body, f"{path} has no content"
  65. text = "\n".join(body).rstrip("\n") + "\n"
  66. for name, value in (subs or {}).items():
  67. text = text.replace("${" + name + "}", value)
  68. # tftpl: "$$" renders as "$"; any other "${...}" would be an interpolation.
  69. assert "${" not in text.replace("$${", ""), "an unescaped template interpolation reached the script"
  70. return text.replace("$$", "$")
  71. def extract_script(
  72. template_text: str,
  73. sources: str = DEFAULT_SOURCES,
  74. metrics_port: str = "",
  75. node_exporter_port: str = "",
  76. path: str = SCRIPT_PATH,
  77. ) -> str:
  78. return extract_file(
  79. template_text,
  80. path,
  81. {
  82. "host_firewall_ssh_sources": sources,
  83. "host_firewall_metrics_port": metrics_port,
  84. "host_firewall_node_exporter": node_exporter_port,
  85. },
  86. node_exporter=node_exporter_port != "",
  87. )
  88. GOOD_LISTING = (
  89. "table inet cah_host {\n"
  90. "\tchain input {\n"
  91. "\t\ttype filter hook input priority filter; policy drop;\n"
  92. "\t\ttcp dport 22 ip saddr { 10.0.0.0/8 } accept\n"
  93. "\t}\n"
  94. "}\n"
  95. )
  96. SSH_LISTENING = "LISTEN 0 128 0.0.0.0:22 0.0.0.0:*\nLISTEN 0 128 [::]:22 [::]:*\n"
  97. def make_fakes(
  98. tmp: Path,
  99. *,
  100. check_rc: int = 0,
  101. apply_rc: int = 0,
  102. ss_out: str = SSH_LISTENING,
  103. listing: str = GOOD_LISTING,
  104. ) -> tuple[Path, Path]:
  105. bindir = tmp / "bin"
  106. bindir.mkdir()
  107. calls = tmp / "calls.log"
  108. (tmp / "ss.out").write_text(ss_out)
  109. (tmp / "nft.list").write_text(listing)
  110. # Only shell builtins: PATH holds nothing but these fakes.
  111. save = (
  112. 'while IFS= read -r line || [ -n "$line" ]; do '
  113. 'printf \'%s\\n\' "$line"; done > "{dest}"\n'
  114. )
  115. show = (
  116. 'while IFS= read -r line || [ -n "$line" ]; do '
  117. 'printf \'%s\\n\' "$line"; done < "{src}"\n'
  118. )
  119. (bindir / "nft").write_text(
  120. f"#!{BASH}\n"
  121. f'echo "nft $*" >> "{calls}"\n'
  122. 'if [ "$1" = "-c" ]; then\n'
  123. + save.format(dest=tmp / "check.stdin")
  124. + f" exit {check_rc}\n"
  125. 'elif [ "$1" = "-f" ]; then\n'
  126. + save.format(dest=tmp / "apply.stdin")
  127. + f" exit {apply_rc}\n"
  128. 'elif [ "$1" = "list" ]; then\n'
  129. + show.format(src=tmp / "nft.list")
  130. + " exit 0\n"
  131. "fi\n"
  132. "exit 0\n"
  133. )
  134. (bindir / "ss").write_text(
  135. f"#!{BASH}\n"
  136. f'echo "ss $*" >> "{calls}"\n' + show.format(src=tmp / "ss.out")
  137. )
  138. for f in bindir.iterdir():
  139. f.chmod(f.stat().st_mode | stat.S_IXUSR)
  140. return bindir, calls
  141. def run_script(
  142. tmp: Path,
  143. *,
  144. sources=DEFAULT_SOURCES,
  145. metrics_port="",
  146. node_exporter_port="",
  147. **fake_kw,
  148. ):
  149. script = tmp / "cah-host-firewall"
  150. script.write_text(
  151. extract_script(
  152. TEMPLATE.read_text(encoding="utf-8"),
  153. sources,
  154. metrics_port,
  155. node_exporter_port,
  156. )
  157. )
  158. bindir, calls = make_fakes(tmp, **fake_kw)
  159. env = {"PATH": str(bindir), "HOME": str(tmp)}
  160. proc = _run([BASH, str(script)], env=env, capture_output=True, text=True, timeout=30)
  161. call_lines = calls.read_text().splitlines() if calls.exists() else []
  162. apply_file = tmp / "apply.stdin"
  163. check_file = tmp / "check.stdin"
  164. return (
  165. proc,
  166. call_lines,
  167. apply_file.read_text() if apply_file.exists() else "",
  168. check_file.read_text() if check_file.exists() else "",
  169. )
  170. # --- extraction guards -------------------------------------------------------
  171. def test_extraction_finds_a_real_script():
  172. text = extract_script(TEMPLATE.read_text(encoding="utf-8"))
  173. assert text.startswith("#!/usr/bin/env bash\n")
  174. assert "set -euo pipefail" in text
  175. assert "policy drop" in text
  176. assert f'ssh_sources="{DEFAULT_SOURCES}"' in text
  177. def test_extraction_negative_case_missing_path_is_an_error():
  178. with pytest.raises(AssertionError):
  179. extract_script(TEMPLATE.read_text(encoding="utf-8"), path="/usr/local/sbin/nope")
  180. def test_extraction_negative_case_rejects_an_unfilled_interpolation():
  181. with pytest.raises(AssertionError):
  182. extract_file(TEMPLATE.read_text(encoding="utf-8"), SCRIPT_PATH, {})
  183. def test_the_unit_is_a_oneshot_ordered_after_cloud_final():
  184. unit = extract_file(TEMPLATE.read_text(encoding="utf-8"), UNIT_PATH)
  185. for needle in (
  186. "Type=oneshot",
  187. "After=cloud-final.service network-online.target",
  188. "ExecStart=/usr/local/sbin/cah-host-firewall",
  189. ):
  190. assert needle in unit
  191. # --- behavior ---------------------------------------------------------------
  192. def test_success_applies_in_order_check_apply_verify(tmp_path):
  193. proc, calls, applied, checked = run_script(tmp_path)
  194. assert proc.returncode == 0, proc.stderr
  195. assert calls == [
  196. "nft -c -f -",
  197. "nft -f -",
  198. "ss -H -ltn",
  199. "nft list table inet cah_host",
  200. ]
  201. # The ruleset that was checked is the one that was applied.
  202. assert checked == applied and applied != ""
  203. def test_ruleset_is_idempotent_self_contained_and_drops_by_default(tmp_path):
  204. _proc, _calls, ruleset, _ = run_script(tmp_path)
  205. lines = [line.strip() for line in ruleset.splitlines()]
  206. first = lines.index("table inet cah_host")
  207. delete = lines.index("delete table inet cah_host")
  208. full = lines.index("table inet cah_host {")
  209. assert first < delete < full
  210. assert "type filter hook input priority 0; policy drop;" in lines
  211. for rule in (
  212. 'iifname "lo" accept',
  213. "ct state established,related accept",
  214. "ct state invalid drop",
  215. "icmp type { echo-request, destination-unreachable, time-exceeded } accept",
  216. "icmpv6 type { destination-unreachable, packet-too-big, time-exceeded, echo-request, nd-router-advert, nd-neighbor-solicit, nd-neighbor-advert } accept",
  217. "udp sport 67 udp dport 68 accept",
  218. f"tcp dport 22 ip saddr {{ {DEFAULT_SOURCES} }} accept",
  219. ):
  220. assert rule in lines
  221. # No flush, no other table, no output or forward chain, no extra inbound.
  222. assert "flush ruleset" not in ruleset
  223. assert "cah_metadata" not in ruleset
  224. assert "chain output" not in ruleset and "chain forward" not in ruleset
  225. assert len(re.findall(r"dport", ruleset)) == 2 # dhcp client port + ssh
  226. def test_no_metrics_rule_without_a_metrics_port(tmp_path):
  227. _proc, _calls, ruleset, _ = run_script(tmp_path)
  228. assert len(re.findall(r"tcp dport", ruleset)) == 1
  229. def test_metrics_port_rule_uses_the_same_private_sources(tmp_path):
  230. _proc, _calls, ruleset, _ = run_script(tmp_path, metrics_port="9999")
  231. lines = [line.strip() for line in ruleset.splitlines()]
  232. assert f"tcp dport 9999 ip saddr {{ {DEFAULT_SOURCES} }} accept" in lines
  233. assert len(re.findall(r"tcp dport", ruleset)) == 2
  234. def test_node_exporter_port_rule_uses_the_same_private_sources(tmp_path):
  235. _proc, _calls, ruleset, _ = run_script(tmp_path, node_exporter_port="9200")
  236. lines = [line.strip() for line in ruleset.splitlines()]
  237. assert f"tcp dport 9200 ip saddr {{ {DEFAULT_SOURCES} }} accept" in lines
  238. assert len(re.findall(r"tcp dport", ruleset)) == 2
  239. def test_the_script_does_not_mention_the_node_exporter_when_it_is_off():
  240. off = extract_script(TEMPLATE.read_text(encoding="utf-8"))
  241. on = extract_script(TEMPLATE.read_text(encoding="utf-8"), node_exporter_port="9100")
  242. assert "node_exporter" not in off
  243. # Negative case: the extractor really does see the conditional lines.
  244. assert "node_exporter_rule" in on
  245. def test_node_exporter_and_connector_metrics_rules_coexist(tmp_path):
  246. _proc, _calls, ruleset, _ = run_script(
  247. tmp_path, metrics_port="9999", node_exporter_port="9100"
  248. )
  249. assert len(re.findall(r"tcp dport", ruleset)) == 3
  250. assert "tcp dport 9100 ip saddr" in ruleset and "tcp dport 9999 ip saddr" in ruleset
  251. def test_custom_sources_replace_the_defaults(tmp_path):
  252. _proc, _calls, ruleset, _ = run_script(
  253. tmp_path, sources="10.20.0.0/16, 192.0.2.7/32"
  254. )
  255. assert "tcp dport 22 ip saddr { 10.20.0.0/16, 192.0.2.7/32 } accept" in ruleset
  256. assert "172.16.0.0/12" not in ruleset
  257. def test_a_failed_check_exits_nonzero_without_applying(tmp_path):
  258. proc, calls, applied, _ = run_script(tmp_path, check_rc=1)
  259. assert proc.returncode != 0
  260. assert "does not parse" in proc.stderr
  261. assert calls == ["nft -c -f -"]
  262. assert applied == ""
  263. def test_a_failed_apply_exits_nonzero_and_never_reports_success(tmp_path):
  264. proc, calls, _applied, _ = run_script(tmp_path, apply_rc=1)
  265. assert proc.returncode != 0
  266. assert "nft -f -" in calls
  267. assert "cah-host-firewall: loaded" not in proc.stdout
  268. def test_sshd_not_listening_deletes_the_table(tmp_path):
  269. proc, calls, _a, _c = run_script(tmp_path, ss_out="LISTEN 0 128 0.0.0.0:2222 *\n")
  270. assert proc.returncode != 0
  271. assert calls[-1] == "nft delete table inet cah_host"
  272. assert "verification failed" in proc.stderr
  273. def test_missing_ssh_rule_in_the_loaded_table_deletes_the_table(tmp_path):
  274. proc, calls, _a, _c = run_script(tmp_path, listing="table inet cah_host {\n}\n")
  275. assert proc.returncode != 0
  276. assert calls[-1] == "nft delete table inet cah_host"
  277. def test_a_failing_ss_counts_as_not_listening_and_rolls_back(tmp_path):
  278. script = tmp_path / "s"
  279. script.write_text(extract_script(TEMPLATE.read_text(encoding="utf-8")))
  280. bindir, calls = make_fakes(tmp_path)
  281. (bindir / "ss").write_text(f"#!{BASH}\nexit 1\n")
  282. proc = _run(
  283. [BASH, str(script)],
  284. env={"PATH": str(bindir)},
  285. capture_output=True,
  286. text=True,
  287. timeout=30,
  288. )
  289. assert proc.returncode != 0
  290. assert calls.read_text().splitlines()[-1] == "nft delete table inet cah_host"
  291. def test_only_the_fake_nft_and_ss_are_invoked(tmp_path):
  292. for kw in ({}, {"check_rc": 1}, {"ss_out": ""}):
  293. sub = tmp_path / str(len(kw)) / (next(iter(kw), "ok"))
  294. sub.mkdir(parents=True)
  295. _proc, calls, _a, _c = run_script(sub, **kw)
  296. assert calls, "the script ran nothing at all"
  297. assert {c.split()[0] for c in calls} <= {"nft", "ss"}
  298. # --- real nft syntax check, in a throwaway namespace, check-only ---------------
  299. def _can_check_syntax() -> bool:
  300. nft, unshare = shutil.which("nft"), shutil.which("unshare")
  301. if not nft or not unshare:
  302. return False
  303. probe = _run(
  304. [unshare, "-rn", nft, "-c", "-f", "-"],
  305. input="table inet cah_probe\n",
  306. capture_output=True,
  307. text=True,
  308. timeout=30,
  309. )
  310. return probe.returncode == 0
  311. def _nft_check(ruleset: str):
  312. return _run(
  313. [shutil.which("unshare"), "-rn", shutil.which("nft"), "-c", "-f", "-"],
  314. input=ruleset,
  315. capture_output=True,
  316. text=True,
  317. timeout=30,
  318. )
  319. @pytest.mark.skipif(not _can_check_syntax(), reason="unshare -rn nft -c is unavailable here")
  320. @pytest.mark.parametrize(
  321. "kw",
  322. [
  323. {},
  324. {"metrics_port": "9999"},
  325. {"metrics_port": "9999", "node_exporter_port": "9100"},
  326. {"sources": "10.20.0.0/16, 192.0.2.7/32"},
  327. {"sources": "10.20.0.0/16", "metrics_port": "1024"},
  328. # Everything the tightened variable validation still accepts: host bits,
  329. # overlapping entries, and the prefix extremes 1 and 32.
  330. {"sources": "10.0.0.1/8, 10.1.0.0/16, 128.0.0.0/1, 192.0.2.7/32"},
  331. ],
  332. ids=[
  333. "defaults",
  334. "telemetry-port",
  335. "both-ports",
  336. "custom-sources",
  337. "both",
  338. "validation-extremes",
  339. ],
  340. )
  341. def test_generated_ruleset_passes_nft_syntax_check(tmp_path, kw):
  342. _proc, _calls, ruleset, _ = run_script(tmp_path, **kw)
  343. assert ruleset, "no ruleset was captured"
  344. check = _nft_check(ruleset)
  345. assert check.returncode == 0, check.stderr
  346. @pytest.mark.skipif(not _can_check_syntax(), reason="unshare -rn nft -c is unavailable here")
  347. def test_syntax_check_negative_cases_the_checker_really_rejects(tmp_path):
  348. _proc, _calls, ruleset, _ = run_script(tmp_path)
  349. assert _nft_check(ruleset.replace("policy drop", "policy dropp")).returncode != 0
  350. assert _nft_check(ruleset.replace("ip saddr {", "ip saddr {{")).returncode != 0
  351. # A source that is not a CIDR is refused by nft too (belt and braces next to
  352. # the variable validation).
  353. (tmp_path / "bad").mkdir()
  354. _p, _c, bad, _ = run_script(tmp_path / "bad", sources="not-a-cidr")
  355. assert _nft_check(bad).returncode != 0
  356. # --- template wiring ---------------------------------------------------------
  357. def test_template_gates_the_firewall_on_host_firewall():
  358. text = TEMPLATE.read_text(encoding="utf-8")
  359. assert len(re.findall(r"%\{ if host_firewall ~\}", text)) == 2
  360. assert len(re.findall(r"%\{ if metadata_lock \|\| host_firewall ~\}", text)) == 1
  361. # nftables is listed exactly once, whichever feature asks for it.
  362. assert len(re.findall(r"^ - nftables$", text, flags=re.MULTILINE)) == 1
  363. assert "--no-block" in text
  364. # --- persistence across nftables.service (issue #90 review) ----------------------
  365. METADATA_UNIT_PATH = "/etc/systemd/system/cah-metadata-lock.service"
  366. def follows_nftables(unit: str, script: str) -> bool:
  367. """True when the unit is ordered after, restarts with, and reloads with
  368. nftables.service (which flushes the whole ruleset), and never hard-depends
  369. on it."""
  370. lines = unit.splitlines()
  371. wanted = (
  372. "After=nftables.service",
  373. "PartOf=nftables.service",
  374. "ReloadPropagatedFrom=nftables.service",
  375. f"ExecReload={script}",
  376. "After=cloud-final.service network-online.target",
  377. "Type=oneshot",
  378. )
  379. hard = ("Requires=nftables", "Requisite=nftables", "BindsTo=nftables", "Wants=nftables")
  380. return (
  381. all(w in lines for w in wanted)
  382. and not any(h in unit for h in hard)
  383. and "ExecStop" not in unit
  384. )
  385. @pytest.mark.parametrize(
  386. ("path", "script"),
  387. [
  388. (UNIT_PATH, "/usr/local/sbin/cah-host-firewall"),
  389. (METADATA_UNIT_PATH, "/usr/local/sbin/cah-metadata-lock"),
  390. ],
  391. ids=["host-firewall", "metadata-lock"],
  392. )
  393. def test_both_units_follow_nftables_service(path, script):
  394. # Ubuntu's nftables.service flushes the whole ruleset on start, restart and
  395. # reload (and package upgrades try-restart it). Each unit must be ordered
  396. # after it, restart with it, and re-run its script on a reload. The checks
  397. # are soft (no Requires=/Wants=): nftables.service may be inactive on first
  398. # boot and our unit must still start.
  399. unit = extract_file(TEMPLATE.read_text(encoding="utf-8"), path)
  400. assert follows_nftables(unit, script)
  401. def test_follows_nftables_negative_cases_the_guard_bites():
  402. unit = extract_file(TEMPLATE.read_text(encoding="utf-8"), UNIT_PATH)
  403. script = "/usr/local/sbin/cah-host-firewall"
  404. assert follows_nftables(unit, script)
  405. for needle in ("PartOf=nftables.service", "After=nftables.service", "ReloadPropagatedFrom=nftables.service"):
  406. assert not follows_nftables(unit.replace(needle, "# removed"), script)
  407. assert not follows_nftables(unit + "Requires=nftables.service\n", script)
  408. assert not follows_nftables(unit + "ExecStop=/usr/sbin/nft flush ruleset\n", script)