From edda790ddcb8a83e691a943bb94076c107b5763a Mon Sep 17 00:00:00 2001 From: Gerrrt Date: Mon, 23 Nov 2026 10:13:21 -0800 Subject: [PATCH 1/2] feat(observability): the range monitoring of ADR-0126, built not deployed (#1651) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A collector for gandalf's own controls (collect-range-state.sh: the vmbr1 ingress barrier, vmbr0/sshd forwarding, and the ragnarok stop timer), a deadline-epoch subcommand on ragnarok-stop.sh so the monitor reads the timer's own effective deadline, and six range.rules.yaml alerts with promtool tests: PveFirewallZeroRules, the barrier/forwarding checks, and the stop timer failing. install-agent-collectors.sh gains the row; §7 gains the host-only install steps. Not host uptime — an always-on host has no fault there. Counts trued up, including the inherited 126->127 ADR count. The morpheus pass, a metrics-only Alloy config, and the live deploy need the lab and are flagged, not in this change. Refs #1651. Co-Authored-By: Claude Opus 4.8 --- README.md | 8 +- docs/changelog.md | 21 ++ docs/observability.md | 9 +- docs/runbooks/build-the-playground.md | 50 ++++ docs/runbooks/deploy-stack.md | 2 +- docs/security.md | 2 +- scripts/README.md | 1 + scripts/collect-range-state.sh | 178 +++++++++++++ scripts/install-agent-collectors.sh | 1 + scripts/ragnarok-stop.sh | 36 ++- scripts/self-tests.sh | 3 + stacks/observability/README.md | 4 +- .../prometheus/rules/range.rules.yaml | 131 +++++++++ .../prometheus/tests/range.test.yaml | 249 ++++++++++++++++++ 14 files changed, 682 insertions(+), 13 deletions(-) create mode 100755 scripts/collect-range-state.sh create mode 100644 stacks/observability/prometheus/rules/range.rules.yaml create mode 100644 stacks/observability/prometheus/tests/range.test.yaml diff --git a/README.md b/README.md index 70354c69e..b14f1657a 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,7 @@ documents for different readers. can't run an agent (firewall, switch, UPS, iLO). One agent config, deployed identically everywhere. [How](docs/architecture.md#observability-data-flow) - **Dashboards and alerting as code.** 8 provisioned dashboards, 156 panels, and - 192 alert rules — 166 metric-based in Prometheus, 26 log-based in Loki — sharing + 198 alert rules — 172 metric-based in Prometheus, 26 log-based in Loki — sharing one Alertmanager routing tree. No dashboard exists only in a database. - **Secrets encrypted in-repo with SOPS + age.** Per-device credentials, decrypted at deploy time into gitignored paths, with `git log` showing which @@ -136,7 +136,7 @@ documents for different readers. at all. Every pinned digest is also scanned weekly for fixable HIGH and CRITICAL CVEs, and each image with findings has an open issue until a scan finds it clean. -- **Documented decisions and runbooks.** 126 ADRs covering what was chosen +- **Documented decisions and runbooks.** 127 ADRs covering what was chosen and what was rejected — including the costs accepted knowingly; 53 runbooks for the operations that are easy to get wrong at 1am, one of which is the handover page a successor reads first. Every critical alert links to @@ -207,7 +207,7 @@ inbound passes may still reach it. Data flow and the maintained Mermaid topology . ├── stacks/ │ ├── observability/ # the estate's stack on prometheus — ten services -│ │ ├── prometheus/ # config, file_sd targets, 166 alert rules +│ │ ├── prometheus/ # config, file_sd targets, 172 alert rules │ │ ├── alertmanager/ # routing and inhibition │ │ ├── loki/ # single-binary config + 26 LogQL rules │ │ ├── alloy/ # the agent config directory, shipped to every host @@ -236,7 +236,7 @@ inbound passes may still reach it. Data flow and the maintained Mermaid topology │ ├── architecture.md network.md hardware.md │ ├── observability.md security.md roadmap.md changelog.md │ ├── diagrams/ # the network diagram (SVG) and its predecessors -│ ├── adr/ # 126 ADRs — architecture decision records +│ ├── adr/ # 127 ADRs — architecture decision records │ ├── exercises/ # purple-team exercise records — see its README │ └── runbooks/ # 53 runbooks; successor-handover.md is the front door └── Makefile # make help diff --git a/docs/changelog.md b/docs/changelog.md index 98771ed87..2a6ac4e66 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -19,6 +19,27 @@ docstring gives: it is a record, not a claim about now. ## 2026-11-23 +- **The range monitoring of ADR-0126 is built in the repository, not yet + deployed ([#1651](https://github.com/Gerrrt/HomeLab/issues/1651)).** A new + collector, `scripts/collect-range-state.sh`, reads `gandalf`'s own controls + — the `vmbr1_host_in` ingress barrier, `vmbr0` and `sshd` forwarding, and the + `ragnarok` stop timer with the deadline it set. The deadline comes from one + place: `ragnarok-stop.sh` gains a `deadline-epoch` subcommand so the monitor + reads the timer's own effective deadline rather than a second copy of its + logic. `stacks/observability/prometheus/rules/range.rules.yaml` adds six + alerts — `PveFirewallZeroRules` (the firewall on with no host rules, which + the collector measured but nothing read), the ingress barrier down, + `vmbr0`/`sshd` forwarding on, and the stop timer failing + (`RagnarokStopTimerInactive`, `RagnarokPastDeadline`) — each with a firing + and a quiet promtool test. Host uptime is deliberately not alerted: an + always-on host has no "up too long" fault. `install-agent-collectors.sh` + gains the `range-state` row, and `build-the-playground.md` §7 gains the + install steps, host-only (no `guest-disk-state`, which reads inside a guest). + - Still to deploy, needing the lab and the firewall: the `morpheus` pass + (`10.0.30.30 → 10.0.99.20:9090`, metrics only), a **metrics-only** Alloy + config and deploy check so the range host ships no logs, and installing + the collectors on `gandalf` plus a converge. The runbook marks these *not + yet deployed*. - **The range host will be monitored now that it stays on ([ADR-0126](adr/0126-monitor-gandalf-now-that-it-stays-on.md), [#1651](https://github.com/Gerrrt/HomeLab/issues/1651)).** ADR-0125 made diff --git a/docs/observability.md b/docs/observability.md index 825b4033f..a01c42fb3 100644 --- a/docs/observability.md +++ b/docs/observability.md @@ -352,7 +352,7 @@ separates a quiet stream from a stopped one. ## Alerting -192 rules in total: 166 metric-based in `prometheus/rules/`, and 26 log-based in +198 rules in total: 172 metric-based in `prometheus/rules/`, and 26 log-based in `loki/rules/`. ### Log-based (Loki ruler) @@ -540,7 +540,7 @@ argument and for what to do when it exits 1. ### Metric-based (Prometheus) -166 rules across twelve files in `prometheus/rules/`: +172 rules across 13 files in `prometheus/rules/`: | File | Covers | | --- | --- | @@ -555,6 +555,7 @@ argument and for what to do when it exits 1. | `backup.rules.yaml` | Whether the scheduled maintenance jobs are still being run at all — staleness, failure, never-ran, and the page: `ScheduledJobStaleCritical` at three of a job's own periods and never under a day, because the warning reaches only the in-house channel and a backup that stopped in week one was otherwise a notification repeating on the same network for as long as nobody acted (2026-10-14) — whether the CA key's offline copy has been proved lately ([#496](https://github.com/Gerrrt/HomeLab/issues/496)), and whether the newest backup sets have been carried onto the second recipient's medium within ninety days ([ADR-0048](adr/0048-carry-the-estates-backup-sets-with-the-second-recipient.md)) | | `deploy.rules.yaml` | Whether each host that pulls — `prometheus` and `trinity` ([#533](https://github.com/Gerrrt/HomeLab/issues/533)) — is running what the repository says: an uncommitted edit made on the host, a revision that did not verify, and how far behind `main` it is, and a host whose record stopped arriving. Reads the record `scripts/converge.sh` writes hourly ([#99](https://github.com/Gerrrt/HomeLab/issues/99), [ADR-0021](adr/0021-converge-on-a-timer-instead-of-deploying-over-ssh.md)). Also whether convergence had to start a stack service that something stopped — `DeployServiceRevived` — and whether one has been left stopped for two hours, held or under a backup — `DeployServicesStopped` ([ADR-0087](adr/0087-start-a-stopped-stack-service-from-the-converge-timer.md)) | | `internet.rules.yaml` | Why the internet is slow ([#914](https://github.com/Gerrrt/HomeLab/issues/914)): three scheduled speed tests in a row under 400 Mbit/s down or 100 up, the WAN held above 85% of what it can carry, frames arriving corrupted on the WAN port — `WanReceiveErrors`, the fault found the day these were written, when a cable between the XB7 and `morpheus` cut downloads to ~2 Mbit/s — and `speedtest-tracker` itself going quiet or unreachable. Also records `homelab_wan_bits_per_second` from pf's own em0 counters. Download thresholds are against the ~940 Mbit/s the 1000baseT WAN port can carry, not the plan's 2000. `speedtest-tracker` is left out of `InstanceDown`, so its outage is a warning and not a page | +| `range.rules.yaml` | The range host `gandalf`'s own controls, now that it stays on ([ADR-0126](adr/0126-monitor-gandalf-now-that-it-stays-on.md), [#1651](https://github.com/Gerrrt/HomeLab/issues/1651)): the `vmbr1_host_in` ingress barrier, `vmbr0` forwarding and `sshd` forwarding being off (`build-the-playground.md` §2, §4), and the attack-VM stop timer (ADR-0125) — read by `scripts/collect-range-state.sh`. `PveFirewallZeroRules` is here too: the firewall collector exports the rule count but no other rule reads it | | `ids.rules.yaml` | Whether Suricata is running on each interface it is declared for, read from the firewall's process table over SNMP — the fast, per-interface half; `SuricataLogsStopped` in `loki/rules/security.rules.yaml` is the slow, aggregate half ([#90](https://github.com/Gerrrt/HomeLab/issues/90), [#441](https://github.com/Gerrrt/HomeLab/issues/441)) | **Every critical alert links to a runbook** ([#842](https://github.com/Gerrrt/HomeLab/issues/842)). @@ -576,8 +577,8 @@ as loaded and healthy and could not fire for any input ([#63](https://github.com `prometheus/tests/*.test.yaml` holds `promtool test rules` unit tests, which feed a rule synthetic series and assert it fires — paired with a case asserting it stays quiet, because a test that only ever expects silence would have passed -against the broken rule too. Coverage is 166 rules of 166 so far ([#843](https://github.com/Gerrrt/HomeLab/issues/843)) — all twelve -in `blackbox.rules.yaml`, all three in `dns.rules.yaml`, `GatewayFilesystemCritical`, `ContainerHighMemory`, +against the broken rule too. Coverage is 172 rules of 172 so far ([#843](https://github.com/Gerrrt/HomeLab/issues/843)) — all twelve +in `blackbox.rules.yaml`, all three in `dns.rules.yaml`, all six in `range.rules.yaml`, `GatewayFilesystemCritical`, `ContainerHighMemory`, `ContainerNearMemoryLimit`, `ContainerRestartLoop`, `ContainerCpuThrottled`, the three container-state rules from [#838](https://github.com/Gerrrt/HomeLab/issues/838) and diff --git a/docs/runbooks/build-the-playground.md b/docs/runbooks/build-the-playground.md index 46f961f9f..0bac4d0be 100644 --- a/docs/runbooks/build-the-playground.md +++ b/docs/runbooks/build-the-playground.md @@ -1424,6 +1424,56 @@ should say it is not running, and `range-extend 2` should refuse. > `logger` under systemd, and was reinstalled. The installed files match the > repository by `sha256sum`. +### Monitoring the host + +`gandalf` stays on, so the per-session read-back above is a gap of days. +[ADR-0126](../adr/0126-monitor-gandalf-now-that-it-stays-on.md) gives it the +same Alloy agent `Saruman` has, reporting *hypervisor state* — the ADR-0028 +class, not guest telemetry — to `prometheus`, with alerts for the faults this +section used to catch by hand. **Not yet deployed on `gandalf`.** + +**First, the pass.** The agent pushes metrics to `10.0.99.20:9090`. On +`morpheus`, add a host-scoped pass `10.0.30.30 → 10.0.99.20` on `9090`, +**metrics only** — beside the two that already carry ImaginationLAN there, and +above the block to Winterfell. No `3100`: the range host does not ship logs +(below). This is the one crossing ADR-0014 counts, and it is outbound. + +**Then the collectors**, host-only. From a Hicks workstation, install each by +name with [`install-agent-collectors.sh`](../../scripts/install-agent-collectors.sh), +which runs it once per collector: + +```bash +for c in pve-firewall-state range-state guest-state smart-state patch-state pve-version; do + scripts/install-agent-collectors.sh --only "$c" root@10.0.30.30 +done +``` + +**Not** `guest-disk-state` or `guest-service-state`: both read *inside* a guest +through its agent (`qm guest cmd … get-fsinfo`), which on the range would read +a target's filesystem — guest telemetry from the attacker's segment, which +ADR-0126 does not allow. `range-state` is `gandalf`'s own control file +([`collect-range-state.sh`](../../scripts/collect-range-state.sh)): the +`vmbr1_host_in` ingress barrier, `vmbr0` and `sshd` forwarding, and the +`ragnarok` stop timer and the deadline it set. + +**Then the agent, metrics only.** `gandalf`'s journal and auth logs can carry +what happens on the attacker's segment, so its agent must not ship them to +Loki. The estate's standard `config.alloy` pushes both metrics and logs, so a +metrics-only variant (no `loki.*`, no `3100`) and a deploy check that requires +only metrics are what [`deploy-agent.sh`](../../scripts/deploy-agent.sh) needs +for this host — **still to build (#1651)**; until it exists, do not deploy the +standard agent here, which would ship the range's logs. + +**What it watches.** Once the collectors report, `gandalf` joins the +`PveFirewall*` alerts in `host.rules.yaml`, and +[`range.rules.yaml`](../../stacks/observability/prometheus/rules/range.rules.yaml) +adds: the firewall enabled with zero host rules (`PveFirewallZeroRules`), the +ingress barrier down, `vmbr0` or `sshd` forwarding on, and the stop timer +failing — `ragnarok` running with the timer inactive, or past the deadline the +timer itself set. `DisposableGuestOutlived` also begins covering any +`disposable`-tagged guest here. Host uptime is deliberately not alerted: an +always-on host has no "up too long" fault (ADR-0126). + --- ## 8. Check the four properties diff --git a/docs/runbooks/deploy-stack.md b/docs/runbooks/deploy-stack.md index 21fb7a125..16e9ee74f 100644 --- a/docs/runbooks/deploy-stack.md +++ b/docs/runbooks/deploy-stack.md @@ -151,7 +151,7 @@ Then in the UI: 1. **Prometheus → Status → Targets.** Every job `UP`. The four `snmp` targets take up to 45 seconds on their first scrape. 2. **Prometheus → Status → Rules.** Every rule loaded, none in error. The - page lists 172: the 166 alert rules this repository counts everywhere + page lists 178: the 172 alert rules this repository counts everywhere else, plus the six recording rules: `homelab_suricata_expected_interface`, `homelab_battery_runtime_seconds`, and the two directions each of diff --git a/docs/security.md b/docs/security.md index cdfff469a..cf00cdc6c 100644 --- a/docs/security.md +++ b/docs/security.md @@ -33,7 +33,7 @@ What this network is actually built to survive: | A rooted range target reaching `gandalf` itself | **Dropped at `vmbr1`, before the host firewall, once applied.** The host has no address on the range bridge, but Linux answers ARP for its addresses on any interface and accepts a packet for them on any interface. So a target that adds an on-link route to `10.0.30.30` was reaching the host, and only the Proxmox firewall dropped it. Nothing watches that firewall on `gandalf`. A netdev `ingress` table on `vmbr1` now drops every frame the bridge passes up to the host, ARP included, without touching guest-to-guest traffic ([`build-the-playground.md`](runbooks/build-the-playground.md) §2, proved by §8 check four). Behind it, `gandalf` holds no estate credential, no GitHub login, no personal tooling and no third-party apt repository (§4, *Nothing else on `gandalf`*), so the host gives nothing beyond itself. The audits of 2026-11-13 and 2026-11-22 found credentials, then tooling and two third-party repositories. The credentials were gone by 2026-11-22. **The table and the tooling removal are not yet applied** | | Someone on Winterfell or Hicks logging in to `trinity` | **Key-only `sshd` since 2026-11-20; no host firewall by decision.** `trinity` holds the household's data and the sensitive tier's age key, and its `sshd` answers Hicks (by [ADR-0031](adr/0031-narrow-hicks-to-a-named-list-on-winterfell-and-leave-the-lab-open.md)'s list) and every host on VLAN 99, between which pfSense never filters. [`build-the-sensitive-tier-host.md`](runbooks/build-the-sensitive-tier-host.md) §3 now makes `sshd` key-only through a drop-in that outranks cloud-init's, refuses root and X11 forwarding, and keeps `authorized_keys` to `prometheus`'s key and Hicks's. The audit of 2026-11-13 found it taking passwords, with X11 forwarding on and 17 keys imported from GitHub. The step was applied on 2026-11-20: a password-only login is refused with `Permission denied (publickey)`, and three keys remain, `prometheus`'s, Hicks's and the operator's laptop, the last kept by decision. Agent sessions run on `trinity` as the operator, by decision ([ADR-0123](adr/0123-keep-agent-sessions-on-trinity.md)). `ufw` is installed and stays disabled, unlike `phoenix`'s ([ADR-0117](adr/0117-give-phoenix-a-key-only-sshd-and-a-default-deny-inbound-policy.md)): the other two ports `trinity` answers, `443` and `53`, are published by Docker, whose rules run ahead of `ufw`'s, so a policy would govern `22` alone, which the drop-in already closes to anything without a key. Nothing routes through `trinity`, and as the spare firewall a host policy is one more thing to get in the way the day it stands in for `morpheus`. What reaches `443` and `53` is set by pfSense and by the stack's bind addresses | | Someone with the trusted Wi-Fi key quietly joining | Kea's lease log reaches Loki; `UnknownDeviceOnTrustedSegment` fires the first time a MAC appears on VLAN 50 in seven days ([ADR-0019](adr/0019-read-device-joins-from-the-dhcp-server.md)) | -| Losing visibility of a failure | 192 alert rules, 30 days of metrics and logs | +| Losing visibility of a failure | 198 alert rules, 30 days of metrics and logs | | Someone on a reachable VLAN silencing an alert to hide a failure | Alertmanager binds to `127.0.0.1`; silences go through authenticated Grafana | | Mains power loss | **The rack, yes; the monitoring path, yes — on two laptop cells that were measured for the first time on 2026-09-12.** A pack fitted to `mjolnir` on 2026-08-28 passed its self-test; the TP-Link carrying `prometheus` and `oracle` has been on UPS power since 2026-09-08 ([#110](https://github.com/Gerrrt/HomeLab/issues/110)); the laptops ride a cut out on their own batteries, which `HostBatteryHealthLow` in `host.rules.yaml` now reads — `prometheus`'s cell was replaced on 2026-09-18 and reads 101 % of design, `oracle`'s was replaced on 2026-09-29 and reads 100 %, its design figure rather than a learned one ([#531](https://github.com/Gerrrt/HomeLab/issues/531)) — and **each runtime was measured once: `prometheus`'s on 2026-09-19, about 2.5 hours from full at the stack's load, and `oracle`'s on 2026-09-29, about 5.2 hours**; since the same day the projection is recorded on every cut and pages under thirty minutes (`HostBatteryRuntimeLow`, [#532](https://github.com/Gerrrt/HomeLab/issues/532)), but neither pack reports a moving cell temperature, so this row is answered for both hosts' runtime and for neither's cell temperature — see below. **What happens when the cut outlasts the pack is configured and accepted without a live test.** Since 2026-09-23 the firewall's NUT server reads `mjolnir`, and `Saruman` and `smaug` subscribe to it on their own gateway addresses, so a real cut would now try to run the sequence [ADR-0049](adr/0049-shut-down-on-the-ups-from-a-nut-server-on-the-firewall.md) decides: `Saruman` and `smaug` halt first and `morpheus` last. Since the move into the 32U rack on 2026-11-06 the PDU also carries `trinity`, `gandalf` (off until its build) and the console, with `smaug` racked and on the PDU directly rather than by its old long cord to the media room. [ADR-0107](adr/0107-subscribe-trinity-to-the-ups-and-bound-saruman-s-guest-stop.md) makes `trinity` a third subscriber and bounds `Saruman`'s guest stop. `Saruman`'s half was applied on 2026-11-13 (`down=90` on the four ordered guests, and its monitor stays logged in until they are down); `trinity`'s subscription, `HOSTSYNC 600` on `morpheus` and the card's 16-minute threshold followed on 2026-11-20, so all three subscribers would now halt before the pack empties; `gandalf`, the console and `neo` are left to the pack by decision. The pack itself is unmeasured: about 47 minutes at 21 % load is the card's own estimate. Neither the forced-shutdown proof nor a mains pull will be run ([ADR-0121](adr/0121-accept-the-ups-shutdown-without-a-live-test.md)) | | The estate being down while the person who runs it is unavailable | **Documentation, yes; data, no copy outside the house, by decision.** ADR-0011 puts the emergency tier on paper; [ADR-0023](adr/0023-keep-the-household-recovery-path-outside-the-estate.md) extends the same reasoning to the sensitive tier's data. That tier has held real photographs since 2026-09-28. [ADR-0122](adr/0122-drop-the-household-copy.md) dropped their copy outside the estate, so a loss of the house loses them — see below | diff --git a/scripts/README.md b/scripts/README.md index 9f6da99bb..212fd0520 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -134,6 +134,7 @@ they describe. The rest are installed on the host they describe by | `collect-wazuh-manager-state.sh` | The Wazuh manager's agent counts, analysisd queues and dropped events, for the lab's Prometheus ([#1038](https://github.com/Gerrrt/HomeLab/issues/1038)) | | `collect-guest-service-state.sh` | Whether the lab Prometheus, Zeek, the Wazuh manager and Velociraptor are healthy, read through the guest agent ([ADR-0088](../docs/adr/0088-let-a-named-lab-services-health-cross-read-through-the-guest-agent.md)) | | `collect-pve-version.sh`, `collect-pve-firewall-state.sh` | The Proxmox version, and whether its firewall is on | +| `collect-range-state.sh` | `gandalf`'s own range controls: the `vmbr1_host_in` ingress barrier, `vmbr0` and `sshd` forwarding, and the `ragnarok` stop timer and its deadline ([ADR-0126](../docs/adr/0126-monitor-gandalf-now-that-it-stays-on.md)) | | `collect-iso-store-state.sh` | Whether the ISOs on the NFS store are the ones the repository expects | | `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)) | diff --git a/scripts/collect-range-state.sh b/scripts/collect-range-state.sh new file mode 100755 index 000000000..506755d21 --- /dev/null +++ b/scripts/collect-range-state.sh @@ -0,0 +1,178 @@ +#!/usr/bin/env bash +# +# The range host's own controls, for Prometheus (#1651, ADR-0126). +# +# WHAT THIS IS FOR. `collect-pve-firewall-state.sh` reads the Proxmox firewall, +# which is one of the barriers §7's read-back checks on `gandalf`. The others +# are not Proxmox's: the netdev `ingress` table `vmbr1_host_in` that drops what +# the range bridge sends the host (§2), `vmbr0`'s IP forwarding being off (§2), +# `sshd`'s forwarding being off (§4), and the attack-VM stop timer (ADR-0125) +# being the thing that bounds `ragnarok` on VLAN 30. On a host that is now on by +# design (ADR-0125), the per-session read-back is a gap of days, so this emits +# those controls as metrics and the range rules alert on them. +# +# HOST ONLY. Every fact here is read on `gandalf` itself — `nft`, `sysctl`, +# `sshd -T`, `systemctl`, and the stop timer's own machine-readable state. None +# is read from inside a guest, so this stays the ADR-0028 class ADR-0126 allows +# across, not guest telemetry. +# +# THE DEADLINE COMES FROM THE TIMER. The effective stop deadline folds in every +# `range-extend` and `dpkg` wait, and that logic lives in `ragnarok-stop.sh`. +# Rather than copy it, this calls `homelab-ragnarok-stop deadline-epoch` and +# reads back one source of truth. +# +# Usage: +# collect-range-state.sh write the .prom to the textfile dir +# collect-range-state.sh --print write it to stdout instead +# collect-range-state.sh --self-test run the parser fixtures +set -euo pipefail + +TEXTFILE_DIR="${TEXTFILE_DIR:-/var/lib/node_exporter/textfile_collector}" +PROM="${TEXTFILE_DIR}/range-state.prom" +HOSTNAME_LABEL="$(hostname)" +STOP_CMD="${STOP_CMD:-homelab-ragnarok-stop}" +STOP_TIMER="${STOP_TIMER:-homelab-ragnarok-stop.timer}" + +die() { printf '\033[0;31merror:\033[0m %s\n' "$*" >&2; exit 1; } + +# 1 when a netdev ingress chain on `vmbr1` drops by default — the barrier that +# stops a rooted target reaching the host (§2, `vmbr1_host_in`). Reads the +# chain's policy from `nft list chain netdev vmbr1_host_in ingress`. An absent +# table (nft prints nothing, or an error to stderr the caller drops) is 0: no +# barrier. `policy accept`, or any chain that is not an ingress hook, is 0 too. +parse_ingress_drop() { + awk ' + /type[[:space:]]+filter[[:space:]]+hook[[:space:]]+ingress/ { hook = 1 } + hook && /policy[[:space:]]+drop/ { drop = 1 } + END { print (drop ? 1 : 0) } + ' +} + +# For an `sshd -T` keyword, 1 when it reads `yes`, 0 when `no`, and nothing when +# the keyword is absent. `sshd -T` lowercases its keys and prints one setting +# per line, e.g. `x11forwarding no`. Used for forwarding keys, where `yes` is +# the fault, so the metric is 1-is-bad. +parse_sshd_flag() { + awk -v key="$1" ' + $1 == key { print ($2 == "yes") ? 1 : 0; found = 1; exit } + END { if (!found) exit 0 } + ' +} + +# The value for a key in `homelab-ragnarok-stop deadline-epoch` output +# (`running=1`, `deadline_epoch=`, `source=...`). Nothing when the key is +# absent. +parse_kv() { + awk -F= -v key="$1" '$1 == key { print $2; exit }' +} + +is_uint() { [[ "$1" =~ ^[0-9]+$ ]]; } + +if [[ "${1:-}" == "--self-test" ]]; then + fail=0 + check() { + local name="$1" got="$2" expect="$3" + if [[ "$got" == "$expect" ]]; then + printf '\033[0;32m PASS\033[0m %s\n' "$name" + else + printf '\033[0;31m FAIL\033[0m %s\n got %s\n expected %s\n' "$name" "$got" "$expect" + fail=1 + fi + } + + # The table as §2 loads it: an ingress hook with a drop policy. + check "a loaded vmbr1_host_in ingress chain is a barrier" \ + "$(printf '%s\n' 'chain ingress { + type filter hook ingress device "vmbr1" priority filter; policy drop; + counter name "dropped" drop + }' | parse_ingress_drop)" "1" + check "an ingress chain that accepts is not a barrier" \ + "$(printf '%s\n' 'chain ingress { + type filter hook ingress device "vmbr1" priority filter; policy accept; + }' | parse_ingress_drop)" "0" + check "no table at all is not a barrier" "$(printf '' | parse_ingress_drop)" "0" + # A drop policy on some other hook is not the ingress barrier. + check "a drop on a non-ingress hook does not count" \ + "$(printf '%s\n' 'chain output { + type filter hook output priority filter; policy drop; + }' | parse_ingress_drop)" "0" + + check "x11forwarding yes is the fault" \ + "$(printf 'x11forwarding yes\nallowtcpforwarding no\n' | parse_sshd_flag x11forwarding)" "1" + check "allowtcpforwarding no is clean" \ + "$(printf 'x11forwarding yes\nallowtcpforwarding no\n' | parse_sshd_flag allowtcpforwarding)" "0" + check "an absent key prints nothing" \ + "$(printf 'permitrootlogin without-password\n' | parse_sshd_flag x11forwarding)" "" + # sshd -T prints the key once; a value that is a substring must not match. + check "the key matches the whole field, not a prefix" \ + "$(printf 'x11forwardingtrusted yes\nx11forwarding no\n' | parse_sshd_flag x11forwarding)" "0" + + check "deadline_epoch is read from the timer's output" \ + "$(printf 'running=1\ndeadline_epoch=1800021600\nsource=extended\n' | parse_kv deadline_epoch)" "1800021600" + check "running is read from the timer's output" \ + "$(printf 'running=0\n' | parse_kv running)" "0" + check "an absent key is nothing" \ + "$(printf 'running=0\n' | parse_kv deadline_epoch)" "" + exit $fail +fi + +PRINT_ONLY=0 +[[ "${1:-}" == "--print" ]] && PRINT_ONLY=1 + +command -v nft >/dev/null 2>&1 || die "no nft on this host — it is not the range host." + +ingress_drop="$(nft list chain netdev vmbr1_host_in ingress 2>/dev/null | parse_ingress_drop)" +fwd4="$(sysctl -n net.ipv4.conf.vmbr0.forwarding 2>/dev/null || echo "")" +fwd6="$(sysctl -n net.ipv6.conf.vmbr0.forwarding 2>/dev/null || echo "")" +sshd_out="$(sshd -T 2>/dev/null || true)" +x11="$(printf '%s\n' "$sshd_out" | parse_sshd_flag x11forwarding)" +tcpf="$(printf '%s\n' "$sshd_out" | parse_sshd_flag allowtcpforwarding)" + +timer_active=0 +[[ "$(systemctl is-active "${STOP_TIMER}" 2>/dev/null)" == "active" ]] && timer_active=1 +stop_state="$("${STOP_CMD}" deadline-epoch 2>/dev/null || true)" +rag_running="$(printf '%s\n' "$stop_state" | parse_kv running)" +is_uint "${rag_running}" || rag_running=0 +rag_deadline="$(printf '%s\n' "$stop_state" | parse_kv deadline_epoch)" + +emit() { + printf '# HELP homelab_range_ingress_table_loaded 1 when vmbr1 drops what it sends the host (vmbr1_host_in, build-the-playground.md §2).\n' + printf '# TYPE homelab_range_ingress_table_loaded gauge\n' + printf 'homelab_range_ingress_table_loaded{host="%s"} %s\n' "$HOSTNAME_LABEL" "$ingress_drop" + + printf '# HELP homelab_range_forwarding IP forwarding on a bridge; 0 is the wanted state (build-the-playground.md §2).\n' + printf '# TYPE homelab_range_forwarding gauge\n' + is_uint "${fwd4}" && printf 'homelab_range_forwarding{host="%s",dev="vmbr0",family="ipv4"} %s\n' "$HOSTNAME_LABEL" "$fwd4" + is_uint "${fwd6}" && printf 'homelab_range_forwarding{host="%s",dev="vmbr0",family="ipv6"} %s\n' "$HOSTNAME_LABEL" "$fwd6" + + printf '# HELP homelab_range_sshd_forwarding 1 when sshd permits a forwarding kind; 0 is the wanted state (build-the-playground.md §4).\n' + printf '# TYPE homelab_range_sshd_forwarding gauge\n' + [[ -n "$x11" ]] && printf 'homelab_range_sshd_forwarding{host="%s",kind="x11"} %s\n' "$HOSTNAME_LABEL" "$x11" + [[ -n "$tcpf" ]] && printf 'homelab_range_sshd_forwarding{host="%s",kind="tcp"} %s\n' "$HOSTNAME_LABEL" "$tcpf" + + printf '# HELP homelab_ragnarok_running 1 when the attack VM (ADR-0125) is running.\n' + printf '# TYPE homelab_ragnarok_running gauge\n' + printf 'homelab_ragnarok_running{host="%s"} %s\n' "$HOSTNAME_LABEL" "$rag_running" + + printf '# HELP homelab_ragnarok_stop_timer_active 1 when the stop timer (ADR-0125) is active.\n' + printf '# TYPE homelab_ragnarok_stop_timer_active gauge\n' + printf 'homelab_ragnarok_stop_timer_active{host="%s"} %s\n' "$HOSTNAME_LABEL" "$timer_active" + + # The effective stop deadline, only while the VM runs. Absent when it is + # stopped, so RagnarokPastDeadline cannot fire on a box with no attack VM. + if [[ "$rag_running" == 1 ]] && is_uint "${rag_deadline}"; then + printf '# HELP homelab_ragnarok_deadline_seconds The epoch the stop timer will shut ragnarok down at (ADR-0125, from the timer itself).\n' + printf '# TYPE homelab_ragnarok_deadline_seconds gauge\n' + printf 'homelab_ragnarok_deadline_seconds{host="%s"} %s\n' "$HOSTNAME_LABEL" "$rag_deadline" + fi +} + +if ((PRINT_ONLY)); then emit; exit 0; fi + +[[ -d "${TEXTFILE_DIR}" ]] || die "no ${TEXTFILE_DIR}" +tmp="${PROM}.$$" +emit > "${tmp}" || { rm -f "${tmp}"; die "could not write ${tmp}"; } +chmod 0644 "${tmp}" +mv -f "${tmp}" "${PROM}" +printf 'range-state host=%s ingress=%s fwd4=%s fwd6=%s x11=%s tcp=%s ragnarok=%s timer=%s\n' \ + "$HOSTNAME_LABEL" "$ingress_drop" "${fwd4:-?}" "${fwd6:-?}" "${x11:-?}" "${tcpf:-?}" "$rag_running" "$timer_active" diff --git a/scripts/install-agent-collectors.sh b/scripts/install-agent-collectors.sh index 72d89e62a..275383b17 100755 --- a/scripts/install-agent-collectors.sh +++ b/scripts/install-agent-collectors.sh @@ -127,6 +127,7 @@ COLLECTORS=( "guest-service-state scripts/collect-guest-service-state.sh guest-service-state.prom /usr/sbin/qm" "wazuh-manager-state scripts/collect-wazuh-manager-state.sh wazuh-manager-state.prom /srv/soc-data" "pve-firewall-state scripts/collect-pve-firewall-state.sh pve-firewall-state.prom /usr/sbin/pve-firewall" + "range-state scripts/collect-range-state.sh range-state.prom /usr/sbin/nft" "iso-store-state scripts/collect-iso-store-state.sh iso-store-state.prom /mnt/smaug-iso" "zeek-mirror scripts/zeek-mirror.sh - /usr/sbin/qm" "zeek-mirror-state scripts/collect-zeek-mirror-state.sh zeek-mirror-state.prom /usr/sbin/qm" diff --git a/scripts/ragnarok-stop.sh b/scripts/ragnarok-stop.sh index 17dd53292..765b7d85e 100755 --- a/scripts/ragnarok-stop.sh +++ b/scripts/ragnarok-stop.sh @@ -243,6 +243,27 @@ cmd_status() { return 0 } +# Machine-readable state for collect-range-state.sh (#1651, ADR-0126), so the +# effective deadline a monitor alerts on comes from one place — here — rather +# than a second copy of this script's run-identity and six-hour-default logic. +# One key=value per line. A stopped VM prints `running=0` and no deadline. +cmd_deadline_epoch() { + local pid + pid="$(vm_pid)" + if [[ -z "${pid}" ]]; then + printf 'running=0\n' + return 0 + fi + printf 'running=1\n' + printf 'deadline_epoch=%s\n' "$(deadline "${pid}")" + if [[ -n "$(extended "${pid}")" ]]; then + printf 'source=extended\n' + else + printf 'source=default\n' + fi + return 0 +} + self_test() { local passed=0 failed=0 tmp tmp="$(mktemp -d)" @@ -334,6 +355,18 @@ self_test() { PID=5151; START=$((NOW + 60)); NOW=$((START + 6 * H)); cmd_check check "a new run ignores the old run's extension" "$(stops)" "1" + # deadline-epoch: the machine-readable state the monitor reads (#1651). + reset; NOW=$((START + H)); PID="" + check "deadline-epoch on a stopped VM prints running=0" "$(cmd_deadline_epoch)" "running=0" + reset; NOW=$((START + H)) + check "deadline-epoch on a fresh run gives start + six hours" \ + "$(cmd_deadline_epoch | sed -n 's/^deadline_epoch=//p')" "$((START + 6 * H))" + check "and marks it the default" "$(cmd_deadline_epoch | sed -n 's/^source=//p')" "default" + reset; NOW=$((START + H)); cmd_extend 3 >/dev/null + check "deadline-epoch after an extension gives the extended deadline" \ + "$(cmd_deadline_epoch | sed -n 's/^deadline_epoch=//p')" "$((NOW + 3 * H))" + check "and marks it extended" "$(cmd_deadline_epoch | sed -n 's/^source=//p')" "extended" + # A restart between reading the PID and stopping: the new run is not the # one whose deadline passed (review on #1652). reset; NOW=$((START + 6 * H + 10)); RESTART=5151; cmd_check @@ -382,5 +415,6 @@ case "${1:-}" in check) cmd_check ;; status) cmd_status ;; extend) shift; cmd_extend "$@" ;; - *) printf 'usage: %s check|status|extend |--self-test\n' "$0" >&2; exit 2 ;; + deadline-epoch) cmd_deadline_epoch ;; + *) printf 'usage: %s check|status|extend |deadline-epoch|--self-test\n' "$0" >&2; exit 2 ;; esac diff --git a/scripts/self-tests.sh b/scripts/self-tests.sh index 1837b2460..799eab40d 100755 --- a/scripts/self-tests.sh +++ b/scripts/self-tests.sh @@ -23,6 +23,9 @@ # collect-pve-version.sh pveversion's format, for a host this repo cannot # reach; one fixture stops the kernel being read as # the PVE version (#311) +# collect-range-state.sh gandalf's range controls (ADR-0126): the ingress +# barrier, forwarding and sshd parses, and the keys +# read back from the stop timer's deadline-epoch # collect-guest-state.sh qm list, same unreachable host; a stopped guest has # no PID column and a guest name can contain a space # record-applied.sh what `make up` applied, kept apart from HEAD; the diff --git a/stacks/observability/README.md b/stacks/observability/README.md index a7d694aa1..dfed3bf9f 100644 --- a/stacks/observability/README.md +++ b/stacks/observability/README.md @@ -53,8 +53,8 @@ prometheus/ targets/snmp.yaml SNMP targets — hot-reloaded, no restart needed targets/node.yaml node_exporter scrapes, for the host that runs no Alloy (smaug) targets/blackbox*.yaml probe targets, http, dns and latency — hot-reloaded, no restart - rules/*.rules.yaml 166 alert rules: host, network, ups, containers, blackbox, - dns, backup, ids, deploy, stack, internet and watchdog + rules/*.rules.yaml 172 alert rules: host, network, ups, containers, blackbox, + dns, backup, ids, deploy, stack, internet, watchdog and range tests/*.test.yaml promtool unit tests — assert the rules can fire blackbox/blackbox.yaml probe modules — reachability, and what a resolver said alertmanager/ diff --git a/stacks/observability/prometheus/rules/range.rules.yaml b/stacks/observability/prometheus/rules/range.rules.yaml new file mode 100644 index 000000000..4c61fbacb --- /dev/null +++ b/stacks/observability/prometheus/rules/range.rules.yaml @@ -0,0 +1,131 @@ +--- +# The range host gandalf's own controls (ADR-0126, #1651). ADR-0125 keeps +# gandalf on, so build-the-playground.md §7's per-session read-back is a gap of +# days; these turn its checks into rules. The firewall itself is covered by the +# PveFirewall* alerts in host.rules.yaml, which gandalf joins the day its +# collector reports; what is here is the rest of §7 — the netdev barrier, +# forwarding, sshd forwarding — and the ADR-0125 stop timer, read by +# scripts/collect-range-state.sh. collect-pve-firewall-state.sh exports the +# rule count but no alert read it, so PveFirewallZeroRules is here too. +groups: + - name: range + interval: 60s + rules: + - alert: PveFirewallZeroRules + # Enabled, DROP policy, and no host rules is a firewall that locks + # everyone out — and the easy thing to "fix" in a hurry is policy + # ACCEPT (PveFirewallPolicyAccept), which opens the segment. The + # collector has carried homelab_pve_firewall_rules since #576; nothing + # alerted on it being zero until now (ADR-0126 review). + expr: >- + homelab_pve_firewall_rules{file="host"} == 0 + and on (host) homelab_pve_firewall_enabled == 1 + and on (host) homelab_pve_firewall_policy_drop == 1 + for: 10m + labels: + component: host + severity: warning + category: security + annotations: + summary: "{{ $labels.instance }} firewall is enabled with a DROP policy and zero host rules" + description: >- + pve-firewall is on and refuses unmatched inbound, but host.fw holds + no rules, so nothing reaches the node — including the management + paths build-the-playground.md §4 grants. Restore host.fw's rules + rather than dropping the policy to ACCEPT, which would open the + whole segment. + + - alert: RangeIngressBarrierDown + # The vmbr1_host_in netdev table drops what the range bridge sends the + # host (§2). Without it, only the Proxmox firewall stands between a + # rooted target and the host, and nothing else here notices. + expr: homelab_range_ingress_table_loaded == 0 + for: 10m + labels: + component: host + severity: warning + category: security + annotations: + summary: "{{ $labels.instance }}: the vmbr1 ingress barrier is not loaded" + description: >- + The netdev ingress table vmbr1_host_in, which drops frames the range + bridge passes up to the host, is gone. A rooted target could reach + the host behind only the Proxmox firewall. Reload it, per + build-the-playground.md §2, and check §8 check four. + + - alert: RangeHostForwardingOn + # ifupdown2's default turns vmbr0 forwarding on; §2 turns it off. A host + # that forwards routes for VLAN 30 hosts that send it traffic. + expr: homelab_range_forwarding{dev="vmbr0"} == 1 + for: 10m + labels: + component: host + severity: warning + category: security + annotations: + summary: "{{ $labels.instance }}: IP forwarding is on for {{ $labels.dev }} ({{ $labels.family }})" + description: >- + The range host should route for no one (build-the-playground.md §2). + Set ip-forward off on the bridge and reload; the proof is a reboot + plus §2's read-back. + + - alert: RangeSshForwardingOn + # §4's drop-in turns X11 and TCP forwarding off, so a root session on + # the isolation host cannot become a tunnel. + expr: homelab_range_sshd_forwarding == 1 + for: 10m + labels: + component: host + severity: warning + category: security + annotations: + summary: "{{ $labels.instance }}: sshd permits {{ $labels.kind }} forwarding" + description: >- + sshd on the range host allows {{ $labels.kind }} forwarding, which + build-the-playground.md §4 turns off so a root session cannot tunnel + off the segment. An upgrade that rewrote sshd_config.d is the usual + cause; rerun §4. + + - alert: RagnarokStopTimerInactive + # The attack VM is running, but the timer that stops it (ADR-0125) is + # not active — disabled or failed. The §7 read-back checks the timer at + # power-on; this catches it going wrong between sessions, by its effect. + expr: >- + homelab_ragnarok_running == 1 + and on (host) homelab_ragnarok_stop_timer_active == 0 + for: 10m + labels: + component: host + severity: warning + category: security + annotations: + summary: "{{ $labels.instance }}: ragnarok is running but its stop timer is not active" + description: >- + The attack VM shares VLAN 30 with the estate, and its bound is the + homelab-ragnarok-stop timer (ADR-0125). The timer is not active, so + nothing stops the VM. Re-enable it (`systemctl enable --now + homelab-ragnarok-stop.timer`) or stop ragnarok by hand. + + - alert: RagnarokPastDeadline + # The timer is meant to be active, but the VM has run well past the + # deadline the timer itself set (extensions and dpkg waits folded in). + # Ten minutes past is not a late run — the timer fires every minute — it + # is a timer that is not stopping the VM. + # The time-past-deadline vector is on the left so $value is the overage + # (an `and` takes the left operand's value), and `and on (host)` keeps + # the attack VM running. + expr: >- + (time() - homelab_ragnarok_deadline_seconds) > 600 + and on (host) homelab_ragnarok_running == 1 + for: 5m + labels: + component: host + severity: warning + category: security + annotations: + summary: "{{ $labels.instance }}: ragnarok is {{ $value | humanizeDuration }} past its stop deadline" + description: >- + The attack VM is running more than ten minutes past the deadline the + stop timer set for it. The timer runs every minute, so it should + have stopped the VM; something is wedging it (check `journalctl -t + homelab-ragnarok-stop`), or stop ragnarok by hand. diff --git a/stacks/observability/prometheus/tests/range.test.yaml b/stacks/observability/prometheus/tests/range.test.yaml new file mode 100644 index 000000000..110926b82 --- /dev/null +++ b/stacks/observability/prometheus/tests/range.test.yaml @@ -0,0 +1,249 @@ +--- +# Tests for range.rules.yaml (#1651, ADR-0126). Each alert gets a firing case +# and a quiet near-miss, as scripts/check_rule_tests.py (#843) requires. +# promtool's time() counts from 0 at the first sample, so the deadline fixtures +# below use small epochs, not real ones. + +rule_files: + - ../rules/range.rules.yaml + +evaluation_interval: 1m + +tests: + # --- PveFirewallZeroRules: fires on enabled + DROP + zero host rules ------- + - interval: 1m + input_series: + - series: 'homelab_pve_firewall_rules{instance="gandalf",host="gandalf",file="host"}' + values: "0x12" + - series: 'homelab_pve_firewall_enabled{instance="gandalf",host="gandalf"}' + values: "1x12" + - series: 'homelab_pve_firewall_policy_drop{instance="gandalf",host="gandalf"}' + values: "1x12" + alert_rule_test: + - eval_time: 11m + alertname: PveFirewallZeroRules + exp_alerts: + - exp_labels: + instance: gandalf + host: gandalf + file: host + component: host + severity: warning + category: security + exp_annotations: + summary: "gandalf firewall is enabled with a DROP policy and zero host rules" + description: >- + pve-firewall is on and refuses unmatched inbound, but host.fw holds + no rules, so nothing reaches the node — including the management + paths build-the-playground.md §4 grants. Restore host.fw's rules + rather than dropping the policy to ACCEPT, which would open the + whole segment. + - eval_time: 5m + alertname: PveFirewallZeroRules + exp_alerts: [] + + # --- PveFirewallZeroRules: quiet when host.fw has rules -------------------- + - interval: 1m + input_series: + - series: 'homelab_pve_firewall_rules{instance="gandalf",host="gandalf",file="host"}' + values: "4x12" + - series: 'homelab_pve_firewall_enabled{instance="gandalf",host="gandalf"}' + values: "1x12" + - series: 'homelab_pve_firewall_policy_drop{instance="gandalf",host="gandalf"}' + values: "1x12" + alert_rule_test: + - eval_time: 11m + alertname: PveFirewallZeroRules + exp_alerts: [] + + # --- RangeIngressBarrierDown: fires when the table is gone ----------------- + - interval: 1m + input_series: + - series: 'homelab_range_ingress_table_loaded{instance="gandalf",host="gandalf"}' + values: "0x12" + alert_rule_test: + - eval_time: 11m + alertname: RangeIngressBarrierDown + exp_alerts: + - exp_labels: + instance: gandalf + host: gandalf + component: host + severity: warning + category: security + exp_annotations: + summary: "gandalf: the vmbr1 ingress barrier is not loaded" + description: >- + The netdev ingress table vmbr1_host_in, which drops frames the range + bridge passes up to the host, is gone. A rooted target could reach + the host behind only the Proxmox firewall. Reload it, per + build-the-playground.md §2, and check §8 check four. + - eval_time: 5m + alertname: RangeIngressBarrierDown + exp_alerts: [] + + # --- RangeIngressBarrierDown: quiet when the table is loaded --------------- + - interval: 1m + input_series: + - series: 'homelab_range_ingress_table_loaded{instance="gandalf",host="gandalf"}' + values: "1x12" + alert_rule_test: + - eval_time: 11m + alertname: RangeIngressBarrierDown + exp_alerts: [] + + # --- RangeHostForwardingOn: fires when vmbr0 forwards ---------------------- + - interval: 1m + input_series: + - series: 'homelab_range_forwarding{instance="gandalf",host="gandalf",dev="vmbr0",family="ipv4"}' + values: "1x12" + alert_rule_test: + - eval_time: 11m + alertname: RangeHostForwardingOn + exp_alerts: + - exp_labels: + instance: gandalf + host: gandalf + dev: vmbr0 + family: ipv4 + component: host + severity: warning + category: security + exp_annotations: + summary: "gandalf: IP forwarding is on for vmbr0 (ipv4)" + description: >- + The range host should route for no one (build-the-playground.md §2). + Set ip-forward off on the bridge and reload; the proof is a reboot + plus §2's read-back. + - eval_time: 5m + alertname: RangeHostForwardingOn + exp_alerts: [] + + # --- RangeHostForwardingOn: quiet when forwarding is off ------------------- + - interval: 1m + input_series: + - series: 'homelab_range_forwarding{instance="gandalf",host="gandalf",dev="vmbr0",family="ipv4"}' + values: "0x12" + alert_rule_test: + - eval_time: 11m + alertname: RangeHostForwardingOn + exp_alerts: [] + + # --- RangeSshForwardingOn: fires when sshd permits forwarding -------------- + - interval: 1m + input_series: + - series: 'homelab_range_sshd_forwarding{instance="gandalf",host="gandalf",kind="x11"}' + values: "1x12" + alert_rule_test: + - eval_time: 11m + alertname: RangeSshForwardingOn + exp_alerts: + - exp_labels: + instance: gandalf + host: gandalf + kind: x11 + component: host + severity: warning + category: security + exp_annotations: + summary: "gandalf: sshd permits x11 forwarding" + description: >- + sshd on the range host allows x11 forwarding, which + build-the-playground.md §4 turns off so a root session cannot tunnel + off the segment. An upgrade that rewrote sshd_config.d is the usual + cause; rerun §4. + - eval_time: 5m + alertname: RangeSshForwardingOn + exp_alerts: [] + + # --- RangeSshForwardingOn: quiet when forwarding is off -------------------- + - interval: 1m + input_series: + - series: 'homelab_range_sshd_forwarding{instance="gandalf",host="gandalf",kind="x11"}' + values: "0x12" + alert_rule_test: + - eval_time: 11m + alertname: RangeSshForwardingOn + exp_alerts: [] + + # --- RagnarokStopTimerInactive: fires when running with no active timer ---- + - interval: 1m + input_series: + - series: 'homelab_ragnarok_running{instance="gandalf",host="gandalf"}' + values: "1x12" + - series: 'homelab_ragnarok_stop_timer_active{instance="gandalf",host="gandalf"}' + values: "0x12" + alert_rule_test: + - eval_time: 11m + alertname: RagnarokStopTimerInactive + exp_alerts: + - exp_labels: + instance: gandalf + host: gandalf + component: host + severity: warning + category: security + exp_annotations: + summary: "gandalf: ragnarok is running but its stop timer is not active" + description: >- + The attack VM shares VLAN 30 with the estate, and its bound is the + homelab-ragnarok-stop timer (ADR-0125). The timer is not active, so + nothing stops the VM. Re-enable it (`systemctl enable --now + homelab-ragnarok-stop.timer`) or stop ragnarok by hand. + - eval_time: 5m + alertname: RagnarokStopTimerInactive + exp_alerts: [] + + # --- RagnarokStopTimerInactive: quiet when the timer is active ------------- + - interval: 1m + input_series: + - series: 'homelab_ragnarok_running{instance="gandalf",host="gandalf"}' + values: "1x12" + - series: 'homelab_ragnarok_stop_timer_active{instance="gandalf",host="gandalf"}' + values: "1x12" + alert_rule_test: + - eval_time: 11m + alertname: RagnarokStopTimerInactive + exp_alerts: [] + + # --- RagnarokPastDeadline: fires when running past the deadline + margin --- + # deadline_seconds=0, so time() - 0 crosses 600s after 10m; held to 16m so + # for: 5m elapses. + - interval: 1m + input_series: + - series: 'homelab_ragnarok_running{instance="gandalf",host="gandalf"}' + values: "1x17" + - series: 'homelab_ragnarok_deadline_seconds{instance="gandalf",host="gandalf"}' + values: "0x17" + alert_rule_test: + - eval_time: 16m + alertname: RagnarokPastDeadline + exp_alerts: + - exp_labels: + instance: gandalf + host: gandalf + component: host + severity: warning + category: security + exp_annotations: + summary: "gandalf: ragnarok is 16m 0s past its stop deadline" + description: >- + The attack VM is running more than ten minutes past the deadline the + stop timer set for it. The timer runs every minute, so it should + have stopped the VM; something is wedging it (check `journalctl -t + homelab-ragnarok-stop`), or stop ragnarok by hand. + - eval_time: 9m + alertname: RagnarokPastDeadline + exp_alerts: [] + + # --- RagnarokPastDeadline: quiet while within the deadline ---------------- + - interval: 1m + input_series: + - series: 'homelab_ragnarok_running{instance="gandalf",host="gandalf"}' + values: "1x17" + - series: 'homelab_ragnarok_deadline_seconds{instance="gandalf",host="gandalf"}' + values: "100000x17" + alert_rule_test: + - eval_time: 16m + alertname: RagnarokPastDeadline + exp_alerts: [] From 45b8f0e6b073ffaf822979e4cbefdd8e55ab6d6a Mon Sep 17 00:00:00 2001 From: Gerrrt Date: Mon, 23 Nov 2026 10:31:55 -0800 Subject: [PATCH 2/2] fix(observability): harden the range collector, timer and rules per review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review on #1679: - Add systemd/agent/homelab-range-state.{service,timer}; the installer requires the unit pair for every row, so without it --only range-state and every default install failed. - collect-range-state.sh: survive an absent nft table under set -e; treat a failed or malformed deadline-epoch as unknown, not a stopped VM; and AllowTcpForwarding local/remote now count as forwarding on (only no is off). - The stop timer records a dpkg deferral; the collector exports it and RagnarokPastDeadline excludes it, so a protected install past the deadline does not read as a failed timer. - Add RangeStateStale: the textfile exporter keeps serving old values when the collector stops, so a barrier that falls afterwards would read healthy. - §7 upgrades the stop helper before the collector; counts trued up. Refs #1651. Co-Authored-By: Claude Opus 4.8 --- README.md | 4 +- docs/changelog.md | 18 +++-- docs/observability.md | 8 +- docs/runbooks/build-the-playground.md | 16 +++- docs/runbooks/deploy-stack.md | 2 +- docs/security.md | 2 +- scripts/collect-range-state.sh | 75 ++++++++++++++----- scripts/ragnarok-stop.sh | 16 +++- stacks/observability/README.md | 2 +- .../prometheus/rules/range.rules.yaml | 22 ++++++ .../prometheus/tests/range.test.yaml | 57 ++++++++++++++ systemd/agent/homelab-range-state.service | 34 +++++++++ systemd/agent/homelab-range-state.timer | 18 +++++ 13 files changed, 238 insertions(+), 36 deletions(-) create mode 100644 systemd/agent/homelab-range-state.service create mode 100644 systemd/agent/homelab-range-state.timer diff --git a/README.md b/README.md index b14f1657a..8fd26339e 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,7 @@ documents for different readers. can't run an agent (firewall, switch, UPS, iLO). One agent config, deployed identically everywhere. [How](docs/architecture.md#observability-data-flow) - **Dashboards and alerting as code.** 8 provisioned dashboards, 156 panels, and - 198 alert rules — 172 metric-based in Prometheus, 26 log-based in Loki — sharing + 199 alert rules — 173 metric-based in Prometheus, 26 log-based in Loki — sharing one Alertmanager routing tree. No dashboard exists only in a database. - **Secrets encrypted in-repo with SOPS + age.** Per-device credentials, decrypted at deploy time into gitignored paths, with `git log` showing which @@ -207,7 +207,7 @@ inbound passes may still reach it. Data flow and the maintained Mermaid topology . ├── stacks/ │ ├── observability/ # the estate's stack on prometheus — ten services -│ │ ├── prometheus/ # config, file_sd targets, 172 alert rules +│ │ ├── prometheus/ # config, file_sd targets, 173 alert rules │ │ ├── alertmanager/ # routing and inhibition │ │ ├── loki/ # single-binary config + 26 LogQL rules │ │ ├── alloy/ # the agent config directory, shipped to every host diff --git a/docs/changelog.md b/docs/changelog.md index 2a6ac4e66..af3b2603a 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -26,15 +26,19 @@ docstring gives: it is a record, not a claim about now. `ragnarok` stop timer with the deadline it set. The deadline comes from one place: `ragnarok-stop.sh` gains a `deadline-epoch` subcommand so the monitor reads the timer's own effective deadline rather than a second copy of its - logic. `stacks/observability/prometheus/rules/range.rules.yaml` adds six + logic. `stacks/observability/prometheus/rules/range.rules.yaml` adds seven alerts — `PveFirewallZeroRules` (the firewall on with no host rules, which the collector measured but nothing read), the ingress barrier down, - `vmbr0`/`sshd` forwarding on, and the stop timer failing - (`RagnarokStopTimerInactive`, `RagnarokPastDeadline`) — each with a firing - and a quiet promtool test. Host uptime is deliberately not alerted: an - always-on host has no "up too long" fault. `install-agent-collectors.sh` - gains the `range-state` row, and `build-the-playground.md` §7 gains the - install steps, host-only (no `guest-disk-state`, which reads inside a guest). + `vmbr0`/`sshd` forwarding on, the stop timer failing + (`RagnarokStopTimerInactive`, `RagnarokPastDeadline`, which excludes a dpkg + wait so a protected install is not mistaken for a failed timer), and + `RangeStateStale` for the collector itself stopping — each with a firing and + a quiet promtool test. Host uptime is deliberately not alerted: an always-on + host has no "up too long" fault. `install-agent-collectors.sh` gains the + `range-state` row and `systemd/agent/` its unit pair, and + `build-the-playground.md` §7 gains the install steps, host-only (no + `guest-disk-state`, which reads inside a guest) and upgrading the stop helper + first. - Still to deploy, needing the lab and the firewall: the `morpheus` pass (`10.0.30.30 → 10.0.99.20:9090`, metrics only), a **metrics-only** Alloy config and deploy check so the range host ships no logs, and installing diff --git a/docs/observability.md b/docs/observability.md index a01c42fb3..36ac93c5c 100644 --- a/docs/observability.md +++ b/docs/observability.md @@ -352,7 +352,7 @@ separates a quiet stream from a stopped one. ## Alerting -198 rules in total: 172 metric-based in `prometheus/rules/`, and 26 log-based in +199 rules in total: 173 metric-based in `prometheus/rules/`, and 26 log-based in `loki/rules/`. ### Log-based (Loki ruler) @@ -540,7 +540,7 @@ argument and for what to do when it exits 1. ### Metric-based (Prometheus) -172 rules across 13 files in `prometheus/rules/`: +173 rules across 13 files in `prometheus/rules/`: | File | Covers | | --- | --- | @@ -577,8 +577,8 @@ as loaded and healthy and could not fire for any input ([#63](https://github.com `prometheus/tests/*.test.yaml` holds `promtool test rules` unit tests, which feed a rule synthetic series and assert it fires — paired with a case asserting it stays quiet, because a test that only ever expects silence would have passed -against the broken rule too. Coverage is 172 rules of 172 so far ([#843](https://github.com/Gerrrt/HomeLab/issues/843)) — all twelve -in `blackbox.rules.yaml`, all three in `dns.rules.yaml`, all six in `range.rules.yaml`, `GatewayFilesystemCritical`, `ContainerHighMemory`, +against the broken rule too. Coverage is 173 rules of 173 so far ([#843](https://github.com/Gerrrt/HomeLab/issues/843)) — all twelve +in `blackbox.rules.yaml`, all three in `dns.rules.yaml`, all seven in `range.rules.yaml`, `GatewayFilesystemCritical`, `ContainerHighMemory`, `ContainerNearMemoryLimit`, `ContainerRestartLoop`, `ContainerCpuThrottled`, the three container-state rules from [#838](https://github.com/Gerrrt/HomeLab/issues/838) and diff --git a/docs/runbooks/build-the-playground.md b/docs/runbooks/build-the-playground.md index 0bac4d0be..d2324b10c 100644 --- a/docs/runbooks/build-the-playground.md +++ b/docs/runbooks/build-the-playground.md @@ -1438,6 +1438,17 @@ section used to catch by hand. **Not yet deployed on `gandalf`.** above the block to Winterfell. No `3100`: the range host does not ship logs (below). This is the one crossing ADR-0014 counts, and it is outbound. +**Upgrade the stop helper first.** `collect-range-state.sh` reads the deadline +from `homelab-ragnarok-stop deadline-epoch`, a subcommand added for the +monitor. An older helper without it makes the collector leave the `ragnarok` +metrics out rather than read a false "stopped", so reinstall the current script +(*The attack VM's timer* above does the same) before the collector: + +```bash +scp scripts/ragnarok-stop.sh root@10.0.30.30:/usr/local/sbin/homelab-ragnarok-stop +ssh root@10.0.30.30 'chmod 0755 /usr/local/sbin/homelab-ragnarok-stop && homelab-ragnarok-stop deadline-epoch' +``` + **Then the collectors**, host-only. From a Hicks workstation, install each by name with [`install-agent-collectors.sh`](../../scripts/install-agent-collectors.sh), which runs it once per collector: @@ -1470,7 +1481,10 @@ standard agent here, which would ship the range's logs. adds: the firewall enabled with zero host rules (`PveFirewallZeroRules`), the ingress barrier down, `vmbr0` or `sshd` forwarding on, and the stop timer failing — `ragnarok` running with the timer inactive, or past the deadline the -timer itself set. `DisposableGuestOutlived` also begins covering any +timer itself set (a dpkg wait inside the VM is excluded, so a protected install +is not mistaken for a failed timer). `RangeStateStale` catches the collector +itself stopping, so a barrier that falls after it goes quiet is not read as +healthy. `DisposableGuestOutlived` also begins covering any `disposable`-tagged guest here. Host uptime is deliberately not alerted: an always-on host has no "up too long" fault (ADR-0126). diff --git a/docs/runbooks/deploy-stack.md b/docs/runbooks/deploy-stack.md index 16e9ee74f..60f4047b8 100644 --- a/docs/runbooks/deploy-stack.md +++ b/docs/runbooks/deploy-stack.md @@ -151,7 +151,7 @@ Then in the UI: 1. **Prometheus → Status → Targets.** Every job `UP`. The four `snmp` targets take up to 45 seconds on their first scrape. 2. **Prometheus → Status → Rules.** Every rule loaded, none in error. The - page lists 178: the 172 alert rules this repository counts everywhere + page lists 179: the 173 alert rules this repository counts everywhere else, plus the six recording rules: `homelab_suricata_expected_interface`, `homelab_battery_runtime_seconds`, and the two directions each of diff --git a/docs/security.md b/docs/security.md index cf00cdc6c..881ccbd8b 100644 --- a/docs/security.md +++ b/docs/security.md @@ -33,7 +33,7 @@ What this network is actually built to survive: | A rooted range target reaching `gandalf` itself | **Dropped at `vmbr1`, before the host firewall, once applied.** The host has no address on the range bridge, but Linux answers ARP for its addresses on any interface and accepts a packet for them on any interface. So a target that adds an on-link route to `10.0.30.30` was reaching the host, and only the Proxmox firewall dropped it. Nothing watches that firewall on `gandalf`. A netdev `ingress` table on `vmbr1` now drops every frame the bridge passes up to the host, ARP included, without touching guest-to-guest traffic ([`build-the-playground.md`](runbooks/build-the-playground.md) §2, proved by §8 check four). Behind it, `gandalf` holds no estate credential, no GitHub login, no personal tooling and no third-party apt repository (§4, *Nothing else on `gandalf`*), so the host gives nothing beyond itself. The audits of 2026-11-13 and 2026-11-22 found credentials, then tooling and two third-party repositories. The credentials were gone by 2026-11-22. **The table and the tooling removal are not yet applied** | | Someone on Winterfell or Hicks logging in to `trinity` | **Key-only `sshd` since 2026-11-20; no host firewall by decision.** `trinity` holds the household's data and the sensitive tier's age key, and its `sshd` answers Hicks (by [ADR-0031](adr/0031-narrow-hicks-to-a-named-list-on-winterfell-and-leave-the-lab-open.md)'s list) and every host on VLAN 99, between which pfSense never filters. [`build-the-sensitive-tier-host.md`](runbooks/build-the-sensitive-tier-host.md) §3 now makes `sshd` key-only through a drop-in that outranks cloud-init's, refuses root and X11 forwarding, and keeps `authorized_keys` to `prometheus`'s key and Hicks's. The audit of 2026-11-13 found it taking passwords, with X11 forwarding on and 17 keys imported from GitHub. The step was applied on 2026-11-20: a password-only login is refused with `Permission denied (publickey)`, and three keys remain, `prometheus`'s, Hicks's and the operator's laptop, the last kept by decision. Agent sessions run on `trinity` as the operator, by decision ([ADR-0123](adr/0123-keep-agent-sessions-on-trinity.md)). `ufw` is installed and stays disabled, unlike `phoenix`'s ([ADR-0117](adr/0117-give-phoenix-a-key-only-sshd-and-a-default-deny-inbound-policy.md)): the other two ports `trinity` answers, `443` and `53`, are published by Docker, whose rules run ahead of `ufw`'s, so a policy would govern `22` alone, which the drop-in already closes to anything without a key. Nothing routes through `trinity`, and as the spare firewall a host policy is one more thing to get in the way the day it stands in for `morpheus`. What reaches `443` and `53` is set by pfSense and by the stack's bind addresses | | Someone with the trusted Wi-Fi key quietly joining | Kea's lease log reaches Loki; `UnknownDeviceOnTrustedSegment` fires the first time a MAC appears on VLAN 50 in seven days ([ADR-0019](adr/0019-read-device-joins-from-the-dhcp-server.md)) | -| Losing visibility of a failure | 198 alert rules, 30 days of metrics and logs | +| Losing visibility of a failure | 199 alert rules, 30 days of metrics and logs | | Someone on a reachable VLAN silencing an alert to hide a failure | Alertmanager binds to `127.0.0.1`; silences go through authenticated Grafana | | Mains power loss | **The rack, yes; the monitoring path, yes — on two laptop cells that were measured for the first time on 2026-09-12.** A pack fitted to `mjolnir` on 2026-08-28 passed its self-test; the TP-Link carrying `prometheus` and `oracle` has been on UPS power since 2026-09-08 ([#110](https://github.com/Gerrrt/HomeLab/issues/110)); the laptops ride a cut out on their own batteries, which `HostBatteryHealthLow` in `host.rules.yaml` now reads — `prometheus`'s cell was replaced on 2026-09-18 and reads 101 % of design, `oracle`'s was replaced on 2026-09-29 and reads 100 %, its design figure rather than a learned one ([#531](https://github.com/Gerrrt/HomeLab/issues/531)) — and **each runtime was measured once: `prometheus`'s on 2026-09-19, about 2.5 hours from full at the stack's load, and `oracle`'s on 2026-09-29, about 5.2 hours**; since the same day the projection is recorded on every cut and pages under thirty minutes (`HostBatteryRuntimeLow`, [#532](https://github.com/Gerrrt/HomeLab/issues/532)), but neither pack reports a moving cell temperature, so this row is answered for both hosts' runtime and for neither's cell temperature — see below. **What happens when the cut outlasts the pack is configured and accepted without a live test.** Since 2026-09-23 the firewall's NUT server reads `mjolnir`, and `Saruman` and `smaug` subscribe to it on their own gateway addresses, so a real cut would now try to run the sequence [ADR-0049](adr/0049-shut-down-on-the-ups-from-a-nut-server-on-the-firewall.md) decides: `Saruman` and `smaug` halt first and `morpheus` last. Since the move into the 32U rack on 2026-11-06 the PDU also carries `trinity`, `gandalf` (off until its build) and the console, with `smaug` racked and on the PDU directly rather than by its old long cord to the media room. [ADR-0107](adr/0107-subscribe-trinity-to-the-ups-and-bound-saruman-s-guest-stop.md) makes `trinity` a third subscriber and bounds `Saruman`'s guest stop. `Saruman`'s half was applied on 2026-11-13 (`down=90` on the four ordered guests, and its monitor stays logged in until they are down); `trinity`'s subscription, `HOSTSYNC 600` on `morpheus` and the card's 16-minute threshold followed on 2026-11-20, so all three subscribers would now halt before the pack empties; `gandalf`, the console and `neo` are left to the pack by decision. The pack itself is unmeasured: about 47 minutes at 21 % load is the card's own estimate. Neither the forced-shutdown proof nor a mains pull will be run ([ADR-0121](adr/0121-accept-the-ups-shutdown-without-a-live-test.md)) | | The estate being down while the person who runs it is unavailable | **Documentation, yes; data, no copy outside the house, by decision.** ADR-0011 puts the emergency tier on paper; [ADR-0023](adr/0023-keep-the-household-recovery-path-outside-the-estate.md) extends the same reasoning to the sensitive tier's data. That tier has held real photographs since 2026-09-28. [ADR-0122](adr/0122-drop-the-household-copy.md) dropped their copy outside the estate, so a loss of the house loses them — see below | diff --git a/scripts/collect-range-state.sh b/scripts/collect-range-state.sh index 506755d21..8967a8c65 100755 --- a/scripts/collect-range-state.sh +++ b/scripts/collect-range-state.sh @@ -48,13 +48,14 @@ parse_ingress_drop() { ' } -# For an `sshd -T` keyword, 1 when it reads `yes`, 0 when `no`, and nothing when -# the keyword is absent. `sshd -T` lowercases its keys and prints one setting -# per line, e.g. `x11forwarding no`. Used for forwarding keys, where `yes` is -# the fault, so the metric is 1-is-bad. +# For an `sshd -T` keyword, 0 only when it reads `no`, 1 for any other value, +# and nothing when the keyword is absent. `sshd -T` lowercases its keys and +# prints one setting per line, e.g. `allowtcpforwarding no`. Only `no` disables +# forwarding: AllowTcpForwarding also takes `local` and `remote`, which both +# permit a tunnel, so anything but `no` is the fault (1-is-bad). parse_sshd_flag() { awk -v key="$1" ' - $1 == key { print ($2 == "yes") ? 1 : 0; found = 1; exit } + $1 == key { print ($2 == "no") ? 0 : 1; found = 1; exit } END { if (!found) exit 0 } ' } @@ -67,6 +68,11 @@ parse_kv() { } is_uint() { [[ "$1" =~ ^[0-9]+$ ]]; } +now() { date +%s; } +# A dpkg deferral counts as current only this close to now: the stop timer runs +# every minute, so a wait that is still happening rewrote the mark within the +# last couple of runs. Older than this and the timer has stopped confirming it. +DEFER_FRESH=180 if [[ "${1:-}" == "--self-test" ]]; then fail=0 @@ -101,6 +107,11 @@ if [[ "${1:-}" == "--self-test" ]]; then "$(printf 'x11forwarding yes\nallowtcpforwarding no\n' | parse_sshd_flag x11forwarding)" "1" check "allowtcpforwarding no is clean" \ "$(printf 'x11forwarding yes\nallowtcpforwarding no\n' | parse_sshd_flag allowtcpforwarding)" "0" + # AllowTcpForwarding local and remote both permit a tunnel — only no is off. + check "allowtcpforwarding local is the fault" \ + "$(printf 'allowtcpforwarding local\n' | parse_sshd_flag allowtcpforwarding)" "1" + check "allowtcpforwarding remote is the fault" \ + "$(printf 'allowtcpforwarding remote\n' | parse_sshd_flag allowtcpforwarding)" "1" check "an absent key prints nothing" \ "$(printf 'permitrootlogin without-password\n' | parse_sshd_flag x11forwarding)" "" # sshd -T prints the key once; a value that is a substring must not match. @@ -121,7 +132,9 @@ PRINT_ONLY=0 command -v nft >/dev/null 2>&1 || die "no nft on this host — it is not the range host." -ingress_drop="$(nft list chain netdev vmbr1_host_in ingress 2>/dev/null | parse_ingress_drop)" +# An absent table makes nft exit non-zero; `|| true` keeps that from aborting +# the collector under `set -e`, so the 0 sample (no barrier) is still written. +ingress_drop="$({ nft list chain netdev vmbr1_host_in ingress 2>/dev/null || true; } | parse_ingress_drop)" fwd4="$(sysctl -n net.ipv4.conf.vmbr0.forwarding 2>/dev/null || echo "")" fwd6="$(sysctl -n net.ipv6.conf.vmbr0.forwarding 2>/dev/null || echo "")" sshd_out="$(sshd -T 2>/dev/null || true)" @@ -130,10 +143,18 @@ tcpf="$(printf '%s\n' "$sshd_out" | parse_sshd_flag allowtcpforwarding)" timer_active=0 [[ "$(systemctl is-active "${STOP_TIMER}" 2>/dev/null)" == "active" ]] && timer_active=1 -stop_state="$("${STOP_CMD}" deadline-epoch 2>/dev/null || true)" + +# The attack-VM state comes from the stop helper (one source of the deadline). +# A command that fails, or output with no `running=` line, is an unusable +# answer — an old helper without `deadline-epoch`, say — NOT a stopped VM, so +# the ragnarok metrics are left out rather than written as running=0, which +# would suppress the alerts. The runbook makes upgrading the helper a step. +stop_ok=1 +stop_state="$("${STOP_CMD}" deadline-epoch 2>/dev/null)" || stop_ok=0 +[[ "$stop_state" == *running=* ]] || stop_ok=0 rag_running="$(printf '%s\n' "$stop_state" | parse_kv running)" -is_uint "${rag_running}" || rag_running=0 rag_deadline="$(printf '%s\n' "$stop_state" | parse_kv deadline_epoch)" +rag_deferred="$(printf '%s\n' "$stop_state" | parse_kv deferred_epoch)" emit() { printf '# HELP homelab_range_ingress_table_loaded 1 when vmbr1 drops what it sends the host (vmbr1_host_in, build-the-playground.md §2).\n' @@ -150,20 +171,38 @@ emit() { [[ -n "$x11" ]] && printf 'homelab_range_sshd_forwarding{host="%s",kind="x11"} %s\n' "$HOSTNAME_LABEL" "$x11" [[ -n "$tcpf" ]] && printf 'homelab_range_sshd_forwarding{host="%s",kind="tcp"} %s\n' "$HOSTNAME_LABEL" "$tcpf" - printf '# HELP homelab_ragnarok_running 1 when the attack VM (ADR-0125) is running.\n' - printf '# TYPE homelab_ragnarok_running gauge\n' - printf 'homelab_ragnarok_running{host="%s"} %s\n' "$HOSTNAME_LABEL" "$rag_running" - printf '# HELP homelab_ragnarok_stop_timer_active 1 when the stop timer (ADR-0125) is active.\n' printf '# TYPE homelab_ragnarok_stop_timer_active gauge\n' printf 'homelab_ragnarok_stop_timer_active{host="%s"} %s\n' "$HOSTNAME_LABEL" "$timer_active" - # The effective stop deadline, only while the VM runs. Absent when it is - # stopped, so RagnarokPastDeadline cannot fire on a box with no attack VM. - if [[ "$rag_running" == 1 ]] && is_uint "${rag_deadline}"; then - printf '# HELP homelab_ragnarok_deadline_seconds The epoch the stop timer will shut ragnarok down at (ADR-0125, from the timer itself).\n' - printf '# TYPE homelab_ragnarok_deadline_seconds gauge\n' - printf 'homelab_ragnarok_deadline_seconds{host="%s"} %s\n' "$HOSTNAME_LABEL" "$rag_deadline" + # Only when the stop helper gave a usable answer. A failed or old helper + # writes none of these, so the alerts cannot read a false "stopped"; the gap + # is a broken helper, which the runbook's reinstall step prevents and + # RangeStateStale catches if the whole collector stops. + if [[ "$stop_ok" == 1 ]] && is_uint "${rag_running}"; then + printf '# HELP homelab_ragnarok_running 1 when the attack VM (ADR-0125) is running.\n' + printf '# TYPE homelab_ragnarok_running gauge\n' + printf 'homelab_ragnarok_running{host="%s"} %s\n' "$HOSTNAME_LABEL" "$rag_running" + + if [[ "$rag_running" == 1 ]]; then + # The effective stop deadline, only while the VM runs, so + # RagnarokPastDeadline cannot fire on a box with no attack VM. + if is_uint "${rag_deadline}"; then + printf '# HELP homelab_ragnarok_deadline_seconds The epoch the stop timer will shut ragnarok down at (ADR-0125, from the timer itself).\n' + printf '# TYPE homelab_ragnarok_deadline_seconds gauge\n' + printf 'homelab_ragnarok_deadline_seconds{host="%s"} %s\n' "$HOSTNAME_LABEL" "$rag_deadline" + fi + # 1 when the timer most recently chose to wait, within the last few runs, + # because dpkg's lock was held inside the VM (ADR-0125). A past-deadline + # VM that is deferring for this reason is not a failed timer, so + # RagnarokPastDeadline excludes it; a stale mark (the timer stopped + # confirming) reads 0 and the alert can fire. + deferred=0 + is_uint "${rag_deferred}" && (( $(now) - rag_deferred < DEFER_FRESH )) && deferred=1 + printf '# HELP homelab_ragnarok_stop_deferred 1 when the stop timer is currently waiting on dpkg inside ragnarok (ADR-0125).\n' + printf '# TYPE homelab_ragnarok_stop_deferred gauge\n' + printf 'homelab_ragnarok_stop_deferred{host="%s"} %s\n' "$HOSTNAME_LABEL" "$deferred" + fi fi } diff --git a/scripts/ragnarok-stop.sh b/scripts/ragnarok-stop.sh index 765b7d85e..5d31ebd9c 100755 --- a/scripts/ragnarok-stop.sh +++ b/scripts/ragnarok-stop.sh @@ -117,7 +117,7 @@ write_state() { mv -f "${tmp}" "${STATE_DIR}/$1" } -clear_state() { rm -f "${STATE_DIR}/deadline" "${STATE_DIR}/run" "${STATE_DIR}/warned-30" "${STATE_DIR}/warned-5"; } +clear_state() { rm -f "${STATE_DIR}/deadline" "${STATE_DIR}/run" "${STATE_DIR}/warned-30" "${STATE_DIR}/warned-5" "${STATE_DIR}/deferred"; } with_lock() { # Run "$@" holding the lock. fd 9 closes when the group ends, which @@ -165,6 +165,7 @@ check_locked() { left=$(( d - t )) if (( left <= 0 )); then if guest_dpkg_busy; then + write_state deferred "${t}" say "deadline $(fmt_time "${d}") has passed, but dpkg's lock is held inside ragnarok; waiting for the next run" return 0 fi @@ -261,6 +262,9 @@ cmd_deadline_epoch() { else printf 'source=default\n' fi + local dfr + dfr="$(read_state deferred)" + [[ -n "${dfr}" ]] && printf 'deferred_epoch=%s\n' "${dfr}" return 0 } @@ -367,6 +371,16 @@ self_test() { "$(cmd_deadline_epoch | sed -n 's/^deadline_epoch=//p')" "$((NOW + 3 * H))" check "and marks it extended" "$(cmd_deadline_epoch | sed -n 's/^source=//p')" "extended" + # A dpkg wait past the deadline records the deferral, so the monitor can tell + # it from a failed timer (#1651 review). BUSY=0 means dpkg is held. + reset; NOW=$((START + 6 * H + 10)); BUSY=0; cmd_check + check "a dpkg deferral past the deadline is recorded" \ + "$(cmd_deadline_epoch | sed -n 's/^deferred_epoch=//p')" "${NOW}" + check "and no stop happened while deferring" "$(stops)" "0" + # It clears when the VM stops, so a stale mark cannot outlive the run. + reset; NOW=$((START + 6 * H + 10)); BUSY=0; cmd_check; PID=""; cmd_check + check "the deferral mark is cleared when the VM stops" "$(read_state deferred)" "" + # A restart between reading the PID and stopping: the new run is not the # one whose deadline passed (review on #1652). reset; NOW=$((START + 6 * H + 10)); RESTART=5151; cmd_check diff --git a/stacks/observability/README.md b/stacks/observability/README.md index dfed3bf9f..2ad89c642 100644 --- a/stacks/observability/README.md +++ b/stacks/observability/README.md @@ -53,7 +53,7 @@ prometheus/ targets/snmp.yaml SNMP targets — hot-reloaded, no restart needed targets/node.yaml node_exporter scrapes, for the host that runs no Alloy (smaug) targets/blackbox*.yaml probe targets, http, dns and latency — hot-reloaded, no restart - rules/*.rules.yaml 172 alert rules: host, network, ups, containers, blackbox, + rules/*.rules.yaml 173 alert rules: host, network, ups, containers, blackbox, dns, backup, ids, deploy, stack, internet, watchdog and range tests/*.test.yaml promtool unit tests — assert the rules can fire blackbox/blackbox.yaml probe modules — reachability, and what a resolver said diff --git a/stacks/observability/prometheus/rules/range.rules.yaml b/stacks/observability/prometheus/rules/range.rules.yaml index 4c61fbacb..d32954e27 100644 --- a/stacks/observability/prometheus/rules/range.rules.yaml +++ b/stacks/observability/prometheus/rules/range.rules.yaml @@ -117,6 +117,7 @@ groups: expr: >- (time() - homelab_ragnarok_deadline_seconds) > 600 and on (host) homelab_ragnarok_running == 1 + and on (host) homelab_ragnarok_stop_deferred == 0 for: 5m labels: component: host @@ -129,3 +130,24 @@ groups: stop timer set for it. The timer runs every minute, so it should have stopped the VM; something is wedging it (check `journalctl -t homelab-ragnarok-stop`), or stop ragnarok by hand. + + - alert: RangeStateStale + # The collector stopped, which is not the range being fine: the + # textfile exporter keeps serving the last values, so a barrier that + # fell afterwards reads healthy. PveFirewallStateStale watches only the + # firewall file. Twenty-five minutes past a five-minute timer is five + # missed runs (ADR-0126 review). + expr: >- + time() - node_textfile_mtime_seconds{file=~".*range-state\\.prom"} > 25 * 60 + for: 10m + labels: + component: host + severity: warning + category: security + annotations: + summary: "{{ $labels.instance }} has not rewritten its range state recently" + description: >- + range-state.prom is {{ $value | humanizeDuration }} old, so the + range barrier and stop-timer alerts are reading an old answer and + cannot fire. Check homelab-range-state.timer on the host and + `journalctl -u homelab-range-state`. diff --git a/stacks/observability/prometheus/tests/range.test.yaml b/stacks/observability/prometheus/tests/range.test.yaml index 110926b82..91f9e70da 100644 --- a/stacks/observability/prometheus/tests/range.test.yaml +++ b/stacks/observability/prometheus/tests/range.test.yaml @@ -215,6 +215,8 @@ tests: values: "1x17" - series: 'homelab_ragnarok_deadline_seconds{instance="gandalf",host="gandalf"}' values: "0x17" + - series: 'homelab_ragnarok_stop_deferred{instance="gandalf",host="gandalf"}' + values: "0x17" alert_rule_test: - eval_time: 16m alertname: RagnarokPastDeadline @@ -243,7 +245,62 @@ tests: values: "1x17" - series: 'homelab_ragnarok_deadline_seconds{instance="gandalf",host="gandalf"}' values: "100000x17" + - series: 'homelab_ragnarok_stop_deferred{instance="gandalf",host="gandalf"}' + values: "0x17" + alert_rule_test: + - eval_time: 16m + alertname: RagnarokPastDeadline + exp_alerts: [] + + # --- RagnarokPastDeadline: quiet while deferring to a dpkg install --------- + # Past the deadline, but the stop timer is waiting on dpkg (deferred=1), which + # is a protected install, not a failed timer (ADR-0126 review). + - interval: 1m + input_series: + - series: 'homelab_ragnarok_running{instance="gandalf",host="gandalf"}' + values: "1x17" + - series: 'homelab_ragnarok_deadline_seconds{instance="gandalf",host="gandalf"}' + values: "0x17" + - series: 'homelab_ragnarok_stop_deferred{instance="gandalf",host="gandalf"}' + values: "1x17" alert_rule_test: - eval_time: 16m alertname: RagnarokPastDeadline exp_alerts: [] + + # --- RangeStateStale: fires when the collector stops writing ------------- + - interval: 1m + input_series: + - series: 'node_textfile_mtime_seconds{instance="gandalf",job="gandalf-metrics",file="range-state.prom"}' + values: "0x40" + alert_rule_test: + - eval_time: 36m + alertname: RangeStateStale + exp_alerts: + - exp_labels: + instance: gandalf + job: gandalf-metrics + file: range-state.prom + component: host + severity: warning + category: security + exp_annotations: + summary: "gandalf has not rewritten its range state recently" + description: >- + range-state.prom is 36m 0s old, so the range barrier and + stop-timer alerts are reading an old answer and cannot fire. + Check homelab-range-state.timer on the host and `journalctl -u + homelab-range-state`. + - eval_time: 20m + alertname: RangeStateStale + exp_alerts: [] + + # --- RangeStateStale: quiet while the file keeps moving ------------------- + - interval: 1m + input_series: + - series: 'node_textfile_mtime_seconds{instance="gandalf",job="gandalf-metrics",file="range-state.prom"}' + values: "0+60x40" + alert_rule_test: + - eval_time: 36m + alertname: RangeStateStale + exp_alerts: [] diff --git a/systemd/agent/homelab-range-state.service b/systemd/agent/homelab-range-state.service new file mode 100644 index 000000000..c0458462a --- /dev/null +++ b/systemd/agent/homelab-range-state.service @@ -0,0 +1,34 @@ +# The range host gandalf's own controls, for Prometheus (#1651, ADR-0126). +# +# WHAT IT IS FOR. ADR-0125 keeps gandalf on, so build-the-playground.md §7's +# per-session read-back is a gap of days. This records the barriers that +# read-back checks that the Proxmox firewall collector cannot see — the +# vmbr1_host_in ingress table, vmbr0 and sshd forwarding — and the attack-VM +# stop timer's state and deadline. The range rules alert on them. +# +# HARDENING AS LIGHT AS homelab-pve-firewall-state.service, for the same +# reason: it reads nft, sysctl, sshd -T, systemctl and the stop helper, which +# touch /run, /proc and /var/run/qemu-server, and a private mount namespace +# could hide those and read as "all clear". Root is for the textfile directory; +# the reads themselves do not need it. +[Unit] +Description=HomeLab: record the range host's own controls (ADR-0126) +Documentation=file:///home/robo/code/Gerrrt/HomeLab/docs/runbooks/schedule-maintenance.md +ConditionPathIsDirectory=/var/lib/node_exporter/textfile_collector +ConditionPathExists=/usr/sbin/nft + +[Service] +Type=oneshot +User=root +Group=root +ExecStart=/usr/local/bin/homelab-collect-range-state +TimeoutStartSec=120 +Restart=no +Nice=10 +NoNewPrivileges=true +RestrictSUIDSGID=true +LockPersonality=true +RestrictRealtime=true +StandardOutput=journal +StandardError=journal +SyslogIdentifier=homelab-range-state diff --git a/systemd/agent/homelab-range-state.timer b/systemd/agent/homelab-range-state.timer new file mode 100644 index 000000000..b1cfdb2fb --- /dev/null +++ b/systemd/agent/homelab-range-state.timer @@ -0,0 +1,18 @@ +[Unit] +Description=HomeLab: the range host's own controls +Documentation=file:///home/robo/code/Gerrrt/HomeLab/docs/runbooks/schedule-maintenance.md + +[Timer] +Unit=homelab-range-state.service +# Every 5 minutes, like homelab-pve-firewall-state: these are the same +# security controls §7 checks, and the stop-timer alerts (ADR-0126) want a +# sample well inside the stop timer's own one-minute cadence rather than a +# daily one. RangeStateStale bounds how long a stopped collector can hide a +# fault. +OnCalendar=*:0/5 +RandomizedDelaySec=30 +Persistent=true +AccuracySec=1m + +[Install] +WantedBy=timers.target