diff --git a/docs/changelog.md b/docs/changelog.md index cfc9eb29..1e330d61 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -19,6 +19,38 @@ docstring gives: it is a record, not a claim about now. ## 2026-11-18 +- **`fenrir` checks hourly that it is still an appliance, the last of its + audit's next steps.** "`fenrir` sheds the last of its audit's leftovers", + below, left a drift check as the one step open. Now + `homelab-appliance-state` reads, as root, what `build-the-sensor-guest.md` + leaves, and writes one 0-or-1 per check, eleven in all, to the lab's + Prometheus. The lab's `ApplianceCheckFailed` names a check that has failed + on two hourly runs, and `ApplianceStateStopped` covers a collector that + stops, for as long as it stays stopped. + - **Measured first.** The allowlists are what `fenrir` held on the day: + `sshd` and resolved and chrony on loopback, the sensor's Alloy on + `127.0.0.1:12345`, `core24` and `snapd`, and Docker's and Ubuntu's apt + sources. Listeners are exact pairs, loopback included, because the tools + the audit found would most likely have listened on localhost only. The + allowed keys' fingerprints stay on the guest, in + `/etc/homelab/appliance-key-fingerprints`. + - **A trap found while measuring.** An SSH session to `fenrir` still listed + `atreus` in `lxd`, though `/etc/group` did not, because a process keeps + the groups it started with. The groups check reads `id -nG atreus`, + which asks the database. + - **Proven.** Installed with `install-agent-collectors --only + appliance-state`, the first run read 1 for all eleven. A throwaway key + appended to `authorized_keys` was read at the next hourly run as + `FAILED: keys`, and `keys` read 0 in the lab's Prometheus; the key was + then removed. The two rules load on `alexander` at the next + `make up STACK=lab`. + - **What it does not do.** Whoever has root on `fenrir` can make every + check read 1, and the lab's Prometheus pages no one (ADR-0020). It + catches drift by accident, the kind the audit found. Letting one bit of + it cross to the estate, as ADR-0088 lets a service's health cross, was + not decided here. + + With this, every next step of `fenrir`'s audit of 2026-11-13 is done. - **The wall's Home row reads the thermostat and the Litter-Robot.** The second of the wall's five steps. The row gains the hallway thermostat's temperature and humidity, and "heating" or "cooling" while it is, read diff --git a/docs/runbooks/build-the-sensor-guest.md b/docs/runbooks/build-the-sensor-guest.md index 21741880..faba58c0 100644 --- a/docs/runbooks/build-the-sensor-guest.md +++ b/docs/runbooks/build-the-sensor-guest.md @@ -449,6 +449,41 @@ It must end with `apt-patch-state.prom written, mode 644`. Until 2026-11-17 this step was missing, and a libc6 upgrade waited four days for a reboot with nothing saying so. +**Check that the guest stays an appliance** (#1577). `homelab-appliance-state` +reads, hourly, what §0 and §3 leave: `sshd`'s settings, the authorized keys, +root's keys, `sudoers.d`, the login accounts, `atreus`'s groups, user units and +lingering, the snaps, the apt sources, what listens in the host's network +namespace, and the size of `$HOME`. The lab's `ApplianceCheckFailed` names a +check that fails. It catches drift by accident; whoever has root here can make +it read clean, and the collector's header says so. + +The keys check needs to know which keys are allowed, and that list stays on the +guest. After §3 has trimmed `authorized_keys` to the machines that administer +the guest, record their fingerprints, on `fenrir`: + +```bash +sudo install -d -m 0755 /etc/homelab +ssh-keygen -lf ~/.ssh/authorized_keys | awk '{print $2}' \ + | sudo tee /etc/homelab/appliance-key-fingerprints >/dev/null +sudo chmod 0644 /etc/homelab/appliance-key-fingerprints +``` + +Then, from the checkout on Hicks: + +```bash +make install-agent-collectors AGENT=atreus@10.0.30.90 ARGS='--only appliance-state' +``` + +It must end with `appliance-state.prom written, mode 644`, and every check must +read 1: + +```bash +cat /var/lib/node_exporter/textfile_collector/appliance-state.prom +``` + +A key added later is a change to that file in the same sitting, or the check +fails within the hour, which is the point. + **On a `fenrir` built before #850**, remove the cron line the timer replaces, so the two do not both prune: diff --git a/docs/runbooks/schedule-maintenance.md b/docs/runbooks/schedule-maintenance.md index 86102957..8e4e9348 100644 --- a/docs/runbooks/schedule-maintenance.md +++ b/docs/runbooks/schedule-maintenance.md @@ -194,7 +194,7 @@ runs Alloy but has no checkout of this repository — `oracle` — gets the collectors and their own timers installed directly, by `make install-agent-collectors AGENT=user@host`. It ships every collector the script's `COLLECTORS` table names — `patch-state`, `smart-state`, `pve-version`, `cert-expiry`, -`guest-state`, `thin-pool-state`, `guest-disk-state`, `guest-service-state`, `pve-firewall-state`, `iso-store-state`, `zeek-mirror-state`, `pbs-task-state` and `drift-check`, plus the two +`guest-state`, `thin-pool-state`, `guest-disk-state`, `guest-service-state`, `pve-firewall-state`, `iso-store-state`, `zeek-mirror-state`, `pbs-task-state`, `drift-check` and `appliance-state`, plus the two rows that collect nothing, `zeek-mirror` and `prune-images`, and one scheduled job, `zeek-archive-prune` — and checks each host's requirements **per collector**, so a host without apt still gets SMART and the one it cannot have is reported rather than skipped silently. `ARGS='--only smart-state'` narrows diff --git a/docs/security.md b/docs/security.md index c4be640f..8ab1c689 100644 --- a/docs/security.md +++ b/docs/security.md @@ -19,7 +19,7 @@ What this network is actually built to survive: | An attacker on the lab segment reaching the hypervisor's management plane | **Closed at the host, and watched.** `Saruman`'s Proxmox firewall admits `8006` and `22` from Hicks and `8006` from the deployment host only ([ADR-0014](adr/0014-put-ifrit-on-imaginationlan-and-give-the-targets-no-route.md), [ADR-0043](adr/0043-keep-the-ca-on-prometheus-and-build-phoenix-as-the-deployment-host.md)). It was found disabled and turned on on 2026-09-20 ([#566](https://github.com/Gerrrt/HomeLab/issues/566)); since [#576](https://github.com/Gerrrt/HomeLab/issues/576) `homelab_pve_firewall_enabled` is read every five minutes and `PveFirewallDisabled` pages after ten, so a `pve-firewall stop` left in place is noticed rather than found. `PveFirewallPolicyAccept` does the same for `policy_in` left at `ACCEPT`, which reads as enabled and admits the whole segment | | Someone on the lab segment reaching the domain's configuration path | **Scoped, key-only, and accepted for `phoenix` itself.** Each of ADR-0029's six listens on `22` for `ansible/` ([ADR-0077](adr/0077-configure-the-lab-domain-with-ansible-from-phoenix.md)). The rule admits `10.0.30.70` alone, `sshd` refuses passwords, and the only administrators' key is `phoenix`'s, installed by the template and never by hand on a clone. The residual: whoever owns `phoenix` owns the lab domain. That was already true through its Proxmox token, so it adds reach to nothing. Host keys are not pinned, because every rebuild replaces them. `phoenix`'s own way in is narrowed to match by [ADR-0117](adr/0117-give-phoenix-a-key-only-sshd-and-a-default-deny-inbound-policy.md): its `sshd` takes keys only, and its `ufw` admits `22` from Hicks and the tunnel's peers and nothing from the rest of VLAN 30. Until [#1496](https://github.com/Gerrrt/HomeLab/issues/1496) applies it on the host, the installer's password login and an open segment are what stand there | | Someone on the lab segment logging in to the sensor | **Closed at `sshd`.** `fenrir` sees every frame on `Saruman`'s lab bridge, and its `sshd` answers all of VLAN 30 with no host firewall. [`build-the-sensor-guest.md`](runbooks/build-the-sensor-guest.md) §3 makes `sshd` key-only for one user through a drop-in that outranks cloud-init's, refuses root and X11 forwarding, and keeps `authorized_keys` to the machines that administer the guest. The audit of 2026-11-13 found it very likely taking passwords, with X11 forwarding on and 18 distinct keys authorized, most imported from GitHub. The step was applied on 2026-11-17: `sshd -T` read `no` for all four settings with `allowusers atreus`, and `authorized_keys` went from 20 lines to the 2 keys that had logged in. The source address stays open: anyone on the segment can still offer a key | -| Someone who takes the sensor reaching beyond its traffic | **Closed by clearing the guest, and kept by the runbook alone.** `fenrir` is an appliance ([`build-the-sensor-guest.md`](runbooks/build-the-sensor-guest.md) §0): the sensor stack, the agent collectors, the repository checkout and the stack's age key, and nothing else. The audit of 2026-11-13 found it used as a workstation as well: dotfiles, a stored Claude Code login with npm MCP servers reaching the internet, a `gh` token, the 1Password CLI and development packages, 4.8 GB in `$HOME`. All of it was removed on 2026-11-17, and a read the same evening found none of it: no user services beyond the distribution's, no TCP connection on the host's own sockets but inbound SSH from Hicks, and 180 MB in `$HOME`, nearly all of it the checkout. That read covered the host's network namespace only. The sensor's own Alloy, in its container, still pushes logs and metrics to `alexander`, as it is meant to. Nothing re-checks this; a tool installed on `fenrir` again would be found only by the next audit | +| Someone who takes the sensor reaching beyond its traffic | **Closed by clearing the guest, and re-checked hourly for drift by accident.** `fenrir` is an appliance ([`build-the-sensor-guest.md`](runbooks/build-the-sensor-guest.md) §0): the sensor stack, the agent collectors, the repository checkout and the stack's age key, and nothing else. The audit of 2026-11-13 found it used as a workstation as well: dotfiles, a stored Claude Code login with npm MCP servers reaching the internet, a `gh` token, the 1Password CLI and development packages, 4.8 GB in `$HOME`. All of it was removed on 2026-11-17, and a read the same evening found none of it: no user services beyond the distribution's, no TCP connection on the host's own sockets but inbound SSH from Hicks, and 180 MB in `$HOME`, nearly all of it the checkout. That read covered the host's network namespace only. The sensor's own Alloy, in its container, still pushes logs and metrics to `alexander`, as it is meant to. Since #1577 an hourly collector on `fenrir` re-reads what the runbook leaves (`sshd`, the keys, accounts and groups, user units, snaps, apt sources, host listeners, the size of `$HOME`) and the lab's `ApplianceCheckFailed` names a check that fails. That catches drift by accident only: whoever has root on `fenrir` can make it read clean, and the lab's Prometheus pages no one (ADR-0020), so it is seen by someone looking at the lab | | Someone on the lab segment logging in to `alexander` | **Closed at `sshd`.** `alexander` holds the lab's only age key, and its `sshd` answers all of VLAN 30 with no host firewall. It is installed by hand from the ISO, so it does not inherit the template's `allow-pw: false`. [`build-the-lab-guest.md`](runbooks/build-the-lab-guest.md) §2 makes `sshd` key-only through a drop-in, refuses root and X11 forwarding, and keeps `garnet`'s `authorized_keys` to Hicks's key and `phoenix`'s; §7 checks it with `sshd -T`. A read on 2026-11-15 found it taking passwords; the step was applied the same day, and `sshd -T` read `no` for all four settings. The source address stays open: anyone on the segment can still offer a key | | Someone on the lab segment logging in to `odin` | **Closed at `sshd`.** `odin` holds the SOC's certificate authority key and its own age key, and its `sshd` answers all of VLAN 30 with no host firewall. It is installed by hand from the ISO, so OpenSSH's default of taking passwords stood. [`build-the-soc-guest.md`](runbooks/build-the-soc-guest.md) §2 makes `sshd` key-only through a drop-in that outranks cloud-init's, and refuses root and X11 forwarding; §10 checks it with `sshd -T`. A read on 2026-11-15 found it taking passwords and X11 forwarding; the step was applied on 2026-11-16, and `sshd -T` read `no` for all four settings. The source address stays open: anyone on the segment can still offer a key | | Someone on the lab segment reading the domain's metrics | **Scoped, unauthenticated, and accepted.** `windows_exporter` listens on `9182` on all six of ADR-0029's guests, on the segment that exists to hold attackers. Each guest's Windows Firewall admits `10.0.30.40` (`alexander`) alone ([`build-the-lab-domain.md`](runbooks/build-the-lab-domain.md) §7). That rule is the difference between an endpoint a `/24` sweep finds and one you have to go looking for, and it is a residual, not a control: the exporter has no authentication, so whoever owns `alexander` reads every gauge. It has no write API, so what leaks is the shape of the host (services, disks, uptime, the licence clock), the same class as `node_exporter` on the NAS below | diff --git a/scripts/README.md b/scripts/README.md index 0ff41b6f..21113424 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -138,6 +138,7 @@ they describe. The rest are installed on the host they describe by | `collect-zeek-mirror-state.sh`, `zeek-mirror.sh` | The `tc` mirror to the Zeek sensor: build it, and whether it carries packets ([ADR-0068](../docs/adr/0068-mirror-the-lab-bridge-to-zeek-with-tc-not-open-vswitch.md)) | | `collect-pbs-task-state.py` | What `golem`'s Proxmox Backup Server last did: verify, prune and garbage-collection outcomes, and its snapshots by verify state and encryption ([ADR-0053](../docs/adr/0053-run-pbs-on-saruman-with-its-datastore-on-smaug-over-nfs.md)) | | `collect-drift-check.sh` | The wiki's drift check and what it found | +| `collect-appliance-state.sh` | Whether `fenrir` is still the appliance its runbook leaves, one pass-or-fail per check ([#1577](https://github.com/Gerrrt/HomeLab/issues/1577)) | | `mark-clean-shutdown.sh` | Clean stops by kind, so a disk-fault page can tell a power cut from a shutdown | ## Live-host checks diff --git a/scripts/collect-appliance-state.sh b/scripts/collect-appliance-state.sh new file mode 100755 index 00000000..a495b093 --- /dev/null +++ b/scripts/collect-appliance-state.sh @@ -0,0 +1,452 @@ +#!/usr/bin/env bash +# +# Whether `fenrir` is still the appliance its runbook leaves (#1577). +# +# THE GAP. build-the-sensor-guest.md §0 decides that `fenrir` holds the sensor +# stack, the agent collectors, the repository checkout and the stack's age key, +# and nothing else. The audit of 2026-11-13 found it had been a workstation for +# weeks: dotfiles, a gh login, an AI CLI with MCP servers reaching the internet, +# sshd taking passwords, 18 keys authorized. Nobody noticed until somebody +# looked, and docs/security.md's row said so: "Nothing re-checks this". This +# is the re-check. +# +# WHAT IT READS. Each check is one fact the runbook sets, compared with what the +# runbook leaves, and published as 1 (as the runbook leaves it) or 0. A check +# whose input cannot be read is 0, never 1: a collector that passes when +# `sshd -T` errored is the silent shape this repository keeps recording. The +# journal line says which checks failed, and the metrics say only that they did. +# +# NOTHING READ LEAVES THE GUEST AS A VALUE. No key, fingerprint, path, port, +# package or group name is a label. The lab's Prometheus sees `check=""` +# and 0 or 1, so a failing check says where to look and not what was found. +# +# WHAT IT CANNOT CATCH, stated so nobody reads more into a row of 1s. The row +# in docs/security.md is about someone who takes the sensor. Whoever has root on +# `fenrir` can stop this timer, edit this script, or write 1s to the file +# themselves. Reading the same facts from `Saruman` through `qm guest exec` +# (ADR-0088's path) only moves the trust to the guest agent, which the same +# root controls. So this catches drift by accident: the workstation tooling the +# audit found, a key added for a quick job, a snap that came with an upgrade. +# That is the drift that has actually happened here. +# +# WHO SEES IT. The lab's Prometheus pages no one (ADR-0020). ApplianceCheckFailed +# shows in /alerts and Grafana and nowhere else. Letting one bit of it cross to +# the estate, as ADR-0088 lets a named service's health cross, would need an ADR +# of its own, and #1577 did not take that decision. +# +# THE ALLOWLISTS. Everything but the keys is the runbook's own outcome and is +# written below, so a change to the runbook is a change here in the same PR. The +# keys are not: which machines administer the guest is kept on the guest, in +# KEYS_FILE, one SHA256 fingerprint per line, written by the runbook's §4 step. +# A missing or empty KEYS_FILE fails the keys check. +# +# Usage: scripts/collect-appliance-state.sh [--print | --self-test] +# --print writes to stdout instead of the textfile directory +# --self-test runs the parsers against fixtures +set -uo pipefail + +TEXTFILE_DIR="${TEXTFILE_DIR:-/var/lib/node_exporter/textfile_collector}" +# Not a job name in install-timers.sh's JOBS table: collect-patch-state.sh's +# header has the reason. +PROM="${TEXTFILE_DIR}/appliance-state.prom" +HOSTNAME_LABEL="$(hostname)" + +USER_NAME=atreus +KEYS_FILE=/etc/homelab/appliance-key-fingerprints +# Twice the checkout as it was on 2026-11-18 (183 MB) and some. The audit found +# 4.8 GB; a checkout that grows past this is worth a look anyway. +HOME_MAX_MB=512 + +# The groups cloud-init gives the first user, less `lxd` (#1576), plus `docker` +# (§4). Every group here is one the user may be in, not one it must be in. +ALLOWED_GROUPS="atreus adm cdrom sudo dip plugdev users docker" +# The two that snapd needs to exist at all. `hwctl` came with 26.04 and was +# removed (#1576); any other snap is one somebody installed. +ALLOWED_SNAPS="core24 snapd" +# Ubuntu's own deb822 file, curtin's copy of it, and Docker's (§4). apt reads +# only *.list and *.sources, so curtin's .orig is a file and not a source. +ALLOWED_APT_SOURCES="docker.list ubuntu.sources ubuntu.sources.curtin.orig" +# What those files may point at, trailing slash dropped. A filename says +# nothing about its contents: a third-party repository added inside +# ubuntu.sources would pass a filename check (review on #1580). +ALLOWED_APT_URIS="http://us.archive.ubuntu.com/ubuntu http://archive.ubuntu.com/ubuntu" +ALLOWED_APT_URIS+=" http://security.ubuntu.com/ubuntu https://download.docker.com/linux/ubuntu" +# /etc/systemd/user as 26.04 ships it, measured on fenrir 2026-11-19: the +# distribution's enabled user units, which start in any login session. A unit +# put here, or in ~/.config or ~/.local/share/systemd/user, runs in every +# session without linger (review on #1580). +ALLOWED_ETC_USER_UNITS="graphical-session-pre.target.wants +graphical-session-pre.target.wants/xdg-user-dirs.service sockets.target.wants +sockets.target.wants/dirmngr.socket sockets.target.wants/gpg-agent-browser.socket +sockets.target.wants/gpg-agent-extra.socket sockets.target.wants/gpg-agent.socket +sockets.target.wants/gpg-agent-ssh.socket sockets.target.wants/keyboxd.socket +sockets.target.wants/pk-debconf-helper.socket sockets.target.wants/snapd.session-agent.socket +sockets.target.wants/ssh-agent.socket timers.target.wants +timers.target.wants/launchpadlib-cache-clean.timer" +# subset_ok splits on spaces; awk -v refuses a newline (listeners_ok says so). +ALLOWED_ETC_USER_UNITS="${ALLOWED_ETC_USER_UNITS//$'\n'/ }" + +die() { printf '\033[0;31merror:\033[0m %s\n' "$*" >&2; exit 1; } + +# --- The parsers. Each reads its input on stdin (or from a path argument) and +# returns 0 when the fact is as the runbook leaves it. They take no other input, +# so --self-test can drive every one of them. + +# `sshd -T`: the four settings §3's drop-in sets, and the one user it allows. +# sshd -T lowercases keywords and prints each once, so an exact line match is +# safe. allowusers is matched exactly: a second user on the line is drift. +sshd_ok() { + awk -v user="${USER_NAME}" ' + $1 == "permitrootlogin" { seen++; if ($2 != "no") bad = 1 } + $1 == "passwordauthentication" { seen++; if ($2 != "no") bad = 1 } + $1 == "kbdinteractiveauthentication" { seen++; if ($2 != "no") bad = 1 } + $1 == "x11forwarding" { seen++; if ($2 != "no") bad = 1 } + $1 == "allowusers" { seen++; if (NF != 2 || $2 != user) bad = 1 } + END { exit (seen == 5 && !bad) ? 0 : 1 } + ' +} + +# `ssh-keygen -lf authorized_keys` on stdin, the allowed fingerprints in $1. +# Every key present must be allowed. No key at all also fails: the guest is +# administered over SSH, so an empty file means the read went wrong. +keys_ok() { + local allow="$1" + [[ -s "${allow}" ]] || return 1 + awk 'NR == FNR { if ($1 ~ /^SHA256:/) ok[$1] = 1; next } + { n++; if (!($2 in ok)) bad = 1 } + END { exit (n > 0 && !bad) ? 0 : 1 }' "${allow}" - +} + +# Words on stdin, every one in the allowed list $1. For `id -nG`, `snap list`'s +# names and the apt sources directory. +subset_ok() { + local allowed="$1" + awk -v allowed="${allowed}" ' + BEGIN { n = split(allowed, a, " "); for (i = 1; i <= n; i++) ok[a[i]] = 1 } + { for (i = 1; i <= NF; i++) if (!($i in ok)) bad = 1 } + END { exit bad ? 1 : 0 } + ' +} + +# Whether file $1 has no line matching $2. Absent is a pass. A path that is +# there but is not a readable regular file is a fail, and so is any grep status +# but 1 (no match): grep's 2 is a read error, and a read error proves nothing +# (review on #1580, which found `! grep ... 2>/dev/null` passing on one). +no_line_ok() { + local file="$1" pattern="$2" rc=0 + [[ -e "${file}" || -L "${file}" ]] || return 0 + [[ -f "${file}" && -r "${file}" ]] || return 1 + grep -qE "${pattern}" "${file}" || rc=$? + ((rc == 1)) +} + +# A key line in authorized_keys: anything but a comment or a blank, indented +# or not. sshd skips leading whitespace, so an indented key is a key. +KEY_LINE='^[[:space:]]*[^#[:space:]]' +# An active source line in a one-line-style file, indented or not. +DEB_LINE='^[[:space:]]*deb(-src)?[[:space:]]' + +# Active apt source lines on stdin, from .list files and deb822 .sources alike: +# every URI must be one ALLOWED_APT_URIS names. A `deb [opts] URI suite` line +# carries it after the bracketed options; a deb822 stanza in `URIs:`, which may +# list several. No URI at all fails: this guest installs from at least two. +apt_uris_ok() { + awk -v allowed="${ALLOWED_APT_URIS}" ' + BEGIN { n = split(allowed, a, " "); for (i = 1; i <= n; i++) ok[a[i]] = 1 } + function check(u) { sub(/\/+$/, "", u); seen++; if (!(u in ok)) bad = 1 } + /^[[:space:]]*#/ { next } + $1 == "deb" || $1 == "deb-src" { + i = 2 + if ($i ~ /^\[/) { while ($i !~ /\]$/ && i < NF) i++; i++ } + check($i) + } + tolower($1) == "uris:" { for (i = 2; i <= NF; i++) check($i) } + END { exit (seen && !bad) ? 0 : 1 } + ' +} + +# `getent passwd` on stdin. The only account that can log in, among the ones a +# person would have (UID 1000 up, short of nobody's 65534), is USER_NAME, and +# its shell is /bin/bash. A second login account is how a workstation starts. +users_ok() { + awk -F: -v user="${USER_NAME}" ' + $3 >= 1000 && $3 < 65534 && $7 !~ /(nologin|false)$/ { + if ($1 != user) bad = 1; else { found = 1; if ($7 != "/bin/bash") bad = 1 } + } + END { exit (found && !bad) ? 0 : 1 } + ' +} + +# `ss -H -lntu` on stdin: what listens in the host's network namespace. The +# sensor's containers have their own, except Zeek (network_mode: host), which +# opens no socket. +# +# Measured on fenrir 2026-11-18: +# tcp 0.0.0.0:22 [::]:22 sshd +# tcp 127.0.0.1:12345 the sensor's Alloy, published to loopback +# tcp+udp 127.0.0.53%lo:53 127.0.0.54:53 systemd-resolved +# udp 127.0.0.1:323 [::1]:323 chronyd's command socket +# +# EXACT PAIRS, loopback included. Allowing any loopback port would be quieter, +# and would miss what the audit actually found: tools that listen on localhost +# only, as an AI CLI's MCP servers and a dev server do. A routine change that +# trips this (chrony moving its command socket, say) costs one line here in a +# PR; a miss costs weeks, as it did. Columns are +# `Netid State Recv-Q Send-Q Local:Port Peer:Port`, so $1 is tcp/udp and $5 the +# local address. No listener at all fails too: sshd is always one, so empty +# output means `ss` did not run. One line: awk -v refuses a newline in a value +# (BSD awk errors, and an error here would read as a failed check, not a bug). +ALLOWED_LISTENERS="tcp/0.0.0.0:22 tcp/[::]:22 tcp/127.0.0.1:12345 tcp/127.0.0.53%lo:53 tcp/127.0.0.54:53" +ALLOWED_LISTENERS+=" udp/127.0.0.53%lo:53 udp/127.0.0.54:53 udp/127.0.0.1:323 udp/[::1]:323" +listeners_ok() { + awk -v allowed="${ALLOWED_LISTENERS}" ' + BEGIN { n = split(allowed, a, " "); for (i = 1; i <= n; i++) ok[a[i]] = 1 } + NF >= 5 { seen++; if (!(($1 "/" $5) in ok)) bad = 1 } + END { exit (seen && !bad) ? 0 : 1 } + ' +} + +# --- --self-test + +if [[ "${1:-}" == "--self-test" ]]; then + fail=0 + tmp="$(mktemp -d)" + trap 'rm -rf "${tmp}"' EXIT + expect() { + local name="$1" want="$2" rc + shift 2 + "$@" && rc=0 || rc=1 + if [[ "${rc}" == "${want}" ]]; then + printf '\033[0;32m PASS\033[0m %s\n' "${name}" + else + printf '\033[0;31m FAIL\033[0m %s: returned %s, expected %s\n' "${name}" "${rc}" "${want}" + fail=1 + fi + } + # shellcheck disable=SC2329 # called through expect "$@" + feed() { local input="$1"; shift; printf '%s\n' "${input}" | "$@"; } + + SSHD_GOOD="port 22 +permitrootlogin no +passwordauthentication no +kbdinteractiveauthentication no +x11forwarding no +allowusers atreus" + expect "sshd: the runbook's settings pass" 0 feed "${SSHD_GOOD}" sshd_ok + expect "sshd: passwords back on fails" 1 feed "${SSHD_GOOD/passwordauthentication no/passwordauthentication yes}" sshd_ok + expect "sshd: root by key fails" 1 feed "${SSHD_GOOD/permitrootlogin no/permitrootlogin prohibit-password}" sshd_ok + expect "sshd: a second allowed user fails" 1 feed "${SSHD_GOOD/allowusers atreus/allowusers atreus ubuntu}" sshd_ok + # The drop-in gone entirely: sshd prints no allowusers line at all. Five + # settings must be seen, so a line that is missing is not a line that passed. + expect "sshd: no allowusers line fails" 1 feed "$(printf '%s\n' "${SSHD_GOOD}" | grep -v allowusers)" sshd_ok + expect "sshd: empty output (sshd -T failed) fails" 1 feed "" sshd_ok + + printf 'SHA256:aaa\nSHA256:bbb\n' > "${tmp}/allow" + : > "${tmp}/empty" + expect "keys: two allowed keys pass" 0 feed "256 SHA256:aaa hicks (ED25519) +256 SHA256:bbb phoenix (ED25519)" keys_ok "${tmp}/allow" + expect "keys: one extra key fails" 1 feed "256 SHA256:aaa hicks (ED25519) +256 SHA256:ccc imported (ED25519)" keys_ok "${tmp}/allow" + expect "keys: no keys at all fails" 1 feed "" keys_ok "${tmp}/allow" + expect "keys: an empty allowlist fails" 1 feed "256 SHA256:aaa hicks (ED25519)" keys_ok "${tmp}/empty" + expect "keys: a missing allowlist fails" 1 feed "256 SHA256:aaa hicks (ED25519)" keys_ok "${tmp}/absent" + + expect "groups: the runbook's pass" 0 feed "atreus adm cdrom sudo dip plugdev users docker" subset_ok "${ALLOWED_GROUPS}" + expect "groups: lxd back fails" 1 feed "atreus adm sudo users lxd docker" subset_ok "${ALLOWED_GROUPS}" + expect "snaps: core24 and snapd pass" 0 feed "core24 +snapd" subset_ok "${ALLOWED_SNAPS}" + expect "snaps: hwctl back fails" 1 feed "core24 +hwctl +snapd" subset_ok "${ALLOWED_SNAPS}" + expect "apt: the measured sources pass" 0 feed "docker.list +ubuntu.sources +ubuntu.sources.curtin.orig" subset_ok "${ALLOWED_APT_SOURCES}" + expect "apt: 1Password's source fails" 1 feed "1password.list +docker.list +ubuntu.sources" subset_ok "${ALLOWED_APT_SOURCES}" + + # root's keys, through no_line_ok (review on #1580). + printf '# no keys here\n\n' > "${tmp}/root_comments" + printf ' ssh-ed25519 AAAA indented\n' > "${tmp}/root_indented" + mkdir "${tmp}/root_dir" + expect "root keys: no file passes" 0 no_line_ok "${tmp}/root_absent" "${KEY_LINE}" + expect "root keys: comments and blanks pass" 0 no_line_ok "${tmp}/root_comments" "${KEY_LINE}" + expect "root keys: an indented key fails" 1 no_line_ok "${tmp}/root_indented" "${KEY_LINE}" + # A directory where the file should be: grep exits 2 on it, and a read error + # is not "no key". + expect "root keys: a path that is not a regular file fails" 1 no_line_ok "${tmp}/root_dir" "${KEY_LINE}" + + # What fenrir's two source files held on 2026-11-19, concatenated as c_apt does. + APT_GOOD="deb [arch=amd64 signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu resolute stable +Types: deb +URIs: http://us.archive.ubuntu.com/ubuntu/ +Suites: resolute resolute-updates resolute-backports +Components: main restricted universe multiverse + +Types: deb +URIs: http://security.ubuntu.com/ubuntu/ +Suites: resolute-security" + expect "apt: the measured origins pass" 0 feed "${APT_GOOD}" apt_uris_ok + expect "apt: a third-party origin inside ubuntu.sources fails" 1 feed "${APT_GOOD} + +Types: deb +URIs: https://downloads.1password.com/linux/debian/amd64 +Suites: stable" apt_uris_ok + expect "apt: a second URI on an allowed URIs: line fails" 1 feed "${APT_GOOD/URIs: http:\/\/security.ubuntu.com\/ubuntu\//URIs: http://security.ubuntu.com/ubuntu/ https://repo.charm.sh/apt/}" apt_uris_ok + expect "apt: a .list line without options fails for its origin" 1 feed "${APT_GOOD} +deb https://cli.github.com/packages stable main" apt_uris_ok + expect "apt: a commented-out origin passes" 0 feed "${APT_GOOD} +# deb https://cli.github.com/packages stable main" apt_uris_ok + expect "apt: no source at all fails" 1 feed "" apt_uris_ok + + ETC_USER_GOOD="$(printf '%s\n' "${ALLOWED_ETC_USER_UNITS}" | tr ' ' '\n')" + expect "user units: /etc/systemd/user as 26.04 ships it passes" 0 feed "${ETC_USER_GOOD}" subset_ok "${ALLOWED_ETC_USER_UNITS}" + expect "user units: a unit enabled in /etc/systemd/user fails" 1 feed "${ETC_USER_GOOD} +default.target.wants/mcp-server.service" subset_ok "${ALLOWED_ETC_USER_UNITS}" + expect "user units: a unit dropped in /etc/systemd/user fails" 1 feed "${ETC_USER_GOOD} +mcp-server.service" subset_ok "${ALLOWED_ETC_USER_UNITS}" + + PASSWD_GOOD="root:x:0:0:root:/root:/bin/bash +nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin +atreus:x:1000:1000:atreus:/home/atreus:/bin/bash" + expect "users: atreus alone passes" 0 feed "${PASSWD_GOOD}" users_ok + expect "users: atreus on zsh fails" 1 feed "${PASSWD_GOOD/\/home\/atreus:\/bin\/bash//home/atreus:/usr/bin/zsh}" users_ok + expect "users: a second login account fails" 1 feed "${PASSWD_GOOD} +dev:x:1001:1001::/home/dev:/bin/bash" users_ok + expect "users: a second account with no shell passes" 0 feed "${PASSWD_GOOD} +svc:x:1001:1001::/nonexistent:/usr/sbin/nologin" users_ok + expect "users: atreus missing fails" 1 feed "root:x:0:0:root:/root:/bin/bash" users_ok + + SS_GOOD="tcp LISTEN 0 4096 0.0.0.0:22 0.0.0.0:* +tcp LISTEN 0 4096 127.0.0.1:12345 0.0.0.0:* +tcp LISTEN 0 4096 127.0.0.53%lo:53 0.0.0.0:* +tcp LISTEN 0 4096 127.0.0.54:53 0.0.0.0:* +tcp LISTEN 0 4096 [::]:22 [::]:* +udp UNCONN 0 0 127.0.0.1:323 0.0.0.0:* +udp UNCONN 0 0 127.0.0.53%lo:53 0.0.0.0:* +udp UNCONN 0 0 127.0.0.54:53 0.0.0.0:* +udp UNCONN 0 0 [::1]:323 [::]:*" + expect "listeners: what was measured on fenrir passes" 0 feed "${SS_GOOD}" listeners_ok + expect "listeners: a new service on every address fails" 1 feed "${SS_GOOD} +tcp LISTEN 0 4096 0.0.0.0:8080 0.0.0.0:*" listeners_ok + expect "listeners: sshd on a second port fails" 1 feed "${SS_GOOD} +tcp LISTEN 0 128 [::]:2222 [::]:*" listeners_ok + expect "listeners: empty output (ss failed) fails" 1 feed "" listeners_ok + # The case the exact pairs exist for: a tool bound to localhost only. + expect "listeners: a new loopback-only service fails" 1 feed "${SS_GOOD} +tcp LISTEN 0 511 127.0.0.1:3000 0.0.0.0:*" listeners_ok + # And the same port as an allowed one, on the other protocol, is not allowed. + expect "listeners: chrony's port over tcp fails" 1 feed "${SS_GOOD} +tcp LISTEN 0 128 127.0.0.1:323 0.0.0.0:*" listeners_ok + + exit "${fail}" +fi + +PRINT_ONLY=0 +[[ "${1:-}" == "--print" ]] && PRINT_ONLY=1 +((EUID == 0)) || die "run as root: sshd -T and root's own keys need it" + +# --- The checks, in the order the runbook applies them. + +declare -A result=() +order=() +record() { + local name="$1" + shift + order+=("${name}") + if "$@"; then result[${name}]=1; else result[${name}]=0; fi +} + +home="$(getent passwd "${USER_NAME}" | cut -d: -f6)" + +# Each check's command is in a function so `record` runs it whole, pipes +# included, and a failure anywhere in it is a 0. +c_sshd() { sshd -T 2>/dev/null | sshd_ok; } +c_keys() { [[ -r "${home}/.ssh/authorized_keys" ]] \ + && ssh-keygen -lf "${home}/.ssh/authorized_keys" 2>/dev/null | keys_ok "${KEYS_FILE}"; } +# root has no key at all: no file, or a readable file with no key line in it. +c_root_keys() { no_line_ok /root/.ssh/authorized_keys "${KEY_LINE}"; } +# The distribution's sudoers.d holds a README and nothing else (#1574). +c_sudoers() { [[ "$(find /etc/sudoers.d -mindepth 1 -printf '%f\n' 2>/dev/null)" == README ]]; } +c_users() { getent passwd | users_ok; } +# The database, not this process's groups: `id -nG` with no user argument +# reports the groups a process started with, and a session that began before a +# `gpasswd -d` still lists the group it left. +c_groups() { id -nG "${USER_NAME}" 2>/dev/null | subset_ok "${ALLOWED_GROUPS}"; } +# No user units beyond the distribution's, in any of the three places systemd +# loads them from, and no lingering, so nothing of the user's runs logged out. +# The two in $HOME must be empty or absent; /etc/systemd/user must hold only +# what 26.04 ships. +empty_or_absent() { [[ ! -e "$1" ]] || { [[ -d "$1" && -r "$1" ]] \ + && [[ -z "$(find "$1" -mindepth 1 -print -quit 2>/dev/null)" ]]; }; } +c_user_units() { empty_or_absent "${home}/.config/systemd/user" \ + && empty_or_absent "${home}/.local/share/systemd/user" \ + && [[ ! -e "/var/lib/systemd/linger/${USER_NAME}" ]] \ + && { [[ ! -e /etc/systemd/user ]] \ + || { local etc; etc="$(find /etc/systemd/user -mindepth 1 -printf '%P\n')" \ + && printf '%s\n' "${etc}" | subset_ok "${ALLOWED_ETC_USER_UNITS}"; }; }; } +c_snaps() { local s; s="$(snap list 2>/dev/null | awk 'NR > 1 { print $1 }')" && [[ -n "${s}" ]] \ + && printf '%s\n' "${s}" | subset_ok "${ALLOWED_SNAPS}"; } +# Two halves. The files in sources.list.d are the ones the runbook leaves, and +# every URI apt would read, from sources.list and each *.list and *.sources, is +# an allowed one. sources.list itself carries no active line on 26.04. +c_apt() { no_line_ok /etc/apt/sources.list "${DEB_LINE}" \ + && find /etc/apt/sources.list.d -mindepth 1 -printf '%f\n' 2>/dev/null \ + | subset_ok "${ALLOWED_APT_SOURCES}" \ + && { local f files=(); for f in /etc/apt/sources.list.d/*.list /etc/apt/sources.list.d/*.sources; do + [[ -e "${f}" ]] || continue + [[ -f "${f}" && -r "${f}" ]] || return 1 + files+=("${f}") + done + ((${#files[@]})) && cat "${files[@]}" | apt_uris_ok; }; } +c_listeners() { ss -H -lntu 2>/dev/null | listeners_ok; } +c_home() { local mb; mb="$(du -sm "${home}" 2>/dev/null | cut -f1)" \ + && [[ "${mb}" =~ ^[0-9]+$ ]] && ((mb <= HOME_MAX_MB)); } + +if [[ -z "${home}" ]]; then + # No such user: every check about it fails, and the line below says why. + printf 'appliance-state: no user %s on this host\n' "${USER_NAME}" >&2 + home=/nonexistent +fi + +record sshd c_sshd +record keys c_keys +record root_keys c_root_keys +record sudoers c_sudoers +record users c_users +record groups c_groups +record user_units c_user_units +record snaps c_snaps +record apt_sources c_apt +record listeners c_listeners +record home_size c_home + +failed=() +for name in "${order[@]}"; do ((result[${name}])) || failed+=("${name}"); done + +emit() { + printf '# HELP homelab_appliance_check 1 when this fact is as build-the-sensor-guest.md leaves it, 0 when not or unreadable.\n' + printf '# TYPE homelab_appliance_check gauge\n' + for name in "${order[@]}"; do + printf 'homelab_appliance_check{host="%s",check="%s"} %s\n' "${HOSTNAME_LABEL}" "${name}" "${result[${name}]}" + done +} + +if ((PRINT_ONLY)); then + emit + exit 0 +fi + +[[ -d "${TEXTFILE_DIR}" ]] || die "no ${TEXTFILE_DIR}: make up STACK=sensor creates it" + +# Written beside the target and renamed: collect-patch-state.sh has the reason. +tmp="${PROM}.$$" +emit > "${tmp}" || { rm -f "${tmp}"; die "could not write ${tmp}"; } +chmod 0644 "${tmp}" +mv -f "${tmp}" "${PROM}" + +if ((${#failed[@]})); then + printf 'appliance-state host=%s FAILED: %s\n' "${HOSTNAME_LABEL}" "${failed[*]}" +else + printf 'appliance-state host=%s all %d checks pass\n' "${HOSTNAME_LABEL}" "${#order[@]}" +fi diff --git a/scripts/install-agent-collectors.sh b/scripts/install-agent-collectors.sh index 55c23a65..72d89e62 100755 --- a/scripts/install-agent-collectors.sh +++ b/scripts/install-agent-collectors.sh @@ -56,7 +56,8 @@ # failed on the one host it was meant for), # pve-firewall-state (#576), # iso-store-state (#440), zeek-mirror-state (#437), pbs-task-state (#485) and -# drift-check (#470), plus +# drift-check (#470), appliance-state (#1577, fenrir only, for the same +# reason as zeek-archive-prune below: its requirement is /srv/sensor-data), plus # two rows that collect nothing (below) and zeek-archive-prune (#850), a # scheduled job rather than a collector (above). Its requirement is the archive # directory, so like iso-store-state's it exists on exactly one host: fenrir. @@ -133,6 +134,7 @@ COLLECTORS=( "drift-check scripts/collect-drift-check.sh wiki-drift-check.prom /home/atropos/code/Gerrrt/Lemmiwinks/.claude/tools/safe-post" "prune-images scripts/prune-images.sh - /usr/bin/docker" "zeek-archive-prune scripts/run-scheduled.sh zeek-archive-prune.prom /srv/sensor-data/zeek/archive" + "appliance-state scripts/collect-appliance-state.sh appliance-state.prom /srv/sensor-data" ) GREEN=$'\033[0;32m'; RED=$'\033[0;31m'; YELLOW=$'\033[0;33m' diff --git a/stacks/lab/README.md b/stacks/lab/README.md index 41d5dbc2..2f905c31 100644 --- a/stacks/lab/README.md +++ b/stacks/lab/README.md @@ -59,13 +59,14 @@ prometheus/ prometheus.yaml six scrape jobs — this stack's four, the domain's windows_exporter and odin's Velociraptor; no alerting block, no file_sd - rules/lab.rules.yaml 23 rules — four for this stack watching itself, + rules/lab.rules.yaml 25 rules — four for this stack watching itself, one for its agents dropping log lines (#1552), two for the guests' disks, three for the domain ADR-0029 sized, seven for golem's backups (ADR-0053), three for fenrir's Zeek archive - prune (#850) and three for the guests' patch - state + prune (#850), three for the guests' patch + state and two for whether fenrir is still an + appliance (#1577) rules/soc.rules.yaml 13 rules — the SOC's indexer on odin, whose health is pushed here by stacks/soc's Alloy (ADR-0030); the manager's agents, queues and drops, from odin's diff --git a/stacks/lab/prometheus/rules/lab.rules.yaml b/stacks/lab/prometheus/rules/lab.rules.yaml index fde6f472..4277dde9 100644 --- a/stacks/lab/prometheus/rules/lab.rules.yaml +++ b/stacks/lab/prometheus/rules/lab.rules.yaml @@ -1,7 +1,7 @@ --- # The lab stack watching itself. # -# Twenty-three rules, and the number is still the point. The estate has 48; +# Twenty-five rules, and the number is still the point. The estate has 48; # ADR-0007 names giving up "Loki, the dashboards and 40 alert rules" as the # price of keeping lab telemetry out of the estate, and this file does not # pretend to replace them. Five cover this stack's own working, its agents' @@ -16,6 +16,8 @@ # prune (#850), the one run-scheduled.sh job whose outcome lands here. Three # cover the guests' patch state, which their own patch-state timers write and # which no estate rule can see, because these guests push here and not there. +# Two cover whether fenrir is still the appliance its runbook leaves (#1577), +# which nothing else checks at all. # # NOTHING HERE PAGES. There is no Alertmanager in this stack (ADR-0020), so a # firing alert is visible in Prometheus's /alerts and in Grafana and nowhere @@ -584,3 +586,74 @@ groups: `make install-agent-collectors AGENT=atreus@10.0.30.90 ARGS='--only zeek-archive-prune'` (docs/runbooks/build-the-sensor-guest.md §4), and check that /var/lib/node_exporter/textfile_collector exists on fenrir. + + # ----------------------------------------------------------------------- + # Whether fenrir is still the appliance build-the-sensor-guest.md §0 + # decides it is (#1577). homelab-appliance-state writes one 0-or-1 per + # check to appliance-state.prom hourly. The audit of 2026-11-13 found the + # guest had been a workstation for weeks with nothing saying so; these + # two are what says so now, to whoever looks here. + # + # What they do not cover, and the collector's header says it at length: + # whoever has root on fenrir can make every check read 1. These catch + # drift by accident, not a guest someone has taken. + # ----------------------------------------------------------------------- + + # A check has read 0 across two hourly runs. One bad run stays exported + # until the next replaces it: an hour, up to 5m more from each run's + # RandomizedDelaySec, and a scrape, so about 67m at most. Two bad runs + # read 0 for at least 110m. 75m sits between, so a run that failed once + # and was put right does not fire (review on #1580: 1h did). The label + # names the check, and `journalctl -u homelab-appliance-state` on fenrir + # names what failed; the value of what was found never leaves the guest. + - alert: ApplianceCheckFailed + expr: homelab_appliance_check == 0 + for: 75m + labels: + component: sensor + severity: warning + category: security + annotations: + summary: "{{ $labels.host }} is no longer the appliance its runbook leaves: {{ $labels.check }}" + description: >- + The `{{ $labels.check }}` check has failed on two hourly runs. Read + `journalctl -u homelab-appliance-state -n 20` on the guest, then + put it back as docs/runbooks/build-the-sensor-guest.md §3 and §4 + leave it. If the change was meant, change the runbook and + scripts/collect-appliance-state.sh in one PR. + + # The checks have stopped reporting, which reads exactly like a guest + # that passes them all. Two branches: the series is gone, or the file + # stopped being rewritten while Alloy keeps serving its last values. + # Three hours is two missed hourly runs and their jitter. + # + # The first branch names fenrir rather than asking "was it reporting a + # day ago", as PatchStateStopped does. That form clears itself about 27h + # after the series goes, once the last sample leaves its window, and if + # Alloy stopped too the mtime branch has nothing to read either (review + # on #1580). This collector belongs on fenrir and nowhere else, so its + # absence there is the condition, for as long as it lasts. A rebuilt + # fenrir that never had the installer run fires it too, which is right. + - alert: ApplianceStateStopped + expr: >- + absent_over_time(homelab_appliance_check{host="fenrir"}[3h]) + or + count by (host) ( + label_replace( + time() - node_textfile_mtime_seconds{file=~".*appliance-state\\.prom"} > 3 * 3600, + "host", "$1", "instance", "(.*)" + ) + ) + for: 30m + labels: + component: sensor + severity: warning + category: security + annotations: + summary: "{{ $labels.host }} has stopped reporting its appliance checks" + description: >- + Its appliance checks have gone absent, or appliance-state.prom has + not been rewritten in three hours, so ApplianceCheckFailed is + reading stale or no data for it. Check + `systemctl status homelab-appliance-state.timer` on the guest. A + stopped timer on a guest that was passing is itself worth a look. diff --git a/stacks/lab/prometheus/tests/lab.test.yaml b/stacks/lab/prometheus/tests/lab.test.yaml index cfbf0ba7..a2a3dade 100644 --- a/stacks/lab/prometheus/tests/lab.test.yaml +++ b/stacks/lab/prometheus/tests/lab.test.yaml @@ -11,7 +11,7 @@ # input, the second proves it does not produce one for the input production # actually supplies. # -# All twenty-three rules in lab.rules.yaml are covered here. That is a deliberate +# All twenty-five rules in lab.rules.yaml are covered here. That is a deliberate # difference from the estate's tests, where four of the nine stack rules are # syntax-checked only: this file is small enough that "test the ones that were # hard" has no advantage over testing all of them, and a new stack has no @@ -928,3 +928,133 @@ tests: - eval_time: 50h alertname: PatchStateStopped exp_alerts: [] + + # --- ApplianceCheckFailed: fires on two failed runs, not before 75m ------ + # The keys check passing to 2h, then a key added: 0 from 2h05m, through the + # next run and beyond. The sshd check beside it keeps passing, so the alert + # names only the one. At 3h15m the 0 has held 70m, inside the 75m `for`; + # at 3h25m it has held 80m and fires. Review on #1580 asked for the boundary. + - interval: 5m + input_series: + - series: 'homelab_appliance_check{host="fenrir",check="keys"}' + values: "1x24 0x30" + - series: 'homelab_appliance_check{host="fenrir",check="sshd"}' + values: "1x54" + alert_rule_test: + - eval_time: 3h15m + alertname: ApplianceCheckFailed + exp_alerts: [] + - eval_time: 3h25m + alertname: ApplianceCheckFailed + exp_alerts: + - exp_labels: + host: fenrir + check: keys + component: sensor + severity: warning + category: security + exp_annotations: + summary: "fenrir is no longer the appliance its runbook leaves: keys" + description: >- + The `keys` check has failed on two hourly runs. Read + `journalctl -u homelab-appliance-state -n 20` on the guest, then + put it back as docs/runbooks/build-the-sensor-guest.md §3 and §4 + leave it. If the change was meant, change the runbook and + scripts/collect-appliance-state.sh in one PR. + + # --- ApplianceCheckFailed: quiet for one bad run at its longest ------------ + # One failed run exported for 65m, the hour plus the next run's jitter, then + # put right. Quiet at its last 0 (3h10m) and after. + - interval: 5m + input_series: + - series: 'homelab_appliance_check{host="fenrir",check="listeners"}' + values: "1x24 0x13 1x20" + alert_rule_test: + - eval_time: 3h10m + alertname: ApplianceCheckFailed + exp_alerts: [] + - eval_time: 4h + alertname: ApplianceCheckFailed + exp_alerts: [] + + # --- ApplianceStateStopped: fires for a collector that died, and stays ---- + # A day of checks, then a real gap. It fires at 30h, and still fires at 52h, + # past the ~27h after which a "was it reporting a day ago" form goes quiet + # with nothing recovered (review on #1580). + - interval: 5m + input_series: + - series: 'homelab_appliance_check{host="fenrir",check="sshd"}' + values: "1x288 _x400" + alert_rule_test: + - eval_time: 30h + alertname: ApplianceStateStopped + exp_alerts: + - exp_labels: + host: fenrir + component: sensor + severity: warning + category: security + exp_annotations: + summary: "fenrir has stopped reporting its appliance checks" + description: >- + Its appliance checks have gone absent, or appliance-state.prom has + not been rewritten in three hours, so ApplianceCheckFailed is + reading stale or no data for it. Check + `systemctl status homelab-appliance-state.timer` on the guest. A + stopped timer on a guest that was passing is itself worth a look. + - eval_time: 52h + alertname: ApplianceStateStopped + exp_alerts: + - exp_labels: + host: fenrir + component: sensor + severity: warning + category: security + exp_annotations: + summary: "fenrir has stopped reporting its appliance checks" + description: >- + Its appliance checks have gone absent, or appliance-state.prom has + not been rewritten in three hours, so ApplianceCheckFailed is + reading stale or no data for it. Check + `systemctl status homelab-appliance-state.timer` on the guest. A + stopped timer on a guest that was passing is itself worth a look. + + # --- ApplianceStateStopped: fires when the file stops being rewritten ------ + # Alloy keeps serving the last 1s, so only the mtime stands still. At 5h it + # is more than three hours old, and has been for over the 30m `for`. + - interval: 5m + input_series: + - series: 'homelab_appliance_check{host="fenrir",instance="fenrir",check="sshd"}' + values: "1x60" + - series: 'node_textfile_mtime_seconds{instance="fenrir",file="/rootfs/var/lib/node_exporter/textfile_collector/appliance-state.prom"}' + values: "0x60" + alert_rule_test: + - eval_time: 5h + alertname: ApplianceStateStopped + exp_alerts: + - exp_labels: + host: fenrir + component: sensor + severity: warning + category: security + exp_annotations: + summary: "fenrir has stopped reporting its appliance checks" + description: >- + Its appliance checks have gone absent, or appliance-state.prom has + not been rewritten in three hours, so ApplianceCheckFailed is + reading stale or no data for it. Check + `systemctl status homelab-appliance-state.timer` on the guest. A + stopped timer on a guest that was passing is itself worth a look. + + # --- ApplianceStateStopped: quiet while the hourly rewrite happens --------- + # The mtime moves every hour (twelve five-minute steps), as the timer's does. + - interval: 5m + input_series: + - series: 'homelab_appliance_check{host="fenrir",instance="fenrir",check="sshd"}' + values: "1x60" + - series: 'node_textfile_mtime_seconds{instance="fenrir",file="/rootfs/var/lib/node_exporter/textfile_collector/appliance-state.prom"}' + values: "0x11 3600x11 7200x11 10800x11 14400x11 18000x5" + alert_rule_test: + - eval_time: 5h + alertname: ApplianceStateStopped + exp_alerts: [] diff --git a/systemd/README.md b/systemd/README.md index 3066976a..b06447ec 100644 --- a/systemd/README.md +++ b/systemd/README.md @@ -112,6 +112,7 @@ for it in `stacks/lab/prometheus/rules/lab.rules.yaml`. | `homelab-zeek-mirror` | 2 min after boot, then every minute | `Saruman` | Builds the `tc` mirror of the lab bridge to `fenrir`, and re-applies it every minute | | `homelab-zeek-mirror-state` | every 5 min | `Saruman` | Whether that mirror carries packets | | `homelab-zeek-archive-prune` | daily 03:17 | `fenrir` | Deletes Zeek archive files past their retention; `homelab_job_*` to the lab | +| `homelab-appliance-state` | 5 min after boot, then hourly | `fenrir` | Whether the guest is still the appliance its runbook leaves: one 0-or-1 per check, to the lab ([#1577](https://github.com/Gerrrt/HomeLab/issues/1577)) | | `homelab-pbs-task-state` | hourly at :17 | `golem` | What PBS last did: each verify, prune and garbage-collection job's outcome, and the snapshots by verify state ([#485](https://github.com/Gerrrt/HomeLab/issues/485)) | ## Adding a timer diff --git a/systemd/agent/homelab-appliance-state.service b/systemd/agent/homelab-appliance-state.service new file mode 100644 index 00000000..c1650787 --- /dev/null +++ b/systemd/agent/homelab-appliance-state.service @@ -0,0 +1,48 @@ +# Whether fenrir is still the appliance build-the-sensor-guest.md leaves (#1577). +# +# fenrir only: the installer's requirement for this row is /srv/sensor-data, +# which no other host has. Like patch-state's unit, it calls the collector +# directly, so there are no homelab_job_* metrics for it; the lab's +# ApplianceStateStopped reads the file's age and the series' absence instead. +# +# RUNS AS ROOT, and needs it, unlike patch-state. `sshd -T` reads the host keys, +# and the root_keys check reads /root/.ssh. Everything it does is a read; the one +# write is the textfile directory. +# +# Two directives are looser than patch-state's, each for one check: +# - ProtectHome=read-only, not true: the keys, user_units and home_size checks +# read atreus's home and the root_keys check reads root's. +# - AF_NETLINK in RestrictAddressFamilies: `ss` asks the kernel for sockets over +# sock_diag netlink. Without it the listeners check reads nothing and fails, +# which is the safe direction but not the right answer. AF_UNIX is `snap +# list` talking to snapd. +# No PrivateNetwork: the listeners check must see the host's namespace. +# +# The collector is installed at /usr/local/bin/homelab-collect-appliance-state +# by scripts/install-agent-collectors.sh, which is also what installs this file. +[Unit] +Description=HomeLab: check fenrir against its appliance runbook +Documentation=file:///home/atreus/code/Gerrrt/HomeLab/docs/runbooks/build-the-sensor-guest.md +ConditionPathIsDirectory=/var/lib/node_exporter/textfile_collector + +[Service] +Type=oneshot +ExecStart=/usr/local/bin/homelab-collect-appliance-state +TimeoutStartSec=120 +Restart=no +Nice=10 +NoNewPrivileges=true +RestrictSUIDSGID=true +LockPersonality=true +RestrictRealtime=true +PrivateTmp=true +ProtectHome=read-only +ProtectSystem=strict +ReadWritePaths=/var/lib/node_exporter/textfile_collector +ProtectKernelTunables=true +ProtectKernelModules=true +ProtectControlGroups=true +RestrictAddressFamilies=AF_UNIX AF_NETLINK +StandardOutput=journal +StandardError=journal +SyslogIdentifier=homelab-appliance-state diff --git a/systemd/agent/homelab-appliance-state.timer b/systemd/agent/homelab-appliance-state.timer new file mode 100644 index 00000000..54f812c8 --- /dev/null +++ b/systemd/agent/homelab-appliance-state.timer @@ -0,0 +1,19 @@ +[Unit] +Description=HomeLab: hourly appliance check on fenrir +Documentation=file:///home/atreus/code/Gerrrt/HomeLab/docs/runbooks/build-the-sensor-guest.md + +[Timer] +Unit=homelab-appliance-state.service +# Hourly, not daily like patch-state. A tool installed on fenrir starts reaching +# out the moment it runs, and the audit's finding was weeks of nobody knowing. +# The run reads a handful of files and two sockets, so the cost is nothing. +# OnBootSec gives a reading soon after a reboot, which is when a changed +# sshd_config or a newly enabled service would first show. +OnCalendar=hourly +OnBootSec=5min +RandomizedDelaySec=300 +Persistent=true +AccuracySec=1m + +[Install] +WantedBy=timers.target