diff --git a/README.md b/README.md index 914ae450..d22ac3da 100644 --- a/README.md +++ b/README.md @@ -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.** 124 ADRs covering what was chosen +- **Documented decisions and runbooks.** 125 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 @@ -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/ # 124 ADRs — architecture decision records +│ ├── adr/ # 125 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/adr/0017-buy-ifrit-for-iops-and-keep-the-range-disposable.md b/docs/adr/0017-buy-ifrit-for-iops-and-keep-the-range-disposable.md index a3080b22..2608ae66 100644 --- a/docs/adr/0017-buy-ifrit-for-iops-and-keep-the-range-disposable.md +++ b/docs/adr/0017-buy-ifrit-for-iops-and-keep-the-range-disposable.md @@ -2,6 +2,17 @@ **Status:** Accepted · 2026-09 +> [!NOTE] +> **The host stays on; the attack VM is what stops.** +> [ADR-0125](0125-keep-gandalf-on-and-stop-ragnarok-on-a-timer.md), which +> supersedes ADR-0124, keeps `gandalf` on and stops `ragnarok` at a deadline: +> six hours after it starts, or what a session's last extension set, up to +> twelve hours ahead. "Off between sessions" no longer holds for the host, +> so *No monitoring*'s reason is gone. Monitoring is +> [#1651](https://github.com/Gerrrt/HomeLab/issues/1651), which needs its own +> ADR to supersede *No monitoring*. The note below about ADR-0124 is +> superseded with it. The text below is left as written, per ADR-0001. +> > [!NOTE] > **"Off between sessions" is enforced by a timer.** Two audits found the > range host left on for days, against the discipline that *No monitoring* diff --git a/docs/adr/0124-power-gandalf-off-on-a-timer.md b/docs/adr/0124-power-gandalf-off-on-a-timer.md index 5e4442ae..29973af7 100644 --- a/docs/adr/0124-power-gandalf-off-on-a-timer.md +++ b/docs/adr/0124-power-gandalf-off-on-a-timer.md @@ -1,7 +1,14 @@ # ADR-0124: Power `gandalf` off on a timer -**Status:** Accepted · 2026-11 · amends -[ADR-0017](0017-buy-ifrit-for-iops-and-keep-the-range-disposable.md) +**Status:** Superseded · 2026-11 · by +[ADR-0125](0125-keep-gandalf-on-and-stop-ragnarok-on-a-timer.md) · accepted 2026-11 + +> [!NOTE] +> Wholly superseded: [ADR-0125](0125-keep-gandalf-on-and-stop-ragnarok-on-a-timer.md) +> keeps `gandalf` on and puts the timer on the attack VM, `ragnarok`, instead +> of the host. The host power-off timer described here was installed on +> 2026-11-22, never proved, and removed the same day. The text here is left +> as written, per ADR-0001 and ADR-0115. ## Context diff --git a/docs/adr/0125-keep-gandalf-on-and-stop-ragnarok-on-a-timer.md b/docs/adr/0125-keep-gandalf-on-and-stop-ragnarok-on-a-timer.md new file mode 100644 index 00000000..bce9aa42 --- /dev/null +++ b/docs/adr/0125-keep-gandalf-on-and-stop-ragnarok-on-a-timer.md @@ -0,0 +1,97 @@ +# ADR-0125: Keep `gandalf` on, and stop `ragnarok` on a timer + +**Status:** Accepted · 2026-11 · supersedes +[ADR-0124](0124-power-gandalf-off-on-a-timer.md) and amends +[ADR-0017](0017-buy-ifrit-for-iops-and-keep-the-range-disposable.md) + +## Context + +[ADR-0124](0124-power-gandalf-off-on-a-timer.md) answered two audits that +found `gandalf` left on for days. It had the host power itself off six hours +after boot, or at the deadline a session's last `range-extend` set. It was +installed on 2026-11-22 and never proved. + +Living with it the same day showed that the host is the wrong thing to turn +off: + +- **Starting a session means walking to the rack.** `gandalf`'s BIOS + powers on only at the button (`build-the-playground.md` §1), and its AMT is + disabled ([ADR-0106](0106-name-the-range-host-gandalf-and-leave-ifrit-to-its-disabled-amt.md)). + A host that turns itself off makes every session start at the rack. +- **The exposure is the attack VM, not the host.** ADR-0124's own Context + names what the left-on host cost. `ragnarok` shares VLAN 30 with the estate + (ADR-0014), and the host firewall goes unchecked while the box is up. The + targets are on `vmbr1`, which has no port, and since 2026-11-22 the host + drops everything `vmbr1` passes up to it (§2, `vmbr1_host_in`). A target + left running reaches only the other guests on that bridge. +- **The host's own hardening no longer depends on being off.** After the + 2026-11-22 audit, `gandalf` has keys-only SSH with no forwarding, no + workstation tooling, no forwarding on `vmbr0`, and the ingress table. + Those hold whether it is up for an hour or a month. + +What a host left on still lacks is anything watching it. ADR-0017 gave it no +monitoring because it was off by design: every rule watching it would be +"permanently firing or permanently silenced". A host that stays on has a +normal state, up, and a rule shape for it. + +## Decision + +**`gandalf` stays on. The attack VM, `ragnarok` (VMID 130), stops itself a +fixed time after it starts, or after the last extension a session asks +for.** The mechanism is ADR-0124's, aimed at the VM. + +- **The deadline is six hours after `ragnarok` starts.** It is counted from + the QEMU process's start, not the host's boot. +- **A session can replace it.** `range-extend H` on the host sets the + deadline H hours from now, H from 1 to 12, as before. The extension is + stored with the running VM's process ID, so a stop and a start always + begin again from six hours, and it is cleared when the VM stops. +- **It warns before it acts.** `wall` at 30 and 5 minutes, on the host and, + through the guest agent, inside `ragnarok`, where the session is. +- **It never stops the VM in the middle of a package install.** Past the + deadline it asks the guest agent whether `dpkg`'s lock is held inside the + VM, and waits for the next run if it is. An agent that does not answer + counts as not busy, so a hung agent cannot hold the VM up. +- **The stop is `qm shutdown` with a forced stop after three minutes.** +- **A systemd timer runs the check every minute, under one lock**, as in + ADR-0124. The script is `scripts/ragnarok-stop.sh` and its units are in + `systemd/range/`. §7 installs them in place of ADR-0124's, and its + read-back checks the timer is enabled and active. +- **The targets are not on the timer.** They have no route off `vmbr1`. They + are reverted to `clean` at the start of each session, as before. +- **Monitoring the host is needed, and is its own decision.** It is + [#1651](https://github.com/Gerrrt/HomeLab/issues/1651). It crosses the + boundary ADR-0014 counts, so it needs its own ADR, which would supersede + ADR-0017's "no monitoring". Until it lands, §7's read-back is the check. + +Built under [#1647](https://github.com/Gerrrt/HomeLab/issues/1647). + +## Consequences + +- **A forgotten session ends the attack VM, not the range.** `ragnarok`'s + time on VLAN 30 is bounded by its deadline, about a minute late, plus any + `dpkg` wait inside the VM. The host and any running targets stay up. +- **The host firewall goes unchecked between sessions, for as long as the + host is up.** ADR-0124 bounded that window at six to twelve hours. This + decision leaves it unbounded until #1651 lands. The ingress table and + keys-only SSH sit behind the firewall, and nothing on VLAN 30 but + `ragnarok`, Hicks and the estate can reach the host, but nothing reports + if the firewall goes off. That is the cost this decision accepts, and the + reason #1651 is not optional. +- **Proxmox's updates are no longer applied at each power-on.** §7 applied + them when a session started, and the box was off between sessions. + `unattended-upgrades` covers Debian's packages daily now that the box is up. + Proxmox's own still need `apt full-upgrade` by hand, and #1651 is where + pending ones become visible. +- **The range SSD runs every hour now.** On 2026-11-22 it read 49,443 + power-on hours and 8 reallocated sectors. Always on, it ages about 730 + hours a month. The range is disposable (ADR-0017), so its failure costs a + rebuild, not data. #1651 should watch its SMART counters. +- **After a power cut it stays off.** The BIOS setting stays at *Power Off*. + Changing it to *Power On* is a visit to the box, and with nothing yet + watching `gandalf`, a host that comes back by itself is one nobody knows + is up. It is reopened with #1651. +- **`range-extend` now needs `ragnarok` running.** It refuses while the VM is + stopped, because there is no run to attach the deadline to. +- **This decision is reopened** if the targets start needing a bound of their + own, which would mean something on `vmbr1` can reach past it. diff --git a/docs/architecture.md b/docs/architecture.md index c1aa1093..5e5c2a2e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -189,7 +189,7 @@ hole from the monitoring VLAN into the monitored one. | --- | --- | --- | --- | | `prometheus` (10.0.99.20) | 🔴 99 | [`stacks/observability`](../stacks/observability) | Prometheus, Alertmanager, Loki, Grafana, snmp-exporter, blackbox-exporter, speedtest-tracker, docker-socket-proxy, Alloy, and Caddy as `ingest-proxy` in front of Prometheus and Loki ([#182](https://github.com/Gerrrt/HomeLab/issues/182)) | | `Saruman` (10.0.30.20) | 🟢 30 | *(none — and none intended)* | Proxmox VE 9, hosting twenty-one guests: `alexander`, built 2026-09-05 ([#262](https://github.com/Gerrrt/HomeLab/issues/262)); `phoenix`, built 2026-09-20 ([#436](https://github.com/Gerrrt/HomeLab/issues/436)); `odin`, built 2026-09-27 for the security tooling (ADR-0030); `fenrir`, built 2026-09-30 as the Zeek sensor ([#437](https://github.com/Gerrrt/HomeLab/issues/437)); `golem`, built 2026-10-03 as the backup server ([#485](https://github.com/Gerrrt/HomeLab/issues/485)); `eden`, built 2026-10-07 as the BloodHound guest ([#451](https://github.com/Gerrrt/HomeLab/issues/451)), off between sessions; `garuda`, built 2026-10-10 as the analyst workstation ([#921](https://github.com/Gerrrt/HomeLab/issues/921)); and ADR-0029's six-machine domain, built by hand 2026-09-24 to 2026-09-25 ([#414](https://github.com/Gerrrt/HomeLab/issues/414)), of which `carbuncle` and `siren` run per session; and all eight of [ADR-0090](adr/0090-test-the-dotfiles-os-layers-on-on-demand-saruman-guests.md)'s on-demand dotfiles test VMs, `dot-debian`, `dot-fedora` and `dot-windows`, built 2026-10-08, and `dot-opensuse`, `dot-arch`, `dot-alpine`, `dot-gentoo` and `dot-nixos`, built 2026-10-09 ([#920](https://github.com/Gerrrt/HomeLab/issues/920)). Alloy agent (native package). It runs no compose stack by decision, not by omission: Docker would rewrite the iptables its own firewall relies on ([ADR-0014](adr/0014-put-ifrit-on-imaginationlan-and-give-the-targets-no-route.md)), which is why the agent here is the native package and why `stacks/lab` runs in a guest | -| `gandalf` (10.0.30.30) | 🟢 30 | *(none — and none intended)* | Proxmox VE 9, the range host, installed 2026-11-07 ([#421](https://github.com/Gerrrt/HomeLab/issues/421)). The attack VM `ragnarok` (VMID 130), declared in [`tofu/`](../tofu/README.md) on `gandalf`'s aliased provider and finished by [`scripts/finish-attack-vm.sh`](../scripts/finish-attack-vm.sh) ([ADR-0116](adr/0116-build-the-range-attack-vm-with-opentofu-and-prove-it-with-a-script.md)), from template 902 and dual-homed: a DHCP lease on VLAN 30, and `172.30.30.10` on `vmbr1`. Three targets, VMIDs 100–102 on `vmbr1` only, made 2026-11-10; the list is [`build-the-playground.md`](runbooks/build-the-playground.md) §6's. Guest disks go on the ZFS pool `range`, targets go on the portless `vmbr1`, and it is off between sessions ([ADR-0017](adr/0017-buy-ifrit-for-iops-and-keep-the-range-disposable.md), [ADR-0106](adr/0106-name-the-range-host-gandalf-and-leave-ifrit-to-its-disabled-amt.md)) | +| `gandalf` (10.0.30.30) | 🟢 30 | *(none — and none intended)* | Proxmox VE 9, the range host, installed 2026-11-07 ([#421](https://github.com/Gerrrt/HomeLab/issues/421)). The attack VM `ragnarok` (VMID 130), declared in [`tofu/`](../tofu/README.md) on `gandalf`'s aliased provider and finished by [`scripts/finish-attack-vm.sh`](../scripts/finish-attack-vm.sh) ([ADR-0116](adr/0116-build-the-range-attack-vm-with-opentofu-and-prove-it-with-a-script.md)), from template 902 and dual-homed: a DHCP lease on VLAN 30, and `172.30.30.10` on `vmbr1`. Three targets, VMIDs 100–102 on `vmbr1` only, made 2026-11-10; the list is [`build-the-playground.md`](runbooks/build-the-playground.md) §6's. Guest disks go on the ZFS pool `range`, targets go on the portless `vmbr1`, and it stays on, while `ragnarok` stops itself six hours after it starts unless a session extends it ([ADR-0125](adr/0125-keep-gandalf-on-and-stop-ragnarok-on-a-timer.md); [ADR-0017](adr/0017-buy-ifrit-for-iops-and-keep-the-range-disposable.md), [ADR-0106](adr/0106-name-the-range-host-gandalf-and-leave-ifrit-to-its-disabled-amt.md)) | | `alexander` (10.0.30.40) | 🟢 30 | [`stacks/lab`](../stacks/lab) | Prometheus, Loki, Grafana, Alloy and its Docker socket proxy, and Caddy as the ingest proxy in front of the first two ([#834](https://github.com/Gerrrt/HomeLab/issues/834)) — the lab's own observability, which never remote-writes to VLAN 99 ([ADR-0007](adr/0007-defensive-estate-and-offensive-range.md), [ADR-0020](adr/0020-run-the-lab-stack-in-a-guest-with-its-own-prometheus.md)). A guest on `Saruman`, not the hypervisor; Alloy agent (Docker) | | `odin` (10.0.30.60) | 🟢 30 | [`stacks/soc`](../stacks/soc) | Wazuh (indexer, manager, dashboard), Velociraptor and Alloy: the security half of ADR-0007, placed by [ADR-0030](adr/0030-give-the-security-tooling-its-own-guest-and-its-own-stack.md) on a second guest on `Saruman` because `alexander`'s 8 GiB cannot hold both. Built 2026-09-27 by [`build-the-soc-guest.md`](runbooks/build-the-soc-guest.md), the stack authored and CI-validated ahead of the guest the way `stacks/lab` was ahead of `alexander` ([#266](https://github.com/Gerrrt/HomeLab/issues/266), [#267](https://github.com/Gerrrt/HomeLab/issues/267)); the six domain machines enrol as agents by GPO, which is the day those two issues close. Its Alloy pushes to `alexander`, never to VLAN 99, and the indexer's health is the one series that crosses into the lab's Prometheus. Alloy agent (Docker) | | `fenrir` (10.0.30.90) | 🟢 30 | [`stacks/sensor`](../stacks/sensor) | Zeek on a `tc` mirror of `Saruman`'s lab bridge, so that the domain's east-west traffic, which crosses no router and so never reaches Suricata on `morpheus`, is observed at all ([#437](https://github.com/Gerrrt/HomeLab/issues/437), [ADR-0068](adr/0068-mirror-the-lab-bridge-to-zeek-with-tc-not-open-vswitch.md)). A guest on `Saruman`, VMID 190, with a second NIC alone on the port-less `vmbr1` that receives only the mirror's copies. Its logs go to `alexander`, never to VLAN 99; whether the mirror is delivering is answered on the hypervisor by `homelab_zeek_mirror_active`. Built 2026-09-30 by [`build-the-sensor-guest.md`](runbooks/build-the-sensor-guest.md), and proved by rebooting `Saruman` with the mirror's timer disabled: the gauge fell to 0 and `ZeekMirrorInactive` fired. Alloy agent (Docker) | diff --git a/docs/changelog.md b/docs/changelog.md index 6022b8ed..dd0b7f9c 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -19,6 +19,68 @@ docstring gives: it is a record, not a claim about now. ## 2026-11-22 +- **`gandalf` stays on, and the attack VM stops on a timer instead + ([ADR-0125](adr/0125-keep-gandalf-on-and-stop-ragnarok-on-a-timer.md), + [#1647](https://github.com/Gerrrt/HomeLab/issues/1647)).** ADR-0125 + supersedes ADR-0124 the day it was accepted. The host power-off timer was + installed at 17:44 and removed at 19:26, never having fired. The exposure + ADR-0124 bounded is `ragnarok` on VLAN 30, and a host that turns itself off + makes every session start at the rack. `scripts/range-poweroff.sh` becomes + `scripts/ragnarok-stop.sh`. The deadline is six hours after the VM starts, + and an extension is stored with the QEMU process's PID, so it never carries + into the next start. The warnings also go inside the VM through the guest + agent. The `dpkg` wait asks the agent about the VM's lock, and the stop is + `qm shutdown` with a forced stop after three minutes. `build-the-playground.md` + §7 now installs it and removes the old timer, and §1's *After Power Loss* + stays at *Power Off*, with ADR-0125's reason. + - The `--self-test` has 27 fixtures. Three deliberate breaks each failed + at least one: an extension that ignores the PID, a stopped VM that keeps + its extension, and a stop without the PID read again. + - Review on the PR caught three things: + - The check now reads the PID again just before `qm shutdown`, so a VM + restarted during the guest-agent calls is not stopped by the old run's + deadline. + - The default deadline comes from the QEMU process's start in + `/proc//stat`, not `now` minus `ps -o etimes`. The old way could + move by a second between runs and repeat a warning. + - §7 now enables the timer last, after `status` and a chance to extend. + - Installed on `gandalf` at 19:26, and proved at 19:32 with a deadline + written a few minutes out. The timer sent the 5-minute warning, then shut + `ragnarok` down with ACPI in 2 seconds and cleared its state, and + `range-extend` refused afterwards. A `wall` reaching a shell inside the VM + was sent but not seen, because none was open. The run logged every line + twice, which ADR-0124's script also did, so `say` no longer calls + `logger` under systemd. + - Monitoring the host is [#1651](https://github.com/Gerrrt/HomeLab/issues/1651), + opened the same day. ADR-0017's reason for none, a host that is off by + design, no longer holds. + - This corrects the entry below on the timer being built: what it built is + replaced, not proved. +- **The 2026-11-22 audit's fixes are applied on `gandalf` + ([#421](https://github.com/Gerrrt/HomeLab/issues/421)).** These are the + steps the audit entry below wrote into `build-the-playground.md`, each then + marked *Not yet applied*. + - **§2** at 19:19: `ip-forward off` and `ip6-forward off` on `vmbr0`, and + the `vmbr1_host_in` table. A reboot at 19:21 proved them: both forwarding + flags `0`, the table loaded, `vmbr1` without an address. + - **§4** at 19:19: the SSH drop-in with both forwardings off, checked with a + password login refused and a key login accepted. The first password test + "passed" through this workstation's shared SSH connection, which never + re-authenticates, so the runbook's tests now carry `-o ControlPath=none`. + - **§4, *Nothing else on `gandalf`*,** at 19:20: root's shell is bash, the + 1Password and Charm repositories and 14 packages are gone, and so is the + dotfiles install. The runbook's `rm` missed about a third of it (atuin's + user unit, Go's and npm's caches, mise, tmux and zsh files), so a second + `rm` was added. About 5 GB came off the root disk. + - **§8 check four** at 19:25, from a throwaway clone of `tpl-kali` at `.199`: + no route, the host unreachable with the `dropped` counter rising, and + `ragnarok` still reaching the target. The clone had no DHCP stanza, which + proves #1341 on the template rebuilt that day. + - The audit's last finding, leftovers with no runbook step, is still open + for two of them: the `PhoenixIsoCleanup` role, revoked from the token but + never deleted, and an empty `local-lvm`. The Kali installer ISO the audit + also listed is not a leftover. `packer/kali.pkr.hcl` builds template 902 + from it (`kali_iso_file`). `/root/.claude/remote` went with the dotfiles. - **`gandalf`'s power-off timer is built, not installed ([#1647](https://github.com/Gerrrt/HomeLab/issues/1647)).** This builds ADR-0124 in the repository. `scripts/range-poweroff.sh` holds the deadline diff --git a/docs/diagrams/current/rack-32u.png b/docs/diagrams/current/rack-32u.png index 93ccb76d..cc800b03 100644 Binary files a/docs/diagrams/current/rack-32u.png and b/docs/diagrams/current/rack-32u.png differ diff --git a/docs/diagrams/current/rack-32u.svg b/docs/diagrams/current/rack-32u.svg index f4fac6e7..2ca19981 100644 --- a/docs/diagrams/current/rack-32u.svg +++ b/docs/diagrams/current/rack-32u.svg @@ -30,7 +30,7 @@ Jadol 24-port patch panel U19 -ThinkCentre M80q · gandalf, off between sessions +ThinkCentre M80q · gandalf, the range U18 gap diff --git a/docs/hardware.md b/docs/hardware.md index 7aca38a7..79fbbf2d 100644 --- a/docs/hardware.md +++ b/docs/hardware.md @@ -141,7 +141,7 @@ power-on, which is empty: select 8 first. | 7 | `trinity`, U16 | Second up; where the passphrase prompt appears if the TPM does not unseal | | 6 | `Saruman`, U3 | Third up; the iLO is the usual path and the KVM the fallback | | 5 | `smaug`, U5–U9 | Racked, it lost the monitor it had in the media room; cabled from the TS150's rear VGA | -| 4 | `gandalf`, U18 | Off between range sessions | +| 4 | `gandalf`, U18 | The range host; always on, with only its attack VM stopped between sessions (ADR-0125) | | 1–3 | spare | | **The PDU follows the rack from the bottom up, bricks at the far end.** It diff --git a/docs/network.md b/docs/network.md index 80505776..eac73017 100644 --- a/docs/network.md +++ b/docs/network.md @@ -599,7 +599,7 @@ Where things get broken on purpose. | morpheus | `10.0.30.1` | `02:26:26:xx:xx:xx` | HP ProDesk 600 G4 Mini | FreeBSD 16.0 | Rack U15 | Firewall | | shiva | `10.0.30.10` | `94:57:a5:xx:xx:xx` | HPE iLO 4 (DL360 Gen9 BMC)[^Shiva] | iLO 2.82 | Rack U3 | Out-of-band management | | Saruman | `10.0.30.20` | `14:02:ec:xx:xx:xx` | HPE ProLiant DL360 Gen9[^Shiva] | Proxmox VE 9 | Rack U3 | Hypervisor | -| gandalf | `10.0.30.30` | `90:2e:16:xx:xx:xx` | Lenovo ThinkCentre M80q | Proxmox VE 9 | Rack U18 | Range hypervisor, off between sessions. Its Intel AMT, the name `ifrit`, is disabled ([ADR-0106](adr/0106-name-the-range-host-gandalf-and-leave-ifrit-to-its-disabled-amt.md)) | +| gandalf | `10.0.30.30` | `90:2e:16:xx:xx:xx` | Lenovo ThinkCentre M80q | Proxmox VE 9 | Rack U18 | Range hypervisor, always on; its attack VM stops on a timer ([ADR-0125](adr/0125-keep-gandalf-on-and-stop-ragnarok-on-a-timer.md)). Its Intel AMT, the name `ifrit`, is disabled ([ADR-0106](adr/0106-name-the-range-host-gandalf-and-leave-ifrit-to-its-disabled-amt.md)) | | alexander | `10.0.30.40` | `bc:24:11:xx:xx:xx` | KVM guest on `Saruman` | Ubuntu 26.04 LTS | Rack U3 | Lab observability | | phoenix | `10.0.30.70` | `bc:24:11:xx:xx:xx` | KVM guest on `Saruman` | Ubuntu 26.04 LTS | Rack U3 | Deployment host | | golem | `10.0.30.80` | `bc:24:11:xx:xx:xx` | KVM guest on `Saruman` | Proxmox Backup Server 4 | Rack U3 | Backups (PBS) | diff --git a/docs/roadmap.md b/docs/roadmap.md index b25ff6f0..886f3127 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -40,13 +40,13 @@ What an entry here may contain: Closes when it is empty. -- **[#1647](https://github.com/Gerrrt/HomeLab/issues/1647) Power `gandalf` - off on a timer.** Decided by - [ADR-0124](adr/0124-power-gandalf-off-on-a-timer.md). No gate. The script - and its units are in the repository and installed on `gandalf`. Left: prove - one power-off, `build-the-playground.md` §7. Until then the - range's "off between sessions" rests on the operator, and two audits found - it left on. +- **[#1651](https://github.com/Gerrrt/HomeLab/issues/1651) Monitor + `gandalf` now that it stays on.** Needed by + [ADR-0125](adr/0125-keep-gandalf-on-and-stop-ragnarok-on-a-timer.md). No + gate. First an ADR of its own, because a collector's metrics leaving the + range host cross the boundary ADR-0014 counts, and it supersedes ADR-0017's + "no monitoring". Until it lands, the host firewall on an always-on range + host is checked only by `build-the-playground.md` §7's read-back. - **[#1226](https://github.com/Gerrrt/HomeLab/issues/1226) The HomePods in Home Assistant, for control.** Decided by [ADR-0099](adr/0099-control-the-homepods-from-home-assistant-and-leave-their-audio-out.md). diff --git a/docs/runbooks/build-the-playground.md b/docs/runbooks/build-the-playground.md index 49f78ea2..87cbc9bb 100644 --- a/docs/runbooks/build-the-playground.md +++ b/docs/runbooks/build-the-playground.md @@ -124,9 +124,12 @@ Never set it up: power it off from the setup screen (Shift+F10, then - **WLAN and Bluetooth off**, or pull the card. ADR-0017 allows one NIC, and `lspci` afterwards should list the I219 alone. - **VT-x and VT-d on**, and *Configuration Change Detection* off. -- **After Power Loss: Power Off.** `gandalf` is off between sessions (§7), - and nothing alerts when it is left on, so a power cut must not bring it - back by itself. A session starts at the power button. +- **After Power Loss: Power Off.** `gandalf` stays on + ([ADR-0125](../adr/0125-keep-gandalf-on-and-stop-ragnarok-on-a-timer.md)), + but nothing watches it yet + ([#1651](https://github.com/Gerrrt/HomeLab/issues/1651)), so a power cut + must not bring it back by itself where nobody knows it is up. After a cut, + it starts at the power button. ADR-0125 reopens this with #1651. - Secure Boot can stay on, because the Proxmox VE 9 installer is signed. Install Proxmox VE **onto the 256 GB M.2, not the SATA SSD** @@ -312,8 +315,13 @@ Applied on `gandalf` the same day, then proved by a reboot at 15:53. After it, `disable_ipv6` read `1`, the `grep -c` read `0`, and the boot's networking log had no failed `sysctl`. The `ip-forward` lines and the `vmbr1_host_in` table were written later on -2026-11-22, from the audit that day. **Not yet applied on `gandalf`.** As with -the `sysctl` line, only a reboot followed by the commands above proves them. +2026-11-22, from the audit that day. As with the `sysctl` line, only a reboot +followed by the commands above proves them. +Applied on `gandalf` the same evening with `ifreload -a`, then proved by a +reboot at 19:21. After it, both `vmbr0` forwarding flags read `0`, the +`policy drop` count read `1`, `vmbr1` had no address, both offloads were +`off`, the ARC cap read `4294967296` and the pool was healthy. §8 check four +proved the table from a target the same night. Then add the reservation for `10.0.30.30` on `morpheus` alongside the other ImaginationLAN statics. `.30` is below `.100` and therefore outside the Kea @@ -722,18 +730,26 @@ isolation host from becoming a tunnel. Nothing here needs one, because `8006` is reached directly from Hicks. The drop-in applied on 2026-11-22 had the first three lines only. The audit that day found both forwardings on (Debian's `X11Forwarding yes` and the `AllowTcpForwarding` default), so the -step is rerun with all five. **Not yet applied on `gandalf`.** The drop-in wins over the main file's +step is rerun with all five, which was done on 2026-11-22 at 19:19 and read +back as above. The drop-in wins over the main file's `PermitRootLogin yes` because `Include` comes first in `sshd_config` and `sshd` keeps the first value it reads. Then, from Hicks, a password login must be refused while a key login still works: ```bash -ssh -o PubkeyAuthentication=no -o PreferredAuthentications=password root@10.0.30.30 true -ssh -o PasswordAuthentication=no root@10.0.30.30 true +ssh -o ControlPath=none -o PubkeyAuthentication=no -o PreferredAuthentications=password root@10.0.30.30 true +ssh -o ControlPath=none -o PasswordAuthentication=no root@10.0.30.30 true ``` The first should fail with `Permission denied (publickey)`, offering no -password prompt. The second should succeed. If it fails, go back to the shell +password prompt. The second should succeed. `ControlPath=none` matters on a +workstation whose SSH config shares connections (`ControlMaster auto`). Without +it, both commands ride the connection already open, which authenticated +before the change, and the first "succeeds" with no password at all. On +2026-11-22 it did exactly that, and only the rerun with `ControlPath=none` +gave the refusal. The same sharing keeps the old login shell after `chsh` +below, so close a shared connection (`ssh -O exit root@10.0.30.30`) before +the next step. If it fails, go back to the shell you kept open, remove the drop-in, and run `systemctl reload ssh`. ### Services on `gandalf`: only what the range uses @@ -804,6 +820,11 @@ find /root -maxdepth 3 -lname '*dotgibson*' -print -delete rm -rf /root/code /root/.local /root/.config/atuin /root/.config/gh /root/.config/go \ /root/.claude /root/.claude.json /root/.ssh/config.d /root/.ssh/sockets \ /root/.ssh/config.pre-dotfiles.* +rm -rf /root/.zshrc /root/.atuin /root/.actual /root/go /root/.npm /root/.w3m /root/.cache \ + /root/.config/carapace /root/.config/git /root/.config/jj /root/.config/lazygit \ + /root/.config/mise /root/.config/sesh /root/.config/systemd /root/.config/tealdeer \ + /root/.config/tmux /root/.config/zsh +rmdir /root/.config 2>/dev/null || true ``` The `find` removes the dotfiles' symlinks before the checkout goes, so none @@ -818,7 +839,16 @@ pgrep -a atuin; command -v gh op zsh **You should see** only `ceph.sources`, `debian.sources`, `proxmox.sources` and `pve-enterprise.sources`, the shell `/bin/bash`, and nothing from the last -line. **Not yet run on `gandalf`.** +line. + +> **Ran on `gandalf` 2026-11-22 at 19:20**, and read back as above. The first +> `rm` left the second's paths behind: atuin's user unit and history, Go's +> module cache (888 MB), npm's cache, mise, the tmux plugins and zsh's own +> files, which the dotfiles install had put outside the symlinks. The second +> `rm` was added from that run. Together they freed about 5 GB of the root +> disk. The dotfiles checkout held one local change, the credential helper +> `gh auth setup-git` writes, and nothing worth keeping. `/root/.bashrc`, +> `.profile` and `.forward` are Debian's and Proxmox's own, and stay. --- @@ -1072,25 +1102,27 @@ Then boot it, run §8's check four on it, power it off and take the snapshot ## 7. Powering the range -`gandalf` is off between sessions. There is no alert for it being left on, and -ADR-0017 says why: every rule shape available says "this host is down", which is -the normal state. Nothing is watching, so the discipline is yours. - -Two audits found the box left on for days anyway (2026-11-13 and 2026-11-22). -[ADR-0124](../adr/0124-power-gandalf-off-on-a-timer.md) takes the backstop -off the person: a timer on the host powers it off at a deadline, six hours -after boot by default or what the last `range-extend` set (1 to 12 hours -ahead), with a warning on every shell 30 and 5 minutes before -([#1647](https://github.com/Gerrrt/HomeLab/issues/1647)). The power-off at -the end below is still the plan. The timer is what happens when the plan is -forgotten. Installed on `gandalf` on 2026-11-22, below. +`gandalf` stays on. The attack VM, `ragnarok`, is what stops between sessions +([ADR-0125](../adr/0125-keep-gandalf-on-and-stop-ragnarok-on-a-timer.md), +which supersedes ADR-0124's host power-off). A timer on the host stops it at a +deadline, six hours after it starts by default or what the last +`range-extend` set (1 to 12 hours ahead), with a warning on every shell, on +the host and inside the VM, 30 and 5 minutes before +([#1647](https://github.com/Gerrrt/HomeLab/issues/1647)). Stopping it at the +end of a session is still the plan. The timer is what happens when the plan +is forgotten. Two audits found it left running for days (2026-11-13 and +2026-11-22). ```text -on → read the firewall back → revert every target to `clean` → work → revert → off - ↑ - 6 h after boot or the last range-extend → off, by itself +start ragnarok → read the host back → revert every target to `clean` → work → revert → stop ragnarok + ↑ + 6 h after ragnarok started, or the last range-extend → stopped, by itself ``` +Nothing watches the host yet +([#1651](https://github.com/Gerrrt/HomeLab/issues/1651)), so the read-back +below is the only check on it, once per session. + **Read the firewall back before anything else.** The collector and the alerts that keep `Saruman`'s firewall on do not reach `gandalf`, because ADR-0017 gives it no agent. So the check §4 hands to Prometheus on `Saruman` is a step here, @@ -1108,81 +1140,118 @@ print `1`. Anything else means the session does not start until §2's lines have been rerun and checked in `/etc/network/interfaces`. `ls /etc/apt/sources.list.d/` should list Debian's and Proxmox's sources only (§4, *Nothing else on `gandalf`*). -`systemctl is-enabled homelab-range-poweroff.timer; systemctl is-active -homelab-range-poweroff.timer` should read `enabled` and `active`, and -`homelab-range-poweroff status` should show a deadline in the future. A -disabled timer puts the range back on discipline alone (ADR-0124), so the -session does not start until *The power-off timer* above has been rerun. +`systemctl is-enabled homelab-ragnarok-stop.timer; systemctl is-active +homelab-ragnarok-stop.timer` should read `enabled` and `active`, and, once +`ragnarok` is up, `homelab-ragnarok-stop status` should show a deadline in the +future. A disabled timer puts the attack VM back on discipline alone +(ADR-0125), so the session does not start until *The attack VM's timer* below +has been rerun. **Then check Proxmox's own updates.** `unattended-upgrades` covers Debian's -packages only (§4, *Services on `gandalf`*). `apt update && apt list ---upgradable` at power-on shows what is waiting from the Proxmox repository, -and `apt full-upgrade` applies it before the session starts, not during one. +packages only (§4, *Services on `gandalf`*), daily now that the host stays +up. `apt update && apt list --upgradable` at the start of a session shows +what is waiting from the Proxmox repository, and `apt full-upgrade` applies it +before the session starts, not during one. Nothing else applies them, so a +month without a session is a month behind. A new kernel does nothing until the box boots into it. So if the upgrade installed a `proxmox-kernel-*` package, or `/run/reboot-required` exists, reboot and start this section again from the top. The firewall read-back runs again too, since a reboot is a fresh power-on. -### The power-off timer +### The attack VM's timer Install it once, from a Hicks workstation in a checkout of this repository. -It is three files and a symlink, and nothing else on the host changes: +It is three files and a symlink, in three steps. The timer is enabled last, +after you have seen the deadline it will act on. The first `ssh` removes +ADR-0124's host power-off timer, if the host still has it: ```bash G=root@10.0.30.30 -ssh "$G" 'install -d -m 0755 /usr/local/sbin' -scp scripts/range-poweroff.sh "$G":/usr/local/sbin/homelab-range-poweroff -scp systemd/range/homelab-range-poweroff.service systemd/range/homelab-range-poweroff.timer "$G":/etc/systemd/system/ -ssh "$G" 'chmod 0755 /usr/local/sbin/homelab-range-poweroff && - chmod 0644 /etc/systemd/system/homelab-range-poweroff.* && - ln -sf /usr/local/sbin/homelab-range-poweroff /usr/local/sbin/range-extend && - homelab-range-poweroff --self-test >/dev/null && echo self-test-ok && - range-extend 6 && - systemd-analyze verify /etc/systemd/system/homelab-range-poweroff.service && - systemctl daemon-reload && systemctl enable --now homelab-range-poweroff.timer && - homelab-range-poweroff status' +ssh "$G" 'systemctl disable --now homelab-range-poweroff.timer 2>/dev/null; + rm -f /etc/systemd/system/homelab-range-poweroff.service /etc/systemd/system/homelab-range-poweroff.timer \ + /usr/local/sbin/homelab-range-poweroff /usr/local/sbin/range-extend; + rm -rf /run/homelab-range-poweroff; install -d -m 0755 /usr/local/sbin' +scp scripts/ragnarok-stop.sh "$G":/usr/local/sbin/homelab-ragnarok-stop +scp systemd/range/homelab-ragnarok-stop.service systemd/range/homelab-ragnarok-stop.timer "$G":/etc/systemd/system/ +ssh "$G" 'chmod 0755 /usr/local/sbin/homelab-ragnarok-stop && + chmod 0644 /etc/systemd/system/homelab-ragnarok-stop.* && + ln -sf /usr/local/sbin/homelab-ragnarok-stop /usr/local/sbin/range-extend && + homelab-ragnarok-stop --self-test >/dev/null && echo self-test-ok && + systemd-analyze verify /etc/systemd/system/homelab-ragnarok-stop.service && + systemctl daemon-reload && + homelab-ragnarok-stop status' +``` + +**You should see** `self-test-ok`, no output from `systemd-analyze`, and +either `ragnarok (VM 130) is not running` or the deadline the timer will act +on. Nothing acts on it yet, because the timer is not enabled. If `ragnarok` +is in use and the deadline is past or close, extend it now. `range-extend` +works before the timer is on: + +```bash +ssh "$G" 'range-extend 3 && homelab-ragnarok-stop status' +``` + +Then turn the timer on. Its first run is within a minute, because +`OnBootSec` has long passed on a host that is already up: + +```bash +ssh "$G" 'systemctl enable --now homelab-ragnarok-stop.timer && + systemctl is-active homelab-ragnarok-stop.timer' ``` -**You should see** `self-test-ok`, no output from `systemd-analyze`, and a -deadline six hours from now. The `range-extend 6` before the enable is -deliberate. Without it the deadline is six hours after *this* boot, and on a -box that has been up longer than that, the first run powers it off a -minute after the install. The self-test exercises every branch with -fakes, so it can run on the host without powering anything off. +The self-test exercises every branch with fakes, so it can run on the host +without stopping anything. Running it, as root on `gandalf`: | | | | --- | --- | -| `homelab-range-poweroff status` | The deadline and the minutes left | -| `range-extend 3` | Set the deadline three hours from now. 1 to 12. It can also bring the deadline closer | -| `journalctl -t homelab-range-poweroff` | Every warning, extension, wait and power-off | - -At 30 minutes and again at 5, every shell on the host gets a `wall` message -that says how to extend. Past the deadline the next run powers off, unless -`dpkg` holds its lock. Then it waits for the run after that. Nothing reaches -the Proxmox web UI, so a session driven only from `8006` gets no warning. -Check `status` from a shell when you start one. - -**Prove it once after installing**, with a session you can afford to lose: - -1. `range-extend 1`, then check `status` reads about 60 minutes. -2. Keep an SSH session open. The 30- and 5-minute `wall` messages should - reach it. -3. Start one guest. At the deadline the box should power itself off, and - `journalctl -t homelab-range-poweroff -b -1` at the next power-on should - end with `powering gandalf off`. - -> **Installed on `gandalf` 2026-11-22 at 17:44**, from #1649's branch -> before it merged, by the commands above. The output was `self-test-ok`, -> nothing from `systemd-analyze`, and a deadline of 23:44. A run of the -> service by hand ended `Result=success`. The timer read `enabled` and -> `active`, with its next run five minutes out. That install had the first -> timer, every five minutes. Review on #1649 moved it to every minute and -> added the lock. The new files were reinstalled the same way, and the -> self-test ran 21 fixtures on the box. - -Record the proof's result here. **Not yet run on `gandalf`.** +| `homelab-ragnarok-stop status` | The deadline and the minutes left, or that `ragnarok` is not running | +| `range-extend 3` | Set the deadline three hours from now. 1 to 12. It can also bring the deadline closer. It refuses while `ragnarok` is stopped, and a new start begins again from six hours | +| `journalctl -t homelab-ragnarok-stop` | Every warning, extension, wait and stop | + +At 30 minutes and again at 5, every shell on the host and inside `ragnarok` +gets a `wall` message that says how to extend. Past the deadline the next run +shuts the VM down, unless `dpkg` holds its lock inside it. Then it waits for +the run after that. `range-extend` runs on the host, not in the VM. Nothing +reaches the Proxmox web UI or a VNC console, so a session driven only from +`8006` gets no warning. Check `status` from a shell when you start one. + +**Prove it once after installing.** Start `ragnarok`, then set its deadline +a few minutes out by writing the state files the way an extension does: + +```bash +pid=$(cat /var/run/qemu-server/130.pid) +printf '%s\n' "$pid" > /run/homelab-ragnarok-stop/run +printf '%s\n' "$(( $(date +%s) + 330 ))" > /run/homelab-ragnarok-stop/deadline +homelab-ragnarok-stop status +``` + +Within a minute, `journalctl -t homelab-ragnarok-stop` should show the +5-minute warning. A minute past the deadline it should show the stop, and +`qm status 130` should read `stopped`. Then `homelab-ragnarok-stop status` +should say it is not running, and `range-extend 2` should refuse. + +> **Installed on `gandalf` 2026-11-22 at 19:26**, in place of ADR-0124's +> host power-off timer, which had been installed at 17:44 and never fired. +> The self-test passed all 25 checks on the box, lock interleavings +> included, `systemd-analyze` printed nothing, and a run by hand ended +> `Result=success`. `range-extend 1` set a deadline 60 minutes out. +> +> **Proved the same evening** by the steps above, with the deadline at +> 19:31:54. The first run, at 19:27:17, was inside five minutes, so it sent +> the single 5-minute warning, as the self-test expects. The run at 19:32:34 +> logged `deadline 2026-11-22 19:31 has passed; stopping ragnarok`, and the +> `qmshutdown` task ended `OK` at 19:32:38. ACPI was enough, so the forced +> stop never ran. The unit ended `Result=success` under its sandbox. After +> it, `status` read `not running`, the state directory held only its lock, +> and `range-extend 2` refused with exit `1`. The guest-agent `wall` returned +> `exitcode 0`. No shell was open inside the VM to see it, so a warning +> reaching a session in `ragnarok` has not been observed. Every message was +> logged twice, by `logger` and by the unit's stdout. The script now skips +> `logger` under systemd, and was reinstalled. The installed files match the +> repository by `sha256sum`. --- @@ -1302,6 +1371,22 @@ means the table is not loaded. The target should still answer `ragnarok`'s ping, which shows that the table drops traffic to the host and not traffic between guests. +> **Check four ran on `gandalf` 2026-11-22 at 19:25**, after the reboot that +> proved §2, on a throwaway full clone of `tpl-kali` at `172.30.30.199`, +> VMID 199. Its `net0` was moved to `vmbr1` before its first boot, because +> the template's is on `vmbr0`. The commands ran through the guest agent, and +> the clone was destroyed afterwards. +> +> - **No DHCP stanza.** `interfaces.d` held only `50-cloud-init`, so the +> template rebuilt that day after #1341 no longer carries the file. +> - **No route.** The only route was `172.30.30.0/24 dev eth0`. Both pings +> gave `Network is unreachable`. +> - **The host takes nothing.** With the on-link route to `10.0.30.30`, both +> pings went unanswered, the neighbour read `INCOMPLETE`, and the `dropped` +> counter rose from 20 to 23 packets. +> - **Guests still reach each other.** `ragnarok` pinged `172.30.30.199` with +> 2 of 2 replies. + --- ## 9. Prove that a leak reports itself @@ -1384,9 +1469,12 @@ Addresses are parsed at query time rather than indexed, per ## Also worth knowing -**The range is not monitored and not backed up, and both are decisions.** -ADR-0017 declines an Alloy agent because `gandalf` is off by design, so any rule -watching it is permanently firing or permanently silenced; and it declines PBS +**The range is not monitored and not backed up.** Only the second is still a +decision. ADR-0017 declined an Alloy agent because `gandalf` was off by design, +so any rule watching it would be permanently firing or permanently silenced. +Since [ADR-0125](../adr/0125-keep-gandalf-on-and-stop-ragnarok-on-a-timer.md) +the host stays on, so that reason is gone, and monitoring it is +[#1651](https://github.com/Gerrrt/HomeLab/issues/1651). ADR-0017 also declines PBS because a deliberately-vulnerable image in the estate's backup store is a supported path for it to arrive somewhere it should not be. If you find yourself wanting to back something up here, the thing you want to keep has stopped being diff --git a/docs/runbooks/shut-down-on-the-ups.md b/docs/runbooks/shut-down-on-the-ups.md index a7896222..a65ae1c3 100644 --- a/docs/runbooks/shut-down-on-the-ups.md +++ b/docs/runbooks/shut-down-on-the-ups.md @@ -1350,8 +1350,10 @@ Both came onto the PDU in the move into the 32U rack, on 2026-11-07. or a disk that a hard stop can leave half-written, so it halts with the first group ([ADR-0107](../adr/0107-subscribe-trinity-to-the-ups-and-bound-saruman-s-guest-stop.md)). -`gandalf` is the range: disposable by decision, off between sessions, and -the only copy of nothing. +`gandalf` is the range: disposable by decision, and the only copy of +nothing. It is on outside sessions too +([ADR-0125](../adr/0125-keep-gandalf-on-and-stop-ragnarok-on-a-timer.md)), +and a hard stop costs it nothing a rebuild does not restore. ### What this does not prove diff --git a/scripts/README.md b/scripts/README.md index bd833c01..78ca765f 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -162,7 +162,7 @@ They need the running estate, so CI cannot run them. Timers do. | `capture-screenshots.sh` | `screenshots` | Renders the dashboards into [`docs/images/`](../docs/images/README.md) | | `packer-smoke.sh` | — | Clones a Packer template, boots it, checks it and destroys it ([`packer/`](../packer/README.md)) | | `finish-attack-vm.sh` | — | Finishes the range's attack VM, `ragnarok`, after `tofu/` makes it on `gandalf` from 902 ([ADR-0116](../docs/adr/0116-build-the-range-attack-vm-with-opentofu-and-prove-it-with-a-script.md)): writes `99-no-forward.conf` and ADR-0014's outbound scope as an nftables policy, at the IP stack and at `eth0`'s egress for raw Ethernet, and proves it neither forwards, NATs nor reaches past `10.0.30.0/24` and the range, over SSH checked against a host key read through the guest agent ([`build-the-playground.md`](../docs/runbooks/build-the-playground.md) §5) | -| `range-poweroff.sh` | — | Powers `gandalf` off at a deadline, six hours after boot or what the last `range-extend` set (1 to 12 hours ahead), checked every minute under one lock, warning on every shell at 30 and 5 minutes, and never while `dpkg` holds its lock ([ADR-0124](../docs/adr/0124-power-gandalf-off-on-a-timer.md)). Installed with [`systemd/range/`](../systemd/range) by [`build-the-playground.md`](../docs/runbooks/build-the-playground.md) §7. Its `--self-test` is the only test of the deadline logic: a real run powers the range host off | +| `ragnarok-stop.sh` | — | Stops the attack VM `ragnarok` on `gandalf` at a deadline, six hours after it started or what the last `range-extend` set for that run (1 to 12 hours ahead), checked every minute under one lock, warning every shell on the host and in the VM at 30 and 5 minutes, and never while `dpkg` holds its lock inside the VM ([ADR-0125](../docs/adr/0125-keep-gandalf-on-and-stop-ragnarok-on-a-timer.md)). Installed with [`systemd/range/`](../systemd/range) by [`build-the-playground.md`](../docs/runbooks/build-the-playground.md) §7. Its `--self-test` is the only test of the deadline logic: a real run stops the attack VM | | `stage-agent-msis.sh` | — | Stages the Wazuh and Velociraptor MSIs the lab pipeline installs, and the two Debian packages `garuda` installs, into `${SOC_DATA_DIR}/agent-msi` on `odin`, which the SOC stack's Caddy serves. The vendor packages are checked against their pins; the Velociraptor `.deb` is built by the server and its hash printed ([#1068](https://github.com/Gerrrt/HomeLab/issues/1068), [ADR-0092](../docs/adr/0092-enrol-garuda-in-odins-soc-with-debian-packages-staged-on-odin.md)) | | `lab-known-hosts.sh` | — | Reads the lab domain's SSH host keys through the guest agent into `ansible/.known_hosts`, after any rebuild ([ADR-0085](../docs/adr/0085-check-the-lab-domains-host-keys-against-keys-read-through-the-guest-agent.md)) | | `gen_population.py` | — | The lab domain's users, into `ansible/population/` | diff --git a/scripts/ragnarok-stop.sh b/scripts/ragnarok-stop.sh new file mode 100755 index 00000000..17dd5329 --- /dev/null +++ b/scripts/ragnarok-stop.sh @@ -0,0 +1,386 @@ +#!/usr/bin/env bash +# Stop the attack VM, ragnarok, at a deadline, so it is never left running +# on VLAN 30 (ADR-0125, which supersedes ADR-0124; #1647). gandalf itself +# stays on. +# +# Usage: +# homelab-ragnarok-stop check what the timer runs: warn, or stop ragnarok +# homelab-ragnarok-stop status print the deadline and the time left +# homelab-ragnarok-stop extend H set the deadline H hours from now (1-12) +# range-extend H the same as `extend H` (a symlink to this) +# scripts/ragnarok-stop.sh --self-test +# +# THE DEADLINE is six hours after ragnarok started, or the time the last +# `extend` set. An extension belongs to one run of the VM: it is stored with +# the QEMU process's PID, and a deadline stored for another PID is ignored. +# So a stop and a start always begin again from six hours, even when both +# fall between two runs of the timer. While ragnarok is stopped, `check` +# clears the state and does nothing else. One extension is capped at twelve +# hours, so a typo or a "just leave it" cannot quietly switch the backstop +# off. +# +# THE WARNINGS go through `wall` to every shell on gandalf and, through the +# guest agent, to every shell inside ragnarok, where the session is: once +# at 30 minutes or less, once at 5 or less. The timer runs this every +# minute, well inside the five-minute window, so a late run cannot skip the +# last warning. A warning is recorded against the deadline it was for, so +# an extension re-arms both without clearing anything. +# +# ONE LOCK. `check` and `extend` each hold an flock on the state +# directory's lock file for the whole operation, the stop included. Without +# it, a check that had read the old deadline could stop the VM after +# `range-extend` reported success (review on #1649). +# +# IT NEVER STOPS RAGNAROK IN THE MIDDLE OF A PACKAGE INSTALL. Past the +# deadline, it asks the guest agent whether anything holds dpkg's lock +# inside the VM. If something does, it logs that it is waiting and exits, +# and the next run asks again. An agent that does not answer counts as not +# busy, so a hung agent cannot keep the VM up. +# +# THE STOP is `qm shutdown` with a three-minute timeout and --forceStop, so +# an ACPI shutdown gets its chance and a guest that ignores it is stopped +# anyway. Just before it, the run reads the PID again. The guest-agent calls +# before it can take seconds, and a VM stopped and started in that time is a +# new run that this run's deadline does not cover, so it is left alone +# (review on #1652). `qm` takes no PID, so a restart in the instant between +# that read and the shutdown is the window left, and it is milliseconds. +# +# THE START TIME is the QEMU process's own, from /proc//stat: boot time +# plus the process's start in clock ticks. It is the same on every run, so +# the default deadline is too, and a warning is never sent twice for it. +# `now` minus `ps -o etimes` would sample two clocks and could move by a +# second between runs (review on #1652). +set -euo pipefail + +VMID="${RAGNAROK_VMID:-130}" +HOURS=6 +MAX_EXTEND=12 +STATE_DIR="${RANGE_STATE_DIR:-/run/homelab-ragnarok-stop}" + +# Each of these is replaced by the self-test, which is the only reason they +# are functions. +now() { date +%s; } +vm_pid() { + # The running QEMU process's PID, or nothing when the VM is stopped. + local p="" + p="$(head -c 16 "/var/run/qemu-server/${VMID}.pid" 2>/dev/null | tr -d '[:space:]')" || true + if is_uint "${p}" && [[ -d "/proc/${p}" ]]; then printf '%s' "${p}"; fi + return 0 +} +vm_start() { + # Seconds since the epoch at which process $1 started. Field 22 of + # /proc//stat, counted after the ") " that ends the command name, + # which may itself hold spaces. + local ticks btime hz + ticks="$(sed 's/^.*) //' "/proc/$1/stat" 2>/dev/null | awk '{print $20}')" + btime="$(awk '/^btime /{print $2}' /proc/stat)" + hz="$(getconf CLK_TCK)" + is_uint "${ticks}" && is_uint "${btime}" && is_uint "${hz}" && printf '%s' "$(( btime + ticks / hz ))" + return 0 +} +guest_dpkg_busy() { + # True only if the agent answers and fuser finds a holder (exit 0). + qm guest exec "${VMID}" --timeout 15 -- fuser -s /var/lib/dpkg/lock-frontend /var/lib/dpkg/lock 2>/dev/null \ + | grep -qE '"exitcode"[[:space:]]*:[[:space:]]*0[^0-9]' +} +take_lock() { flock -w 30 9; } +say() { + # Under systemd, stdout already goes to the journal under this unit's + # SyslogIdentifier, so logger as well would record every line twice. + # From a shell (range-extend), logger is what puts it in the journal. + [[ -n "${INVOCATION_ID:-}" ]] || logger -t homelab-ragnarok-stop -- "$*" 2>/dev/null || true + printf '%s\n' "$*" +} +warn_all() { + wall -- "$*" 2>/dev/null || true + qm guest exec "${VMID}" --timeout 15 -- wall -- "$*" >/dev/null 2>&1 || true +} +stop_vm() { qm shutdown "${VMID}" --timeout 180 --forceStop 1; } + +is_uint() { [[ "$1" =~ ^[0-9]+$ ]]; } + +read_state() { + # One integer per file. Anything else reads as absent. + local f="${STATE_DIR}/$1" v="" + [[ -f "${f}" ]] && v="$(head -c 32 "${f}" 2>/dev/null | tr -d '[:space:]')" + is_uint "${v}" && printf '%s' "${v}" + return 0 +} + +write_state() { + # Write then rename, so a reader never sees half a number. + # The temporary name is unique, so two writers never share one. + local tmp + mkdir -p "${STATE_DIR}" + tmp="$(mktemp "${STATE_DIR}/.$1.XXXXXX")" + printf '%s\n' "$2" > "${tmp}" + mv -f "${tmp}" "${STATE_DIR}/$1" +} + +clear_state() { rm -f "${STATE_DIR}/deadline" "${STATE_DIR}/run" "${STATE_DIR}/warned-30" "${STATE_DIR}/warned-5"; } + +with_lock() { + # Run "$@" holding the lock. fd 9 closes when the group ends, which + # releases it, so nothing outlives the operation. + mkdir -p "${STATE_DIR}" + { + take_lock || { say "could not take ${STATE_DIR}/lock in 30 s"; return 1; } + "$@" + } 9>"${STATE_DIR}/lock" +} + +extended() { + # The stored deadline, if it was set for this run of the VM ($1 is the PID). + local d + d="$(read_state deadline)" + if [[ -n "${d}" && "$(read_state run)" == "$1" ]]; then printf '%s' "${d}"; fi + return 0 +} + +deadline() { + # $1 is the PID of the running VM. + local d st + d="$(extended "$1")" + if [[ -n "${d}" ]]; then printf '%s' "${d}"; return; fi + st="$(vm_start "$1")" + is_uint "${st}" || st="$(now)" + printf '%s' "$(( st + HOURS * 3600 ))" +} + +minutes_left() { printf '%s' "$(( ($1 + 59) / 60 ))"; } + +fmt_time() { date -d "@$1" '+%Y-%m-%d %H:%M' 2>/dev/null || date -r "$1" '+%Y-%m-%d %H:%M'; } + +cmd_check() { with_lock check_locked; } + +check_locked() { + local pid t d left mins + pid="$(vm_pid)" + if [[ -z "${pid}" ]]; then + clear_state + return 0 + fi + t="$(now)" + d="$(deadline "${pid}")" + left=$(( d - t )) + if (( left <= 0 )); then + if guest_dpkg_busy; then + say "deadline $(fmt_time "${d}") has passed, but dpkg's lock is held inside ragnarok; waiting for the next run" + return 0 + fi + say "deadline $(fmt_time "${d}") has passed; stopping ragnarok" + warn_all "ragnarok: the deadline has passed (ADR-0125). Shutting down now." + if [[ "$(vm_pid)" != "${pid}" ]]; then + say "ragnarok stopped or restarted during this check; leaving the new run to its own deadline" + return 0 + fi + stop_vm + clear_state + return 0 + fi + mins="$(minutes_left "${left}")" + if (( left <= 300 )); then + if [[ "$(read_state warned-5)" != "${d}" ]]; then + warn_all "ragnarok shuts down in ${mins} min (ADR-0125). To keep it running, on gandalf: range-extend " + write_state warned-5 "${d}" + write_state warned-30 "${d}" + say "warned: ${mins} min to the deadline" + fi + elif (( left <= 1800 )); then + if [[ "$(read_state warned-30)" != "${d}" ]]; then + warn_all "ragnarok shuts down in ${mins} min (ADR-0125). To keep it running, on gandalf: range-extend " + write_state warned-30 "${d}" + say "warned: ${mins} min to the deadline" + fi + fi + return 0 +} + +cmd_extend() { + local h="${1:-}" + if ! is_uint "${h}" || (( 10#${h} < 1 || 10#${h} > MAX_EXTEND )); then + printf 'usage: range-extend , a whole number from 1 to %d\n' "${MAX_EXTEND}" >&2 + return 2 + fi + with_lock extend_locked "$(( 10#${h} ))" +} + +extend_locked() { + local h="$1" pid t d + pid="$(vm_pid)" + if [[ -z "${pid}" ]]; then + printf 'ragnarok (VM %s) is not running, so there is no deadline to extend\n' "${VMID}" >&2 + return 1 + fi + t="$(now)" + d=$(( t + h * 3600 )) + write_state run "${pid}" + write_state deadline "${d}" + say "deadline set to $(fmt_time "${d}"), ${h} h from now, by ${SUDO_USER:-${USER:-root}}" + return 0 +} + +cmd_status() { + local pid t d left + pid="$(vm_pid)" + if [[ -z "${pid}" ]]; then + printf 'ragnarok (VM %s) is not running; nothing to stop\n' "${VMID}" + return 0 + fi + t="$(now)" + d="$(deadline "${pid}")" + left=$(( d - t )) + if [[ -n "$(extended "${pid}")" ]]; then + printf 'deadline %s (set by range-extend)\n' "$(fmt_time "${d}")" + else + printf 'deadline %s (%d h after ragnarok started)\n' "$(fmt_time "${d}")" "${HOURS}" + fi + if (( left > 0 )); then + printf '%d min left\n' "$(minutes_left "${left}")" + else + printf 'passed %d min ago; the next run stops ragnarok unless dpkg is busy inside it\n' "$(( -left / 60 ))" + fi + return 0 +} + +self_test() { + local passed=0 failed=0 tmp + tmp="$(mktemp -d)" + trap 'rm -rf "${tmp}"' RETURN + STATE_DIR="${tmp}/state" + + # Fakes. START is when the VM started; NOW, PID, BUSY and the logs are + # set per fixture. An empty PID is a stopped VM. + local START=1800000000 NOW=0 PID=4242 BUSY=1 WALL_LOG="${tmp}/wall" STOP_LOG="${tmp}/stop" + now() { printf '%s' "${NOW}"; } + vm_pid() { printf '%s' "${PID}"; } + vm_start() { printf '%s' "${START}"; } + # RESTART, when set, is the PID the VM comes back with while the check is + # asking the guest agent about dpkg: a stop and a start mid-check. + local RESTART="" + guest_dpkg_busy() { if [[ -n "${RESTART}" ]]; then PID="${RESTART}"; fi; return "${BUSY}"; } + say() { :; } + warn_all() { printf '%s\n' "$*" >> "${WALL_LOG}"; } + stop_vm() { printf 'stop\n' >> "${STOP_LOG}"; } + local HAVE_FLOCK=1 + if ! command -v flock >/dev/null 2>&1; then + HAVE_FLOCK=0 + take_lock() { :; } + fi + + reset() { rm -rf "${STATE_DIR}" "${WALL_LOG}" "${STOP_LOG}"; BUSY=1; PID=4242; START=1800000000; RESTART=""; } + walls() { [[ -f "${WALL_LOG}" ]] && wc -l < "${WALL_LOG}" | tr -d ' ' || printf 0; } + stops() { [[ -f "${STOP_LOG}" ]] && wc -l < "${STOP_LOG}" | tr -d ' ' || printf 0; } + check() { + local name="$1" got="$2" expect="$3" + if [[ "${got}" == "${expect}" ]]; then + printf '\033[0;32m PASS\033[0m %s\n' "${name}"; passed=$((passed + 1)) + else + printf '\033[0;31m FAIL\033[0m %s\n got %s\n expected %s\n' "${name}" "${got}" "${expect}" + failed=$((failed + 1)) + fi + } + + local H=3600 + reset; NOW=$((START + 60)); cmd_check + check "a fresh start neither warns nor stops" "$(walls)/$(stops)" "0/0" + + reset; NOW=$((START + 6 * H - 1700)); cmd_check; cmd_check + check "under 30 min warns once, not on every run" "$(walls)/$(stops)" "1/0" + + reset; NOW=$((START + 6 * H - 1700)); cmd_check; NOW=$((START + 6 * H - 200)); cmd_check; cmd_check + check "under 5 min warns a second time, once" "$(walls)/$(stops)" "2/0" + + reset; NOW=$((START + 6 * H - 200)); cmd_check; NOW=$((START + 6 * H - 100)); cmd_check + check "a first run inside 5 min sends one warning, not two" "$(walls)/$(stops)" "1/0" + + reset; NOW=$((START + 6 * H)); cmd_check + check "at the deadline it stops ragnarok" "$(stops)" "1" + + reset; NOW=$((START + 6 * H + 10)); BUSY=0; cmd_check + check "past the deadline with dpkg busy inside the VM it waits" "$(stops)" "0" + BUSY=1; cmd_check + check "and stops it on the next run once dpkg is done" "$(stops)" "1" + + reset; NOW=$((START + 5 * H)); cmd_extend 3 >/dev/null; NOW=$((START + 6 * H + 60)); cmd_check + check "an extension moves the deadline past six hours" "$(stops)" "0" + NOW=$((START + 8 * H)); cmd_check + check "and the extended deadline is enforced" "$(stops)" "1" + + reset; NOW=$((START + 6 * H - 1700)); cmd_check; cmd_extend 1 >/dev/null; NOW=$((NOW + H - 1700)); cmd_check + check "an extension re-arms the 30-minute warning" "$(walls)" "2" + + reset; NOW=$((START + H)) + check "extend refuses 0" "$(cmd_extend 0 2>/dev/null; printf '%s' "$?")" "2" + check "extend refuses 13 (the cap is 12)" "$(cmd_extend 13 2>/dev/null; printf '%s' "$?")" "2" + check "extend refuses a non-number" "$(cmd_extend 2h 2>/dev/null; printf '%s' "$?")" "2" + check "extend refuses nothing at all" "$(cmd_extend 2>/dev/null; printf '%s' "$?")" "2" + check "a refused extend leaves no deadline behind" "$(read_state deadline)" "" + check "extend accepts 12" "$(cmd_extend 12 >/dev/null; read_state deadline)" "$((NOW + 12 * H))" + check "extend reads 08 as eight, not as octal" "$(cmd_extend 08 >/dev/null; read_state deadline)" "$((NOW + 8 * H))" + + reset; mkdir -p "${STATE_DIR}"; printf 'garbage\n' > "${STATE_DIR}/deadline"; printf '4242\n' > "${STATE_DIR}/run"; NOW=$((START + H)) + check "an unreadable deadline falls back to six hours after the start" "$(deadline 4242)" "$((START + 6 * H))" + + # A stopped VM: nothing to do, and nothing left over for the next start. + reset; NOW=$((START + 5 * H)); cmd_extend 3 >/dev/null; PID=""; cmd_check + check "a stopped VM is not stopped again" "$(walls)/$(stops)" "0/0" + check "and its extension is cleared" "$(read_state deadline)" "" + check "extend refuses while the VM is stopped" "$(cmd_extend 2 2>/dev/null; printf '%s' "$?")" "1" + + # A new run of the VM never inherits the last run's extension, even when + # no check ran in between to clear it. + reset; NOW=$((START + H)); cmd_extend 12 >/dev/null + PID=5151; START=$((NOW + 60)); NOW=$((START + 6 * H)); cmd_check + check "a new run ignores the old run's extension" "$(stops)" "1" + + # 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 + check "a VM restarted during the check is not stopped by the old run's deadline" "$(stops)" "0" + RESTART=""; START=$((NOW - 60)); cmd_check + check "and the new run gets its own six hours" "$(stops)" "0" + + # The two interleavings the lock exists for. The test holds the lock on + # fd 8, starts the other operation in the background, does what the + # lock's holder would do, and lets go. + if ((HAVE_FLOCK)); then + local pid + reset; mkdir -p "${STATE_DIR}"; NOW=$((START + 6 * H + 10)) + exec 8>"${STATE_DIR}/lock"; flock 8 + # 8>&-: the child must not inherit the test's hold on the lock, or it + # waits on itself until the timeout. + cmd_check 8>&- & pid=$! + sleep 0.3 + write_state run "${PID}" + write_state deadline "$((NOW + H))" + exec 8>&- + wait "${pid}" + check "a check waiting on the lock reads the deadline the extension wrote" "$(stops)" "0" + + reset; mkdir -p "${STATE_DIR}"; NOW=$((START + H)) + exec 8>"${STATE_DIR}/lock"; flock 8 + cmd_extend 2 >/dev/null 8>&- & pid=$! + sleep 0.3 + check "an extension waits while a check holds the lock" "$(read_state deadline)" "" + exec 8>&- + wait "${pid}" + check "and writes its deadline once the check lets go" "$(read_state deadline)" "$((NOW + 2 * H))" + else + printf '\033[0;33m SKIP\033[0m the two lock interleavings: no flock on this host\n' + fi + + ((failed == 0)) +} + +case "$(basename "$0")" in + range-extend) cmd_extend "$@"; exit $? ;; +esac + +case "${1:-}" in + --self-test) self_test ;; + check) cmd_check ;; + status) cmd_status ;; + extend) shift; cmd_extend "$@" ;; + *) printf 'usage: %s check|status|extend |--self-test\n' "$0" >&2; exit 2 ;; +esac diff --git a/scripts/range-poweroff.sh b/scripts/range-poweroff.sh deleted file mode 100755 index af7b449b..00000000 --- a/scripts/range-poweroff.sh +++ /dev/null @@ -1,284 +0,0 @@ -#!/usr/bin/env bash -# Power gandalf off at a deadline, so the range is never left running -# (ADR-0124, #1647). -# -# Usage: -# homelab-range-poweroff check what the timer runs: warn, or power off -# homelab-range-poweroff status print the deadline and the time left -# homelab-range-poweroff extend H set the deadline H hours from now (1-12) -# range-extend H the same as `extend H` (a symlink to this) -# scripts/range-poweroff.sh --self-test -# -# THE DEADLINE is six hours after boot, or the time the last `extend` set. -# It lives under /run, which a boot clears, so every boot starts the six -# hours again and an extension never outlives the session that asked for -# it. One extension is capped at twelve hours, so a typo or a "just leave -# it" cannot quietly switch the backstop off. -# -# THE WARNINGS go to every shell through `wall`: once at 30 minutes or -# less, once at 5 or less. The timer runs this every minute, well inside -# the five-minute window, so a late run cannot skip the last warning (at -# five minutes it could: review on #1649). A warning is recorded against the -# deadline it was for, so an extension re-arms both without clearing -# anything. -# -# ONE LOCK. `check` and `extend` each hold an flock on the state -# directory's lock file for the whole operation, the power-off request -# included. Without it, a check that had read the old deadline could power -# off after `range-extend` reported success, and two extensions could race -# on one temporary file (review on #1649). -# -# IT NEVER POWERS OFF IN THE MIDDLE OF A PACKAGE INSTALL. While something -# holds dpkg's lock, a run past the deadline logs that it is waiting and -# exits. The next run checks again. Cutting dpkg off half way leaves a -# hypervisor that may not boot, which is worse than a range left on for -# five more minutes. -# -# THE POWER-OFF is the ordinary `systemctl poweroff`. pve-guests.service's -# ExecStop runs Proxmox's stopall, which shuts every guest down and forces -# any that ignore ACPI, as Mr-Robot does. Reverting the targets to `clean` -# is build-the-playground.md §7's first step at the next power-on. -set -euo pipefail - -HOURS=6 -MAX_EXTEND=12 -STATE_DIR="${RANGE_STATE_DIR:-/run/homelab-range-poweroff}" - -# Each of these is replaced by the self-test, which is the only reason they -# are functions. -now() { date +%s; } -boot_time() { awk '/^btime /{print $2}' /proc/stat; } -dpkg_busy() { fuser -s /var/lib/dpkg/lock-frontend /var/lib/dpkg/lock 2>/dev/null; } -take_lock() { flock -w 30 9; } -say() { logger -t homelab-range-poweroff -- "$*" 2>/dev/null || true; printf '%s\n' "$*"; } -warn_all() { wall -- "$*" 2>/dev/null || true; } -power_off() { systemctl poweroff; } - -is_uint() { [[ "$1" =~ ^[0-9]+$ ]]; } - -read_state() { - # One integer per file. Anything else reads as absent. - local f="${STATE_DIR}/$1" v="" - [[ -f "${f}" ]] && v="$(head -c 32 "${f}" 2>/dev/null | tr -d '[:space:]')" - is_uint "${v}" && printf '%s' "${v}" - return 0 -} - -write_state() { - # Write then rename, so a reader never sees half a number. - # The temporary name is unique, so two writers never share one. - local tmp - mkdir -p "${STATE_DIR}" - tmp="$(mktemp "${STATE_DIR}/.$1.XXXXXX")" - printf '%s\n' "$2" > "${tmp}" - mv -f "${tmp}" "${STATE_DIR}/$1" -} - -with_lock() { - # Run "$@" holding the lock. fd 9 closes when the group ends, which - # releases it, so nothing outlives the operation. - mkdir -p "${STATE_DIR}" - { - take_lock || { say "could not take ${STATE_DIR}/lock in 30 s"; return 1; } - "$@" - } 9>"${STATE_DIR}/lock" -} - -deadline() { - local d - d="$(read_state deadline)" - if [[ -n "${d}" ]]; then printf '%s' "${d}"; return; fi - printf '%s' "$(( $(boot_time) + HOURS * 3600 ))" -} - -minutes_left() { printf '%s' "$(( ($1 + 59) / 60 ))"; } - -fmt_time() { date -d "@$1" '+%Y-%m-%d %H:%M' 2>/dev/null || date -r "$1" '+%Y-%m-%d %H:%M'; } - -cmd_check() { with_lock check_locked; } - -check_locked() { - local t d left mins - t="$(now)" - d="$(deadline)" - left=$(( d - t )) - if (( left <= 0 )); then - if dpkg_busy; then - say "deadline $(fmt_time "${d}") has passed, but dpkg's lock is held; waiting for the next run" - return 0 - fi - say "deadline $(fmt_time "${d}") has passed; powering gandalf off" - warn_all "gandalf: the range deadline has passed (ADR-0124). Powering off now." - power_off - return 0 - fi - mins="$(minutes_left "${left}")" - if (( left <= 300 )); then - if [[ "$(read_state warned-5)" != "${d}" ]]; then - warn_all "gandalf powers off in ${mins} min (ADR-0124). To keep it on: range-extend " - write_state warned-5 "${d}" - write_state warned-30 "${d}" - say "warned: ${mins} min to the deadline" - fi - elif (( left <= 1800 )); then - if [[ "$(read_state warned-30)" != "${d}" ]]; then - warn_all "gandalf powers off in ${mins} min (ADR-0124). To keep it on: range-extend " - write_state warned-30 "${d}" - say "warned: ${mins} min to the deadline" - fi - fi - return 0 -} - -cmd_extend() { - local h="${1:-}" - if ! is_uint "${h}" || (( 10#${h} < 1 || 10#${h} > MAX_EXTEND )); then - printf 'usage: range-extend , a whole number from 1 to %d\n' "${MAX_EXTEND}" >&2 - return 2 - fi - with_lock extend_locked "$(( 10#${h} ))" -} - -extend_locked() { - local h="$1" t d - t="$(now)" - d=$(( t + h * 3600 )) - write_state deadline "${d}" - say "deadline set to $(fmt_time "${d}"), ${h} h from now, by ${SUDO_USER:-${USER:-root}}" - return 0 -} - -cmd_status() { - local t d left - t="$(now)" - d="$(deadline)" - left=$(( d - t )) - if [[ -n "$(read_state deadline)" ]]; then - printf 'deadline %s (set by range-extend)\n' "$(fmt_time "${d}")" - else - printf 'deadline %s (%d h after boot)\n' "$(fmt_time "${d}")" "${HOURS}" - fi - if (( left > 0 )); then - printf '%d min left\n' "$(minutes_left "${left}")" - else - printf 'passed %d min ago; the next run powers off unless dpkg is busy\n' "$(( -left / 60 ))" - fi - return 0 -} - -self_test() { - local passed=0 failed=0 tmp - tmp="$(mktemp -d)" - trap 'rm -rf "${tmp}"' RETURN - STATE_DIR="${tmp}/state" - - # Fakes. BOOT is fixed; NOW, BUSY and the logs are set per fixture. - local BOOT=1800000000 NOW=0 BUSY=1 WALL_LOG="${tmp}/wall" OFF_LOG="${tmp}/off" - now() { printf '%s' "${NOW}"; } - boot_time() { printf '%s' "${BOOT}"; } - dpkg_busy() { return "${BUSY}"; } - say() { :; } - warn_all() { printf '%s\n' "$*" >> "${WALL_LOG}"; } - power_off() { printf 'off\n' >> "${OFF_LOG}"; } - local HAVE_FLOCK=1 - if ! command -v flock >/dev/null 2>&1; then - HAVE_FLOCK=0 - take_lock() { :; } - fi - - reset() { rm -rf "${STATE_DIR}" "${WALL_LOG}" "${OFF_LOG}"; BUSY=1; } - walls() { [[ -f "${WALL_LOG}" ]] && wc -l < "${WALL_LOG}" | tr -d ' ' || printf 0; } - offs() { [[ -f "${OFF_LOG}" ]] && wc -l < "${OFF_LOG}" | tr -d ' ' || printf 0; } - check() { - local name="$1" got="$2" expect="$3" - if [[ "${got}" == "${expect}" ]]; then - printf '\033[0;32m PASS\033[0m %s\n' "${name}"; passed=$((passed + 1)) - else - printf '\033[0;31m FAIL\033[0m %s\n got %s\n expected %s\n' "${name}" "${got}" "${expect}" - failed=$((failed + 1)) - fi - } - - local H=3600 - reset; NOW=$((BOOT + 60)); cmd_check - check "a fresh boot neither warns nor powers off" "$(walls)/$(offs)" "0/0" - - reset; NOW=$((BOOT + 6 * H - 1700)); cmd_check; cmd_check - check "under 30 min warns once, not on every run" "$(walls)/$(offs)" "1/0" - - reset; NOW=$((BOOT + 6 * H - 1700)); cmd_check; NOW=$((BOOT + 6 * H - 200)); cmd_check; cmd_check - check "under 5 min warns a second time, once" "$(walls)/$(offs)" "2/0" - - reset; NOW=$((BOOT + 6 * H - 200)); cmd_check; NOW=$((BOOT + 6 * H - 100)); cmd_check - check "a first run inside 5 min sends one warning, not two" "$(walls)/$(offs)" "1/0" - - reset; NOW=$((BOOT + 6 * H)); cmd_check - check "at the deadline it powers off" "$(offs)" "1" - - reset; NOW=$((BOOT + 6 * H + 10)); BUSY=0; cmd_check - check "past the deadline with dpkg busy it waits" "$(offs)" "0" - BUSY=1; cmd_check - check "and powers off on the next run once dpkg is done" "$(offs)" "1" - - reset; NOW=$((BOOT + 5 * H)); cmd_extend 3 >/dev/null; NOW=$((BOOT + 6 * H + 60)); cmd_check - check "an extension moves the deadline past six hours" "$(offs)" "0" - NOW=$((BOOT + 8 * H)); cmd_check - check "and the extended deadline is enforced" "$(offs)" "1" - - reset; NOW=$((BOOT + 6 * H - 1700)); cmd_check; cmd_extend 1 >/dev/null; NOW=$((NOW + H - 1700)); cmd_check - check "an extension re-arms the 30-minute warning" "$(walls)" "2" - - reset; NOW=$((BOOT + H)) - check "extend refuses 0" "$(cmd_extend 0 2>/dev/null; printf '%s' "$?")" "2" - check "extend refuses 13 (the cap is 12)" "$(cmd_extend 13 2>/dev/null; printf '%s' "$?")" "2" - check "extend refuses a non-number" "$(cmd_extend 2h 2>/dev/null; printf '%s' "$?")" "2" - check "extend refuses nothing at all" "$(cmd_extend 2>/dev/null; printf '%s' "$?")" "2" - check "a refused extend leaves no deadline behind" "$(read_state deadline)" "" - check "extend accepts 12" "$(cmd_extend 12 >/dev/null; read_state deadline)" "$((NOW + 12 * H))" - check "extend reads 08 as eight, not as octal" "$(cmd_extend 08 >/dev/null; read_state deadline)" "$((NOW + 8 * H))" - - reset; mkdir -p "${STATE_DIR}"; printf 'garbage\n' > "${STATE_DIR}/deadline" - check "an unreadable deadline file falls back to six hours after boot" "$(deadline)" "$((BOOT + 6 * H))" - - # The two interleavings the lock exists for. The test holds the lock on - # fd 8, starts the other operation in the background, does what the - # lock's holder would do, and lets go. - if ((HAVE_FLOCK)); then - local pid - reset; mkdir -p "${STATE_DIR}"; NOW=$((BOOT + 6 * H + 10)) - exec 8>"${STATE_DIR}/lock"; flock 8 - # 8>&-: the child must not inherit the test's hold on the lock, or it - # waits on itself until the timeout. - cmd_check 8>&- & pid=$! - sleep 0.3 - write_state deadline "$((NOW + H))" - exec 8>&- - wait "${pid}" - check "a check waiting on the lock reads the deadline the extension wrote" "$(offs)" "0" - - reset; mkdir -p "${STATE_DIR}"; NOW=$((BOOT + H)) - exec 8>"${STATE_DIR}/lock"; flock 8 - cmd_extend 2 >/dev/null 8>&- & pid=$! - sleep 0.3 - check "an extension waits while a check holds the lock" "$(read_state deadline)" "" - exec 8>&- - wait "${pid}" - check "and writes its deadline once the check lets go" "$(read_state deadline)" "$((NOW + 2 * H))" - else - printf '\033[0;33m SKIP\033[0m the two lock interleavings: no flock on this host\n' - fi - - ((failed == 0)) -} - -case "$(basename "$0")" in - range-extend) cmd_extend "$@"; exit $? ;; -esac - -case "${1:-}" in - --self-test) self_test ;; - check) cmd_check ;; - status) cmd_status ;; - extend) shift; cmd_extend "$@" ;; - *) printf 'usage: %s check|status|extend |--self-test\n' "$0" >&2; exit 2 ;; -esac diff --git a/scripts/self-tests.sh b/scripts/self-tests.sh index dee64436..11aa5aee 100755 --- a/scripts/self-tests.sh +++ b/scripts/self-tests.sh @@ -75,9 +75,10 @@ # tree, a non-fast-forward, red CI. None can be # staged on a deployment host, and each was tested # only by never having fired (#854) -# range-poweroff.sh the deadline, the two warnings and the dpkg wait; -# a real run powers gandalf off, so the fixtures are -# the only way to see each branch before it fires +# ragnarok-stop.sh the deadline, the two warnings, the dpkg wait and +# the per-run extension; a real run stops the attack +# VM, so the fixtures are the only way to see each +# branch before it fires # backup-volumes.sh a real backup of a throwaway volume with real age: # the set opens with either recipient's key and not # a third's (#835), and the refusals refuse (#854) diff --git a/systemd/README.md b/systemd/README.md index 09185cdc..d0ccde83 100644 --- a/systemd/README.md +++ b/systemd/README.md @@ -31,7 +31,7 @@ job goes stale, is | [`sensitive/`](sensitive) | `trinity` | `make install-timers ARGS="--profile sensitive"` | the same, with `@DEPLOY_ROOT@` and `@RUN_USER@` filled in at install | | [`agent/`](agent) | each agent host, by what it can run | `make install-agent-collectors AGENT=user@host` | a collector copied to `/usr/local/bin`; an agent host has no checkout | | [`host/`](host) | `prometheus` | `make install-host-units` | nothing: boot ordering, not a schedule. Docker waits for `10.0.99.20` ([ADR-0105](../docs/adr/0105-hold-docker-until-the-monitoring-hosts-address-exists.md)) | -| [`range/`](range) | `gandalf` | by hand, [`build-the-playground.md`](../docs/runbooks/build-the-playground.md) §7 | `scripts/range-poweroff.sh`, copied to `/usr/local/sbin`. The range's power-off backstop, every minute ([ADR-0124](../docs/adr/0124-power-gandalf-off-on-a-timer.md)); it reports nothing, by ADR-0017 | +| [`range/`](range) | `gandalf` | by hand, [`build-the-playground.md`](../docs/runbooks/build-the-playground.md) §7 | `scripts/ragnarok-stop.sh`, copied to `/usr/local/sbin`. Stops the attack VM `ragnarok` at its deadline, checked every minute ([ADR-0125](../docs/adr/0125-keep-gandalf-on-and-stop-ragnarok-on-a-timer.md)); it reports nothing until [#1651](https://github.com/Gerrrt/HomeLab/issues/1651) | The estate's units name the deployment checkout's absolute path, because the live stack runs from that checkout and nowhere else, and `install-timers.sh diff --git a/systemd/range/homelab-ragnarok-stop.service b/systemd/range/homelab-ragnarok-stop.service new file mode 100644 index 00000000..d164b3a0 --- /dev/null +++ b/systemd/range/homelab-ragnarok-stop.service @@ -0,0 +1,43 @@ +# The attack VM's stop backstop (ADR-0125, #1647). It runs on gandalf only, +# which has no checkout of this repository and no agent, so this unit calls +# the script directly, the way systemd/agent/ units do. Nothing reports its +# outcome to Prometheus yet: gandalf's monitoring is its own follow-up under +# ADR-0125, and build-the-playground.md §7's read-back is what checks the +# timer is on. +# +# RUNS AS ROOT because `qm` and writing to every terminal need it. `qm` +# writes the cluster filesystem, its lock and its task log, so those are +# the paths this unit may write besides its own state directory. The state +# directory is kept when the unit stops, because the deadline and the +# warnings already sent have to survive from one run to the next. +# +# TimeoutStartSec covers `qm shutdown`'s three-minute wait and its +# forced stop, with room to spare. +# +# The script is installed at /usr/local/sbin/homelab-ragnarok-stop by +# build-the-playground.md §7, which also installs this file. +[Unit] +Description=HomeLab: stop the attack VM ragnarok at its deadline (ADR-0125) +Documentation=https://github.com/Gerrrt/HomeLab/blob/main/docs/runbooks/build-the-playground.md +After=pve-cluster.service +Requires=pve-cluster.service + +[Service] +Type=oneshot +ExecStart=/usr/local/sbin/homelab-ragnarok-stop check +TimeoutStartSec=300 +Restart=no +RuntimeDirectory=homelab-ragnarok-stop +RuntimeDirectoryPreserve=yes +NoNewPrivileges=true +RestrictSUIDSGID=true +LockPersonality=true +RestrictRealtime=true +ProtectHome=true +ProtectSystem=strict +ReadWritePaths=/etc/pve /var/log/pve /var/lock /run +ProtectKernelModules=true +RestrictAddressFamilies=AF_UNIX AF_NETLINK +StandardOutput=journal +StandardError=journal +SyslogIdentifier=homelab-ragnarok-stop diff --git a/systemd/range/homelab-range-poweroff.timer b/systemd/range/homelab-ragnarok-stop.timer similarity index 54% rename from systemd/range/homelab-range-poweroff.timer rename to systemd/range/homelab-ragnarok-stop.timer index 452aad7e..b248b619 100644 --- a/systemd/range/homelab-range-poweroff.timer +++ b/systemd/range/homelab-ragnarok-stop.timer @@ -1,21 +1,21 @@ [Unit] -Description=HomeLab: power gandalf off at the range deadline (ADR-0124) +Description=HomeLab: stop the attack VM ragnarok at its deadline (ADR-0125) Documentation=https://github.com/Gerrrt/HomeLab/blob/main/docs/runbooks/build-the-playground.md [Timer] -Unit=homelab-range-poweroff.service +Unit=homelab-ragnarok-stop.service # Every minute from a minute after boot. The script decides; the timer only # asks. The period has to sit well inside the five-minute warning window. # At five minutes, a run that came a little late could land past the -# deadline having skipped the window, and power off with no last warning -# (review on #1649). A minute is also about how far the power-off lags the -# deadline. A run is a few reads of /run and costs nothing. +# deadline having skipped the window, and stop the VM with no last warning +# (review on #1649). A minute is also about how far the stop lags the +# deadline. A run while ragnarok is stopped reads one PID file and exits. # # AccuracySec is tight for the same reason. systemd's default of a minute # would let a run slip by a whole period. # -# No Persistent=: a run missed while the box was off has nothing to catch -# up on, because the deadline is counted from this boot. +# No Persistent=: the deadline is counted from the VM's start, so a missed +# run has nothing to catch up on. OnBootSec=1min OnUnitActiveSec=1min AccuracySec=5s diff --git a/systemd/range/homelab-range-poweroff.service b/systemd/range/homelab-range-poweroff.service deleted file mode 100644 index 12839975..00000000 --- a/systemd/range/homelab-range-poweroff.service +++ /dev/null @@ -1,38 +0,0 @@ -# The range's power-off backstop (ADR-0124, #1647). It runs on gandalf only, -# which has no checkout of this repository and no agent, so this unit calls -# the script directly, the way systemd/agent/ units do. Nothing reports its -# outcome to Prometheus: ADR-0017 gives the range no monitoring, and -# build-the-playground.md §7's read-back is what checks the timer is on. -# -# RUNS AS ROOT because powering off and writing to every terminal need it. -# The state directory under /run is the only path it writes. The directory -# is kept when the unit stops, because the deadline and the warnings -# already sent have to survive from one run to the next. -# -# The script is installed at /usr/local/sbin/homelab-range-poweroff by -# build-the-playground.md §7, which also installs this file. -[Unit] -Description=HomeLab: power gandalf off at the range deadline (ADR-0124) -Documentation=https://github.com/Gerrrt/HomeLab/blob/main/docs/runbooks/build-the-playground.md - -[Service] -Type=oneshot -ExecStart=/usr/local/sbin/homelab-range-poweroff check -TimeoutStartSec=60 -Restart=no -RuntimeDirectory=homelab-range-poweroff -RuntimeDirectoryPreserve=yes -NoNewPrivileges=true -RestrictSUIDSGID=true -LockPersonality=true -RestrictRealtime=true -PrivateTmp=true -ProtectHome=true -ProtectSystem=strict -ProtectKernelTunables=true -ProtectKernelModules=true -ProtectControlGroups=true -RestrictAddressFamilies=AF_UNIX -StandardOutput=journal -StandardError=journal -SyslogIdentifier=homelab-range-poweroff