| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803 |
- #cloud-config
- # Hardened baseline for a Twingate connector droplet. SSH is reachable only
- # through Twingate (the DigitalOcean firewall allows no inbound traffic); the
- # sshd settings below are the second layer. Changing this file changes
- # user_data, which forces a droplet rebuild.
- # First-hour order (the same one the stage guides state): update, baseline,
- # harden, then applications. In this file: the package update, upgrade and
- # unattended-upgrades come first, the baseline (users, sshd settings, files) is
- # written next, the hardening is switched on (sshd restarted) before the
- # Twingate connector, which is installed last.
- disable_root: true
- # Local time, so the reboot window and the weekly update below are Eastern.
- timezone: ${timezone}
- ssh_pwauth: false
- package_update: true
- package_upgrade: true
- packages:
- - unattended-upgrades
- - chrony
- %{ if node_exporter ~}
- - prometheus-node-exporter
- %{ endif ~}
- %{ if log_shipping ~}
- - auditd
- %{ endif ~}
- %{ if metadata_lock || host_firewall ~}
- - nftables
- %{ endif ~}
- users:
- - name: cah-admin
- gecos: CAH admin
- lock_passwd: true
- shell: /bin/bash
- groups: [sudo]
- sudo: ALL=(ALL) NOPASSWD:ALL
- ssh_authorized_keys:
- - ${admin_ssh_public_key}
- write_files:
- # First boot races Ubuntu's own apt-daily and unattended-upgrades for the
- # dpkg lock; wait for it instead of failing the Twingate install.
- # The connector config, written directly as in Twingate's own Terraform
- # (https://www.twingate.com/docs/terraform-aws). Root-only. The tokens appear
- # here and nowhere else in this file.
- - path: /etc/twingate/connector.conf
- permissions: "0600"
- owner: root:root
- content: |
- TWINGATE_URL=https://${network}.twingate.com
- TWINGATE_ACCESS_TOKEN=${access_token}
- TWINGATE_REFRESH_TOKEN=${refresh_token}
- ${telemetry_conf}%{ if metadata_lock ~}
- # Lock the droplet metadata endpoint (it serves this very user-data, tokens
- # included) to root and to the DigitalOcean monitoring agent's user. The rule
- # lives in its own nftables table, so it never touches any other rule.
- - path: /usr/local/sbin/cah-metadata-lock
- permissions: "0750"
- owner: root:root
- content: |
- #!/usr/bin/env bash
- set -euo pipefail
- # uid 0 always; the do-agent user too when it exists (DigitalOcean's
- # monitoring agent reads the metadata address as that user). AWS has none.
- allowed="0"
- if agent_uid="$(id -u do-agent 2>/dev/null)"; then
- allowed="0, $agent_uid"
- fi
- nft -f - <<EOF
- table inet cah_metadata
- delete table inet cah_metadata
- table inet cah_metadata {
- chain output {
- type filter hook output priority 0; policy accept;
- ip daddr 169.254.169.254 meta skuid != { $allowed } reject with icmp type admin-prohibited
- }
- }
- EOF
- echo "cah-metadata-lock: metadata endpoint allowed for uids: $allowed"
- # After cloud-final so the do-agent user already exists on first boot.
- # Ubuntu's nftables.service loads /etc/nftables.conf, which starts with
- # "flush ruleset", on start, restart and reload, and its package upgrade
- # try-restarts it: that would silently drop our table. So this unit is ordered
- # After= it, is PartOf= it (a stop or restart of nftables.service restarts this
- # unit, which re-runs the idempotent script) and takes its reloads too. All
- # three are soft: no Requires=, Wants= or Requisite=, so when nftables.service
- # is inactive (the first-boot state) this unit still starts and does not fail.
- # PartOf= and ReloadPropagatedFrom= only forward jobs that nftables.service
- # already has; they never start it. Untested on a real machine.
- - path: /etc/systemd/system/cah-metadata-lock.service
- permissions: "0644"
- content: |
- [Unit]
- Description=Restrict the droplet metadata endpoint to root and do-agent
- After=cloud-final.service network-online.target
- After=nftables.service
- PartOf=nftables.service
- ReloadPropagatedFrom=nftables.service
- Wants=network-online.target
- [Service]
- Type=oneshot
- RemainAfterExit=yes
- ExecStart=/usr/local/sbin/cah-metadata-lock
- ExecReload=/usr/local/sbin/cah-metadata-lock
- [Install]
- WantedBy=multi-user.target
- %{ endif ~}
- %{ if host_firewall ~}
- # A default-drop host firewall, the second layer behind the cloud firewall. It
- # lives in its own nftables table (inet cah_host), so it never flushes or
- # touches any other rule, including the metadata lock's table. Only the input
- # chain is filtered; output and forward are left alone.
- - path: /usr/local/sbin/cah-host-firewall
- permissions: "0750"
- owner: root:root
- content: |
- #!/usr/bin/env bash
- set -euo pipefail
- ssh_sources="${host_firewall_ssh_sources}"
- # Empty unless connector_telemetry.metrics_port is set.
- metrics_port="${host_firewall_metrics_port}"
- metrics_rule=""
- if [ -n "$metrics_port" ]; then
- metrics_rule="tcp dport $metrics_port ip saddr { $ssh_sources } accept"
- fi
- %{ if node_exporter ~}
- node_exporter_port="${host_firewall_node_exporter}"
- node_exporter_rule="tcp dport $node_exporter_port ip saddr { $ssh_sources } accept"
- %{ endif ~}
- # Why each accept exists:
- # - lo and established/related: local traffic and replies to what this
- # machine started (the connector, apt, DNS, NTP all work on replies).
- # - ICMPv4 echo, unreachable and time-exceeded: ping, and path MTU and
- # error reporting.
- # - ICMPv6 neighbour discovery and packet-too-big: the machines have no
- # public IPv6, but link-local neighbour discovery must keep working.
- # - DHCPv4 replies (server port 67 to client port 68): lease renewal.
- # - TCP 22 and the metrics port: only from the private sources.
- # The same ruleset serves DigitalOcean and AWS.
- read -r -d '' ruleset <<EOF || true
- table inet cah_host
- delete table inet cah_host
- table inet cah_host {
- chain input {
- type filter hook input priority 0; policy drop;
- iifname "lo" accept
- ct state established,related accept
- ct state invalid drop
- icmp type { echo-request, destination-unreachable, time-exceeded } accept
- icmpv6 type { destination-unreachable, packet-too-big, time-exceeded, echo-request, nd-router-advert, nd-neighbor-solicit, nd-neighbor-advert } accept
- udp sport 67 udp dport 68 accept
- tcp dport 22 ip saddr { $ssh_sources } accept
- $metrics_rule
- %{ if node_exporter ~}
- $node_exporter_rule
- %{ endif ~}
- }
- }
- EOF
- # Refuse a ruleset that does not parse, before anything changes.
- if ! printf '%s\n' "$ruleset" | nft -c -f -; then
- echo "cah-host-firewall: refusing to apply: the ruleset does not parse" >&2
- exit 1
- fi
- printf '%s\n' "$ruleset" | nft -f -
- # Verify, and roll back (delete only our own table) if the machine could
- # no longer be reached over SSH.
- listening=""
- listed=""
- listening="$(ss -H -ltn)" || listening=""
- listed="$(nft list table inet cah_host)" || listed=""
- if [[ ! "$listening" =~ :22[[:space:]] ]] || [[ "$listed" != *"tcp dport 22"* ]]; then
- echo "cah-host-firewall: verification failed (sshd not listening on 22, or the ssh accept is not loaded): removing the table" >&2
- nft delete table inet cah_host || echo "cah-host-firewall: could not delete the table" >&2
- exit 1
- fi
- echo "cah-host-firewall: loaded; ssh and metrics allowed from: $ssh_sources"
- # Same reasoning as the metadata lock unit: nftables.service flushes the whole
- # ruleset, so this unit is After=, PartOf= and ReloadPropagatedFrom= it (soft,
- # nothing is pulled in, and it still starts when nftables.service is inactive).
- # No ExecStop: a plain "stop nftables" still flushes our table, and the docs say so.
- - path: /etc/systemd/system/cah-host-firewall.service
- permissions: "0644"
- content: |
- [Unit]
- Description=Default-drop host firewall (inet cah_host)
- After=cloud-final.service network-online.target
- After=nftables.service
- PartOf=nftables.service
- ReloadPropagatedFrom=nftables.service
- Wants=network-online.target
- [Service]
- Type=oneshot
- RemainAfterExit=yes
- ExecStart=/usr/local/sbin/cah-host-firewall
- ExecReload=/usr/local/sbin/cah-host-firewall
- [Install]
- WantedBy=multi-user.target
- %{ endif ~}
- %{ if node_exporter ~}
- # Host metrics (node exporter), bound to the private address only. The Ubuntu
- # package starts the exporter on every interface by default, so a systemd
- # drop-in replaces its command line before the package ever starts it
- # (write_files runs before the package install). The drop-in's ExecStart is a
- # wrapper that picks the private address itself at every start and then execs
- # the exporter, so nothing depends on the order systemd reads files in. If the
- # wrapper finds no private IPv4 address it exits 1 and the exporter does not
- # start at all, so there is no wildcard fallback. The exporter has no
- # authentication: the cloud firewall (tag-sourced rule) and the optional host
- # firewall are what limit who reaches it.
- - path: /usr/local/sbin/cah-node-exporter-run
- permissions: "0755"
- owner: root:root
- content: |
- #!/usr/bin/env bash
- set -euo pipefail
- port="${node_exporter_port}"
- # The first RFC 1918 IPv4 address on an interface that holds no public
- # IPv4 address. On DigitalOcean eth0 holds the public address plus a legacy
- # private one, and the VPC address is on eth1; AWS's primary interface
- # holds one private address. Fields of `ip -o`: the interface name and the
- # CIDR. Pass 1 marks interfaces with a public address, pass 2 picks.
- addr="$(ip -4 -o addr show scope global | awk '
- function priv(a) {
- return (a ~ /^10\./ || a ~ /^192\.168\./ || a ~ /^172\.(1[6-9]|2[0-9]|3[01])\./)
- }
- { split($4, c, "/"); n++; ifn[n] = $2; ip[n] = c[1]; if (!priv(c[1])) pub[$2] = 1 }
- END {
- for (i = 1; i <= n; i++)
- if (priv(ip[i]) && !(ifn[i] in pub)) { print ip[i]; exit }
- }')"
- if [ -z "$addr" ]; then
- echo "cah-node-exporter-run: no private IPv4 address found; refusing to start the node exporter" >&2
- exit 1
- fi
- exec /usr/bin/prometheus-node-exporter "--web.listen-address=$addr:$port"
- - path: /etc/systemd/system/prometheus-node-exporter.service.d/10-cah-private-bind.conf
- permissions: "0644"
- content: |
- [Service]
- ExecStart=
- ExecStart=/usr/local/sbin/cah-node-exporter-run
- %{ endif ~}
- # The pinned-key check, shared by every apt repository key this file trusts
- # (the Twingate connector always, Wazuh with log shipping). gpg lists the
- # downloaded key file; this accepts it only when it holds exactly ONE primary
- # key (one pub record, no secret keys) whose primary fingerprint equals the
- # pin. A subkey carries its own fpr record, so an
- # fpr is accepted only directly after a sub record; a second fpr that follows
- # no sub, or any second pub, is refused. So a bundle of the pinned key plus an
- # attacker key is never trusted.
- - path: /usr/local/sbin/cah-apt-key-check
- permissions: "0755"
- owner: root:root
- content: |
- #!/usr/bin/env bash
- set -euo pipefail
- refuse() { echo "cah-apt-key-check: refusing: $1" >&2; exit 1; }
- [ "$#" -eq 2 ] || refuse "usage: cah-apt-key-check <keyfile> <fingerprint>"
- keyfile="$1"
- pin="$2"
- listing="$(gpg --show-keys --with-colons "$keyfile")" || refuse "gpg could not read the key file"
- pubs=0
- primary=""
- prev=""
- while IFS=: read -r rec _ _ _ _ _ _ _ _ f10 _; do
- case "$rec" in
- pub) pubs=$((pubs + 1)); prev=pub ;;
- sub) prev=sub ;;
- sec|ssb) refuse "the file holds a secret key" ;;
- fpr)
- if [ "$prev" = pub ] && [ -z "$primary" ]; then
- primary="$f10"
- prev=fpr
- elif [ "$prev" = sub ]; then
- prev=fpr
- else
- refuse "an unexpected extra fingerprint record"
- fi
- ;;
- esac
- done <<< "$listing"
- [ "$pubs" -eq 1 ] || refuse "expected exactly one public key, found $pubs"
- [ "$primary" = "$pin" ] || refuse "the key fingerprint is not the pinned one"
- %{ if log_shipping ~}
- # Log shipping (opt-in): the Wazuh agent and auditd. The ONLY secret-related
- # value in this file is the short-lived, read-only Doppler token for the
- # config "${log_shipping_hostboot_config}", written to a root-only file that the
- # first-boot script deletes before it uses the token. The enrollment password
- # is NOT here: the script pulls it from Doppler at first boot, uses it once and
- # removes it. No Twingate service key and no Doppler secret value is rendered
- # anywhere. Untested on a real machine.
- - path: /etc/cah/hostboot.token
- permissions: "0600"
- owner: root:root
- content: |
- ${log_shipping_bootstrap_token}
- # Runs once, from runcmd, after the agent package is installed. Fails closed:
- # when the pull or the enrollment fails the agent is never enabled or started,
- # the reason goes to the cloud-init log, and nothing falls back to a literal.
- # Never add set -x here: it would print the token and the password.
- - path: /usr/local/sbin/cah-log-shipping-firstboot
- permissions: "0750"
- owner: root:root
- content: |
- #!/usr/bin/env bash
- set -euo pipefail
- umask 077
- TOKEN_FILE=/etc/cah/hostboot.token
- PASS_FILE=/var/ossec/etc/authd.pass
- GUARD=/usr/local/sbin/cah-agent-guard
- OSSEC_INSERT=/usr/local/sbin/cah-ossec-insert
- OSSEC_CONF=/var/ossec/etc/ossec.conf
- LOCALFILE_XML=/etc/cah/wazuh-localfile.xml
- RULES_B64=/etc/audit/rules.d/60-cah.rules
- RULES_B32=/etc/audit/rules.d/61-cah-b32.rules
- AGENT_AUTH=/var/ossec/bin/agent-auth
- RUN_DIR=/run/cah-log-shipping
- manager="${log_shipping_manager_address}"
- manager_port="${log_shipping_manager_port}"
- enroll_port="${log_shipping_enroll_port}"
- agent_name="${log_shipping_agent_name}"
- agent_group="${log_shipping_agent_group}"
- work=""
- log() { echo "cah-log-shipping: $*" >&2; }
- fail() {
- log "FAILED: $1; failing closed, the Wazuh agent is not started"
- systemctl stop wazuh-agent >/dev/null 2>&1 || true
- systemctl disable wazuh-agent >/dev/null 2>&1 || true
- # The unit is masked directly first, whatever state policy-rc.d is in.
- if ! systemctl mask wazuh-agent; then
- log "CRITICAL: could not mask wazuh-agent; it may be startable, check it by hand"
- fi
- # Then both guards back. If the guard cannot restore the policy-rc.d
- # denial (an unmanaged file is in the way), it has already masked the unit,
- # and this says so on the record instead of hiding it.
- if ! "$GUARD" deny; then
- 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"
- fi
- exit 1
- }
- # Whatever happens, the token file, the password file and the pulled
- # config do not outlive this script.
- cleanup() {
- rm -f "$TOKEN_FILE" "$PASS_FILE"
- if [ -n "$work" ]; then rm -rf "$work"; fi
- }
- trap cleanup EXIT
- # A killed earlier run (SIGKILL, power loss) skips the trap. A password
- # file or a pulled config found now can only be such a leftover, so remove
- # it before anything else. The token file is this script's input and is not
- # swept here; the boot-time sweep unit covers a token that outlived a boot.
- rm -f "$PASS_FILE"
- rm -rf "$RUN_DIR"
- [ -f "$TOKEN_FILE" ] || fail "no bootstrap token file at $TOKEN_FILE"
- token="$(cat "$TOKEN_FILE")"
- rm -f "$TOKEN_FILE"
- [ -n "$token" ] || fail "the bootstrap token file was empty"
- [ -x "$AGENT_AUTH" ] || fail "the Wazuh agent is not installed ($AGENT_AUTH is missing)"
- # The 60-cah.rules file watches 64-bit programs (arch=b64). A 32-bit
- # program could still write the same files unseen, which the old -w watch
- # would have caught, so on x86_64 (where 32-bit programs run) each rule is
- # copied with arch=b32. Elsewhere (arm64 Graviton) an arch=b32 rule may not
- # load, which would fail this script closed, so it is not written there.
- if [ "$(uname -m)" = x86_64 ]; then
- sed 's/arch=b64/arch=b32/' "$RULES_B64" > "$RULES_B32" || fail "could not write $RULES_B32"
- chmod 0640 "$RULES_B32"
- else
- rm -f "$RULES_B32"
- fi
- augenrules --load || fail "augenrules --load failed"
- mkdir -p "$RUN_DIR"
- work="$(mktemp -d "$RUN_DIR/pull.XXXXXX")"
- # The token goes to curl on stdin (-K -), so it is never in an argument list.
- 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
- fail "pull from Doppler failed (config ${log_shipping_hostboot_config}; the token may have expired)"
- fi
- unset token
- 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
- fail "the pulled config has no usable WAZUH_ENROLLMENT_PASSWORD"
- fi
- # Only that one value is kept; the rest of the pulled config goes now.
- rm -rf "$work"
- work=""
- printf '%s' "$password" > "$PASS_FILE"
- chmod 0600 "$PASS_FILE"
- unset password
- args=(-m "$manager" -p "$enroll_port" -A "$agent_name")
- if [ -n "$agent_group" ]; then args+=(-G "$agent_group"); fi
- if ! "$AGENT_AUTH" "$${args[@]}"; then
- rm -f "$PASS_FILE"
- fail "enrollment failed (agent-auth against $manager:$enroll_port)"
- fi
- # Enrolled: the password is not needed again. The per-host agent key stays.
- rm -f "$PASS_FILE"
- 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"
- if ! grep -q 'cah-log-shipping-localfiles' "$OSSEC_CONF"; then
- "$OSSEC_INSERT" "$OSSEC_CONF" "$LOCALFILE_XML" || fail "could not add the log sources to $OSSEC_CONF"
- fi
- # Enrolled and configured: only now is the agent allowed to run. Both
- # guards (the mask and the policy-rc.d denial) are lifted here and nowhere
- # else; every failure above leaves them in place, and a failure after this
- # point puts both back.
- "$GUARD" allow || fail "could not lift the guards on wazuh-agent"
- systemctl enable --now wazuh-agent || fail "wazuh-agent did not start"
- systemctl is-active --quiet wazuh-agent || fail "wazuh-agent is not active after start"
- log "agent $agent_name enrolled with $manager and started"
- # Log sources, inserted inside the agent's existing <ossec_config> element by
- # the script above (a fragment of <localfile> blocks and one <labels> block,
- # not a document). The site label is what the Grafana Wazuh dashboard filters
- # on (agent.labels.site); it is the site part of the agent name. The
- # journald log format and its filter fields are UNVERIFIED against the agent
- # version your manager runs (design section 6.1); if the agent rejects them,
- # remove the journald blocks and use the documented syslog fallback.
- - path: /etc/cah/wazuh-localfile.xml
- permissions: "0640"
- owner: root:root
- content: |
- <!-- cah-log-shipping-localfiles -->
- <labels>
- <label key="site">${log_shipping_site}</label>
- </labels>
- <localfile>
- <log_format>journald</log_format>
- <location>journald</location>
- <filter field="_SYSTEMD_UNIT">^twingate-connector\.service$</filter>
- </localfile>
- <localfile>
- <log_format>journald</log_format>
- <location>journald</location>
- <filter field="_SYSTEMD_UNIT">^(ssh|sshd)\.service$</filter>
- </localfile>
- <localfile>
- <log_format>journald</log_format>
- <location>journald</location>
- <filter field="SYSLOG_IDENTIFIER">^sudo$</filter>
- </localfile>
- <localfile>
- <log_format>syslog</log_format>
- <location>/var/log/auth.log</location>
- </localfile>
- <localfile>
- <log_format>audit</log_format>
- <location>/var/log/audit/audit.log</location>
- </localfile>
- # A short auditd rule set: file watches only (who changed identity files, sudo
- # configuration or the Twingate config), written as -a always,exit rules, the
- # form the auditctl man page recommends over the deprecated -w watch. Each rule
- # keeps the old watch's path, write and attribute-change (wa) permissions and
- # key; dir= keeps a directory watch recursive. This file is the arch=b64 half;
- # the first-boot script adds the arch=b32 twin of every rule on x86_64 only
- # (61-cah-b32.rules), so a 32-bit program is seen as the old watch saw it.
- # No -S syscall filters and no
- # execve, because per-command auditing is too noisy for the 1 GB droplets.
- - path: /etc/audit/rules.d/60-cah.rules
- permissions: "0640"
- owner: root:root
- content: |
- -a always,exit -F arch=b64 -F path=/etc/passwd -F perm=wa -F key=cah_identity
- -a always,exit -F arch=b64 -F path=/etc/group -F perm=wa -F key=cah_identity
- -a always,exit -F arch=b64 -F path=/etc/shadow -F perm=wa -F key=cah_identity
- -a always,exit -F arch=b64 -F path=/etc/gshadow -F perm=wa -F key=cah_identity
- -a always,exit -F arch=b64 -F path=/etc/sudoers -F perm=wa -F key=cah_sudo
- -a always,exit -F arch=b64 -F dir=/etc/sudoers.d/ -F perm=wa -F key=cah_sudo
- -a always,exit -F arch=b64 -F dir=/etc/twingate/ -F perm=wa -F key=cah_twingate
- # The Wazuh deb may start its service when it is installed, before the agent is
- # enrolled. This script puts both guards in place (deny) or lifts them (allow):
- # the unit is masked, and a policy-rc.d answers 101 ("denied") for wazuh-agent
- # only. Any policy-rc.d that already existed is moved aside, not replaced: the
- # new one delegates every other request to it, and "allow" puts it back byte for
- # byte (or removes ours when there was none).
- # Ownership of the policy file is not guessed from its text. deny records the
- # sha256 of exactly what it installed in a state file; a policy is ours only
- # when that file exists and the hash still matches, so an unrelated policy that
- # happens to mention a marker is never overwritten or deleted. A symlink is
- # refused (nothing is written through it) and the policy is installed from a
- # temporary file in the same directory by rename. deny masks the unit FIRST and
- # whatever else happens, so a policy problem can never leave the unit startable;
- # any problem is reported on stderr and makes the script exit non-zero.
- # UNVERIFIED on a real machine.
- - path: /usr/local/sbin/cah-agent-guard
- permissions: "0755"
- owner: root:root
- content: |
- #!/usr/bin/env bash
- set -uo pipefail
- POLICY_RC=/usr/sbin/policy-rc.d
- POLICY_ORIG=/usr/sbin/policy-rc.d.cah-orig
- STATE=/var/lib/cah/agent-guard.state
- problem=0
- warn() { echo "cah-agent-guard: $1" >&2; }
- refuse() { warn "refusing: $1"; problem=1; }
- hash_of() { local h _; read -r h _ < <(sha256sum "$1") && printf '%s\n' "$h"; }
- ours() {
- local want have
- [ -f "$STATE" ] && [ -f "$POLICY_RC" ] && [ ! -L "$POLICY_RC" ] || return 1
- read -r want < "$STATE" || return 1
- have="$(hash_of "$POLICY_RC")" || return 1
- [ -n "$want" ] && [ "$want" = "$have" ]
- }
- install_policy() {
- local dir tmp
- dir="$(dirname "$POLICY_RC")"
- tmp="$(mktemp "$dir/.cah-policy.XXXXXX")" || { refuse "could not create a temporary file in $dir"; return; }
- cat > "$tmp" <<'EOF'
- #!/bin/sh
- # cah-wazuh-deny
- if [ "$1" = "wazuh-agent" ]; then
- exit 101
- fi
- if [ -x /usr/sbin/policy-rc.d.cah-orig ]; then
- exec /usr/sbin/policy-rc.d.cah-orig "$@"
- fi
- exit 0
- EOF
- chmod 0755 "$tmp"
- mkdir -p "$(dirname "$STATE")"
- hash_of "$tmp" > "$STATE.new" && mv -f "$STATE.new" "$STATE" || { rm -f "$tmp" "$STATE.new"; refuse "could not record the policy hash"; return; }
- mv -T -f "$tmp" "$POLICY_RC" || { rm -f "$tmp"; refuse "could not install $POLICY_RC"; return; }
- }
- deny() {
- systemctl mask wazuh-agent || { warn "could not mask wazuh-agent"; problem=1; }
- if [ -L "$POLICY_RC" ]; then refuse "$POLICY_RC is a symlink"; return; fi
- if [ -e "$POLICY_RC" ] && ! ours; then
- if [ -e "$POLICY_ORIG" ] || [ -L "$POLICY_ORIG" ]; then
- refuse "an unmanaged $POLICY_RC and a saved original both exist; leaving both untouched"
- return
- fi
- mv -T "$POLICY_RC" "$POLICY_ORIG" || { refuse "could not save the existing policy"; return; }
- fi
- install_policy
- }
- allow() {
- systemctl unmask wazuh-agent || { warn "could not unmask wazuh-agent; leaving both guards in place"; problem=1; return; }
- if [ -L "$POLICY_RC" ]; then warn "$POLICY_RC is a symlink; leaving it alone"; return; fi
- if ours; then
- if [ -e "$POLICY_ORIG" ]; then
- mv -T -f "$POLICY_ORIG" "$POLICY_RC" || { refuse "could not restore the original policy"; return; }
- else
- rm -f "$POLICY_RC"
- fi
- rm -f "$STATE"
- fi
- }
- case "$${1:-}" in
- deny) deny ;;
- allow) allow ;;
- *) warn "usage: cah-agent-guard deny|allow"; exit 1 ;;
- esac
- exit "$problem"
- # Inserts the log sources into the agent's ossec.conf. The file is rewritten by
- # a same-directory temporary file (written, flushed, fsynced, mode and owner
- # copied) and an atomic rename, so a full disk or a kill leaves the original
- # intact. The result must be well-formed and must not add a top-level element;
- # otherwise nothing is installed.
- - path: /usr/local/sbin/cah-ossec-insert
- permissions: "0755"
- owner: root:root
- content: |
- #!/usr/bin/env python3
- import os
- import sys
- import tempfile
- import xml.etree.ElementTree as ET
- def refuse(why):
- sys.stderr.write("cah-ossec-insert: refusing: " + why + "\n")
- sys.exit(1)
- def top_level(text):
- return len(ET.fromstring("<cah>" + text + "</cah>"))
- path, frag_path = sys.argv[1], sys.argv[2]
- with open(path) as f:
- conf = f.read()
- with open(frag_path) as f:
- frag = f.read()
- i = conf.rfind("</ossec_config>")
- if i < 0:
- refuse(path + " has no closing </ossec_config>")
- new = conf[:i] + frag + conf[i:]
- try:
- before, after = top_level(conf), top_level(new)
- except ET.ParseError as exc:
- refuse("the result would not be well-formed XML (" + str(exc) + ")")
- if before != after:
- refuse("the result would have " + str(after) + " top-level elements, not " + str(before))
- st = os.stat(path)
- fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path) or ".", prefix=".ossec.conf.")
- try:
- with os.fdopen(fd, "w") as out:
- out.write(new)
- out.flush()
- os.fsync(out.fileno())
- os.chmod(tmp, st.st_mode & 0o7777)
- os.chown(tmp, st.st_uid, st.st_gid)
- os.replace(tmp, path)
- except BaseException:
- try:
- os.unlink(tmp)
- except OSError:
- pass
- raise
- # Belt and braces for a SIGKILL or power loss that skipped the first-boot
- # script's cleanup: remove a leftover token and password file at every boot,
- # before the agent starts. Enabled for the NEXT boot only (never --now), because
- # on the first boot the token file is still needed by the first-boot script.
- - path: /etc/systemd/system/cah-log-shipping-sweep.service
- permissions: "0644"
- content: |
- [Unit]
- Description=Remove any leftover log-shipping token and enrollment password
- Before=wazuh-agent.service
- [Service]
- Type=oneshot
- ExecStart=/bin/rm -f /etc/cah/hostboot.token /var/ossec/etc/authd.pass
- [Install]
- WantedBy=multi-user.target
- # The agent never needs the enrollment password after it has enrolled, so a stale
- # file is removed before every start of the agent (the leading "-" ignores a
- # missing file).
- - path: /etc/systemd/system/wazuh-agent.service.d/10-cah-no-stale-password.conf
- permissions: "0644"
- content: |
- [Service]
- ExecStartPre=-/bin/rm -f /var/ossec/etc/authd.pass
- %{ endif ~}
- - path: /etc/apt/apt.conf.d/99cah-lock-wait
- permissions: "0644"
- content: |
- DPkg::Lock::Timeout "300";
- - path: /etc/ssh/sshd_config.d/99-cah-hardening.conf
- permissions: "0644"
- content: |
- PermitRootLogin no
- PasswordAuthentication no
- KbdInteractiveAuthentication no
- PubkeyAuthentication yes
- X11Forwarding no
- AllowUsers cah-admin
- MaxAuthTries 3
- LoginGraceTime 20
- - path: /etc/apt/apt.conf.d/20auto-upgrades
- permissions: "0644"
- content: |
- APT::Periodic::Update-Package-Lists "1";
- APT::Periodic::Unattended-Upgrade "1";
- - path: /etc/apt/apt.conf.d/52cah-unattended-upgrades
- permissions: "0644"
- content: |
- #clear Unattended-Upgrade::Allowed-Origins;
- Unattended-Upgrade::Allowed-Origins {
- "$${distro_id}:$${distro_codename}-security";
- "$${distro_id}ESMApps:$${distro_codename}-apps-security";
- "$${distro_id}ESM:$${distro_codename}-infra-security";
- };
- Unattended-Upgrade::Remove-Unused-Dependencies "true";
- Unattended-Upgrade::Automatic-Reboot "true";
- Unattended-Upgrade::Automatic-Reboot-WithUsers "true";
- Unattended-Upgrade::Automatic-Reboot-Time "${reboot_time}";
- - path: /etc/sysctl.d/99-cah-hardening.conf
- permissions: "0644"
- content: |
- # ip_forward is deliberately not set here: the connector may need it.
- # rp_filter is loose (2), not strict, so replies on the second interface survive.
- net.ipv4.conf.all.rp_filter = 2
- net.ipv4.conf.default.rp_filter = 2
- net.ipv4.conf.all.accept_redirects = 0
- net.ipv4.conf.default.accept_redirects = 0
- net.ipv4.conf.all.send_redirects = 0
- net.ipv4.conf.default.send_redirects = 0
- net.ipv6.conf.all.accept_redirects = 0
- net.ipv6.conf.default.accept_redirects = 0
- net.ipv4.conf.all.accept_source_route = 0
- net.ipv4.conf.default.accept_source_route = 0
- net.ipv6.conf.all.accept_source_route = 0
- net.ipv6.conf.default.accept_source_route = 0
- net.ipv4.tcp_syncookies = 1
- net.ipv4.conf.all.log_martians = 1
- net.ipv4.conf.default.log_martians = 1
- # Weekly connector update, from Twingate's systemd update guide. The two
- # connectors update an hour apart so they are never restarted together.
- - path: /etc/cron.d/twingate-connector-update
- permissions: "0644"
- content: |
- ${update_minute} ${update_hour} * * 0 root apt-get update -q && apt-get install -yq twingate-connector && systemctl restart twingate-connector
- runcmd:
- - [sysctl, --system]
- - [bash, -c, "sshd -t && systemctl restart ssh"]
- - [systemctl, enable, --now, chrony]
- %{ if metadata_lock ~}
- # --no-block is required: the unit waits for cloud-final, which is what runs
- # this very command, so waiting here would deadlock.
- - [systemctl, daemon-reload]
- - [systemctl, enable, --now, --no-block, cah-metadata-lock.service]
- %{ endif ~}
- %{ if host_firewall ~}
- # --no-block for the same reason. The firewall only filters inbound traffic and
- # allows replies, so it can come up before the connector installs.
- - [systemctl, daemon-reload]
- - [systemctl, enable, --now, --no-block, cah-host-firewall.service]
- %{ endif ~}
- %{ if node_exporter ~}
- # Pick up the drop-in and restart so the exporter runs with the private
- # address even if the package started it first. A failure here (no private
- # address) is reported and does not stop the connector install below.
- - [bash, -c, "systemctl daemon-reload; systemctl restart prometheus-node-exporter || echo 'cah: node exporter did not start' >&2"]
- %{ endif ~}
- # Install the connector from Twingate's signed apt repository and start it,
- # the way their Terraform guide does, instead of running their setup.sh (an
- # installer that is piped into bash can have its script swallowed by apt's
- # package configuration). The repository key is checked against a pinned
- # fingerprint before it is trusted: the file must hold exactly one key, the
- # pinned one (cah-apt-key-check). Success means the service is active.
- # Retry up to 10 times, 30 seconds apart. Never add set -x here.
- - - bash
- - -o
- - pipefail
- - -c
- - |
- export DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a
- KEYRING=/usr/share/keyrings/twingate-connector-keyring.gpg
- FPR=EC952DEE4701A407A82B0C505C363F09A9174A9E
- for attempt in $(seq 1 10); do
- if curl -fsSL --proto '=https' --tlsv1.2 --retry 5 -o /root/twingate.gpg.key https://packages.twingate.com/apt/gpg.key \
- && /usr/local/sbin/cah-apt-key-check /root/twingate.gpg.key "$FPR" \
- && gpg --dearmor --yes -o "$KEYRING" /root/twingate.gpg.key \
- && echo "deb [signed-by=$KEYRING] https://packages.twingate.com/apt/ /" > /etc/apt/sources.list.d/twingate.list \
- && apt-get update -q \
- && apt-get install -yq twingate-connector \
- && systemctl enable --now twingate-connector \
- && sleep 5 && systemctl is-active --quiet twingate-connector; then
- echo "cah: connector install succeeded on attempt $attempt"
- exit 0
- fi
- echo "cah: connector install attempt $attempt of 10 failed"
- sleep 30
- done
- echo "cah: connector install failed after 10 attempts" >&2
- exit 1
- %{ if log_shipping ~}
- # Install the Wazuh agent from Wazuh's signed apt repository, the same way the
- # connector is installed above. The key file must hold exactly one key, whose
- # fingerprint is the pinned one (an input, never a default), before it is
- # trusted. The agent must NOT start from the install: the unit is masked first
- # (and policy-rc.d denies it, see cah-agent-guard), and the first-boot script lifts
- # both only after a successful enrollment. If the mask fails nothing is
- # installed. Retry up to 10 times, 30 seconds apart. Never add set -x here.
- - - bash
- - -o
- - pipefail
- - -c
- - |
- export DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a
- KEYRING=/usr/share/keyrings/wazuh-agent-keyring.gpg
- FPR=${log_shipping_key_fingerprint}
- AGENT_PACKAGE=${log_shipping_agent_package}
- /usr/local/sbin/cah-agent-guard deny || { echo "cah: could not guard wazuh-agent; not installing it" >&2; exit 1; }
- for attempt in $(seq 1 10); do
- if curl -fsSL --proto '=https' --tlsv1.2 --retry 5 -o /root/wazuh.gpg.key https://packages.wazuh.com/key/GPG-KEY-WAZUH \
- && /usr/local/sbin/cah-apt-key-check /root/wazuh.gpg.key "$FPR" \
- && gpg --dearmor --yes -o "$KEYRING" /root/wazuh.gpg.key \
- && echo "deb [signed-by=$KEYRING] https://packages.wazuh.com/4.x/apt/ stable main" > /etc/apt/sources.list.d/wazuh.list \
- && apt-get update -q \
- && apt-get install -yq "$AGENT_PACKAGE"; then
- echo "cah: wazuh agent install succeeded on attempt $attempt"
- exit 0
- fi
- echo "cah: wazuh agent install attempt $attempt of 10 failed"
- sleep 30
- done
- echo "cah: wazuh agent install failed after 10 attempts" >&2
- exit 1
- # Remove a leftover token or password file at every LATER boot (never started
- # now: the token file is still needed below). The audit rules are loaded inside
- # the first-boot script, where a failure fails closed.
- - [bash, -c, "systemctl daemon-reload && systemctl enable cah-log-shipping-sweep.service"]
- # Always runs, even when the install above failed, so the token file is
- # deleted either way; the script then fails closed.
- - [/usr/local/sbin/cah-log-shipping-firstboot]
- %{ endif ~}
- # Leave the outcome where someone can read it later. No token is read here.
- - - bash
- - -c
- - |
- umask 027
- {
- echo "== date"; date
- echo "== systemctl is-active twingate-connector"; systemctl is-active twingate-connector
- echo "== journalctl -u twingate-connector (last 50)"; journalctl -u twingate-connector -n 50 --no-pager
- echo "== /var/log/cloud-init-output.log (last 50)"; tail -n 50 /var/log/cloud-init-output.log
- } > /var/log/cah-connector-install.log 2>&1
- chmod 0640 /var/log/cah-connector-install.log
|