cloud-init.yaml.tftpl 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  1. #cloud-config
  2. # Hardened baseline for a Twingate connector droplet. SSH is reachable only
  3. # through Twingate (the DigitalOcean firewall allows no inbound traffic); the
  4. # sshd settings below are the second layer. Changing this file changes
  5. # user_data, which forces a droplet rebuild.
  6. # First-hour order (the same one the stage guides state): update, baseline,
  7. # harden, then applications. In this file: the package update, upgrade and
  8. # unattended-upgrades come first, the baseline (users, sshd settings, files) is
  9. # written next, the hardening is switched on (sshd restarted) before the
  10. # Twingate connector, which is installed last.
  11. disable_root: true
  12. # Local time, so the reboot window and the weekly update below are Eastern.
  13. timezone: ${timezone}
  14. ssh_pwauth: false
  15. package_update: true
  16. package_upgrade: true
  17. packages:
  18. - unattended-upgrades
  19. - chrony
  20. %{ if node_exporter ~}
  21. - prometheus-node-exporter
  22. %{ endif ~}
  23. %{ if log_shipping ~}
  24. - auditd
  25. %{ endif ~}
  26. %{ if metadata_lock || host_firewall ~}
  27. - nftables
  28. %{ endif ~}
  29. users:
  30. - name: cah-admin
  31. gecos: CAH admin
  32. lock_passwd: true
  33. shell: /bin/bash
  34. groups: [sudo]
  35. sudo: ALL=(ALL) NOPASSWD:ALL
  36. ssh_authorized_keys:
  37. - ${admin_ssh_public_key}
  38. write_files:
  39. # First boot races Ubuntu's own apt-daily and unattended-upgrades for the
  40. # dpkg lock; wait for it instead of failing the Twingate install.
  41. # The connector config, written directly as in Twingate's own Terraform
  42. # (https://www.twingate.com/docs/terraform-aws). Root-only. The tokens appear
  43. # here and nowhere else in this file.
  44. - path: /etc/twingate/connector.conf
  45. permissions: "0600"
  46. owner: root:root
  47. content: |
  48. TWINGATE_URL=https://${network}.twingate.com
  49. TWINGATE_ACCESS_TOKEN=${access_token}
  50. TWINGATE_REFRESH_TOKEN=${refresh_token}
  51. ${telemetry_conf}%{ if metadata_lock ~}
  52. # Lock the droplet metadata endpoint (it serves this very user-data, tokens
  53. # included) to root and to the DigitalOcean monitoring agent's user. The rule
  54. # lives in its own nftables table, so it never touches any other rule.
  55. - path: /usr/local/sbin/cah-metadata-lock
  56. permissions: "0750"
  57. owner: root:root
  58. content: |
  59. #!/usr/bin/env bash
  60. set -euo pipefail
  61. # uid 0 always; the do-agent user too when it exists (DigitalOcean's
  62. # monitoring agent reads the metadata address as that user). AWS has none.
  63. allowed="0"
  64. if agent_uid="$(id -u do-agent 2>/dev/null)"; then
  65. allowed="0, $agent_uid"
  66. fi
  67. nft -f - <<EOF
  68. table inet cah_metadata
  69. delete table inet cah_metadata
  70. table inet cah_metadata {
  71. chain output {
  72. type filter hook output priority 0; policy accept;
  73. ip daddr 169.254.169.254 meta skuid != { $allowed } reject with icmp type admin-prohibited
  74. }
  75. }
  76. EOF
  77. echo "cah-metadata-lock: metadata endpoint allowed for uids: $allowed"
  78. # After cloud-final so the do-agent user already exists on first boot.
  79. # Ubuntu's nftables.service loads /etc/nftables.conf, which starts with
  80. # "flush ruleset", on start, restart and reload, and its package upgrade
  81. # try-restarts it: that would silently drop our table. So this unit is ordered
  82. # After= it, is PartOf= it (a stop or restart of nftables.service restarts this
  83. # unit, which re-runs the idempotent script) and takes its reloads too. All
  84. # three are soft: no Requires=, Wants= or Requisite=, so when nftables.service
  85. # is inactive (the first-boot state) this unit still starts and does not fail.
  86. # PartOf= and ReloadPropagatedFrom= only forward jobs that nftables.service
  87. # already has; they never start it. Untested on a real machine.
  88. - path: /etc/systemd/system/cah-metadata-lock.service
  89. permissions: "0644"
  90. content: |
  91. [Unit]
  92. Description=Restrict the droplet metadata endpoint to root and do-agent
  93. After=cloud-final.service network-online.target
  94. After=nftables.service
  95. PartOf=nftables.service
  96. ReloadPropagatedFrom=nftables.service
  97. Wants=network-online.target
  98. [Service]
  99. Type=oneshot
  100. RemainAfterExit=yes
  101. ExecStart=/usr/local/sbin/cah-metadata-lock
  102. ExecReload=/usr/local/sbin/cah-metadata-lock
  103. [Install]
  104. WantedBy=multi-user.target
  105. %{ endif ~}
  106. %{ if host_firewall ~}
  107. # A default-drop host firewall, the second layer behind the cloud firewall. It
  108. # lives in its own nftables table (inet cah_host), so it never flushes or
  109. # touches any other rule, including the metadata lock's table. Only the input
  110. # chain is filtered; output and forward are left alone.
  111. - path: /usr/local/sbin/cah-host-firewall
  112. permissions: "0750"
  113. owner: root:root
  114. content: |
  115. #!/usr/bin/env bash
  116. set -euo pipefail
  117. ssh_sources="${host_firewall_ssh_sources}"
  118. # Empty unless connector_telemetry.metrics_port is set.
  119. metrics_port="${host_firewall_metrics_port}"
  120. metrics_rule=""
  121. if [ -n "$metrics_port" ]; then
  122. metrics_rule="tcp dport $metrics_port ip saddr { $ssh_sources } accept"
  123. fi
  124. %{ if node_exporter ~}
  125. node_exporter_port="${host_firewall_node_exporter}"
  126. node_exporter_rule="tcp dport $node_exporter_port ip saddr { $ssh_sources } accept"
  127. %{ endif ~}
  128. # Why each accept exists:
  129. # - lo and established/related: local traffic and replies to what this
  130. # machine started (the connector, apt, DNS, NTP all work on replies).
  131. # - ICMPv4 echo, unreachable and time-exceeded: ping, and path MTU and
  132. # error reporting.
  133. # - ICMPv6 neighbour discovery and packet-too-big: the machines have no
  134. # public IPv6, but link-local neighbour discovery must keep working.
  135. # - DHCPv4 replies (server port 67 to client port 68): lease renewal.
  136. # - TCP 22 and the metrics port: only from the private sources.
  137. # The same ruleset serves DigitalOcean and AWS.
  138. read -r -d '' ruleset <<EOF || true
  139. table inet cah_host
  140. delete table inet cah_host
  141. table inet cah_host {
  142. chain input {
  143. type filter hook input priority 0; policy drop;
  144. iifname "lo" accept
  145. ct state established,related accept
  146. ct state invalid drop
  147. icmp type { echo-request, destination-unreachable, time-exceeded } accept
  148. icmpv6 type { destination-unreachable, packet-too-big, time-exceeded, echo-request, nd-router-advert, nd-neighbor-solicit, nd-neighbor-advert } accept
  149. udp sport 67 udp dport 68 accept
  150. tcp dport 22 ip saddr { $ssh_sources } accept
  151. $metrics_rule
  152. %{ if node_exporter ~}
  153. $node_exporter_rule
  154. %{ endif ~}
  155. }
  156. }
  157. EOF
  158. # Refuse a ruleset that does not parse, before anything changes.
  159. if ! printf '%s\n' "$ruleset" | nft -c -f -; then
  160. echo "cah-host-firewall: refusing to apply: the ruleset does not parse" >&2
  161. exit 1
  162. fi
  163. printf '%s\n' "$ruleset" | nft -f -
  164. # Verify, and roll back (delete only our own table) if the machine could
  165. # no longer be reached over SSH.
  166. listening=""
  167. listed=""
  168. listening="$(ss -H -ltn)" || listening=""
  169. listed="$(nft list table inet cah_host)" || listed=""
  170. if [[ ! "$listening" =~ :22[[:space:]] ]] || [[ "$listed" != *"tcp dport 22"* ]]; then
  171. echo "cah-host-firewall: verification failed (sshd not listening on 22, or the ssh accept is not loaded): removing the table" >&2
  172. nft delete table inet cah_host || echo "cah-host-firewall: could not delete the table" >&2
  173. exit 1
  174. fi
  175. echo "cah-host-firewall: loaded; ssh and metrics allowed from: $ssh_sources"
  176. # Same reasoning as the metadata lock unit: nftables.service flushes the whole
  177. # ruleset, so this unit is After=, PartOf= and ReloadPropagatedFrom= it (soft,
  178. # nothing is pulled in, and it still starts when nftables.service is inactive).
  179. # No ExecStop: a plain "stop nftables" still flushes our table, and the docs say so.
  180. - path: /etc/systemd/system/cah-host-firewall.service
  181. permissions: "0644"
  182. content: |
  183. [Unit]
  184. Description=Default-drop host firewall (inet cah_host)
  185. After=cloud-final.service network-online.target
  186. After=nftables.service
  187. PartOf=nftables.service
  188. ReloadPropagatedFrom=nftables.service
  189. Wants=network-online.target
  190. [Service]
  191. Type=oneshot
  192. RemainAfterExit=yes
  193. ExecStart=/usr/local/sbin/cah-host-firewall
  194. ExecReload=/usr/local/sbin/cah-host-firewall
  195. [Install]
  196. WantedBy=multi-user.target
  197. %{ endif ~}
  198. %{ if node_exporter ~}
  199. # Host metrics (node exporter), bound to the private address only. The Ubuntu
  200. # package starts the exporter on every interface by default, so a systemd
  201. # drop-in replaces its command line before the package ever starts it
  202. # (write_files runs before the package install). The drop-in's ExecStart is a
  203. # wrapper that picks the private address itself at every start and then execs
  204. # the exporter, so nothing depends on the order systemd reads files in. If the
  205. # wrapper finds no private IPv4 address it exits 1 and the exporter does not
  206. # start at all, so there is no wildcard fallback. The exporter has no
  207. # authentication: the cloud firewall (tag-sourced rule) and the optional host
  208. # firewall are what limit who reaches it.
  209. - path: /usr/local/sbin/cah-node-exporter-run
  210. permissions: "0755"
  211. owner: root:root
  212. content: |
  213. #!/usr/bin/env bash
  214. set -euo pipefail
  215. port="${node_exporter_port}"
  216. # The first RFC 1918 IPv4 address on an interface that holds no public
  217. # IPv4 address. On DigitalOcean eth0 holds the public address plus a legacy
  218. # private one, and the VPC address is on eth1; AWS's primary interface
  219. # holds one private address. Fields of `ip -o`: the interface name and the
  220. # CIDR. Pass 1 marks interfaces with a public address, pass 2 picks.
  221. addr="$(ip -4 -o addr show scope global | awk '
  222. function priv(a) {
  223. return (a ~ /^10\./ || a ~ /^192\.168\./ || a ~ /^172\.(1[6-9]|2[0-9]|3[01])\./)
  224. }
  225. { split($4, c, "/"); n++; ifn[n] = $2; ip[n] = c[1]; if (!priv(c[1])) pub[$2] = 1 }
  226. END {
  227. for (i = 1; i <= n; i++)
  228. if (priv(ip[i]) && !(ifn[i] in pub)) { print ip[i]; exit }
  229. }')"
  230. if [ -z "$addr" ]; then
  231. echo "cah-node-exporter-run: no private IPv4 address found; refusing to start the node exporter" >&2
  232. exit 1
  233. fi
  234. exec /usr/bin/prometheus-node-exporter "--web.listen-address=$addr:$port"
  235. - path: /etc/systemd/system/prometheus-node-exporter.service.d/10-cah-private-bind.conf
  236. permissions: "0644"
  237. content: |
  238. [Service]
  239. ExecStart=
  240. ExecStart=/usr/local/sbin/cah-node-exporter-run
  241. %{ endif ~}
  242. # The pinned-key check, shared by every apt repository key this file trusts
  243. # (the Twingate connector always, Wazuh with log shipping). gpg lists the
  244. # downloaded key file; this accepts it only when it holds exactly ONE primary
  245. # key (one pub record, no secret keys) whose primary fingerprint equals the
  246. # pin. A subkey carries its own fpr record, so an
  247. # fpr is accepted only directly after a sub record; a second fpr that follows
  248. # no sub, or any second pub, is refused. So a bundle of the pinned key plus an
  249. # attacker key is never trusted.
  250. - path: /usr/local/sbin/cah-apt-key-check
  251. permissions: "0755"
  252. owner: root:root
  253. content: |
  254. #!/usr/bin/env bash
  255. set -euo pipefail
  256. refuse() { echo "cah-apt-key-check: refusing: $1" >&2; exit 1; }
  257. [ "$#" -eq 2 ] || refuse "usage: cah-apt-key-check <keyfile> <fingerprint>"
  258. keyfile="$1"
  259. pin="$2"
  260. listing="$(gpg --show-keys --with-colons "$keyfile")" || refuse "gpg could not read the key file"
  261. pubs=0
  262. primary=""
  263. prev=""
  264. while IFS=: read -r rec _ _ _ _ _ _ _ _ f10 _; do
  265. case "$rec" in
  266. pub) pubs=$((pubs + 1)); prev=pub ;;
  267. sub) prev=sub ;;
  268. sec|ssb) refuse "the file holds a secret key" ;;
  269. fpr)
  270. if [ "$prev" = pub ] && [ -z "$primary" ]; then
  271. primary="$f10"
  272. prev=fpr
  273. elif [ "$prev" = sub ]; then
  274. prev=fpr
  275. else
  276. refuse "an unexpected extra fingerprint record"
  277. fi
  278. ;;
  279. esac
  280. done <<< "$listing"
  281. [ "$pubs" -eq 1 ] || refuse "expected exactly one public key, found $pubs"
  282. [ "$primary" = "$pin" ] || refuse "the key fingerprint is not the pinned one"
  283. %{ if log_shipping ~}
  284. # Log shipping (opt-in): the Wazuh agent and auditd. The ONLY secret-related
  285. # value in this file is the short-lived, read-only Doppler token for the
  286. # config "${log_shipping_hostboot_config}", written to a root-only file that the
  287. # first-boot script deletes before it uses the token. The enrollment password
  288. # is NOT here: the script pulls it from Doppler at first boot, uses it once and
  289. # removes it. No Twingate service key and no Doppler secret value is rendered
  290. # anywhere. Untested on a real machine.
  291. - path: /etc/cah/hostboot.token
  292. permissions: "0600"
  293. owner: root:root
  294. content: |
  295. ${log_shipping_bootstrap_token}
  296. # Runs once, from runcmd, after the agent package is installed. Fails closed:
  297. # when the pull or the enrollment fails the agent is never enabled or started,
  298. # the reason goes to the cloud-init log, and nothing falls back to a literal.
  299. # Never add set -x here: it would print the token and the password.
  300. - path: /usr/local/sbin/cah-log-shipping-firstboot
  301. permissions: "0750"
  302. owner: root:root
  303. content: |
  304. #!/usr/bin/env bash
  305. set -euo pipefail
  306. umask 077
  307. TOKEN_FILE=/etc/cah/hostboot.token
  308. PASS_FILE=/var/ossec/etc/authd.pass
  309. GUARD=/usr/local/sbin/cah-agent-guard
  310. OSSEC_INSERT=/usr/local/sbin/cah-ossec-insert
  311. OSSEC_CONF=/var/ossec/etc/ossec.conf
  312. LOCALFILE_XML=/etc/cah/wazuh-localfile.xml
  313. RULES_B64=/etc/audit/rules.d/60-cah.rules
  314. RULES_B32=/etc/audit/rules.d/61-cah-b32.rules
  315. AGENT_AUTH=/var/ossec/bin/agent-auth
  316. RUN_DIR=/run/cah-log-shipping
  317. manager="${log_shipping_manager_address}"
  318. manager_port="${log_shipping_manager_port}"
  319. enroll_port="${log_shipping_enroll_port}"
  320. agent_name="${log_shipping_agent_name}"
  321. agent_group="${log_shipping_agent_group}"
  322. work=""
  323. log() { echo "cah-log-shipping: $*" >&2; }
  324. fail() {
  325. log "FAILED: $1; failing closed, the Wazuh agent is not started"
  326. systemctl stop wazuh-agent >/dev/null 2>&1 || true
  327. systemctl disable wazuh-agent >/dev/null 2>&1 || true
  328. # The unit is masked directly first, whatever state policy-rc.d is in.
  329. if ! systemctl mask wazuh-agent; then
  330. log "CRITICAL: could not mask wazuh-agent; it may be startable, check it by hand"
  331. fi
  332. # Then both guards back. If the guard cannot restore the policy-rc.d
  333. # denial (an unmanaged file is in the way), it has already masked the unit,
  334. # and this says so on the record instead of hiding it.
  335. if ! "$GUARD" deny; then
  336. log "CRITICAL: the guard could not restore the policy-rc.d denial; the unit is masked and stopped, check /usr/sbin/policy-rc.d by hand"
  337. fi
  338. exit 1
  339. }
  340. # Whatever happens, the token file, the password file and the pulled
  341. # config do not outlive this script.
  342. cleanup() {
  343. rm -f "$TOKEN_FILE" "$PASS_FILE"
  344. if [ -n "$work" ]; then rm -rf "$work"; fi
  345. }
  346. trap cleanup EXIT
  347. # A killed earlier run (SIGKILL, power loss) skips the trap. A password
  348. # file or a pulled config found now can only be such a leftover, so remove
  349. # it before anything else. The token file is this script's input and is not
  350. # swept here; the boot-time sweep unit covers a token that outlived a boot.
  351. rm -f "$PASS_FILE"
  352. rm -rf "$RUN_DIR"
  353. [ -f "$TOKEN_FILE" ] || fail "no bootstrap token file at $TOKEN_FILE"
  354. token="$(cat "$TOKEN_FILE")"
  355. rm -f "$TOKEN_FILE"
  356. [ -n "$token" ] || fail "the bootstrap token file was empty"
  357. [ -x "$AGENT_AUTH" ] || fail "the Wazuh agent is not installed ($AGENT_AUTH is missing)"
  358. # The 60-cah.rules file watches 64-bit programs (arch=b64). A 32-bit
  359. # program could still write the same files unseen, which the old -w watch
  360. # would have caught, so on x86_64 (where 32-bit programs run) each rule is
  361. # copied with arch=b32. Elsewhere (arm64 Graviton) an arch=b32 rule may not
  362. # load, which would fail this script closed, so it is not written there.
  363. if [ "$(uname -m)" = x86_64 ]; then
  364. sed 's/arch=b64/arch=b32/' "$RULES_B64" > "$RULES_B32" || fail "could not write $RULES_B32"
  365. chmod 0640 "$RULES_B32"
  366. else
  367. rm -f "$RULES_B32"
  368. fi
  369. augenrules --load || fail "augenrules --load failed"
  370. mkdir -p "$RUN_DIR"
  371. work="$(mktemp -d "$RUN_DIR/pull.XXXXXX")"
  372. # The token goes to curl on stdin (-K -), so it is never in an argument list.
  373. if ! printf 'user = "%s:"\n' "$token" | curl -fsS --proto '=https' --tlsv1.2 --retry 3 --max-time 60 -K - -o "$work/secrets.json" "https://api.doppler.com/v3/configs/config/secrets/download?format=json"; then
  374. fail "pull from Doppler failed (config ${log_shipping_hostboot_config}; the token may have expired)"
  375. fi
  376. unset token
  377. if ! password="$(python3 -c 'import json,sys; v=json.load(open(sys.argv[1])).get(sys.argv[2]); sys.exit(1) if (not isinstance(v, str) or not v or chr(10) in v) else sys.stdout.write(v)' "$work/secrets.json" WAZUH_ENROLLMENT_PASSWORD 2>/dev/null)"; then
  378. fail "the pulled config has no usable WAZUH_ENROLLMENT_PASSWORD"
  379. fi
  380. # Only that one value is kept; the rest of the pulled config goes now.
  381. rm -rf "$work"
  382. work=""
  383. printf '%s' "$password" > "$PASS_FILE"
  384. chmod 0600 "$PASS_FILE"
  385. unset password
  386. args=(-m "$manager" -p "$enroll_port" -A "$agent_name")
  387. if [ -n "$agent_group" ]; then args+=(-G "$agent_group"); fi
  388. if ! "$AGENT_AUTH" "$${args[@]}"; then
  389. rm -f "$PASS_FILE"
  390. fail "enrollment failed (agent-auth against $manager:$enroll_port)"
  391. fi
  392. # Enrolled: the password is not needed again. The per-host agent key stays.
  393. rm -f "$PASS_FILE"
  394. sed -i -e "0,/<address>[^<]*<\/address>/s//<address>$manager<\/address>/" -e "0,/<port>[^<]*<\/port>/s//<port>$manager_port<\/port>/" "$OSSEC_CONF" || fail "could not set the manager in $OSSEC_CONF"
  395. if ! grep -q 'cah-log-shipping-localfiles' "$OSSEC_CONF"; then
  396. "$OSSEC_INSERT" "$OSSEC_CONF" "$LOCALFILE_XML" || fail "could not add the log sources to $OSSEC_CONF"
  397. fi
  398. # Enrolled and configured: only now is the agent allowed to run. Both
  399. # guards (the mask and the policy-rc.d denial) are lifted here and nowhere
  400. # else; every failure above leaves them in place, and a failure after this
  401. # point puts both back.
  402. "$GUARD" allow || fail "could not lift the guards on wazuh-agent"
  403. systemctl enable --now wazuh-agent || fail "wazuh-agent did not start"
  404. systemctl is-active --quiet wazuh-agent || fail "wazuh-agent is not active after start"
  405. log "agent $agent_name enrolled with $manager and started"
  406. # Log sources, inserted inside the agent's existing <ossec_config> element by
  407. # the script above (a fragment of <localfile> blocks and one <labels> block,
  408. # not a document). The site label is what the Grafana Wazuh dashboard filters
  409. # on (agent.labels.site); it is the site part of the agent name. The
  410. # journald log format and its filter fields are UNVERIFIED against the agent
  411. # version your manager runs (design section 6.1); if the agent rejects them,
  412. # remove the journald blocks and use the documented syslog fallback.
  413. - path: /etc/cah/wazuh-localfile.xml
  414. permissions: "0640"
  415. owner: root:root
  416. content: |
  417. <!-- cah-log-shipping-localfiles -->
  418. <labels>
  419. <label key="site">${log_shipping_site}</label>
  420. </labels>
  421. <localfile>
  422. <log_format>journald</log_format>
  423. <location>journald</location>
  424. <filter field="_SYSTEMD_UNIT">^twingate-connector\.service$</filter>
  425. </localfile>
  426. <localfile>
  427. <log_format>journald</log_format>
  428. <location>journald</location>
  429. <filter field="_SYSTEMD_UNIT">^(ssh|sshd)\.service$</filter>
  430. </localfile>
  431. <localfile>
  432. <log_format>journald</log_format>
  433. <location>journald</location>
  434. <filter field="SYSLOG_IDENTIFIER">^sudo$</filter>
  435. </localfile>
  436. <localfile>
  437. <log_format>syslog</log_format>
  438. <location>/var/log/auth.log</location>
  439. </localfile>
  440. <localfile>
  441. <log_format>audit</log_format>
  442. <location>/var/log/audit/audit.log</location>
  443. </localfile>
  444. # A short auditd rule set: file watches only (who changed identity files, sudo
  445. # configuration or the Twingate config), written as -a always,exit rules, the
  446. # form the auditctl man page recommends over the deprecated -w watch. Each rule
  447. # keeps the old watch's path, write and attribute-change (wa) permissions and
  448. # key; dir= keeps a directory watch recursive. This file is the arch=b64 half;
  449. # the first-boot script adds the arch=b32 twin of every rule on x86_64 only
  450. # (61-cah-b32.rules), so a 32-bit program is seen as the old watch saw it.
  451. # No -S syscall filters and no
  452. # execve, because per-command auditing is too noisy for the 1 GB droplets.
  453. - path: /etc/audit/rules.d/60-cah.rules
  454. permissions: "0640"
  455. owner: root:root
  456. content: |
  457. -a always,exit -F arch=b64 -F path=/etc/passwd -F perm=wa -F key=cah_identity
  458. -a always,exit -F arch=b64 -F path=/etc/group -F perm=wa -F key=cah_identity
  459. -a always,exit -F arch=b64 -F path=/etc/shadow -F perm=wa -F key=cah_identity
  460. -a always,exit -F arch=b64 -F path=/etc/gshadow -F perm=wa -F key=cah_identity
  461. -a always,exit -F arch=b64 -F path=/etc/sudoers -F perm=wa -F key=cah_sudo
  462. -a always,exit -F arch=b64 -F dir=/etc/sudoers.d/ -F perm=wa -F key=cah_sudo
  463. -a always,exit -F arch=b64 -F dir=/etc/twingate/ -F perm=wa -F key=cah_twingate
  464. # The Wazuh deb may start its service when it is installed, before the agent is
  465. # enrolled. This script puts both guards in place (deny) or lifts them (allow):
  466. # the unit is masked, and a policy-rc.d answers 101 ("denied") for wazuh-agent
  467. # only. Any policy-rc.d that already existed is moved aside, not replaced: the
  468. # new one delegates every other request to it, and "allow" puts it back byte for
  469. # byte (or removes ours when there was none).
  470. # Ownership of the policy file is not guessed from its text. deny records the
  471. # sha256 of exactly what it installed in a state file; a policy is ours only
  472. # when that file exists and the hash still matches, so an unrelated policy that
  473. # happens to mention a marker is never overwritten or deleted. A symlink is
  474. # refused (nothing is written through it) and the policy is installed from a
  475. # temporary file in the same directory by rename. deny masks the unit FIRST and
  476. # whatever else happens, so a policy problem can never leave the unit startable;
  477. # any problem is reported on stderr and makes the script exit non-zero.
  478. # UNVERIFIED on a real machine.
  479. - path: /usr/local/sbin/cah-agent-guard
  480. permissions: "0755"
  481. owner: root:root
  482. content: |
  483. #!/usr/bin/env bash
  484. set -uo pipefail
  485. POLICY_RC=/usr/sbin/policy-rc.d
  486. POLICY_ORIG=/usr/sbin/policy-rc.d.cah-orig
  487. STATE=/var/lib/cah/agent-guard.state
  488. problem=0
  489. warn() { echo "cah-agent-guard: $1" >&2; }
  490. refuse() { warn "refusing: $1"; problem=1; }
  491. hash_of() { local h _; read -r h _ < <(sha256sum "$1") && printf '%s\n' "$h"; }
  492. ours() {
  493. local want have
  494. [ -f "$STATE" ] && [ -f "$POLICY_RC" ] && [ ! -L "$POLICY_RC" ] || return 1
  495. read -r want < "$STATE" || return 1
  496. have="$(hash_of "$POLICY_RC")" || return 1
  497. [ -n "$want" ] && [ "$want" = "$have" ]
  498. }
  499. install_policy() {
  500. local dir tmp
  501. dir="$(dirname "$POLICY_RC")"
  502. tmp="$(mktemp "$dir/.cah-policy.XXXXXX")" || { refuse "could not create a temporary file in $dir"; return; }
  503. cat > "$tmp" <<'EOF'
  504. #!/bin/sh
  505. # cah-wazuh-deny
  506. if [ "$1" = "wazuh-agent" ]; then
  507. exit 101
  508. fi
  509. if [ -x /usr/sbin/policy-rc.d.cah-orig ]; then
  510. exec /usr/sbin/policy-rc.d.cah-orig "$@"
  511. fi
  512. exit 0
  513. EOF
  514. chmod 0755 "$tmp"
  515. mkdir -p "$(dirname "$STATE")"
  516. hash_of "$tmp" > "$STATE.new" && mv -f "$STATE.new" "$STATE" || { rm -f "$tmp" "$STATE.new"; refuse "could not record the policy hash"; return; }
  517. mv -T -f "$tmp" "$POLICY_RC" || { rm -f "$tmp"; refuse "could not install $POLICY_RC"; return; }
  518. }
  519. deny() {
  520. systemctl mask wazuh-agent || { warn "could not mask wazuh-agent"; problem=1; }
  521. if [ -L "$POLICY_RC" ]; then refuse "$POLICY_RC is a symlink"; return; fi
  522. if [ -e "$POLICY_RC" ] && ! ours; then
  523. if [ -e "$POLICY_ORIG" ] || [ -L "$POLICY_ORIG" ]; then
  524. refuse "an unmanaged $POLICY_RC and a saved original both exist; leaving both untouched"
  525. return
  526. fi
  527. mv -T "$POLICY_RC" "$POLICY_ORIG" || { refuse "could not save the existing policy"; return; }
  528. fi
  529. install_policy
  530. }
  531. allow() {
  532. systemctl unmask wazuh-agent || { warn "could not unmask wazuh-agent; leaving both guards in place"; problem=1; return; }
  533. if [ -L "$POLICY_RC" ]; then warn "$POLICY_RC is a symlink; leaving it alone"; return; fi
  534. if ours; then
  535. if [ -e "$POLICY_ORIG" ]; then
  536. mv -T -f "$POLICY_ORIG" "$POLICY_RC" || { refuse "could not restore the original policy"; return; }
  537. else
  538. rm -f "$POLICY_RC"
  539. fi
  540. rm -f "$STATE"
  541. fi
  542. }
  543. case "$${1:-}" in
  544. deny) deny ;;
  545. allow) allow ;;
  546. *) warn "usage: cah-agent-guard deny|allow"; exit 1 ;;
  547. esac
  548. exit "$problem"
  549. # Inserts the log sources into the agent's ossec.conf. The file is rewritten by
  550. # a same-directory temporary file (written, flushed, fsynced, mode and owner
  551. # copied) and an atomic rename, so a full disk or a kill leaves the original
  552. # intact. The result must be well-formed and must not add a top-level element;
  553. # otherwise nothing is installed.
  554. - path: /usr/local/sbin/cah-ossec-insert
  555. permissions: "0755"
  556. owner: root:root
  557. content: |
  558. #!/usr/bin/env python3
  559. import os
  560. import sys
  561. import tempfile
  562. import xml.etree.ElementTree as ET
  563. def refuse(why):
  564. sys.stderr.write("cah-ossec-insert: refusing: " + why + "\n")
  565. sys.exit(1)
  566. def top_level(text):
  567. return len(ET.fromstring("<cah>" + text + "</cah>"))
  568. path, frag_path = sys.argv[1], sys.argv[2]
  569. with open(path) as f:
  570. conf = f.read()
  571. with open(frag_path) as f:
  572. frag = f.read()
  573. i = conf.rfind("</ossec_config>")
  574. if i < 0:
  575. refuse(path + " has no closing </ossec_config>")
  576. new = conf[:i] + frag + conf[i:]
  577. try:
  578. before, after = top_level(conf), top_level(new)
  579. except ET.ParseError as exc:
  580. refuse("the result would not be well-formed XML (" + str(exc) + ")")
  581. if before != after:
  582. refuse("the result would have " + str(after) + " top-level elements, not " + str(before))
  583. st = os.stat(path)
  584. fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path) or ".", prefix=".ossec.conf.")
  585. try:
  586. with os.fdopen(fd, "w") as out:
  587. out.write(new)
  588. out.flush()
  589. os.fsync(out.fileno())
  590. os.chmod(tmp, st.st_mode & 0o7777)
  591. os.chown(tmp, st.st_uid, st.st_gid)
  592. os.replace(tmp, path)
  593. except BaseException:
  594. try:
  595. os.unlink(tmp)
  596. except OSError:
  597. pass
  598. raise
  599. # Belt and braces for a SIGKILL or power loss that skipped the first-boot
  600. # script's cleanup: remove a leftover token and password file at every boot,
  601. # before the agent starts. Enabled for the NEXT boot only (never --now), because
  602. # on the first boot the token file is still needed by the first-boot script.
  603. - path: /etc/systemd/system/cah-log-shipping-sweep.service
  604. permissions: "0644"
  605. content: |
  606. [Unit]
  607. Description=Remove any leftover log-shipping token and enrollment password
  608. Before=wazuh-agent.service
  609. [Service]
  610. Type=oneshot
  611. ExecStart=/bin/rm -f /etc/cah/hostboot.token /var/ossec/etc/authd.pass
  612. [Install]
  613. WantedBy=multi-user.target
  614. # The agent never needs the enrollment password after it has enrolled, so a stale
  615. # file is removed before every start of the agent (the leading "-" ignores a
  616. # missing file).
  617. - path: /etc/systemd/system/wazuh-agent.service.d/10-cah-no-stale-password.conf
  618. permissions: "0644"
  619. content: |
  620. [Service]
  621. ExecStartPre=-/bin/rm -f /var/ossec/etc/authd.pass
  622. %{ endif ~}
  623. - path: /etc/apt/apt.conf.d/99cah-lock-wait
  624. permissions: "0644"
  625. content: |
  626. DPkg::Lock::Timeout "300";
  627. - path: /etc/ssh/sshd_config.d/99-cah-hardening.conf
  628. permissions: "0644"
  629. content: |
  630. PermitRootLogin no
  631. PasswordAuthentication no
  632. KbdInteractiveAuthentication no
  633. PubkeyAuthentication yes
  634. X11Forwarding no
  635. AllowUsers cah-admin
  636. MaxAuthTries 3
  637. LoginGraceTime 20
  638. - path: /etc/apt/apt.conf.d/20auto-upgrades
  639. permissions: "0644"
  640. content: |
  641. APT::Periodic::Update-Package-Lists "1";
  642. APT::Periodic::Unattended-Upgrade "1";
  643. - path: /etc/apt/apt.conf.d/52cah-unattended-upgrades
  644. permissions: "0644"
  645. content: |
  646. #clear Unattended-Upgrade::Allowed-Origins;
  647. Unattended-Upgrade::Allowed-Origins {
  648. "$${distro_id}:$${distro_codename}-security";
  649. "$${distro_id}ESMApps:$${distro_codename}-apps-security";
  650. "$${distro_id}ESM:$${distro_codename}-infra-security";
  651. };
  652. Unattended-Upgrade::Remove-Unused-Dependencies "true";
  653. Unattended-Upgrade::Automatic-Reboot "true";
  654. Unattended-Upgrade::Automatic-Reboot-WithUsers "true";
  655. Unattended-Upgrade::Automatic-Reboot-Time "${reboot_time}";
  656. - path: /etc/sysctl.d/99-cah-hardening.conf
  657. permissions: "0644"
  658. content: |
  659. # ip_forward is deliberately not set here: the connector may need it.
  660. # rp_filter is loose (2), not strict, so replies on the second interface survive.
  661. net.ipv4.conf.all.rp_filter = 2
  662. net.ipv4.conf.default.rp_filter = 2
  663. net.ipv4.conf.all.accept_redirects = 0
  664. net.ipv4.conf.default.accept_redirects = 0
  665. net.ipv4.conf.all.send_redirects = 0
  666. net.ipv4.conf.default.send_redirects = 0
  667. net.ipv6.conf.all.accept_redirects = 0
  668. net.ipv6.conf.default.accept_redirects = 0
  669. net.ipv4.conf.all.accept_source_route = 0
  670. net.ipv4.conf.default.accept_source_route = 0
  671. net.ipv6.conf.all.accept_source_route = 0
  672. net.ipv6.conf.default.accept_source_route = 0
  673. net.ipv4.tcp_syncookies = 1
  674. net.ipv4.conf.all.log_martians = 1
  675. net.ipv4.conf.default.log_martians = 1
  676. # Weekly connector update, from Twingate's systemd update guide. The two
  677. # connectors update an hour apart so they are never restarted together.
  678. - path: /etc/cron.d/twingate-connector-update
  679. permissions: "0644"
  680. content: |
  681. ${update_minute} ${update_hour} * * 0 root apt-get update -q && apt-get install -yq twingate-connector && systemctl restart twingate-connector
  682. runcmd:
  683. - [sysctl, --system]
  684. - [bash, -c, "sshd -t && systemctl restart ssh"]
  685. - [systemctl, enable, --now, chrony]
  686. %{ if metadata_lock ~}
  687. # --no-block is required: the unit waits for cloud-final, which is what runs
  688. # this very command, so waiting here would deadlock.
  689. - [systemctl, daemon-reload]
  690. - [systemctl, enable, --now, --no-block, cah-metadata-lock.service]
  691. %{ endif ~}
  692. %{ if host_firewall ~}
  693. # --no-block for the same reason. The firewall only filters inbound traffic and
  694. # allows replies, so it can come up before the connector installs.
  695. - [systemctl, daemon-reload]
  696. - [systemctl, enable, --now, --no-block, cah-host-firewall.service]
  697. %{ endif ~}
  698. %{ if node_exporter ~}
  699. # Pick up the drop-in and restart so the exporter runs with the private
  700. # address even if the package started it first. A failure here (no private
  701. # address) is reported and does not stop the connector install below.
  702. - [bash, -c, "systemctl daemon-reload; systemctl restart prometheus-node-exporter || echo 'cah: node exporter did not start' >&2"]
  703. %{ endif ~}
  704. # Install the connector from Twingate's signed apt repository and start it,
  705. # the way their Terraform guide does, instead of running their setup.sh (an
  706. # installer that is piped into bash can have its script swallowed by apt's
  707. # package configuration). The repository key is checked against a pinned
  708. # fingerprint before it is trusted: the file must hold exactly one key, the
  709. # pinned one (cah-apt-key-check). Success means the service is active.
  710. # Retry up to 10 times, 30 seconds apart. Never add set -x here.
  711. - - bash
  712. - -o
  713. - pipefail
  714. - -c
  715. - |
  716. export DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a
  717. KEYRING=/usr/share/keyrings/twingate-connector-keyring.gpg
  718. FPR=EC952DEE4701A407A82B0C505C363F09A9174A9E
  719. for attempt in $(seq 1 10); do
  720. if curl -fsSL --proto '=https' --tlsv1.2 --retry 5 -o /root/twingate.gpg.key https://packages.twingate.com/apt/gpg.key \
  721. && /usr/local/sbin/cah-apt-key-check /root/twingate.gpg.key "$FPR" \
  722. && gpg --dearmor --yes -o "$KEYRING" /root/twingate.gpg.key \
  723. && echo "deb [signed-by=$KEYRING] https://packages.twingate.com/apt/ /" > /etc/apt/sources.list.d/twingate.list \
  724. && apt-get update -q \
  725. && apt-get install -yq twingate-connector \
  726. && systemctl enable --now twingate-connector \
  727. && sleep 5 && systemctl is-active --quiet twingate-connector; then
  728. echo "cah: connector install succeeded on attempt $attempt"
  729. exit 0
  730. fi
  731. echo "cah: connector install attempt $attempt of 10 failed"
  732. sleep 30
  733. done
  734. echo "cah: connector install failed after 10 attempts" >&2
  735. exit 1
  736. %{ if log_shipping ~}
  737. # Install the Wazuh agent from Wazuh's signed apt repository, the same way the
  738. # connector is installed above. The key file must hold exactly one key, whose
  739. # fingerprint is the pinned one (an input, never a default), before it is
  740. # trusted. The agent must NOT start from the install: the unit is masked first
  741. # (and policy-rc.d denies it, see cah-agent-guard), and the first-boot script lifts
  742. # both only after a successful enrollment. If the mask fails nothing is
  743. # installed. Retry up to 10 times, 30 seconds apart. Never add set -x here.
  744. - - bash
  745. - -o
  746. - pipefail
  747. - -c
  748. - |
  749. export DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a
  750. KEYRING=/usr/share/keyrings/wazuh-agent-keyring.gpg
  751. FPR=${log_shipping_key_fingerprint}
  752. AGENT_PACKAGE=${log_shipping_agent_package}
  753. /usr/local/sbin/cah-agent-guard deny || { echo "cah: could not guard wazuh-agent; not installing it" >&2; exit 1; }
  754. for attempt in $(seq 1 10); do
  755. if curl -fsSL --proto '=https' --tlsv1.2 --retry 5 -o /root/wazuh.gpg.key https://packages.wazuh.com/key/GPG-KEY-WAZUH \
  756. && /usr/local/sbin/cah-apt-key-check /root/wazuh.gpg.key "$FPR" \
  757. && gpg --dearmor --yes -o "$KEYRING" /root/wazuh.gpg.key \
  758. && echo "deb [signed-by=$KEYRING] https://packages.wazuh.com/4.x/apt/ stable main" > /etc/apt/sources.list.d/wazuh.list \
  759. && apt-get update -q \
  760. && apt-get install -yq "$AGENT_PACKAGE"; then
  761. echo "cah: wazuh agent install succeeded on attempt $attempt"
  762. exit 0
  763. fi
  764. echo "cah: wazuh agent install attempt $attempt of 10 failed"
  765. sleep 30
  766. done
  767. echo "cah: wazuh agent install failed after 10 attempts" >&2
  768. exit 1
  769. # Remove a leftover token or password file at every LATER boot (never started
  770. # now: the token file is still needed below). The audit rules are loaded inside
  771. # the first-boot script, where a failure fails closed.
  772. - [bash, -c, "systemctl daemon-reload && systemctl enable cah-log-shipping-sweep.service"]
  773. # Always runs, even when the install above failed, so the token file is
  774. # deleted either way; the script then fails closed.
  775. - [/usr/local/sbin/cah-log-shipping-firstboot]
  776. %{ endif ~}
  777. # Leave the outcome where someone can read it later. No token is read here.
  778. - - bash
  779. - -c
  780. - |
  781. umask 027
  782. {
  783. echo "== date"; date
  784. echo "== systemctl is-active twingate-connector"; systemctl is-active twingate-connector
  785. echo "== journalctl -u twingate-connector (last 50)"; journalctl -u twingate-connector -n 50 --no-pager
  786. echo "== /var/log/cloud-init-output.log (last 50)"; tail -n 50 /var/log/cloud-init-output.log
  787. } > /var/log/cah-connector-install.log 2>&1
  788. chmod 0640 /var/log/cah-connector-install.log