test_log_shipping_script.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. """Hermetic tests for the log-shipping first-boot script in the connector cloud-init.
  2. Stage 2 step 7 (design 2026-10-16, section 2.8): the Wazuh agent is enrolled by a
  3. script that pulls its secret from Doppler with a short-lived token. The script is
  4. extracted from modules/twingate-bootstrap/cloud-init.yaml.tftpl (the same
  5. extraction as the host-firewall and node-exporter tests) and run in a temporary
  6. directory with fake `curl`, `systemctl` and `agent-auth` binaries on a PATH that
  7. holds nothing else but a few coreutils and python3. All paths the script uses are
  8. rewritten into that directory. No network, no service and no file outside the
  9. temporary directory is touched. Fixture secrets are built at run time and are
  10. obviously fake.
  11. What is proved: the success path, a failed pull, a missing secret, a failed
  12. enrollment, a missing agent and a missing token each fail closed (the agent is
  13. never enabled or started), the token file and the enrollment password file are
  14. gone afterwards in every case, the token travels on stdin and never in an
  15. argument, and no secret appears in the script's output.
  16. """
  17. import json
  18. import re
  19. import shutil
  20. import subprocess
  21. import xml.etree.ElementTree as ET
  22. from pathlib import Path
  23. import pytest
  24. from test_host_firewall_script import TEMPLATE, extract_file
  25. BASH = shutil.which("bash")
  26. PYTHON3 = shutil.which("python3")
  27. SCRIPT_PATH = "/usr/local/sbin/cah-log-shipping-firstboot"
  28. TOKEN_PATH = "/etc/cah/hostboot.token"
  29. LOCALFILE_PATH = "/etc/cah/wazuh-localfile.xml"
  30. RULES_PATH = "/etc/audit/rules.d/60-cah.rules"
  31. RULES_B32_PATH = "/etc/audit/rules.d/61-cah-b32.rules"
  32. GUARD_PATH = "/usr/local/sbin/cah-agent-guard"
  33. INSERT_PATH = "/usr/local/sbin/cah-ossec-insert"
  34. KEYCHECK_PATH = "/usr/local/sbin/cah-apt-key-check"
  35. SWEEP_UNIT_PATH = "/etc/systemd/system/cah-log-shipping-sweep.service"
  36. DROPIN_PATH = "/etc/systemd/system/wazuh-agent.service.d/10-cah-no-stale-password.conf"
  37. pytestmark = pytest.mark.skipif(BASH is None or PYTHON3 is None, reason="bash and python3 are required")
  38. # Obviously fake fixture values, none of them shaped like a real credential.
  39. TOKEN = "fixture-bootstrap-token-0001"
  40. PASSWORD = "fixture-wazuh-enroll-password-0001"
  41. OTHER_SECRET = "fixture-twingate-service-key-0001"
  42. SUBS = {
  43. "log_shipping_manager_address": "192.0.2.10",
  44. "log_shipping_manager_port": "1514",
  45. "log_shipping_enroll_port": "1515",
  46. "log_shipping_agent_name": "site-tor1-connector-a",
  47. "log_shipping_agent_group": "site-tor1",
  48. "log_shipping_site": "site-tor1",
  49. "log_shipping_hostboot_config": "cah-tor1-hostboot",
  50. }
  51. # The part of the Wazuh agent's stock ossec.conf the script edits.
  52. STOCK_OSSEC = """\
  53. <ossec_config>
  54. <client>
  55. <server>
  56. <address>MANAGER_IP</address>
  57. <port>1514</port>
  58. <protocol>tcp</protocol>
  59. </server>
  60. </client>
  61. </ossec_config>
  62. """
  63. COREUTILS = ("env", "bash", "cat", "rm", "mv", "mkdir", "mktemp", "chmod", "grep", "sed", "dirname", "stat", "sha256sum")
  64. def extract(**over: str) -> str:
  65. subs = dict(SUBS)
  66. subs.update(over)
  67. return extract_file(TEMPLATE.read_text(encoding="utf-8"), SCRIPT_PATH, subs)
  68. def extract_localfile_text(**over: str) -> str:
  69. return extract_file(TEMPLATE.read_text(encoding="utf-8"), LOCALFILE_PATH, dict(SUBS, **over))
  70. class Box:
  71. """A throwaway filesystem and PATH for one run of the script."""
  72. def __init__(self, tmp: Path, orig_policy: str | None = None, **over: str):
  73. self.tmp = tmp
  74. self.bin = tmp / "bin"
  75. self.bin.mkdir()
  76. self.etc = tmp / "sb-cah"
  77. self.etc.mkdir()
  78. self.ossec = tmp / "sb-ossec"
  79. (self.ossec / "bin").mkdir(parents=True)
  80. (self.ossec / "etc").mkdir()
  81. self.run_dir = tmp / "sb-run"
  82. self.run_dir.mkdir()
  83. self.calls = tmp / "calls.log"
  84. self.over = over
  85. for name in COREUTILS:
  86. src = shutil.which(name)
  87. if src:
  88. (self.bin / name).symlink_to(src)
  89. (self.bin / "python3").symlink_to(PYTHON3)
  90. (self.etc / "wazuh-localfile.xml").write_text(extract_localfile_text(), encoding="utf-8")
  91. self.token_file.write_text(TOKEN)
  92. (self.ossec / "etc" / "ossec.conf").write_text(STOCK_OSSEC)
  93. self.set_secrets({"WAZUH_ENROLLMENT_PASSWORD": PASSWORD, "OTHER": OTHER_SECRET})
  94. self.curl_rc = 0
  95. self.agent_auth_rc = 0
  96. self.systemctl_rc = 0
  97. self.augenrules_rc = 0
  98. self.unmask_rc = 0
  99. self.mask_rc = 0
  100. self.state_dir = tmp / "sb-state"
  101. self.rules_dir = tmp / "sb-rules"
  102. self.rules_dir.mkdir()
  103. (self.rules_dir / "60-cah.rules").write_text(extract_file(TEMPLATE.read_text(encoding="utf-8"), RULES_PATH))
  104. self.machine = "x86_64"
  105. self.ossec_insert = tmp / "sb-ossec-insert.py"
  106. self.policy = tmp / "sb-policy-rc.d"
  107. self.policy_orig = tmp / "sb-policy-rc.d.cah-orig"
  108. if orig_policy is not None:
  109. self.policy.write_text(orig_policy)
  110. self.policy.chmod(0o755)
  111. self.guard = tmp / "sb-guard.sh"
  112. self.guard.write_text(self.sandboxed(extract_file(TEMPLATE.read_text(encoding="utf-8"), GUARD_PATH)))
  113. self.guard.chmod(0o755)
  114. self.ossec_insert.write_text(self.sandboxed(extract_file(TEMPLATE.read_text(encoding="utf-8"), INSERT_PATH)))
  115. self.ossec_insert.chmod(0o755)
  116. self.install_agent_auth()
  117. self.write_fakes()
  118. # What the install step of runcmd does before the package is installed.
  119. (tmp / "systemctl.rc").write_text("0")
  120. (tmp / "unmask.rc").write_text("0")
  121. (tmp / "mask.rc").write_text("0")
  122. done = self.run_guard("deny")
  123. assert done.returncode == 0, done.stderr
  124. self.calls.unlink()
  125. def sandboxed(self, text: str) -> str:
  126. text = text.replace("/run/cah-log-shipping", str(self.run_dir / "cah-log-shipping"))
  127. text = text.replace("/etc/cah", str(self.etc))
  128. text = text.replace("/var/ossec", str(self.ossec))
  129. text = text.replace("/usr/sbin/policy-rc.d", str(self.policy))
  130. text = text.replace("/var/lib/cah", str(self.state_dir))
  131. text = text.replace("/etc/audit/rules.d", str(self.rules_dir))
  132. text = text.replace(GUARD_PATH, str(self.guard))
  133. text = text.replace(INSERT_PATH, str(self.ossec_insert))
  134. for root in ("/etc/cah", "/var/ossec", "/run/cah-log-shipping", "/usr/sbin/policy-rc.d", "/etc/audit/rules.d"):
  135. assert root not in text
  136. return text
  137. def swap_policy_on_enable(self, unmanaged: str, with_saved_original: bool) -> None:
  138. """When the agent is enabled, replace policy-rc.d with an unmanaged file."""
  139. lines = [f"rm -f '{self.policy}'", f"printf '%s' '{unmanaged}' > '{self.policy}'"]
  140. if with_saved_original:
  141. lines.append(f"printf '%s' 'saved' > '{self.policy_orig}'")
  142. (self.tmp / "swap.sh").write_text("\n".join(lines) + "\n")
  143. def run_guard(self, action: str):
  144. return subprocess.run(
  145. [BASH, str(self.guard), action],
  146. env={"PATH": str(self.bin), "HOME": str(self.tmp)},
  147. capture_output=True,
  148. text=True,
  149. timeout=30,
  150. check=False,
  151. )
  152. @property
  153. def token_file(self) -> Path:
  154. return self.etc / "hostboot.token"
  155. @property
  156. def pass_file(self) -> Path:
  157. return self.ossec / "etc" / "authd.pass"
  158. @property
  159. def conf(self) -> str:
  160. return (self.ossec / "etc" / "ossec.conf").read_text()
  161. def set_secrets(self, secrets: dict) -> None:
  162. (self.tmp / "secrets.json").write_text(json.dumps(secrets))
  163. def install_agent_auth(self) -> None:
  164. fake = self.ossec / "bin" / "agent-auth"
  165. fake.write_text(
  166. f"#!{BASH}\n"
  167. f'echo "agent-auth $*" >> "{self.calls}"\n'
  168. f'p="{self.pass_file}"\n'
  169. 'if [ -e "$p" ]; then\n'
  170. f' echo "present $(stat -c %a "$p") $(cat "$p")" > "{self.tmp}/enroll.seen"\n'
  171. "else\n"
  172. f' echo "absent" > "{self.tmp}/enroll.seen"\n'
  173. "fi\n"
  174. f'exit "$(cat "{self.tmp}/agent_auth.rc")"\n'
  175. )
  176. fake.chmod(0o755)
  177. def write_fakes(self) -> None:
  178. tmp = self.tmp
  179. (self.bin / "curl").write_text(
  180. f"#!{BASH}\n"
  181. f'echo "curl $*" >> "{self.calls}"\n'
  182. f'if [ -e "{self.token_file}" ]; then echo present > "{tmp}/token.at.curl"; '
  183. f'else echo absent > "{tmp}/token.at.curl"; fi\n'
  184. f'if [ -e "{self.pass_file}" ]; then echo present > "{tmp}/pass.at.curl"; '
  185. f'else echo absent > "{tmp}/pass.at.curl"; fi\n'
  186. f'[ -e "{self.run_dir}/cah-log-shipping/stale" ] && echo present > "{tmp}/work.at.curl" || echo absent > "{tmp}/work.at.curl"\n'
  187. # -K - : the credential config arrives on stdin.
  188. f'cat > "{tmp}/curl.stdin"\n'
  189. 'out=""\nwhile [ $# -gt 0 ]; do [ "$1" = "-o" ] && out="$2"; shift; done\n'
  190. f'rc="$(cat "{tmp}/curl.rc")"\n'
  191. '[ "$rc" = 0 ] || exit "$rc"\n'
  192. f'cat "{tmp}/secrets.json" > "$out"\n'
  193. )
  194. (self.bin / "systemctl").write_text(
  195. f"#!{BASH}\n" f'echo "systemctl $*" >> "{self.calls}"\n'
  196. f'if [ "$1" = enable ] && [ -e "{tmp}/swap.sh" ]; then {BASH} "{tmp}/swap.sh"; fi\n'
  197. 'case "$1" in stop|disable) exit 0 ;; esac\n'
  198. f'if [ "$1" = mask ]; then exit "$(cat "{tmp}/mask.rc")"; fi\n'
  199. f'if [ "$1" = unmask ]; then exit "$(cat "{tmp}/unmask.rc")"; fi\n'
  200. f'exit "$(cat "{tmp}/systemctl.rc")"\n'
  201. )
  202. (self.bin / "augenrules").write_text(
  203. f"#!{BASH}\n" f'echo "augenrules $*" >> "{self.calls}"\n'
  204. f'exit "$(cat "{tmp}/augenrules.rc")"\n'
  205. )
  206. (self.bin / "uname").write_text(f"#!{BASH}\n" f'cat "{tmp}/machine"\n')
  207. for name in ("curl", "systemctl", "augenrules", "uname"):
  208. (self.bin / name).chmod(0o755)
  209. def run(self):
  210. (self.tmp / "curl.rc").write_text(str(self.curl_rc))
  211. (self.tmp / "agent_auth.rc").write_text(str(self.agent_auth_rc))
  212. (self.tmp / "systemctl.rc").write_text(str(self.systemctl_rc))
  213. (self.tmp / "unmask.rc").write_text(str(self.unmask_rc))
  214. (self.tmp / "mask.rc").write_text(str(self.mask_rc))
  215. (self.tmp / "augenrules.rc").write_text(str(self.augenrules_rc))
  216. (self.tmp / "machine").write_text(self.machine)
  217. text = extract(**self.over)
  218. text = self.sandboxed(text)
  219. script = self.tmp / "firstboot.sh"
  220. script.write_text(text)
  221. return subprocess.run(
  222. [BASH, str(script)],
  223. env={"PATH": str(self.bin), "HOME": str(self.tmp)},
  224. capture_output=True,
  225. text=True,
  226. timeout=60,
  227. check=False,
  228. )
  229. def log(self) -> str:
  230. return self.calls.read_text() if self.calls.exists() else ""
  231. def work_files(self) -> list[Path]:
  232. work = self.run_dir / "cah-log-shipping"
  233. return [p for p in work.rglob("*") if p.is_file()] if work.exists() else []
  234. def never_started(log: str) -> bool:
  235. return not re.search(r"systemctl (enable|start|restart)", log)
  236. # --- extraction ------------------------------------------------------------
  237. def test_extraction_finds_the_script():
  238. assert extract().startswith("#!/usr/bin/env bash\n")
  239. def test_extraction_negative_case_missing_path_is_an_error():
  240. with pytest.raises(AssertionError):
  241. extract_file(TEMPLATE.read_text(encoding="utf-8"), "/usr/local/sbin/not-written")
  242. # --- success ---------------------------------------------------------------
  243. def test_success_enrolls_with_the_pulled_password_then_starts_the_agent(tmp_path):
  244. box = Box(tmp_path)
  245. proc = box.run()
  246. assert proc.returncode == 0, proc.stderr
  247. log = box.log()
  248. assert "agent-auth -m 192.0.2.10 -p 1515 -A site-tor1-connector-a -G site-tor1" in log
  249. # The password file existed, root-only, with exactly the pulled value, when
  250. # the enrollment ran.
  251. assert (tmp_path / "enroll.seen").read_text().strip() == f"present 600 {PASSWORD}"
  252. assert "systemctl enable --now wazuh-agent" in log
  253. # enrollment happens before the agent starts
  254. assert log.index("agent-auth") < log.index("systemctl enable --now wazuh-agent")
  255. def test_success_deletes_the_token_the_password_and_the_pulled_json(tmp_path):
  256. box = Box(tmp_path)
  257. assert box.run().returncode == 0
  258. assert not box.token_file.exists()
  259. assert not box.pass_file.exists()
  260. assert box.work_files() == []
  261. def test_the_token_is_gone_before_the_network_is_touched(tmp_path):
  262. box = Box(tmp_path)
  263. assert box.run().returncode == 0
  264. assert (tmp_path / "token.at.curl").read_text().strip() == "absent"
  265. def test_the_token_travels_on_stdin_never_in_an_argument(tmp_path):
  266. box = Box(tmp_path)
  267. assert box.run().returncode == 0
  268. assert TOKEN not in box.log()
  269. stdin = (tmp_path / "curl.stdin").read_text()
  270. assert TOKEN in stdin
  271. assert "https://api.doppler.com/" in box.log()
  272. assert "--proto =https" in box.log() and "--tlsv1.2" in box.log()
  273. def test_no_secret_reaches_stdout_or_stderr(tmp_path):
  274. box = Box(tmp_path)
  275. proc = box.run()
  276. for secret in (TOKEN, PASSWORD, OTHER_SECRET):
  277. assert secret not in proc.stdout
  278. assert secret not in proc.stderr
  279. def test_only_the_wazuh_secret_is_kept_not_the_rest_of_the_config(tmp_path):
  280. box = Box(tmp_path)
  281. assert box.run().returncode == 0
  282. for path in tmp_path.rglob("*"):
  283. if path.is_file() and path.name not in ("secrets.json", "firstboot.sh"):
  284. assert OTHER_SECRET not in path.read_text(errors="ignore"), path
  285. def test_the_manager_address_and_port_are_written_into_the_agent_config(tmp_path):
  286. box = Box(tmp_path, log_shipping_manager_port="1600")
  287. assert box.run().returncode == 0
  288. conf = box.conf
  289. assert "<address>192.0.2.10</address>" in conf
  290. assert "<port>1600</port>" in conf
  291. assert "MANAGER_IP" not in conf
  292. def test_the_localfile_block_is_appended_once(tmp_path):
  293. box = Box(tmp_path)
  294. assert box.run().returncode == 0
  295. assert box.conf.count("twingate-connector") == 1
  296. # A second first-boot run (token supplied again) does not append it again.
  297. box.token_file.write_text(TOKEN)
  298. assert box.run().returncode == 0
  299. assert box.conf.count("twingate-connector") == 1
  300. def test_an_empty_agent_group_leaves_out_the_group_flag(tmp_path):
  301. box = Box(tmp_path, log_shipping_agent_group="")
  302. assert box.run().returncode == 0
  303. call = next(line for line in box.log().splitlines() if line.startswith("agent-auth"))
  304. assert call == "agent-auth -m 192.0.2.10 -p 1515 -A site-tor1-connector-a"
  305. # --- fail closed -----------------------------------------------------------
  306. def assert_closed(box: Box, proc, reason: str) -> None:
  307. assert proc.returncode != 0
  308. assert never_started(box.log()), box.log()
  309. # The agent stays masked and denied by policy-rc.d.
  310. assert box.policy.exists() and "cah-wazuh-deny" in box.policy.read_text()
  311. assert "systemctl mask wazuh-agent" in box.log()
  312. assert not box.token_file.exists()
  313. assert not box.pass_file.exists()
  314. assert box.work_files() == []
  315. assert reason in proc.stderr
  316. for secret in (TOKEN, PASSWORD, OTHER_SECRET):
  317. assert secret not in proc.stdout and secret not in proc.stderr
  318. assert "failing closed, the Wazuh agent is not started" in proc.stderr
  319. def test_a_failed_pull_does_not_start_the_agent_and_says_why(tmp_path):
  320. box = Box(tmp_path)
  321. box.curl_rc = 22
  322. proc = box.run()
  323. assert_closed(box, proc, "pull from Doppler failed")
  324. assert "agent-auth" not in box.log()
  325. def test_a_pull_without_the_wazuh_secret_fails_closed(tmp_path):
  326. box = Box(tmp_path)
  327. box.set_secrets({"OTHER": OTHER_SECRET})
  328. proc = box.run()
  329. assert_closed(box, proc, "WAZUH_ENROLLMENT_PASSWORD")
  330. assert "agent-auth" not in box.log()
  331. @pytest.mark.parametrize("value", ["", "two\nlines"], ids=["empty", "newline"])
  332. def test_an_unusable_secret_value_fails_closed(tmp_path, value):
  333. box = Box(tmp_path)
  334. box.set_secrets({"WAZUH_ENROLLMENT_PASSWORD": value})
  335. proc = box.run()
  336. assert_closed(box, proc, "WAZUH_ENROLLMENT_PASSWORD")
  337. assert "agent-auth" not in box.log()
  338. def test_a_failed_enrollment_removes_the_password_and_does_not_start_the_agent(tmp_path):
  339. box = Box(tmp_path)
  340. box.agent_auth_rc = 1
  341. proc = box.run()
  342. # The enrollment did run, with the password present, and it was removed anyway.
  343. assert (tmp_path / "enroll.seen").read_text().strip() == f"present 600 {PASSWORD}"
  344. assert_closed(box, proc, "enrollment failed")
  345. def test_a_missing_token_file_fails_closed(tmp_path):
  346. box = Box(tmp_path)
  347. box.token_file.unlink()
  348. proc = box.run()
  349. assert_closed(box, proc, "no bootstrap token")
  350. assert "curl" not in box.log()
  351. def test_an_empty_token_file_fails_closed(tmp_path):
  352. box = Box(tmp_path)
  353. box.token_file.write_text("")
  354. proc = box.run()
  355. assert_closed(box, proc, "bootstrap token")
  356. assert "curl" not in box.log()
  357. def test_a_missing_agent_fails_closed_and_still_deletes_the_token(tmp_path):
  358. box = Box(tmp_path)
  359. (box.ossec / "bin" / "agent-auth").unlink()
  360. proc = box.run()
  361. assert_closed(box, proc, "not installed")
  362. assert "curl" not in box.log()
  363. def test_a_failed_start_is_reported_not_swallowed(tmp_path):
  364. box = Box(tmp_path)
  365. box.systemctl_rc = 1
  366. proc = box.run()
  367. assert proc.returncode != 0
  368. assert "did not start" in proc.stderr
  369. assert not box.token_file.exists() and not box.pass_file.exists()
  370. # --- the script text -------------------------------------------------------
  371. def test_the_script_has_no_literal_fallback_and_writes_only_the_pulled_value():
  372. text = extract()
  373. assert "set -euo pipefail" in text
  374. assert "trap cleanup EXIT" in text
  375. # The only thing written to the password file is the pulled variable.
  376. assert len(re.findall(r'>\s*"\$PASS_FILE"', text)) == 1
  377. assert "printf '%s' \"$password\" > \"$PASS_FILE\"" in text
  378. # No password flag on a command line (it would show in ps), no tracing.
  379. assert not re.search(r"\s-P\s", text)
  380. assert "set -x" not in text and "bash -x" not in text
  381. def test_the_bootstrap_token_variable_is_rendered_only_into_its_own_file():
  382. template = TEMPLATE.read_text(encoding="utf-8")
  383. hits = [m.start() for m in re.finditer(r"\$\{log_shipping_bootstrap_token\}", template)]
  384. assert len(hits) == 1
  385. body = extract_file(template, TOKEN_PATH, {"log_shipping_bootstrap_token": TOKEN})
  386. assert body == TOKEN + "\n"
  387. paths = re.findall(r"- path: (\S+)", template[: hits[0]])
  388. assert paths[-1] == TOKEN_PATH
  389. def test_the_token_file_is_root_only():
  390. lines = TEMPLATE.read_text(encoding="utf-8").splitlines()
  391. i = lines.index(f" - path: {TOKEN_PATH}")
  392. assert lines[i + 1].strip() == 'permissions: "0600"'
  393. assert lines[i + 2].strip() == "owner: root:root"
  394. # --- the other fragments ---------------------------------------------------
  395. def test_localfile_block_is_well_formed_and_collects_the_named_sources():
  396. text = extract_localfile_text()
  397. root = ET.fromstring(f"<root>{text}</root>")
  398. localfiles = root.findall("localfile")
  399. # Only <localfile> blocks: no second <ossec_config> wrapper in the fragment.
  400. assert root.find("ossec_config") is None
  401. assert localfiles, "no <localfile> entries"
  402. journald = [lf for lf in localfiles if lf.findtext("log_format") == "journald"]
  403. filters = " ".join((f.text or "") for lf in journald for f in lf.findall("filter"))
  404. for needle in ("twingate-connector", "ssh", "sudo"):
  405. assert needle in filters, needle
  406. files = [
  407. lf.findtext("location") for lf in localfiles if lf.findtext("log_format") != "journald"
  408. ]
  409. assert "/var/log/auth.log" in files
  410. assert "cah-log-shipping-localfiles" in text
  411. def test_localfile_fragment_sets_the_site_label_the_wazuh_dashboard_filters_on():
  412. # The dashboard filters on agent.labels.site; Wazuh writes that field from a
  413. # <labels><label key="site"> block in the agent's ossec.conf.
  414. for site in ("site-tor1", "site-tor2"):
  415. root = ET.fromstring(f"<root>{extract_localfile_text(log_shipping_site=site)}</root>")
  416. labels = root.findall("labels/label")
  417. assert [(lb.get("key"), lb.text) for lb in labels] == [("site", site)]
  418. def test_the_site_label_is_inserted_inside_the_single_root_element(tmp_path):
  419. box = Box(tmp_path)
  420. assert box.run().returncode == 0
  421. root = ET.fromstring(box.conf)
  422. assert [(lb.get("key"), lb.text) for lb in root.findall("labels/label")] == [("site", "site-tor1")]
  423. assert box.conf.count("<ossec_config>") == 1
  424. RULE = re.compile(r"^-a always,exit -F arch=(b64|b32) -F (path|dir)=(\S+) -F perm=(\S+) -F key=(\S+)$")
  425. def check_rule_set(lines: list[str], arches: set[str]) -> None:
  426. """The rule set must be the 7 watch-equivalent rules for each arch in `arches`, nothing else."""
  427. parsed = [RULE.match(ln) for ln in lines]
  428. assert lines and all(parsed), f"every rule must be an exact watch-equivalent -a rule: {lines}"
  429. assert not any(re.match(r"\s*-w\s", ln) for ln in lines)
  430. by_arch: dict[str, dict] = {}
  431. for m in parsed:
  432. by_arch.setdefault(m.group(1), {})[m.group(3)] = (m.group(2), m.group(4), m.group(5))
  433. assert set(by_arch) == arches, f"arches {set(by_arch)} != {arches}"
  434. assert len(lines) == 7 * len(arches), f"{len(lines)} rules for {arches}"
  435. for watched in by_arch.values():
  436. for f in ("/etc/passwd", "/etc/group", "/etc/shadow", "/etc/gshadow"):
  437. assert watched[f] == ("path", "wa", "cah_identity")
  438. assert watched["/etc/sudoers"] == ("path", "wa", "cah_sudo")
  439. # A directory keeps the recursive meaning of the old -w on a directory.
  440. assert watched["/etc/sudoers.d/"] == ("dir", "wa", "cah_sudo")
  441. assert watched["/etc/twingate/"] == ("dir", "wa", "cah_twingate")
  442. assert len(watched) == 7
  443. text = "\n".join(lines)
  444. # File rules only: no syscall filter (-S) and no execve, whatever the spelling.
  445. assert "execve" not in text
  446. assert not re.search(r"(?m)\s-S\s", text)
  447. def rule_lines(text: str) -> list[str]:
  448. return [ln for ln in text.splitlines() if ln.strip()]
  449. def test_audit_rules_cover_identity_sudo_and_twingate_and_never_execve():
  450. rules = extract_file(TEMPLATE.read_text(encoding="utf-8"), RULES_PATH)
  451. check_rule_set(rule_lines(rules), {"b64"})
  452. def test_b32_twins_are_written_on_x86_64_only(tmp_path):
  453. for machine, expect in (("x86_64", True), ("aarch64", False)):
  454. d = tmp_path / machine
  455. d.mkdir()
  456. box = Box(d)
  457. box.machine = machine
  458. done = box.run()
  459. assert done.returncode == 0, done.stderr
  460. twin = box.rules_dir / "61-cah-b32.rules"
  461. assert twin.exists() == expect, machine
  462. base = rule_lines((box.rules_dir / "60-cah.rules").read_text())
  463. if expect:
  464. both = base + rule_lines(twin.read_text())
  465. check_rule_set(both, {"b64", "b32"})
  466. assert len(both) == 14
  467. assert oct(twin.stat().st_mode & 0o777) == "0o640"
  468. else:
  469. check_rule_set(base, {"b64"})
  470. assert len(base) == 7
  471. # The rules are loaded after the twin decision, in both cases.
  472. assert "augenrules --load" in box.log()
  473. def test_a_stale_b32_file_is_removed_off_x86_64(tmp_path):
  474. box = Box(tmp_path)
  475. box.machine = "aarch64"
  476. (box.rules_dir / "61-cah-b32.rules").write_text("stale\n")
  477. assert box.run().returncode == 0
  478. assert not (box.rules_dir / "61-cah-b32.rules").exists()
  479. def test_rule_set_check_bites():
  480. good = rule_lines(extract_file(TEMPLATE.read_text(encoding="utf-8"), RULES_PATH))
  481. twins = [ln.replace("arch=b64", "arch=b32") for ln in good]
  482. check_rule_set(good + twins, {"b64", "b32"})
  483. # b64 only where both were required: the regression the review found.
  484. with pytest.raises(AssertionError):
  485. check_rule_set(good, {"b64", "b32"})
  486. # a missing twin, the old -w form, a syscall filter and a wrong key are all caught
  487. with pytest.raises(AssertionError):
  488. check_rule_set(good + twins[:-1], {"b64", "b32"})
  489. with pytest.raises(AssertionError):
  490. check_rule_set(["-w /etc/passwd -p wa -k cah_identity"], {"b64"})
  491. with pytest.raises(AssertionError):
  492. check_rule_set([ln + " -S execve" for ln in good], {"b64"})
  493. with pytest.raises(AssertionError):
  494. check_rule_set([ln.replace("cah_sudo", "cah_x") for ln in good], {"b64"})
  495. def test_template_gates_every_log_shipping_piece_on_the_flag():
  496. text = TEMPLATE.read_text(encoding="utf-8")
  497. needles = (
  498. "- auditd",
  499. SCRIPT_PATH,
  500. TOKEN_PATH,
  501. LOCALFILE_PATH,
  502. RULES_PATH,
  503. "packages.wazuh.com",
  504. "log_shipping_key_fingerprint",
  505. "augenrules",
  506. GUARD_PATH,
  507. INSERT_PATH,
  508. "/var/lib/cah/agent-guard.state",
  509. "/etc/systemd/system/cah-log-shipping-sweep.service",
  510. "/etc/systemd/system/wazuh-agent.service.d/10-cah-no-stale-password.conf",
  511. "systemctl mask wazuh-agent",
  512. )
  513. for needle in needles:
  514. found = list(re.finditer(re.escape(needle), text))
  515. assert found, f"{needle} is not in the template"
  516. for m in found:
  517. before = text[: m.start()]
  518. assert before.rfind("%{ if log_shipping ~}") > before.rfind("%{ endif ~}"), (
  519. f"{needle} is outside a log_shipping conditional"
  520. )
  521. def test_the_apt_key_is_checked_against_the_pinned_fingerprint_before_it_is_trusted():
  522. text = TEMPLATE.read_text(encoding="utf-8")
  523. start = text.index("packages.wazuh.com/key")
  524. block = text[start - 900 : start + 1400]
  525. check = block.index('/usr/local/sbin/cah-apt-key-check /root/wazuh.gpg.key "$FPR"')
  526. dearmor = block.index("gpg --dearmor")
  527. sources = block.index("sources.list.d/wazuh.list")
  528. assert check < dearmor < sources
  529. assert "FPR=${log_shipping_key_fingerprint}" in block
  530. # The fingerprint is an input: the only 40-hex literal in the template is
  531. # Twingate's, which was there before this feature.
  532. assert len(re.findall(r"\b[0-9A-Fa-f]{40}\b", text)) == 1
  533. def test_the_agent_install_runs_after_the_connector_and_the_script_after_the_agent():
  534. text = TEMPLATE.read_text(encoding="utf-8")
  535. connector = text.index("&& apt-get install -yq twingate-connector \\\n")
  536. wazuh = text.index('apt-get install -yq "$AGENT_PACKAGE"')
  537. firstboot = text.index("[/usr/local/sbin/cah-log-shipping-firstboot]")
  538. status = text.index("cah-connector-install.log")
  539. assert connector < wazuh < firstboot < status