diff --git a/README.md b/README.md index 5ce00e4..29ea98d 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,9 @@ Supported: agents on **Debian 12/13** and **Ubuntu 22.04/24.04/26.04 LTS**; serv browser ──HTTPS──▶ Caddy/nginx ──▶ kernelwatch (127.0.0.1:8080) ──▶ SQLite ``` -## What the dashboard tells you +It's read-only by design: the server can't make hosts do anything. + +## What you see Each host gets one status. When several apply, the worst one wins: @@ -27,92 +29,17 @@ Each host gets one status. When several apply, the worst one wins: |----------|---------| | `stale` | No report in `stale_after_hours` (default 3h), or never. Other data can't be trusted. | | `reboot` | A newer kernel is installed but not running, or `/run/reboot-required` exists. | -| `update` | A kernel or security update is available but not installed, services are running outdated libraries and need a restart, or apt's package lists are too old (`apt_stale_after_hours`) for "no updates" to mean anything. | +| `update` | A kernel or security update is available but not installed, services are running outdated libraries and need a restart, or apt's package lists are too old for "no updates" to mean anything. | | `ok` | Running the newest installed kernel, with no security or kernel updates pending. | -Each row also lists the reasons behind its status, and clicking a host shows -its full report and recent history. +Each row lists the reasons behind its status, and clicking a host shows its full +report and recent history. [How it works](docs/how-it-works.md) explains how the +agent works each of these out (kernel comparison, needrestart, Ubuntu Livepatch, +phased updates, package list freshness). -How the agent works it out: +## Quick start -- **Running vs. installed kernel**, three ways: - - A newer `linux-image-*` installed than `uname -r` means a version upgrade. - - The build in `uname -v` (`Debian 6.12.57-1`, `#85-Ubuntu`, `#33~24.04.1-Ubuntu`) - is compared with the installed package version of the running kernel - (`6.12.57-1`, `6.8.0-85.85`, `6.14.0-33.33~24.04.1`). A mismatch means the - package was upgraded in place after boot; `uname -r` didn't change, but a - reboot is still needed. - - [`needrestart`](https://github.com/liske/needrestart)'s kernel result, for - build strings the server doesn't recognise (see below). -- **Services needing a restart** (e.g. nginx still using the old OpenSSL - after an upgrade): from `needrestart -b`, if it's installed. Ubuntu ships it; - on Debian, install with `install.sh --with-needrestart`. Without it, the - Services column shows `?` and status isn't affected. needrestart has to - inspect every process, so it runs as root in its own unit, - `kernelwatch-needrestart.service`. That unit has no network access, only the - two capabilities needrestart needs, and list-only mode, so it never restarts - anything. It writes its results to `/run/kernelwatch/needrestart`, and the - unprivileged agent unit runs it just before each report and reads the file. - The agent never runs as root, and needrestart never gets network access. Fix it on the host: - `sudo needrestart -r a` (or restart the listed services), and the next report - clears it. -- **Ubuntu Livepatch**: with [Livepatch](https://ubuntu.com/security/livepatch) - (free for personal use with Ubuntu Pro), a newer kernel being installed doesn't - mean the running one is unpatched. If Livepatch is healthy (`applied` or - `nothing-to-apply`, checked, supported), a pending kernel reboot, or a - `/run/reboot-required` caused only by `linux-*` packages, shows as a note - instead of `reboot`, and the note gives the date by which the kernel must be - upgraded. Livepatch only fixes high and critical CVEs, and only until that - date, so cover ends 14 days before it and the host goes to `reboot` as usual. - Any other reboot reason (libc, systemd) still counts. If Livepatch is failing, - unsupported or in a state we don't know, the host gets no cover and the reason - is noted. Hosts without Livepatch are unaffected. `canonical-livepatch` needs - root and a snap cgroup, so like needrestart it runs in its own unit, - `kernelwatch-livepatch.service`, which writes `/run/kernelwatch/livepatch` - before each report. It's skipped when the snap isn't installed. -- **Agent version**: each report includes it. Hosts running an older agent - than the server shipped with get a note to run `agent/deploy.sh`; their status - isn't changed. -- **Hostname check**: each report includes the host's own name. If its first - DNS label differs from the name the host is registered under (ignoring case), - the row gets a note: "registered as web01 but reports itself as db01". This - catches a token copied to the wrong machine. It never changes the status. A - host you registered under a custom label (` ` in - `agent/hosts`) shows the note until you tell its agent which name to report: - `agent/deploy.sh iris -- --report-hostname iris` (or `install.sh - --report-hostname iris` on the host, which sets `REPORT_HOSTNAME` in - `agent.conf`). Upgrades and `--rotate` keep it; - `--default-report-hostname` removes it. That's the host's own say-so, so it - only silences the note for hosts you've deliberately named. -- **Available updates**: a simulated `apt-get dist-upgrade`. It is read-only, takes - no locks and writes no cache files. `dist-upgrade` is used so that new-ABI kernel - packages pulled in by the meta-package show up. Lines whose origin contains - `-security` count as security updates. -- **Fresh package lists**: the simulation only knows what apt's package lists - say, and the agent can't refresh them itself. Ubuntu refreshes them about once - a day. Debian doesn't by default unless `unattended-upgrades` is set up, so a - new kernel or security update can stay invisible until someone runs - `apt update`. Install with `--with-apt-update` and - `kernelwatch-apt-update.service` runs `apt-get update` just before each - report, so updates show up within the hour. Either way, lists older than - `apt_stale_after_hours` put the host in `update`. -- **Phased updates** (Ubuntu only): Ubuntu rolls some updates out gradually and - holds them back from a share of machines at first. apt doesn't offer these to - the host yet, so they aren't counted as available updates. They appear as - their own Phased column (hover for the packages, `–` on Debian), with the - list also on the host page. - They never affect status, because Ubuntu doesn't phase security updates and - there's nothing to act on until apt offers them. -- **Package list freshness**: the mtime of apt's update stamps. The agent - **doesn't run `apt update`** itself; it relies on the stock `apt-daily.timer`. - If that's disabled, the host shows `update` with "package lists N days old". - -The agent sends raw facts and the server decides what they mean, so you can -change the status rules without touching the agents. - -## Server setup - -On the dashboard host: +**1. Install the server** on the dashboard host: ```sh git clone && cd kernel-automation @@ -120,566 +47,42 @@ sudo ./server/install.sh sudo kernelwatch set-password admin # dashboard login ``` -This installs to `/opt/kernelwatch` and keeps config in `/etc/kernelwatch/server.toml` -(see [`server/server.toml.example`](server/server.toml.example)) and data in -`/var/lib/kernelwatch`. The `kernelwatch.service` unit runs it as the unprivileged -`kernelwatch` user. Re-run `install.sh` to upgrade; it keeps your config. +It listens on plain HTTP on `127.0.0.1:8080`. Put a TLS reverse proxy in front; +[Reverse proxy and access control](docs/reverse-proxy.md) has Caddy, nginx, +CloudPanel and Authelia setups. -### TLS reverse proxy - -The server speaks plain HTTP on `127.0.0.1:8080`. Put a TLS proxy in front of it. -The agents and your browser both connect through it. - -**Caddy** (simplest): - -```caddyfile -kernelwatch.example.internal { - reverse_proxy 127.0.0.1:8080 -} -``` - -**nginx**: - -```nginx -server { - listen 443 ssl; - server_name kernelwatch.example.internal; - # ssl_certificate / ssl_certificate_key ... - location / { - proxy_pass http://127.0.0.1:8080; - proxy_set_header Host $host; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - } -} -``` - -With either proxy, set `trust_proxy_headers = true` in `server.toml` so login -rate limiting sees real client IPs. - -If you use a private CA (e.g. Caddy's `tls internal`), give the agents its -root cert with `--ca` (below). - -You can expose only `/api/v1/report` to the fleet network and keep the -dashboard on a VPN or tailnet. That's a proxy rule, not a kernelwatch setting. - -### CloudPanel - -CloudPanel gives each site its own Linux user and a document root at -`/home//htdocs//`. kernelwatch doesn't use that directory. -nginx forwards requests to the app; it doesn't serve kernelwatch's files. Install -with `server/install.sh` as above, so the app runs as the `kernelwatch` user -with its data in `/var/lib/kernelwatch`, outside every site user's home. Leave -the document root empty, and keep your clone of this repo out of `htdocs`. - -1. **Pick a free port.** CloudPanel's Varnish setup can run an nginx backend - on 8080. Check with `ss -ltnp | grep ':8080\b'`. If it's taken, set another port - in `/etc/kernelwatch/server.toml` and restart (`sudo systemctl restart kernelwatch`): - - ```toml - listen_port = 8095 - trust_proxy_headers = true - ``` - - Check it: `curl -s http://127.0.0.1:8095/healthz` should print `ok`. - -2. **Create the site as a Reverse Proxy.** In CloudPanel: *Add Site → Create a - Reverse Proxy*, with your domain and Reverse Proxy URL - `http://127.0.0.1:8095`. CloudPanel can't change an existing site's type. If - the domain already exists as a PHP or static site, delete and recreate it. - Deleting a site also removes its site user and home directory, so move - anything you need out first. - -3. **TLS.** In the site's *SSL/TLS* tab, issue a Let's Encrypt certificate. Agents - then need no `--ca`. - -4. **Check the generated vhost** (the site's *Vhost* tab). The `location` - that proxies to the app should pass the original `Host` header and the - client address: - - ```nginx - proxy_set_header Host $host; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - ``` - - Add them if they're missing. Without `Host`, logins fail the origin check - with "cross-origin request refused". Without `X-Forwarded-For`, every login - appears to come from 127.0.0.1, so one person's failed attempts lock everyone out. - Also check that the login page is styled. If `/static/style.css` returns 404, - a static-file `location` in the template is looking in the empty document root - instead of proxying. Make it fall through to the proxy, or remove it. - -5. **Optionally restrict the dashboard.** The site's domain is public, so the - login page is reachable from the internet unless you limit it. Agents only - need `/api/v1/report`. In the Vhost tab, add an `allow ; deny all;` - to `location /` and a separate unrestricted - `location = /api/v1/report { proxy_pass http://127.0.0.1:8095; }`. - Changes made in the Vhost tab persist. Back them up before - recreating the site. - To require a login through Authelia instead of an IP allowlist, see - [Authelia (forward auth)](#authelia-forward-auth). - -### Authelia (forward auth) - -If you already run [Authelia](https://www.authelia.com/), you can put it in -front of the dashboard. That adds Authelia's 2FA and single sign-on, and -kernelwatch's own login still applies behind it. You log in to both, but -Authelia's remember-me makes that rare. This uses nginx's `auth_request`, so -you don't need an OIDC client. - -**Agents must bypass Authelia.** They authenticate with their bearer token and -can't follow a login redirect. If Authelia covers `/api/v1/report`, every -report gets a redirect instead of a 401 or 204, and the whole fleet goes stale -within 3 hours. - -1. **Authelia `access_control`.** Rules are checked in order, so put the bypass - first, and keep a single `rules:` list: - - ```yaml - access_control: - default_policy: two_factor - rules: - - domain: kernelwatch.example.com - resources: - - '^/api/v1/report$' - - '^/healthz$' - policy: bypass - - domain: "*.example.com" - policy: two_factor - ``` - - For the redirect to the login page to work, your `session.cookies` entry has - to cover the dashboard's domain and set `authelia_url`. Without them, browsers - get a bare 401 page. Authelia reads this file only at startup, so restart it - after editing (in Kubernetes: `kubectl rollout restart deployment/authelia`). - Check the file first with `authelia validate-config`. - -2. **nginx.** Add an internal location for Authelia's check, an exact-match - location for the agents with no check, and the check on `location /`. - For CloudPanel, edit the site's *Vhost* tab: leave the template's - `@reverse_proxy` block alone and add or replace these: - - ```nginx - # Authelia's check (internal subrequest only) - location = /internal/authelia/authz { - internal; - proxy_pass https://auth.example.com/api/authz/auth-request; - proxy_http_version 1.1; - proxy_ssl_server_name on; - proxy_set_header Host auth.example.com; - proxy_set_header X-Original-Method $request_method; - proxy_set_header X-Original-URL $scheme://$http_host$request_uri; - proxy_set_header X-Forwarded-For $remote_addr; - proxy_set_header Content-Length ""; - proxy_set_header Connection ""; - proxy_pass_request_body off; - } - - # Agents: token auth only - location = /api/v1/report { - try_files $uri @reverse_proxy; - } - - # Dashboard: Authelia first, then kernelwatch's login - location / { - auth_request /internal/authelia/authz; - auth_request_set $redirection_url $upstream_http_location; - error_page 401 =302 $redirection_url; - try_files $uri @reverse_proxy; - } - ``` - - Without CloudPanel, use `proxy_pass http://127.0.0.1:8095;` plus the `Host` - and `X-Forwarded-For` headers in place of `try_files ... @reverse_proxy`. If - Authelia runs on the same machine, point the check straight at it (e.g. - `http://127.0.0.1:9091/api/authz/auth-request`) and drop the - `proxy_ssl_server_name` and `Host` lines. Keep `location ^~ /.well-known` - unprotected so certificate renewals still work. If something monitors - `/healthz`, give it an exact-match location like the agents' one. - -3. **Check it.** - - ```sh - curl -sI https://kernelwatch.example.com/ | head -3 - # 302, Location pointing at Authelia - - curl -si -X POST https://kernelwatch.example.com/api/v1/report | head -1 - # 401 from kernelwatch (no token), not a 302 - ``` - - Then run `sudo systemctl start kernelwatch-agent` on one host and check - that its *Last seen* updates. If the POST gets a 302, the agents' location - isn't matching. Fix that before the fleet goes stale. - -## Adding a host - -On the server: +**2. Add a host.** On the server, `sudo kernelwatch add-host web01` prints a token +(shown once). Then on the host: ```sh -sudo kernelwatch add-host web01 -# prints a token, shown once -``` - -On the host (copy the `agent/` directory over, or clone the repo): - -```sh -sudo ./agent/install.sh --server https://kernelwatch.example.internal [--ca root.pem] +sudo ./agent/install.sh --server https://kernelwatch.example.internal # paste the token when prompted ``` -The installer puts the agent in `/usr/local/sbin`, writes `/etc/kernelwatch/agent.conf` -and `agent.token` (root, 0600), enables `kernelwatch-agent.timer` and sends a first -report. After that, the agent reports 2 minutes after boot and then hourly, with up -to 15 minutes of jitter. - -For unattended installs, set `KERNELWATCH_TOKEN=...` instead of using the prompt. - -Add `--with-needrestart` to also report services needing a restart (Debian -needs this; Ubuntu already has needrestart). It installs needrestart if -missing and sets it to *list* services after apt upgrades instead of asking -interactively. Delete `/etc/needrestart/conf.d/kernelwatch.conf` to undo that. - -Add `--with-apt-update` to refresh apt's package lists before each report -(recommended on Debian, see above). It's the same as running `apt update` -hourly: lists only, nothing is installed. If apt is busy, the refresh is -skipped and the report goes ahead. `--without-apt-update` turns it off; -re-running the installer with neither keeps the current setting. - -Useful on a host: +or, for many hosts at once, from your workstation over SSH (after a one-time +`agent/deploy.conf`, see [Agents](docs/agents.md)): ```sh -sudo kernelwatch-agent --print # see exactly what would be sent -sudo systemctl start kernelwatch-agent # report now -systemctl list-timers kernelwatch-agent.timer -journalctl -u kernelwatch-agent +agent/deploy.sh --register web01 db01 ``` -### Deploying to many hosts +[Agents](docs/agents.md) also covers the options (private CA, needrestart, apt update, +reporting under a different name) and for upgrading the fleet. -`agent/deploy.sh` does all of the above over SSH from your workstation's -checkout, so hosts need neither git nor Gitea access. Set it up once: +**3. Set up alerts and backups** (recommended): [Alerts and +monitoring](docs/alerts.md) covers ntfy notifications and the heartbeat that +tells you if kernelwatch itself stops. [Operations](docs/operations.md) covers +nightly backups. -```sh -cp agent/deploy.conf.example agent/deploy.conf # SERVER_URL, DASHBOARD (ssh target) -cp agent/hosts.example agent/hosts # optional; --register fills it in -``` +## Documentation -Then: - -```sh -agent/deploy.sh --register web01 db01 # register on the dashboard + install -agent/deploy.sh # upgrade every host in agent/hosts -agent/deploy.sh web01 # upgrade one -agent/deploy.sh --rotate web01 # new token, reinstall -agent/deploy.sh --dry-run # show the plan -agent/deploy.sh -- --with-needrestart # pass options through to install.sh -agent/deploy.sh -- --with-apt-update # refresh package lists before each report -``` - -For each host it copies the agent into a private temp directory and runs -`install.sh`, which sends a first report, then deletes the temp directory. -With `--register`/`--rotate`, it also runs -`sudo kernelwatch add-host --token-only` on the dashboard host and passes the -token to the host on SSH stdin. The token never appears on a command line or -in your terminal. A plain run is an upgrade: config and token stay as they -are. You'll get sudo prompts on each host, and on the dashboard when -registering, unless you have passwordless sudo. - -Both files are git-ignored. Host names default to each host's `hostname -s`; -put ` ` in `agent/hosts` to override. For a host your -workstation can't reach directly (e.g. IPv6-only while you're on IPv4), give it -a jump host in `~/.ssh/config` and `deploy.sh` works unchanged: - -``` -Host zeus - ProxyJump eurus -``` - -## Stale-host, reboot and update alerts (ntfy) - -The server can notify an [ntfy](https://ntfy.sh/) topic when a host stops -reporting and when its reports resume. Agents report hourly with up to 15 minutes -of jitter. Alerts use the same `stale_after_hours` as the dashboard (3 hours by -default), leaving room for ordinary delays. Newly registered hosts get that same -grace period to send their first report. - -Re-run `sudo ./server/install.sh` to install the alert timer when upgrading. -The installer preserves your existing config, so add these settings to -`/etc/kernelwatch/server.toml`: - -```toml -ntfy_url = "https://ntfy.example.com/kernelwatch" -ntfy_token = "" # optional access token with publish permission for this topic -ntfy_timeout_seconds = 10.0 -``` - -Subscribe to that topic in your ntfy app, then check delivery: - -```sh -sudo kernelwatch test-alert -systemctl list-timers kernelwatch-alerts.timer -``` - -`kernelwatch-alerts.timer` runs a separate, unprivileged check every five minutes, -even when no hosts report and nobody opens the dashboard. Notifications normally -arrive within about five minutes of crossing the stale threshold or receiving a -fresh report. Run `sudo kernelwatch check-alerts` to check immediately, or inspect -`journalctl -u kernelwatch-alerts.service` for delivery failures. - -- Each host gets one stale notification and one reporting-recovery notification - per detected outage. Successful sends are saved in SQLite, so routine checks - and server restarts don't repeat them. Recovery confirms reporting has resumed; - the host may still need updates or a reboot. -- Failed sends are retried on the next check, and a failure for one host doesn't - stop checks for the others. A recovery is sent only after a stale notification - was successfully delivered. A timeout or crash after ntfy accepted a message - can cause a duplicate on retry. -- An empty `ntfy_url` disables notifications. The timer reads its configuration - on every run; changing ntfy settings needs no restart. If you change - `stale_after_hours`, restart `kernelwatch.service` too so the dashboard uses the - new threshold. - -- **Reboot and update alerts.** A host that has stayed in `reboot` or `update` - for `status_alert_after_hours` (default 24) gets one notification listing the - reasons shown on the dashboard. The clock starts when the host entered that - status, so hourly reports don't restart it. Fixing the host (back to `ok`) - re-arms it. Going from `update` to `reboot` notifies again after another - period; going back down doesn't. Stale hosts are skipped, since the stale - alert covers them. Set `status_alert_after_hours = 0` to turn these off. - Upgrading starts the clock at the first check, so expect the first - notifications a day after you re-run `install.sh`. - -Use the topic's direct publish URL, with token authentication if needed; it must -accept the POST without a browser login or redirect. The topic and token stay -in the server config (root-owned, readable by the `kernelwatch` service group). -Agents need no changes. - -## Scripting: `kernelwatch status` - -`kernelwatch status` prints the fleet the way the dashboard shows it, from the -database, with no network port or token involved. It needs `sudo`, like the other -admin commands. Run it over SSH from anywhere else. - -``` -$ sudo kernelwatch status -stale new01 ? (last seen never) - - never reported -reboot web01 6.8.0-136 -> 6.8.0-138 (last seen 1m ago) - - kernel: running 6.8.0-136, 6.8.0-138 installed - - 2 security updates pending -ok db01 6.12.57 (last seen 1m ago) -3 hosts: 1 stale, 1 reboot, 0 update, 1 ok -``` - -Hosts come worst first, in the dashboard's order, and use the same status logic -(Livepatch cover, the hostname note and so on). Narrow it with `--host NAME` and -`--level stale|reboot|update|ok` (repeatable); both also work with `--json`. - -`--json` is for scripts. It has `generated_at`, `counts` and `hosts`. The counts -always cover the whole fleet, and the filters only trim `hosts`. Each host has `name`, -`status`, `reasons`, `last_report_at` (UTC ISO 8601, or `null` if it never -reported), `last_report_age_seconds`, `os`, `kernel_running`, -`kernel_newest_installed`, `reboot_required`, `updates_pending`, -`security_updates`, `kernel_updates`, `services_need_restart`, `livepatch` -(or `null`), `uptime_seconds` and `agent_version`. Fields a host hasn't -reported are `null`, and the keys are always present. It never includes tokens -or password hashes. - -```sh -# hosts that need a reboot -sudo kernelwatch status --json | jq -r '.hosts[] | select(.status=="reboot") | .name' - -# one line per host that needs attention, with the reasons -sudo kernelwatch status --json --level reboot --level update | - jq -r '.hosts[] | "\(.name): \(.reasons | join("; "))"' - -# from your workstation; exits non-zero (for cron or a monitor) if any host is stale -ssh triton 'sudo kernelwatch status --json' | jq -e '.counts.stale == 0' >/dev/null -``` - -There's deliberately no HTTP endpoint for this. It would expose every host's -kernel and pending security updates to anything holding a token, and nothing -needs it yet. If something has to poll remotely, add one behind your proxy's -IP allow-list rather than relying on a token alone. - -## Heartbeat: is kernelwatch itself running? - -Every alert above depends on `kernelwatch-alerts.timer` running on the dashboard -host. If that host is down, or the timer breaks, nothing tells you. A heartbeat -fixes this: kernelwatch pings an external monitor, and the monitor alerts when the -pings **stop**. [healthchecks.io](https://healthchecks.io) has a free tier; -Uptime Kuma's push monitors work the same way. - -1. In the monitor, create two checks and copy their ping URLs: - - **alerts**: period 5 minutes, grace 20 minutes. - - **backup**: period 1 day, grace a few hours (the timer fires about 03:30 and - can be up to 30 minutes late). -2. Add the URLs to `/etc/kernelwatch/server.toml` (no restart needed for the - alert check or the backup; they read it on every run): - - ```toml - heartbeat_url = "https://hc-ping.com/" - backup_heartbeat_url = "https://hc-ping.com/" - ``` - -3. Check both: `sudo kernelwatch test-heartbeat` pings each configured URL once. - -What counts as a heartbeat: - -- `heartbeat_url` is pinged at the end of every alert check (every five minutes) - that sent all its notifications. If ntfy delivery is failing, the ping is - skipped on purpose, so the monitor also notices a broken alert pipeline. It's - pinged even with no `ntfy_url`, since the timer is still alive. -- `backup_heartbeat_url` is pinged after each successful nightly backup, so a - timer that never ran, or a backup that failed, shows up as a missing ping. - A manual `kernelwatch backup` doesn't ping. -- A heartbeat that can't be delivered is logged (status code or error type, never - the URL) and never fails the check or the backup. - -The pings leave from the dashboard host, so a dead host is exactly what stops -them. Set the monitor to notify you some way that doesn't depend on that host: -email, the monitor's own app, or ntfy.sh. Not a ntfy server running behind it. -The URLs are secrets (whoever has one can fake a heartbeat), so keep -`server.toml` readable by root and the `kernelwatch` group only. - -## Server admin commands - -``` -sudo kernelwatch add-host NAME register a host, print its token (--token-only for scripts) -sudo kernelwatch rotate-token NAME issue a new token (old one stops working) -sudo kernelwatch remove-host NAME delete a host and its history -sudo kernelwatch list-hosts hosts and when they last reported -sudo kernelwatch status [--json] fleet status like the dashboard (--host, --level to filter) -sudo kernelwatch set-password USER create a user / change password (logs out their sessions) -sudo kernelwatch remove-user USER -sudo kernelwatch list-users -sudo kernelwatch backup PATH write a consistent copy of the database (safe while running) -sudo kernelwatch scheduled-backup dated copy in backup_dir, then prune old ones (what the timer runs) -sudo kernelwatch notify-backup-failure send the failed-backup notification now (also runs on failure) -sudo kernelwatch check-alerts check for stale, recovered, reboot and update alerts now -sudo kernelwatch test-alert send a test notification to the configured ntfy topic -sudo kernelwatch test-heartbeat ping the configured heartbeat URLs once and report -``` - -## Backups - -Everything kernelwatch knows lives in one SQLite file, `/var/lib/kernelwatch/kernelwatch.db`: -host tokens (hashed), dashboard logins and report history. Without it you'd -re-register every host and reinstall its token. Don't copy the file while the -server runs, since recent writes can sit in its `-wal` sidecar. Use: - -```sh -sudo kernelwatch backup /var/lib/kernelwatch/backups/kernelwatch.db -``` - -This uses SQLite's online backup, so it's safe while hosts are reporting. It -replaces any existing file at that path and writes it mode 0600. It refuses to -overwrite the live database. The command runs as the `kernelwatch` user, so the -destination directory has to be writable by it (create one with -`sudo install -d -o kernelwatch -g kernelwatch -m 0700 /var/lib/kernelwatch/backups`), -then copy the result off the machine with your usual backup tool. - -### Nightly backups - -`server/install.sh` also enables `kernelwatch-backup.timer`, which runs -`kernelwatch scheduled-backup` at about 03:30 (up to 30 minutes late; a run missed -while the machine was off happens at the next boot). It writes -`/var/lib/kernelwatch/backups/kernelwatch-YYYY-MM-DD.db` (UTC date, mode 0600, -directory 0700) and then deletes dated backups that are `backup_keep_days` (default -7) or more days old. It deletes only files with exactly that name, and only after -the new backup succeeded, so a failing run never costs you the ones you have. Set -`backup_keep_days = 0` to keep them all. The unit can only write under -`/var/lib/kernelwatch`, so keep `backup_dir` there unless you give it more access. - -```sh -systemctl list-timers kernelwatch-backup.timer -journalctl -u kernelwatch-backup # a failed run shows up here -sudo systemctl start kernelwatch-backup # back up now -``` - -If a run fails, whether from an error, the 10-minute timeout, an out-of-memory -kill or a crash, systemd starts `kernelwatch-backup-failed.service` -(`OnFailure=`), which sends a high-priority message to your ntfy topic naming the -newest backup still on disk. The cause is in `journalctl -u kernelwatch-backup`. -Without `ntfy_url` it only logs that it had nothing to send to. If ntfy itself is -unreachable at that moment, the failure shows up only in the journal -(`journalctl -u kernelwatch-backup-failed`). It can't tell you that the timer -never ran at all, for example because the host was down; that needs a heartbeat -monitor. You can check delivery with -`sudo kernelwatch notify-backup-failure`, which sends the same message. - -These copies sit on the dashboard host, so they protect against a corrupted or -mistakenly changed database but not against losing the machine. Copy -`/var/lib/kernelwatch/backups/` elsewhere with whatever you already back up with. - -To restore, stop the service, put the file at `db_path` owned by `kernelwatch` -(mode 0600), and start it again. The stale-alert state restores with it. - -## Security notes - -- **Host identity comes from the token, not the payload.** A host can only - report as itself. Tokens are 256-bit random values; only their SHA-256 is stored. -- **Report rate limit.** A report arriving less than `report_min_interval_seconds` - (default 30) after the host's previous one gets HTTP 429 with a `Retry-After` - header, and isn't stored. So a stuck agent or a leaked token can't flood the - database or push real history off the host page. The agent's curl waits out the - `Retry-After` and retries, so running `systemctl start kernelwatch-agent` twice - in a row just pauses briefly. Set it to `0` to disable. -- **Livepatch status** runs in a separate root unit with no network access and a - read-only filesystem. It has no capability bound, syscall filter or - `NoNewPrivileges`, because the snap's setuid `snap-confine` can't run under - them (tested: `NoNewPrivileges=yes` fails with "cannot change profile for the - next exec call"). It only runs `canonical-livepatch status`. -- **needrestart** runs in a separate root unit with `PrivateNetwork=yes`, a - capability set of just `CAP_SYS_PTRACE` + `CAP_DAC_READ_SEARCH` (to read other - processes' memory maps), a read-only filesystem except `/run/kernelwatch`, - and `-r l` (list, never restart). -- **apt-get update** (with `--with-apt-update`) runs as root with network - access, like apt's own `apt-daily.service`, but sandboxed: no access to home - directories, devices or kernel settings. apt drops to its `_apt` user for the - downloads, and nothing gets installed. -- **The agent** runs as a throwaway unprivileged user (`DynamicUser=yes`) with - no capabilities, a read-only filesystem view and a syscall filter. The token - reaches it through `LoadCredential=` and goes to curl on stdin, so it never - appears in a process listing. -- **The dashboard** uses scrypt-hashed passwords, server-side sessions, - `HttpOnly` + `Secure` + `SameSite=Strict` cookies, an Origin check on form - posts, per-IP login rate limiting, and a strict CSP. Everything a host - reports is HTML-escaped. -- **It's read-only by design.** The server can't make hosts do anything. - Adding remote actions (like "reboot this host") would turn it into a - remote-execution system; think hard before doing that. - -## Development - -```sh -make test # unit + integration tests (stdlib unittest) -make lint # shellcheck, if available -``` - -Gitea Actions (`.gitea/workflows/ci.yml`) runs both on every push to `main` -and every pull request: the tests on Python 3.10–3.13 (the versions on the -supported Ubuntu and Debian releases) and shellcheck on the shell scripts. - -The tests run a real server on an ephemeral port. They also run the real agent -script against stubbed `dpkg-query`/`apt-get`/`needrestart`/`uname` and a fake -filesystem root (`KERNELWATCH_ROOT`), including one end-to-end agent → server -report. -Both installers (`agent/install.sh`, `server/install.sh`) run for real in the tests -against a fake root: `KERNELWATCH_ROOT` prefixes every path they write and skips -their root check, and `systemctl`, `apt-get`, `useradd` and the like are stubs that -log their arguments. Don't set it on a real host. - -Run a local server against a scratch database: - -```sh -printf 'db_path = "/tmp/kw.db"\nsecure_cookies = false\n' > /tmp/kw.toml -export KERNELWATCH_CONFIG=/tmp/kw.toml -./server/kernelwatch-server set-password admin -./server/kernelwatch-server serve # http://127.0.0.1:8080 -``` - -## Ideas for later - -- Additional notification channels -- A JSON endpoint for scripting -- Grouping or tagging hosts (prod/staging, location) +| Page | What's in it | +|------|--------------| +| [How it works](docs/how-it-works.md) | Status rules and how the agent collects each fact | +| [Server](docs/server.md) | Installing and upgrading, the admin commands | +| [Reverse proxy and access control](docs/reverse-proxy.md) | TLS with Caddy or nginx, CloudPanel, Authelia | +| [Agents](docs/agents.md) | Adding hosts, `agent/deploy.sh`, agent options | +| [Alerts and monitoring](docs/alerts.md) | ntfy alerts for stale, reboot and update, heartbeat monitoring | +| [Operations](docs/operations.md) | `kernelwatch status --json` for scripts, backups and restore | +| [Security notes](docs/security.md) | How tokens, sandboxing and the dashboard are locked down | +| [Development](docs/development.md) | Running the tests, a local server, ideas for later | diff --git a/docs/agents.md b/docs/agents.md new file mode 100644 index 0000000..f85721a --- /dev/null +++ b/docs/agents.md @@ -0,0 +1,89 @@ +# Agents + +[← kernelwatch](../README.md) + +Installing the agent on hosts, one at a time or across the whole fleet. + +## Adding a host + +On the server: + +```sh +sudo kernelwatch add-host web01 +# prints a token, shown once +``` + +On the host (copy the `agent/` directory over, or clone the repo): + +```sh +sudo ./agent/install.sh --server https://kernelwatch.example.internal [--ca root.pem] +# paste the token when prompted +``` + +The installer puts the agent in `/usr/local/sbin`, writes `/etc/kernelwatch/agent.conf` +and `agent.token` (root, 0600), enables `kernelwatch-agent.timer` and sends a first +report. After that, the agent reports 2 minutes after boot and then hourly, with up +to 15 minutes of jitter. + +For unattended installs, set `KERNELWATCH_TOKEN=...` instead of using the prompt. + +Add `--with-needrestart` to also report services needing a restart (Debian +needs this; Ubuntu already has needrestart). It installs needrestart if +missing and sets it to *list* services after apt upgrades instead of asking +interactively. Delete `/etc/needrestart/conf.d/kernelwatch.conf` to undo that. + +Add `--with-apt-update` to refresh apt's package lists before each report +(recommended on Debian, see "Fresh package lists" in [How it works](how-it-works.md)). It's the same as running `apt update` +hourly: lists only, nothing is installed. If apt is busy, the refresh is +skipped and the report goes ahead. `--without-apt-update` turns it off; +re-running the installer with neither keeps the current setting. + +Useful on a host: + +```sh +sudo kernelwatch-agent --print # see exactly what would be sent +sudo systemctl start kernelwatch-agent # report now +systemctl list-timers kernelwatch-agent.timer +journalctl -u kernelwatch-agent +``` + +## Deploying to many hosts + +`agent/deploy.sh` does all of the above over SSH from your workstation's +checkout, so hosts need neither git nor Gitea access. Set it up once: + +```sh +cp agent/deploy.conf.example agent/deploy.conf # SERVER_URL, DASHBOARD (ssh target) +cp agent/hosts.example agent/hosts # optional; --register fills it in +``` + +Then: + +```sh +agent/deploy.sh --register web01 db01 # register on the dashboard + install +agent/deploy.sh # upgrade every host in agent/hosts +agent/deploy.sh web01 # upgrade one +agent/deploy.sh --rotate web01 # new token, reinstall +agent/deploy.sh --dry-run # show the plan +agent/deploy.sh -- --with-needrestart # pass options through to install.sh +agent/deploy.sh -- --with-apt-update # refresh package lists before each report +``` + +For each host it copies the agent into a private temp directory and runs +`install.sh`, which sends a first report, then deletes the temp directory. +With `--register`/`--rotate`, it also runs +`sudo kernelwatch add-host --token-only` on the dashboard host and passes the +token to the host on SSH stdin. The token never appears on a command line or +in your terminal. A plain run is an upgrade: config and token stay as they +are. You'll get sudo prompts on each host, and on the dashboard when +registering, unless you have passwordless sudo. + +Both files are git-ignored. Host names default to each host's `hostname -s`; +put ` ` in `agent/hosts` to override. For a host your +workstation can't reach directly (e.g. IPv6-only while you're on IPv4), give it +a jump host in `~/.ssh/config` and `deploy.sh` works unchanged: + +``` +Host zeus + ProxyJump eurus +``` diff --git a/docs/alerts.md b/docs/alerts.md new file mode 100644 index 0000000..0896a25 --- /dev/null +++ b/docs/alerts.md @@ -0,0 +1,104 @@ +# Alerts and monitoring + +[← kernelwatch](../README.md) + +ntfy notifications for stale hosts, pending reboots and updates, plus heartbeat monitoring so you find out if kernelwatch itself stops. + +## Stale-host, reboot and update alerts (ntfy) + +The server can notify an [ntfy](https://ntfy.sh/) topic when a host stops +reporting and when its reports resume. Agents report hourly with up to 15 minutes +of jitter. Alerts use the same `stale_after_hours` as the dashboard (3 hours by +default), leaving room for ordinary delays. Newly registered hosts get that same +grace period to send their first report. + +Re-run `sudo ./server/install.sh` to install the alert timer when upgrading. +The installer preserves your existing config, so add these settings to +`/etc/kernelwatch/server.toml`: + +```toml +ntfy_url = "https://ntfy.example.com/kernelwatch" +ntfy_token = "" # optional access token with publish permission for this topic +ntfy_timeout_seconds = 10.0 +``` + +Subscribe to that topic in your ntfy app, then check delivery: + +```sh +sudo kernelwatch test-alert +systemctl list-timers kernelwatch-alerts.timer +``` + +`kernelwatch-alerts.timer` runs a separate, unprivileged check every five minutes, +even when no hosts report and nobody opens the dashboard. Notifications normally +arrive within about five minutes of crossing the stale threshold or receiving a +fresh report. Run `sudo kernelwatch check-alerts` to check immediately, or inspect +`journalctl -u kernelwatch-alerts.service` for delivery failures. + +- Each host gets one stale notification and one reporting-recovery notification + per detected outage. Successful sends are saved in SQLite, so routine checks + and server restarts don't repeat them. Recovery confirms reporting has resumed; + the host may still need updates or a reboot. +- Failed sends are retried on the next check, and a failure for one host doesn't + stop checks for the others. A recovery is sent only after a stale notification + was successfully delivered. A timeout or crash after ntfy accepted a message + can cause a duplicate on retry. +- An empty `ntfy_url` disables notifications. The timer reads its configuration + on every run; changing ntfy settings needs no restart. If you change + `stale_after_hours`, restart `kernelwatch.service` too so the dashboard uses the + new threshold. + +- **Reboot and update alerts.** A host that has stayed in `reboot` or `update` + for `status_alert_after_hours` (default 24) gets one notification listing the + reasons shown on the dashboard. The clock starts when the host entered that + status, so hourly reports don't restart it. Fixing the host (back to `ok`) + re-arms it. Going from `update` to `reboot` notifies again after another + period; going back down doesn't. Stale hosts are skipped, since the stale + alert covers them. Set `status_alert_after_hours = 0` to turn these off. + Upgrading starts the clock at the first check, so expect the first + notifications a day after you re-run `install.sh`. + +Use the topic's direct publish URL, with token authentication if needed; it must +accept the POST without a browser login or redirect. The topic and token stay +in the server config (root-owned, readable by the `kernelwatch` service group). +Agents need no changes. + +## Heartbeat: is kernelwatch itself running? + +Every alert above depends on `kernelwatch-alerts.timer` running on the dashboard +host. If that host is down, or the timer breaks, nothing tells you. A heartbeat +fixes this: kernelwatch pings an external monitor, and the monitor alerts when the +pings **stop**. [healthchecks.io](https://healthchecks.io) has a free tier; +Uptime Kuma's push monitors work the same way. + +1. In the monitor, create two checks and copy their ping URLs: + - **alerts**: period 5 minutes, grace 20 minutes. + - **backup**: period 1 day, grace a few hours (the timer fires about 03:30 and + can be up to 30 minutes late). +2. Add the URLs to `/etc/kernelwatch/server.toml` (no restart needed for the + alert check or the backup; they read it on every run): + + ```toml + heartbeat_url = "https://hc-ping.com/" + backup_heartbeat_url = "https://hc-ping.com/" + ``` + +3. Check both: `sudo kernelwatch test-heartbeat` pings each configured URL once. + +What counts as a heartbeat: + +- `heartbeat_url` is pinged at the end of every alert check (every five minutes) + that sent all its notifications. If ntfy delivery is failing, the ping is + skipped on purpose, so the monitor also notices a broken alert pipeline. It's + pinged even with no `ntfy_url`, since the timer is still alive. +- `backup_heartbeat_url` is pinged after each successful nightly backup, so a + timer that never ran, or a backup that failed, shows up as a missing ping. + A manual `kernelwatch backup` doesn't ping. +- A heartbeat that can't be delivered is logged (status code or error type, never + the URL) and never fails the check or the backup. + +The pings leave from the dashboard host, so a dead host is exactly what stops +them. Set the monitor to notify you some way that doesn't depend on that host: +email, the monitor's own app, or ntfy.sh. Not a ntfy server running behind it. +The URLs are secrets (whoever has one can fake a heartbeat), so keep +`server.toml` readable by root and the `kernelwatch` group only. diff --git a/docs/development.md b/docs/development.md new file mode 100644 index 0000000..e668761 --- /dev/null +++ b/docs/development.md @@ -0,0 +1,44 @@ +# Development + +[← kernelwatch](../README.md) + +Running the tests and a local server. + +```sh +make test # unit + integration tests (stdlib unittest) +make lint # shellcheck, if available +``` + +Gitea Actions (`.gitea/workflows/ci.yml`) runs both on every push to `main` +and every pull request: the tests on Python 3.10–3.13 (the versions on the +supported Ubuntu and Debian releases) and shellcheck on the shell scripts. + +The tests run a real server on an ephemeral port. They also run the real agent +script against stubbed `dpkg-query`/`apt-get`/`needrestart`/`uname` and a fake +filesystem root (`KERNELWATCH_ROOT`), including one end-to-end agent → server +report. + +Both installers (`agent/install.sh`, `server/install.sh`) run for real in the tests +against a fake root: `KERNELWATCH_ROOT` prefixes every path they write and skips +their root check, and `systemctl`, `apt-get`, `useradd` and the like are stubs that +log their arguments. Don't set it on a real host. + +`tests/test_docs.py` checks that every relative link and `#anchor` in the README +and `docs/` resolves, so move or rename a heading and it tells you what broke. + +Run a local server against a scratch database: + +```sh +printf 'db_path = "/tmp/kw.db"\nsecure_cookies = false\n' > /tmp/kw.toml +export KERNELWATCH_CONFIG=/tmp/kw.toml +./server/kernelwatch-server set-password admin +./server/kernelwatch-server serve # http://127.0.0.1:8080 +``` + +## Ideas for later + +- Additional notification channels +- An HTTP endpoint for `kernelwatch status`, behind a hashed API token and your + proxy's IP allow-list, if something has to poll remotely (the CLI already + covers scripting on the dashboard host) +- Grouping or tagging hosts (prod/staging, location) diff --git a/docs/how-it-works.md b/docs/how-it-works.md new file mode 100644 index 0000000..edbff1f --- /dev/null +++ b/docs/how-it-works.md @@ -0,0 +1,94 @@ +# How it works + +[← kernelwatch](../README.md) + +How each host's status is decided, and how the agent collects the facts behind it. + +Each host gets one status. When several apply, the worst one wins: + +| Status | Meaning | +|----------|---------| +| `stale` | No report in `stale_after_hours` (default 3h), or never. Other data can't be trusted. | +| `reboot` | A newer kernel is installed but not running, or `/run/reboot-required` exists. | +| `update` | A kernel or security update is available but not installed, services are running outdated libraries and need a restart, or apt's package lists are too old (`apt_stale_after_hours`) for "no updates" to mean anything. | +| `ok` | Running the newest installed kernel, with no security or kernel updates pending. | + +Each row also lists the reasons behind its status, and clicking a host shows +its full report and recent history. + +How the agent works it out: + +- **Running vs. installed kernel**, three ways: + - A newer `linux-image-*` installed than `uname -r` means a version upgrade. + - The build in `uname -v` (`Debian 6.12.57-1`, `#85-Ubuntu`, `#33~24.04.1-Ubuntu`) + is compared with the installed package version of the running kernel + (`6.12.57-1`, `6.8.0-85.85`, `6.14.0-33.33~24.04.1`). A mismatch means the + package was upgraded in place after boot; `uname -r` didn't change, but a + reboot is still needed. + - [`needrestart`](https://github.com/liske/needrestart)'s kernel result, for + build strings the server doesn't recognise (see "Services needing a restart", below). +- **Services needing a restart** (e.g. nginx still using the old OpenSSL + after an upgrade): from `needrestart -b`, if it's installed. Ubuntu ships it; + on Debian, install with `install.sh --with-needrestart`. Without it, the + Services column shows `?` and status isn't affected. needrestart has to + inspect every process, so it runs as root in its own unit, + `kernelwatch-needrestart.service`. That unit has no network access, only the + two capabilities needrestart needs, and list-only mode, so it never restarts + anything. It writes its results to `/run/kernelwatch/needrestart`, and the + unprivileged agent unit runs it just before each report and reads the file. + The agent never runs as root, and needrestart never gets network access. Fix it on the host: + `sudo needrestart -r a` (or restart the listed services), and the next report + clears it. +- **Ubuntu Livepatch**: with [Livepatch](https://ubuntu.com/security/livepatch) + (free for personal use with Ubuntu Pro), a newer kernel being installed doesn't + mean the running one is unpatched. If Livepatch is healthy (`applied` or + `nothing-to-apply`, checked, supported), a pending kernel reboot, or a + `/run/reboot-required` caused only by `linux-*` packages, shows as a note + instead of `reboot`, and the note gives the date by which the kernel must be + upgraded. Livepatch only fixes high and critical CVEs, and only until that + date, so cover ends 14 days before it and the host goes to `reboot` as usual. + Any other reboot reason (libc, systemd) still counts. If Livepatch is failing, + unsupported or in a state we don't know, the host gets no cover and the reason + is noted. Hosts without Livepatch are unaffected. `canonical-livepatch` needs + root and a snap cgroup, so like needrestart it runs in its own unit, + `kernelwatch-livepatch.service`, which writes `/run/kernelwatch/livepatch` + before each report. It's skipped when the snap isn't installed. +- **Agent version**: each report includes it. Hosts running an older agent + than the server shipped with get a note to run `agent/deploy.sh`; their status + isn't changed. +- **Hostname check**: each report includes the host's own name. If its first + DNS label differs from the name the host is registered under (ignoring case), + the row gets a note: "registered as web01 but reports itself as db01". This + catches a token copied to the wrong machine. It never changes the status. A + host you registered under a custom label (` ` in + `agent/hosts`) shows the note until you tell its agent which name to report: + `agent/deploy.sh iris -- --report-hostname iris` (or `install.sh + --report-hostname iris` on the host, which sets `REPORT_HOSTNAME` in + `agent.conf`). Upgrades and `--rotate` keep it; + `--default-report-hostname` removes it. That's the host's own say-so, so it + only silences the note for hosts you've deliberately named. +- **Available updates**: a simulated `apt-get dist-upgrade`. It is read-only, takes + no locks and writes no cache files. `dist-upgrade` is used so that new-ABI kernel + packages pulled in by the meta-package show up. Lines whose origin contains + `-security` count as security updates. +- **Fresh package lists**: the simulation only knows what apt's package lists + say, and the agent can't refresh them itself. Ubuntu refreshes them about once + a day. Debian doesn't by default unless `unattended-upgrades` is set up, so a + new kernel or security update can stay invisible until someone runs + `apt update`. Install with `--with-apt-update` and + `kernelwatch-apt-update.service` runs `apt-get update` just before each + report, so updates show up within the hour. Either way, lists older than + `apt_stale_after_hours` put the host in `update`. +- **Phased updates** (Ubuntu only): Ubuntu rolls some updates out gradually and + holds them back from a share of machines at first. apt doesn't offer these to + the host yet, so they aren't counted as available updates. They appear as + their own Phased column (hover for the packages, `–` on Debian), with the + list also on the host page. + They never affect status, because Ubuntu doesn't phase security updates and + there's nothing to act on until apt offers them. +- **Package list freshness**: the mtime of apt's update stamps. The agent + **doesn't run `apt update`** itself; it relies on the stock `apt-daily.timer`. + If that's disabled, the host shows `update` with "package lists N days old". + +The agent sends raw facts and the server decides what they mean, so you can +change the status rules without touching the agents. diff --git a/docs/operations.md b/docs/operations.md new file mode 100644 index 0000000..09ddafd --- /dev/null +++ b/docs/operations.md @@ -0,0 +1,107 @@ +# Operations + +[← kernelwatch](../README.md) + +Day-to-day tasks: querying the fleet from a script, and backing up the database. + +## Scripting: `kernelwatch status` + +`kernelwatch status` prints the fleet the way the dashboard shows it, from the +database, with no network port or token involved. It needs `sudo`, like the other +[admin commands](server.md#admin-commands). Run it over SSH from anywhere else. + +``` +$ sudo kernelwatch status +stale new01 ? (last seen never) + - never reported +reboot web01 6.8.0-136 -> 6.8.0-138 (last seen 1m ago) + - kernel: running 6.8.0-136, 6.8.0-138 installed + - 2 security updates pending +ok db01 6.12.57 (last seen 1m ago) +3 hosts: 1 stale, 1 reboot, 0 update, 1 ok +``` + +Hosts come worst first, in the dashboard's order, and use the same status logic +(Livepatch cover, the hostname note and so on). Narrow it with `--host NAME` and +`--level stale|reboot|update|ok` (repeatable); both also work with `--json`. + +`--json` is for scripts. It has `generated_at`, `counts` and `hosts`. The counts +always cover the whole fleet, and the filters only trim `hosts`. Each host has `name`, +`status`, `reasons`, `last_report_at` (UTC ISO 8601, or `null` if it never +reported), `last_report_age_seconds`, `os`, `kernel_running`, +`kernel_newest_installed`, `reboot_required`, `updates_pending`, +`security_updates`, `kernel_updates`, `services_need_restart`, `livepatch` +(or `null`), `uptime_seconds` and `agent_version`. Fields a host hasn't +reported are `null`, and the keys are always present. It never includes tokens +or password hashes. + +```sh +# hosts that need a reboot +sudo kernelwatch status --json | jq -r '.hosts[] | select(.status=="reboot") | .name' + +# one line per host that needs attention, with the reasons +sudo kernelwatch status --json --level reboot --level update | + jq -r '.hosts[] | "\(.name): \(.reasons | join("; "))"' + +# from your workstation; exits non-zero (for cron or a monitor) if any host is stale +ssh triton 'sudo kernelwatch status --json' | jq -e '.counts.stale == 0' >/dev/null +``` + +There's deliberately no HTTP endpoint for this. It would expose every host's +kernel and pending security updates to anything holding a token, and nothing +needs it yet. If something has to poll remotely, add one behind your proxy's +IP allow-list rather than relying on a token alone. + +## Backups + +Everything kernelwatch knows lives in one SQLite file, `/var/lib/kernelwatch/kernelwatch.db`: +host tokens (hashed), dashboard logins and report history. Without it you'd +re-register every host and reinstall its token. Don't copy the file while the +server runs, since recent writes can sit in its `-wal` sidecar. Use: + +```sh +sudo kernelwatch backup /var/lib/kernelwatch/backups/kernelwatch.db +``` + +This uses SQLite's online backup, so it's safe while hosts are reporting. It +replaces any existing file at that path and writes it mode 0600. It refuses to +overwrite the live database. The command runs as the `kernelwatch` user, so the +destination directory has to be writable by it (create one with +`sudo install -d -o kernelwatch -g kernelwatch -m 0700 /var/lib/kernelwatch/backups`), +then copy the result off the machine with your usual backup tool. + +### Nightly backups + +`server/install.sh` also enables `kernelwatch-backup.timer`, which runs +`kernelwatch scheduled-backup` at about 03:30 (up to 30 minutes late; a run missed +while the machine was off happens at the next boot). It writes +`/var/lib/kernelwatch/backups/kernelwatch-YYYY-MM-DD.db` (UTC date, mode 0600, +directory 0700) and then deletes dated backups that are `backup_keep_days` (default +7) or more days old. It deletes only files with exactly that name, and only after +the new backup succeeded, so a failing run never costs you the ones you have. Set +`backup_keep_days = 0` to keep them all. The unit can only write under +`/var/lib/kernelwatch`, so keep `backup_dir` there unless you give it more access. + +```sh +systemctl list-timers kernelwatch-backup.timer +journalctl -u kernelwatch-backup # a failed run shows up here +sudo systemctl start kernelwatch-backup # back up now +``` + +If a run fails, whether from an error, the 10-minute timeout, an out-of-memory +kill or a crash, systemd starts `kernelwatch-backup-failed.service` +(`OnFailure=`), which sends a high-priority message to your ntfy topic naming the +newest backup still on disk. The cause is in `journalctl -u kernelwatch-backup`. +Without `ntfy_url` it only logs that it had nothing to send to. If ntfy itself is +unreachable at that moment, the failure shows up only in the journal +(`journalctl -u kernelwatch-backup-failed`). It can't tell you that the timer +never ran at all, for example because the host was down; that needs a [heartbeat +monitor](alerts.md#heartbeat-is-kernelwatch-itself-running). You can check delivery with +`sudo kernelwatch notify-backup-failure`, which sends the same message. + +These copies sit on the dashboard host, so they protect against a corrupted or +mistakenly changed database but not against losing the machine. Copy +`/var/lib/kernelwatch/backups/` elsewhere with whatever you already back up with. + +To restore, stop the service, put the file at `db_path` owned by `kernelwatch` +(mode 0600), and start it again. The stale-alert state restores with it. diff --git a/docs/reverse-proxy.md b/docs/reverse-proxy.md new file mode 100644 index 0000000..3d9207d --- /dev/null +++ b/docs/reverse-proxy.md @@ -0,0 +1,190 @@ +# Reverse proxy and access control + +[← kernelwatch](../README.md) + +How to put TLS, and optionally extra access control, in front of the server. + +## TLS reverse proxy + +The server speaks plain HTTP on `127.0.0.1:8080`. Put a TLS proxy in front of it. +The agents and your browser both connect through it. + +**Caddy** (simplest): + +```caddyfile +kernelwatch.example.internal { + reverse_proxy 127.0.0.1:8080 +} +``` + +**nginx**: + +```nginx +server { + listen 443 ssl; + server_name kernelwatch.example.internal; + # ssl_certificate / ssl_certificate_key ... + location / { + proxy_pass http://127.0.0.1:8080; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + } +} +``` + +With either proxy, set `trust_proxy_headers = true` in `server.toml` so login +rate limiting sees real client IPs. + +If you use a private CA (e.g. Caddy's `tls internal`), give the agents its +root cert with `--ca` (see [Agents](agents.md#adding-a-host)). + +You can expose only `/api/v1/report` to the fleet network and keep the +dashboard on a VPN or tailnet. That's a proxy rule, not a kernelwatch setting. + +## CloudPanel + +CloudPanel gives each site its own Linux user and a document root at +`/home//htdocs//`. kernelwatch doesn't use that directory. +nginx forwards requests to the app; it doesn't serve kernelwatch's files. Install +with `server/install.sh` as in [Server](server.md), so the app runs as the `kernelwatch` user +with its data in `/var/lib/kernelwatch`, outside every site user's home. Leave +the document root empty, and keep your clone of this repo out of `htdocs`. + +1. **Pick a free port.** CloudPanel's Varnish setup can run an nginx backend + on 8080. Check with `ss -ltnp | grep ':8080\b'`. If it's taken, set another port + in `/etc/kernelwatch/server.toml` and restart (`sudo systemctl restart kernelwatch`): + + ```toml + listen_port = 8095 + trust_proxy_headers = true + ``` + + Check it: `curl -s http://127.0.0.1:8095/healthz` should print `ok`. + +2. **Create the site as a Reverse Proxy.** In CloudPanel: *Add Site → Create a + Reverse Proxy*, with your domain and Reverse Proxy URL + `http://127.0.0.1:8095`. CloudPanel can't change an existing site's type. If + the domain already exists as a PHP or static site, delete and recreate it. + Deleting a site also removes its site user and home directory, so move + anything you need out first. + +3. **TLS.** In the site's *SSL/TLS* tab, issue a Let's Encrypt certificate. Agents + then need no `--ca`. + +4. **Check the generated vhost** (the site's *Vhost* tab). The `location` + that proxies to the app should pass the original `Host` header and the + client address: + + ```nginx + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + ``` + + Add them if they're missing. Without `Host`, logins fail the origin check + with "cross-origin request refused". Without `X-Forwarded-For`, every login + appears to come from 127.0.0.1, so one person's failed attempts lock everyone out. + Also check that the login page is styled. If `/static/style.css` returns 404, + a static-file `location` in the template is looking in the empty document root + instead of proxying. Make it fall through to the proxy, or remove it. + +5. **Optionally restrict the dashboard.** The site's domain is public, so the + login page is reachable from the internet unless you limit it. Agents only + need `/api/v1/report`. In the Vhost tab, add an `allow ; deny all;` + to `location /` and a separate unrestricted + `location = /api/v1/report { proxy_pass http://127.0.0.1:8095; }`. + Changes made in the Vhost tab persist. Back them up before + recreating the site. + To require a login through Authelia instead of an IP allowlist, see + [Authelia (forward auth)](#authelia-forward-auth). + +## Authelia (forward auth) + +If you already run [Authelia](https://www.authelia.com/), you can put it in +front of the dashboard. That adds Authelia's 2FA and single sign-on, and +kernelwatch's own login still applies behind it. You log in to both, but +Authelia's remember-me makes that rare. This uses nginx's `auth_request`, so +you don't need an OIDC client. + +**Agents must bypass Authelia.** They authenticate with their bearer token and +can't follow a login redirect. If Authelia covers `/api/v1/report`, every +report gets a redirect instead of a 401 or 204, and the whole fleet goes stale +within 3 hours. + +1. **Authelia `access_control`.** Rules are checked in order, so put the bypass + first, and keep a single `rules:` list: + + ```yaml + access_control: + default_policy: two_factor + rules: + - domain: kernelwatch.example.com + resources: + - '^/api/v1/report$' + - '^/healthz$' + policy: bypass + - domain: "*.example.com" + policy: two_factor + ``` + + For the redirect to the login page to work, your `session.cookies` entry has + to cover the dashboard's domain and set `authelia_url`. Without them, browsers + get a bare 401 page. Authelia reads this file only at startup, so restart it + after editing (in Kubernetes: `kubectl rollout restart deployment/authelia`). + Check the file first with `authelia validate-config`. + +2. **nginx.** Add an internal location for Authelia's check, an exact-match + location for the agents with no check, and the check on `location /`. + For CloudPanel, edit the site's *Vhost* tab: leave the template's + `@reverse_proxy` block alone and add or replace these: + + ```nginx + # Authelia's check (internal subrequest only) + location = /internal/authelia/authz { + internal; + proxy_pass https://auth.example.com/api/authz/auth-request; + proxy_http_version 1.1; + proxy_ssl_server_name on; + proxy_set_header Host auth.example.com; + proxy_set_header X-Original-Method $request_method; + proxy_set_header X-Original-URL $scheme://$http_host$request_uri; + proxy_set_header X-Forwarded-For $remote_addr; + proxy_set_header Content-Length ""; + proxy_set_header Connection ""; + proxy_pass_request_body off; + } + + # Agents: token auth only + location = /api/v1/report { + try_files $uri @reverse_proxy; + } + + # Dashboard: Authelia first, then kernelwatch's login + location / { + auth_request /internal/authelia/authz; + auth_request_set $redirection_url $upstream_http_location; + error_page 401 =302 $redirection_url; + try_files $uri @reverse_proxy; + } + ``` + + Without CloudPanel, use `proxy_pass http://127.0.0.1:8095;` plus the `Host` + and `X-Forwarded-For` headers in place of `try_files ... @reverse_proxy`. If + Authelia runs on the same machine, point the check straight at it (e.g. + `http://127.0.0.1:9091/api/authz/auth-request`) and drop the + `proxy_ssl_server_name` and `Host` lines. Keep `location ^~ /.well-known` + unprotected so certificate renewals still work. If something monitors + `/healthz`, give it an exact-match location like the agents' one. + +3. **Check it.** + + ```sh + curl -sI https://kernelwatch.example.com/ | head -3 + # 302, Location pointing at Authelia + + curl -si -X POST https://kernelwatch.example.com/api/v1/report | head -1 + # 401 from kernelwatch (no token), not a 302 + ``` + + Then run `sudo systemctl start kernelwatch-agent` on one host and check + that its *Last seen* updates. If the POST gets a 302, the agents' location + isn't matching. Fix that before the fleet goes stale. diff --git a/docs/security.md b/docs/security.md new file mode 100644 index 0000000..efe27c0 --- /dev/null +++ b/docs/security.md @@ -0,0 +1,38 @@ +# Security notes + +[← kernelwatch](../README.md) + +How kernelwatch is locked down, and what it deliberately can't do. + +- **Host identity comes from the token, not the payload.** A host can only + report as itself. Tokens are 256-bit random values; only their SHA-256 is stored. +- **Report rate limit.** A report arriving less than `report_min_interval_seconds` + (default 30) after the host's previous one gets HTTP 429 with a `Retry-After` + header, and isn't stored. So a stuck agent or a leaked token can't flood the + database or push real history off the host page. The agent's curl waits out the + `Retry-After` and retries, so running `systemctl start kernelwatch-agent` twice + in a row just pauses briefly. Set it to `0` to disable. +- **Livepatch status** runs in a separate root unit with no network access and a + read-only filesystem. It has no capability bound, syscall filter or + `NoNewPrivileges`, because the snap's setuid `snap-confine` can't run under + them (tested: `NoNewPrivileges=yes` fails with "cannot change profile for the + next exec call"). It only runs `canonical-livepatch status`. +- **needrestart** runs in a separate root unit with `PrivateNetwork=yes`, a + capability set of just `CAP_SYS_PTRACE` + `CAP_DAC_READ_SEARCH` (to read other + processes' memory maps), a read-only filesystem except `/run/kernelwatch`, + and `-r l` (list, never restart). +- **apt-get update** (with `--with-apt-update`) runs as root with network + access, like apt's own `apt-daily.service`, but sandboxed: no access to home + directories, devices or kernel settings. apt drops to its `_apt` user for the + downloads, and nothing gets installed. +- **The agent** runs as a throwaway unprivileged user (`DynamicUser=yes`) with + no capabilities, a read-only filesystem view and a syscall filter. The token + reaches it through `LoadCredential=` and goes to curl on stdin, so it never + appears in a process listing. +- **The dashboard** uses scrypt-hashed passwords, server-side sessions, + `HttpOnly` + `Secure` + `SameSite=Strict` cookies, an Origin check on form + posts, per-IP login rate limiting, and a strict CSP. Everything a host + reports is HTML-escaped. +- **It's read-only by design.** The server can't make hosts do anything. + Adding remote actions (like "reboot this host") would turn it into a + remote-execution system; think hard before doing that. diff --git a/docs/server.md b/docs/server.md new file mode 100644 index 0000000..dc185a8 --- /dev/null +++ b/docs/server.md @@ -0,0 +1,44 @@ +# Server + +[← kernelwatch](../README.md) + +Installing and upgrading the dashboard server, and the admin commands. + +## Install and upgrade + +On the dashboard host: + +```sh +git clone && cd kernel-automation +sudo ./server/install.sh +sudo kernelwatch set-password admin # dashboard login +``` + +This installs to `/opt/kernelwatch` and keeps config in `/etc/kernelwatch/server.toml` +(see [`server/server.toml.example`](../server/server.toml.example)) and data in +`/var/lib/kernelwatch`. The `kernelwatch.service` unit runs it as the unprivileged +`kernelwatch` user. Re-run `install.sh` to upgrade; it keeps your config. + +The server speaks plain HTTP on `127.0.0.1:8080`. Put a TLS reverse proxy in front +of it; [Reverse proxy and access control](reverse-proxy.md) has the setups. Then +[add hosts](agents.md), and set up [alerts](alerts.md) and +[backups](operations.md#backups). + +## Admin commands + +``` +sudo kernelwatch add-host NAME register a host, print its token (--token-only for scripts) +sudo kernelwatch rotate-token NAME issue a new token (old one stops working) +sudo kernelwatch remove-host NAME delete a host and its history +sudo kernelwatch list-hosts hosts and when they last reported +sudo kernelwatch status [--json] fleet status like the dashboard (--host, --level to filter) +sudo kernelwatch set-password USER create a user / change password (logs out their sessions) +sudo kernelwatch remove-user USER +sudo kernelwatch list-users +sudo kernelwatch backup PATH write a consistent copy of the database (safe while running) +sudo kernelwatch scheduled-backup dated copy in backup_dir, then prune old ones (what the timer runs) +sudo kernelwatch notify-backup-failure send the failed-backup notification now (also runs on failure) +sudo kernelwatch check-alerts check for stale, recovered, reboot and update alerts now +sudo kernelwatch test-alert send a test notification to the configured ntfy topic +sudo kernelwatch test-heartbeat ping the configured heartbeat URLs once and report +``` diff --git a/server/install.sh b/server/install.sh index 70b80e9..f6282b8 100755 --- a/server/install.sh +++ b/server/install.sh @@ -5,7 +5,7 @@ # # Installs to /opt/kernelwatch, config in /etc/kernelwatch/server.toml (kept # on upgrade), data in /var/lib/kernelwatch. Then put a TLS reverse proxy in -# front (see README) and create a dashboard user: sudo kernelwatch set-password admin +# front (see docs/reverse-proxy.md) and create a dashboard user: sudo kernelwatch set-password admin set -euo pipefail here=$(cd "$(dirname "$0")" && pwd) diff --git a/tests/test_docs.py b/tests/test_docs.py new file mode 100644 index 0000000..a39c769 --- /dev/null +++ b/tests/test_docs.py @@ -0,0 +1,71 @@ +"""The README and docs/ pages link to each other; keep those links from rotting.""" + +import os +import re +import unittest + +from helpers import REPO + +PAGES = ["README.md"] + sorted(f"docs/{n}" for n in os.listdir(os.path.join(REPO, "docs")) + if n.endswith(".md")) + + +def read(rel): + with open(os.path.join(REPO, rel)) as f: + return f.read() + + +def strip_code(text): + """Drop fenced blocks and inline code, where `[x](y)` is an example, not a link.""" + text = re.sub(r"^```.*?^```", "", text, flags=re.S | re.M) + return re.sub(r"`[^`\n]*`", "", text) + + +def slug(heading): + """The anchor Gitea/GitHub make for a heading.""" + heading = heading.replace("`", "").strip().lower() + return re.sub(r"\s", "-", re.sub(r"[^\w\s-]", "", heading)) + + +def anchors(rel): + text = re.sub(r"^```.*?^```", "", read(rel), flags=re.S | re.M) + return {slug(m.group(2)) for m in re.finditer(r"^(#{1,6})\s+(.*)$", text, re.M)} + + +def links(rel): + for m in re.finditer(r"\[[^\]]*\]\(([^)\s]+)\)", strip_code(read(rel)).replace("\n", " ")): + target = m.group(1) + if not re.match(r"[a-z]+:", target): # skip https:, mailto: + yield target + + +class DocsLinksTest(unittest.TestCase): + def test_relative_links_and_anchors_resolve(self): + problems = [] + for page in PAGES: + for target in links(page): + path, _, fragment = target.partition("#") + dest = os.path.normpath(os.path.join(os.path.dirname(page), path)) if path else page + if not os.path.exists(os.path.join(REPO, dest)): + problems.append(f"{page}: {target} -> {dest} does not exist") + elif fragment and dest.endswith(".md") and fragment not in anchors(dest): + problems.append(f"{page}: {target} -> no heading #{fragment} in {dest}") + self.assertEqual(problems, []) + + def test_every_docs_page_is_linked_from_the_readme(self): + linked = {os.path.normpath(t.partition("#")[0]) for t in links("README.md")} + self.assertEqual(sorted(set(PAGES[1:]) - linked), []) + + def test_every_docs_page_links_back_to_the_readme(self): + for page in PAGES[1:]: + self.assertIn("../README.md", set(links(page)), page) + + def test_slug_matches_how_gitea_names_anchors(self): + self.assertEqual(slug("Heartbeat: is kernelwatch itself running?"), + "heartbeat-is-kernelwatch-itself-running") + self.assertEqual(slug("Scripting: `kernelwatch status`"), "scripting-kernelwatch-status") + self.assertEqual(slug("Authelia (forward auth)"), "authelia-forward-auth") + + +if __name__ == "__main__": + unittest.main()