commit 07749b01b088d2a4fab4fbdd3efabcf70fd377e5 Author: patrick Date: Sat Oct 17 10:15:06 2026 -0400 Scaffold kernelwatch: fleet kernel status agent and dashboard Agent: bash script run hourly by a hardened systemd timer on Debian 12/13 and Ubuntu 24.04. Collects running vs installed kernel (needrestart when available), pending/security updates via a read-only apt simulation, reboot-required state and apt list freshness, and POSTs them as JSON. Server: stdlib-only Python + SQLite (system python3 >= 3.11). Token-bound ingest API, login-protected dashboard with per-host status (stale/reboot/update/ok) and history, admin CLI, systemd unit and installer. Co-Authored-By: Claude Opus 5.5 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4730077 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +__pycache__/ +*.pyc +*.db +*.db-wal +*.db-shm diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..cb938c2 --- /dev/null +++ b/Makefile @@ -0,0 +1,7 @@ +.PHONY: test lint + +test: + python3 -m unittest discover -s tests + +lint: + shellcheck agent/kernelwatch-agent agent/install.sh server/install.sh server/kernelwatch.sh diff --git a/README.md b/README.md new file mode 100644 index 0000000..9a40456 --- /dev/null +++ b/README.md @@ -0,0 +1,194 @@ +# kernelwatch + +A small, self-hosted dashboard that shows whether each machine in a Debian/Ubuntu +fleet is running its newest kernel, has updates waiting, or needs a reboot. + +- **Agent**: a bash script run hourly by a systemd timer on each host. It + collects facts and POSTs them as JSON. It runs no daemon and listens on no port. +- **Server**: a standard-library Python app with SQLite. It has a token-authenticated + ingest API and a login-protected dashboard. You don't need pip, a venv or a + build step. + +Supported: agents on **Debian 12/13** and **Ubuntu 24.04 LTS**; server on +**Debian 12+** or **Ubuntu 24.04** (needs the system `python3` ≥ 3.11). + +``` + host ──(systemd timer)── kernelwatch-agent ──HTTPS POST /api/v1/report──┐ + host ──(systemd timer)── kernelwatch-agent ─────────────────────────────┤ + ▼ + browser ──HTTPS──▶ Caddy/nginx ──▶ kernelwatch (127.0.0.1:8080) ──▶ SQLite +``` + +## What the dashboard tells you + +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, 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**: if [`needrestart`](https://github.com/liske/needrestart) + is installed, the agent uses `needrestart -b -k`, which also catches + ABI-compatible upgrades where the package name stays the same. Otherwise it + compares `uname -r` with the newest installed `linux-image-*` package. + Ubuntu 24.04 ships needrestart by default. **On Debian, install it** + (`apt install needrestart`) for accurate results. +- **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. +- **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: + +```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. + +### 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. + +## 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. + +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 +``` + +## Server admin commands + +``` +sudo kernelwatch add-host NAME register a host, print its token +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 set-password USER create a user / change password (logs out their sessions) +sudo kernelwatch remove-user USER +sudo kernelwatch list-users +``` + +## 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. +- **The agent** runs from a systemd unit with an empty capability set, a + read-only filesystem view and a syscall filter. It runs as uid 0 only because + Ubuntu's `/boot/vmlinuz-*` files are root-only, and needrestart has to read + them. 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 +``` + +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. + +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 + +- Alerts on status changes (email/ntfy/webhook) +- Ubuntu Livepatch / Pro status, so live-patched hosts aren't flagged for reboot +- A JSON endpoint for scripting +- Grouping or tagging hosts (prod/staging, location) diff --git a/agent/agent.conf.example b/agent/agent.conf.example new file mode 100644 index 0000000..a84cb2e --- /dev/null +++ b/agent/agent.conf.example @@ -0,0 +1,14 @@ +# /etc/kernelwatch/agent.conf + +# Base URL of the kernelwatch server (the agent POSTs to /api/v1/report). +SERVER_URL=https://kernelwatch.example.internal + +# The host token is read from the systemd credential when run by the timer. +# This path is only used for manual runs (sudo kernelwatch-agent). +TOKEN_FILE=/etc/kernelwatch/agent.token + +# CA bundle for a server certificate signed by a private CA (optional). +#CA_FILE=/etc/kernelwatch/ca.pem + +# curl timeout in seconds. +#TIMEOUT=30 diff --git a/agent/install.sh b/agent/install.sh new file mode 100755 index 0000000..a01f3ac --- /dev/null +++ b/agent/install.sh @@ -0,0 +1,83 @@ +#!/usr/bin/env bash +# Install or upgrade kernelwatch-agent on a Debian 12/13 or Ubuntu 24.04 host. +# +# sudo ./install.sh --server https://kernelwatch.example.internal [--ca ca.pem] +# +# The host token (from `kernelwatch add-host ` on the server) is read +# from the KERNELWATCH_TOKEN environment variable or prompted for, so it never +# lands in shell history. Re-running without --server keeps the existing config. +set -euo pipefail + +here=$(cd "$(dirname "$0")" && pwd) +server= +ca= + +while (($#)); do + case $1 in + --server) server=${2:?--server needs a URL}; shift 2 ;; + --ca) ca=${2:?--ca needs a file}; shift 2 ;; + -h | --help) sed -n '2,8s/^# \{0,1\}//p' "$0"; exit 0 ;; + *) echo "unknown argument: $1" >&2; exit 2 ;; + esac +done + +[[ $(id -u) == 0 ]] || { echo "run as root" >&2; exit 1; } + +# shellcheck source=/dev/null +. /etc/os-release +case "$ID:$VERSION_ID" in +debian:12 | debian:13 | ubuntu:24.04) ;; +*) echo "warning: untested OS $PRETTY_NAME; continuing" >&2 ;; +esac + +if ! command -v curl >/dev/null; then + apt-get install -y --no-install-recommends curl ca-certificates +fi +if ! command -v needrestart >/dev/null; then + echo "note: needrestart is not installed; kernel ABI-compatible upgrades won't be detected." >&2 + echo " Install it with: apt-get install needrestart" >&2 +fi + +install -d -m 0755 /etc/kernelwatch +install -m 0755 "$here/kernelwatch-agent" /usr/local/sbin/kernelwatch-agent +install -m 0644 "$here/kernelwatch-agent.service" "$here/kernelwatch-agent.timer" /etc/systemd/system/ + +if [[ -n $ca ]]; then + install -m 0644 "$ca" /etc/kernelwatch/ca.pem +fi + +if [[ -n $server ]]; then + { + echo "SERVER_URL=$server" + echo "TOKEN_FILE=/etc/kernelwatch/agent.token" + [[ -e /etc/kernelwatch/ca.pem ]] && echo "CA_FILE=/etc/kernelwatch/ca.pem" + } >/etc/kernelwatch/agent.conf + chmod 0644 /etc/kernelwatch/agent.conf +elif [[ ! -e /etc/kernelwatch/agent.conf ]]; then + echo "no /etc/kernelwatch/agent.conf yet; pass --server URL" >&2 + exit 1 +fi + +if [[ ! -s /etc/kernelwatch/agent.token || -n ${KERNELWATCH_TOKEN:-} ]]; then + token=${KERNELWATCH_TOKEN:-} + if [[ -z $token ]]; then + read -r -s -p "Host token: " token + echo + fi + [[ -n $token ]] || { echo "empty token" >&2; exit 1; } + (umask 077 && printf '%s\n' "$token" >/etc/kernelwatch/agent.token) +fi +chown root:root /etc/kernelwatch/agent.token +chmod 0600 /etc/kernelwatch/agent.token + +systemctl daemon-reload +systemctl enable --now kernelwatch-agent.timer + +echo "Sending first report..." +if systemctl start kernelwatch-agent.service; then + echo "OK. Check the dashboard, or: journalctl -u kernelwatch-agent" +else + echo "First report failed:" >&2 + journalctl -u kernelwatch-agent -n 20 --no-pager >&2 + exit 1 +fi diff --git a/agent/kernelwatch-agent b/agent/kernelwatch-agent new file mode 100755 index 0000000..abc288f --- /dev/null +++ b/agent/kernelwatch-agent @@ -0,0 +1,257 @@ +#!/usr/bin/env bash +# kernelwatch-agent: collect kernel/update state on a Debian or Ubuntu host and +# report it to the kernelwatch server. Run by kernelwatch-agent.timer. +# +# The agent only gathers facts; the server decides what they mean, so status +# rules can change without redeploying agents. +set -euo pipefail + +AGENT_VERSION=0.1.0 + +# Prefix for every file the agent reads. Only the test suite sets this. +ROOT=${KERNELWATCH_ROOT:-} +CONF=${KERNELWATCH_CONF:-$ROOT/etc/kernelwatch/agent.conf} + +usage() { + cat <&2 + exit 1 +} + +# --- JSON helpers ----------------------------------------------------------- + +json_str() { + local s + s=$(printf '%s' "$1" | tr -d '\000-\037') + s=${s//\\/\\\\} + s=${s//\"/\\\"} + printf '"%s"' "$s" +} + +# Integer or null. +json_int() { + if [[ $1 =~ ^-?[0-9]+$ ]]; then printf '%s' "$1"; else printf 'null'; fi +} + +json_bool() { + if [[ $1 == 1 ]]; then printf 'true'; else printf 'false'; fi +} + +# JSON array of strings from newline-separated input on stdin. +json_str_array() { + local line first=1 + printf '[' + while IFS= read -r line; do + [[ -z $line ]] && continue + ((first)) || printf ',' + first=0 + json_str "$line" + done + printf ']' +} + +# --- config ----------------------------------------------------------------- + +SERVER_URL= +TOKEN_FILE=$ROOT/etc/kernelwatch/agent.token +CA_FILE= +TIMEOUT=30 + +load_config() { + [[ -r $CONF ]] || return 0 + local key value + while IFS='=' read -r key value; do + key=${key//[[:space:]]/} + [[ -z $key || $key == \#* ]] && continue + value=${value#"${value%%[![:space:]]*}"} + value=${value%"${value##*[![:space:]]}"} + value=${value#\"} + value=${value%\"} + case $key in + SERVER_URL) SERVER_URL=$value ;; + TOKEN_FILE) TOKEN_FILE=$value ;; + CA_FILE) CA_FILE=$value ;; + TIMEOUT) TIMEOUT=$value ;; + *) echo "kernelwatch-agent: ignoring unknown config key '$key'" >&2 ;; + esac + done <"$CONF" +} + +# --- collectors ------------------------------------------------------------- + +os_release_field() { + local key=$1 k v + [[ -r $ROOT/etc/os-release ]] || return 0 + while IFS='=' read -r k v; do + if [[ $k == "$key" ]]; then + v=${v#\"} + v=${v%\"} + printf '%s' "$v" + return 0 + fi + done <"$ROOT/etc/os-release" +} + +# Installed kernel image versions (e.g. 6.12.57+deb13-amd64), oldest first. +installed_kernels() { + dpkg-query -W -f='${db:Status-Abbrev} ${Package}\n' \ + 'linux-image-[0-9]*' 'linux-image-unsigned-[0-9]*' 2>/dev/null | + awk '$1 == "ii" { print $2 }' | + grep -v -- '-dbg$' | + sed -E 's/^linux-image-(unsigned-)?//' | + sort -uV || true +} + +# Sets NR_KSTA / NR_KEXP from `needrestart -b`. KSTA: 0 unknown, 1 current, +# 2 ABI-compatible upgrade pending, 3 version upgrade pending. +NR_KSTA= +NR_KEXP= +read_needrestart() { + command -v needrestart >/dev/null 2>&1 || return 0 + local line + while IFS= read -r line; do + case $line in + NEEDRESTART-KSTA:*) NR_KSTA=${line#*: } ;; + NEEDRESTART-KEXP:*) NR_KEXP=${line#*: } ;; + esac + done < <(needrestart -b -k -r l 2>/dev/null || true) +} + +# Simulated dist-upgrade. Reads only: no locks, no cache files written. +# dist-upgrade (not upgrade) so new-ABI kernel packages pulled in by the +# meta-package show up. +apt_simulation() { + apt-get -s -q \ + -o Debug::NoLocking=true \ + -o Dir::Cache::pkgcache= \ + -o Dir::Cache::srcpkgcache= \ + dist-upgrade 2>/dev/null || true +} + +# Seconds since apt last refreshed its package lists, or empty if unknown. +apt_lists_age() { + local newest=0 f m + for f in \ + "$ROOT/var/lib/apt/periodic/update-success-stamp" \ + "$ROOT/var/lib/apt/periodic/update-stamp" \ + "$ROOT/var/lib/apt/lists/partial"; do + [[ -e $f ]] || continue + m=$(stat -c %Y "$f" 2>/dev/null) || continue + ((m > newest)) && newest=$m + done + ((newest > 0)) && printf '%s' $(($(date +%s) - newest)) + return 0 +} + +uptime_seconds() { + local up _ + [[ -r $ROOT/proc/uptime ]] || return 0 + read -r up _ <"$ROOT/proc/uptime" + printf '%s' "${up%%.*}" +} + +build_report() { + local running newest kernels sim inst reboot_file=0 reboot_pkgs= + + running=$(uname -r) + kernels=$(installed_kernels) + newest=$(tail -n1 <<<"$kernels") + read_needrestart + + sim=$(apt_simulation) + inst=$(grep '^Inst ' <<<"$sim" || true) + + if [[ -e $ROOT/run/reboot-required ]]; then + reboot_file=1 + [[ -r $ROOT/run/reboot-required.pkgs ]] && reboot_pkgs=$(sort -u "$ROOT/run/reboot-required.pkgs") + fi + + printf '{' + printf '"agent_version":%s,' "$(json_str "$AGENT_VERSION")" + printf '"reported_hostname":%s,' "$(json_str "$(hostname -f 2>/dev/null || hostname)")" + printf '"os_id":%s,' "$(json_str "$(os_release_field ID)")" + printf '"os_version_id":%s,' "$(json_str "$(os_release_field VERSION_ID)")" + printf '"os_pretty_name":%s,' "$(json_str "$(os_release_field PRETTY_NAME)")" + printf '"kernel_running":%s,' "$(json_str "$running")" + printf '"kernel_build":%s,' "$(json_str "$(uname -v)")" + printf '"kernels_installed":%s,' "$(json_str_array <<<"$kernels")" + printf '"kernel_newest_installed":%s,' "$(json_str "$newest")" + printf '"needrestart_ksta":%s,' "$(json_int "$NR_KSTA")" + printf '"needrestart_kexp":%s,' "$(json_str "$NR_KEXP")" + printf '"reboot_required":%s,' "$(json_bool "$reboot_file")" + printf '"reboot_required_pkgs":%s,' "$(json_str_array <<<"$reboot_pkgs")" + printf '"upgradable_count":%s,' "$(json_int "$(grep -c . <<<"$inst" || true)")" + printf '"security_count":%s,' "$(json_int "$(grep -ci 'security' <<<"$inst" || true)")" + printf '"kernel_upgradable":%s,' "$(awk '$2 ~ /^linux-image-/ { print $2 }' <<<"$inst" | json_str_array)" + printf '"apt_lists_age_seconds":%s,' "$(json_int "$(apt_lists_age)")" + printf '"uptime_seconds":%s' "$(json_int "$(uptime_seconds)")" + printf '}\n' +} + +send_report() { + local payload=$1 token + [[ -n $SERVER_URL ]] || die "SERVER_URL is not set in $CONF" + + # Prefer the systemd credential (LoadCredential=token:...). + if [[ -n ${CREDENTIALS_DIRECTORY:-} && -r $CREDENTIALS_DIRECTORY/token ]]; then + token=$(<"$CREDENTIALS_DIRECTORY/token") + elif [[ -r $TOKEN_FILE ]]; then + token=$(<"$TOKEN_FILE") + else + die "no token: neither \$CREDENTIALS_DIRECTORY/token nor $TOKEN_FILE is readable" + fi + token=${token//[[:space:]]/} + [[ -n $token ]] || die "token is empty" + + local -a args=(--silent --show-error --fail-with-body + --max-time "$TIMEOUT" --retry 3 --retry-delay 10 --retry-connrefused + --header 'Content-Type: application/json' + --data-binary "$payload" + --config -) + [[ -n $CA_FILE ]] && args+=(--cacert "$CA_FILE") + + # Token goes in via a curl config on stdin so it never appears in argv. + printf 'header = "Authorization: Bearer %s"\n' "$token" | + curl "${args[@]}" "${SERVER_URL%/}/api/v1/report" >/dev/null +} + +main() { + local mode=send + case ${1:-} in + --print) mode=print ;; + --help | -h) + usage + return 0 + ;; + "") ;; + *) + usage >&2 + return 2 + ;; + esac + + load_config + local report + report=$(build_report) + + if [[ $mode == print ]]; then + printf '%s\n' "$report" + else + send_report "$report" + echo "kernelwatch-agent: report sent to $SERVER_URL" + fi +} + +main "$@" diff --git a/agent/kernelwatch-agent.service b/agent/kernelwatch-agent.service new file mode 100644 index 0000000..7f52b15 --- /dev/null +++ b/agent/kernelwatch-agent.service @@ -0,0 +1,36 @@ +[Unit] +Description=Report kernel and update status to kernelwatch +Wants=network-online.target +After=network-online.target apt-daily.service + +[Service] +Type=oneshot +ExecStart=/usr/local/sbin/kernelwatch-agent +LoadCredential=token:/etc/kernelwatch/agent.token + +# Runs as root only so needrestart can read the root-only kernel images in +# /boot (mode 0600 on Ubuntu). It holds no capabilities and sees a read-only +# filesystem. +User=root +CapabilityBoundingSet= +AmbientCapabilities= +NoNewPrivileges=yes +ProtectSystem=strict +ProtectHome=yes +PrivateTmp=yes +PrivateDevices=yes +ProtectKernelTunables=yes +ProtectKernelModules=yes +ProtectKernelLogs=yes +ProtectControlGroups=yes +ProtectClock=yes +ProtectHostname=yes +RestrictNamespaces=yes +RestrictRealtime=yes +RestrictSUIDSGID=yes +LockPersonality=yes +MemoryDenyWriteExecute=yes +RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 +SystemCallArchitectures=native +SystemCallFilter=@system-service +UMask=0077 diff --git a/agent/kernelwatch-agent.timer b/agent/kernelwatch-agent.timer new file mode 100644 index 0000000..c6cf66b --- /dev/null +++ b/agent/kernelwatch-agent.timer @@ -0,0 +1,13 @@ +[Unit] +Description=Periodically report kernel and update status to kernelwatch + +[Timer] +# Report soon after boot so a reboot shows up on the dashboard quickly, +# then hourly with jitter so the fleet doesn't report all at once. +OnBootSec=2min +OnCalendar=hourly +RandomizedDelaySec=15min +Persistent=true + +[Install] +WantedBy=timers.target diff --git a/server/install.sh b/server/install.sh new file mode 100755 index 0000000..de95e1c --- /dev/null +++ b/server/install.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash +# Install or upgrade the kernelwatch server on Debian 12/13 or Ubuntu 24.04. +# +# sudo ./install.sh +# +# 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 +set -euo pipefail + +here=$(cd "$(dirname "$0")" && pwd) +[[ $(id -u) == 0 ]] || { echo "run as root" >&2; exit 1; } + +if ! /usr/bin/python3 -c 'import sys; sys.exit(sys.version_info < (3, 11))' 2>/dev/null; then + echo "kernelwatch needs /usr/bin/python3 >= 3.11 (Debian 12+, Ubuntu 24.04)" >&2 + exit 1 +fi + +if ! id kernelwatch >/dev/null 2>&1; then + useradd --system --home-dir /var/lib/kernelwatch --no-create-home \ + --shell /usr/sbin/nologin kernelwatch +fi + +rm -rf /opt/kernelwatch.new +install -d -m 0755 /opt/kernelwatch.new/kernelwatch +install -m 0755 "$here/kernelwatch-server" /opt/kernelwatch.new/ +install -m 0644 "$here"/kernelwatch/*.py /opt/kernelwatch.new/kernelwatch/ +rm -rf /opt/kernelwatch.old +[[ -d /opt/kernelwatch ]] && mv /opt/kernelwatch /opt/kernelwatch.old +mv /opt/kernelwatch.new /opt/kernelwatch +rm -rf /opt/kernelwatch.old + +install -m 0755 "$here/kernelwatch.sh" /usr/local/bin/kernelwatch + +install -d -m 0755 /etc/kernelwatch +if [[ ! -e /etc/kernelwatch/server.toml ]]; then + install -m 0640 -g kernelwatch "$here/server.toml.example" /etc/kernelwatch/server.toml +fi +install -d -m 0750 -o kernelwatch -g kernelwatch /var/lib/kernelwatch + +install -m 0644 "$here/kernelwatch.service" /etc/systemd/system/ +systemctl daemon-reload +systemctl enable kernelwatch.service +systemctl restart kernelwatch.service + +echo +echo "kernelwatch is running on $(grep -E '^listen_' /etc/kernelwatch/server.toml | tr '\n' ' ')" +if [[ -z $(kernelwatch list-users) ]]; then + echo "Create a dashboard login: sudo kernelwatch set-password admin" +fi +echo "Register a host: sudo kernelwatch add-host " diff --git a/server/kernelwatch-server b/server/kernelwatch-server new file mode 100755 index 0000000..336d994 --- /dev/null +++ b/server/kernelwatch-server @@ -0,0 +1,11 @@ +#!/usr/bin/python3 -I +"""Entry point. Runs from a checkout or /opt/kernelwatch with the system python3 (3.11+).""" + +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.realpath(__file__))) + +from kernelwatch.cli import main # noqa: E402 + +sys.exit(main()) diff --git a/server/kernelwatch.service b/server/kernelwatch.service new file mode 100644 index 0000000..18c4526 --- /dev/null +++ b/server/kernelwatch.service @@ -0,0 +1,40 @@ +[Unit] +Description=kernelwatch fleet kernel dashboard +After=network.target + +[Service] +User=kernelwatch +Group=kernelwatch +Environment=KERNELWATCH_CONFIG=/etc/kernelwatch/server.toml +ExecStart=/usr/bin/python3 -I /opt/kernelwatch/kernelwatch-server serve +Restart=on-failure +RestartSec=5s +StateDirectory=kernelwatch +StateDirectoryMode=0750 + +CapabilityBoundingSet= +AmbientCapabilities= +NoNewPrivileges=yes +ProtectSystem=strict +ProtectHome=yes +PrivateTmp=yes +PrivateDevices=yes +ProtectKernelTunables=yes +ProtectKernelModules=yes +ProtectKernelLogs=yes +ProtectControlGroups=yes +ProtectClock=yes +ProtectHostname=yes +ProtectProc=invisible +RestrictNamespaces=yes +RestrictRealtime=yes +RestrictSUIDSGID=yes +LockPersonality=yes +MemoryDenyWriteExecute=yes +RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 +SystemCallArchitectures=native +SystemCallFilter=@system-service +UMask=0077 + +[Install] +WantedBy=multi-user.target diff --git a/server/kernelwatch.sh b/server/kernelwatch.sh new file mode 100644 index 0000000..d29b622 --- /dev/null +++ b/server/kernelwatch.sh @@ -0,0 +1,14 @@ +#!/bin/sh +# /usr/local/bin/kernelwatch — admin CLI wrapper. Runs as the service user so +# the database stays owned by it. +set -e +if [ "$(id -u)" = 0 ]; then + exec runuser -u kernelwatch -- env KERNELWATCH_CONFIG=/etc/kernelwatch/server.toml \ + /usr/bin/python3 -I /opt/kernelwatch/kernelwatch-server "$@" +fi +if [ "$(id -un)" = kernelwatch ]; then + exec env KERNELWATCH_CONFIG=/etc/kernelwatch/server.toml \ + /usr/bin/python3 -I /opt/kernelwatch/kernelwatch-server "$@" +fi +echo "kernelwatch: run with sudo" >&2 +exit 1 diff --git a/server/kernelwatch/__init__.py b/server/kernelwatch/__init__.py new file mode 100644 index 0000000..d5e1deb --- /dev/null +++ b/server/kernelwatch/__init__.py @@ -0,0 +1,3 @@ +"""kernelwatch: fleet kernel and reboot status dashboard.""" + +__version__ = "0.1.0" diff --git a/server/kernelwatch/__main__.py b/server/kernelwatch/__main__.py new file mode 100644 index 0000000..dd8a8c9 --- /dev/null +++ b/server/kernelwatch/__main__.py @@ -0,0 +1,5 @@ +import sys + +from .cli import main + +sys.exit(main()) diff --git a/server/kernelwatch/auth.py b/server/kernelwatch/auth.py new file mode 100644 index 0000000..5e9a2d0 --- /dev/null +++ b/server/kernelwatch/auth.py @@ -0,0 +1,55 @@ +"""Password hashing and token helpers. Standard library only.""" + +from __future__ import annotations + +import base64 +import hashlib +import hmac +import secrets + +# scrypt parameters: ~16 MiB memory, tens of milliseconds per hash. +_N, _R, _P = 2**14, 8, 1 +_DKLEN = 32 + + +def _b64(b: bytes) -> str: + return base64.urlsafe_b64encode(b).decode().rstrip("=") + + +def _unb64(s: str) -> bytes: + return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4)) + + +def hash_password(password: str) -> str: + salt = secrets.token_bytes(16) + dk = hashlib.scrypt(password.encode(), salt=salt, n=_N, r=_R, p=_P, dklen=_DKLEN) + return f"scrypt${_N}${_R}${_P}${_b64(salt)}${_b64(dk)}" + + +def verify_password(password: str, stored: str) -> bool: + try: + scheme, n, r, p, salt, dk = stored.split("$") + if scheme != "scrypt": + return False + expected = _unb64(dk) + actual = hashlib.scrypt( + password.encode(), salt=_unb64(salt), n=int(n), r=int(r), p=int(p), + dklen=len(expected), + ) + except (ValueError, TypeError): + return False + return hmac.compare_digest(actual, expected) + + +# Used to equalise timing when a login names a user that doesn't exist. +DUMMY_HASH = hash_password(secrets.token_urlsafe(16)) + + +def new_token() -> str: + """A high-entropy secret for host tokens and session IDs.""" + return secrets.token_urlsafe(32) + + +def token_hash(token: str) -> str: + # Tokens are 256-bit random, so a fast hash is fine; we only store this. + return hashlib.sha256(token.encode()).hexdigest() diff --git a/server/kernelwatch/cli.py b/server/kernelwatch/cli.py new file mode 100644 index 0000000..3b6600f --- /dev/null +++ b/server/kernelwatch/cli.py @@ -0,0 +1,153 @@ +"""Command-line interface: run the server and manage hosts and users.""" + +from __future__ import annotations + +import argparse +import getpass +import sqlite3 +import sys +import time + +from . import __version__, auth, db, web +from .config import load + + +def _conn(cfg): + db.init(cfg.db_path) + return db.connect(cfg.db_path) + + +def _valid_host(name: str) -> str: + if not web.HOST_NAME_RE.match(name): + raise argparse.ArgumentTypeError("host names may contain letters, digits, '.', '_' and '-'") + return name + + +def cmd_serve(cfg, args) -> int: + web.serve(cfg) + return 0 + + +def cmd_add_host(cfg, args) -> int: + token = auth.new_token() + conn = _conn(cfg) + try: + db.add_host(conn, args.name, auth.token_hash(token)) + except sqlite3.IntegrityError: + print(f"host {args.name!r} already exists (use rotate-token)", file=sys.stderr) + return 1 + finally: + conn.close() + print(f"Added {args.name}. Its token (shown once):\n\n {token}\n") + print("On the host, run: sudo ./agent/install.sh --server and paste the token.") + return 0 + + +def cmd_rotate_token(cfg, args) -> int: + token = auth.new_token() + conn = _conn(cfg) + try: + if not db.set_host_token(conn, args.name, auth.token_hash(token)): + print(f"no such host {args.name!r}", file=sys.stderr) + return 1 + finally: + conn.close() + print(f"New token for {args.name} (the old one no longer works):\n\n {token}\n") + print("On the host, run: sudo KERNELWATCH_TOKEN=... ./agent/install.sh or edit /etc/kernelwatch/agent.token") + return 0 + + +def cmd_remove_host(cfg, args) -> int: + conn = _conn(cfg) + try: + if not db.remove_host(conn, args.name): + print(f"no such host {args.name!r}", file=sys.stderr) + return 1 + finally: + conn.close() + print(f"Removed {args.name} and its reports.") + return 0 + + +def cmd_list_hosts(cfg, args) -> int: + conn = _conn(cfg) + try: + hosts = db.list_hosts(conn) + finally: + conn.close() + now = time.time() + for h in hosts: + print(f"{h['name']:<32} last seen {web.ago(h['last_seen'], now)}") + return 0 + + +def cmd_set_password(cfg, args) -> int: + password = getpass.getpass(f"Password for {args.name}: ") + if len(password) < 12: + print("use at least 12 characters", file=sys.stderr) + return 1 + if getpass.getpass("Again: ") != password: + print("passwords don't match", file=sys.stderr) + return 1 + conn = _conn(cfg) + try: + db.set_user(conn, args.name, auth.hash_password(password)) + finally: + conn.close() + print(f"Password set for {args.name}.") + return 0 + + +def cmd_remove_user(cfg, args) -> int: + conn = _conn(cfg) + try: + if not db.remove_user(conn, args.name): + print(f"no such user {args.name!r}", file=sys.stderr) + return 1 + finally: + conn.close() + print(f"Removed user {args.name}.") + return 0 + + +def cmd_list_users(cfg, args) -> int: + conn = _conn(cfg) + try: + for name in db.list_users(conn): + print(name) + finally: + conn.close() + return 0 + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(prog="kernelwatch", description="Fleet kernel status dashboard.") + parser.add_argument("-c", "--config", help="config file (default: $KERNELWATCH_CONFIG or " + "/etc/kernelwatch/server.toml)") + parser.add_argument("--version", action="version", version=f"kernelwatch {__version__}") + sub = parser.add_subparsers(dest="command", required=True) + + sub.add_parser("serve", help="run the HTTP server").set_defaults(func=cmd_serve) + + for name, func, help_ in ( + ("add-host", cmd_add_host, "register a host and print its token"), + ("rotate-token", cmd_rotate_token, "issue a new token for a host"), + ("remove-host", cmd_remove_host, "delete a host and its reports"), + ): + p = sub.add_parser(name, help=help_) + p.add_argument("name", type=_valid_host) + p.set_defaults(func=func) + sub.add_parser("list-hosts", help="list hosts and when they last reported").set_defaults( + func=cmd_list_hosts) + + for name, func, help_ in ( + ("set-password", cmd_set_password, "create a dashboard user or change their password"), + ("remove-user", cmd_remove_user, "delete a dashboard user"), + ): + p = sub.add_parser(name, help=help_) + p.add_argument("name") + p.set_defaults(func=func) + sub.add_parser("list-users", help="list dashboard users").set_defaults(func=cmd_list_users) + + args = parser.parse_args(argv) + return args.func(load(args.config), args) diff --git a/server/kernelwatch/config.py b/server/kernelwatch/config.py new file mode 100644 index 0000000..194630c --- /dev/null +++ b/server/kernelwatch/config.py @@ -0,0 +1,56 @@ +"""Server configuration, loaded from a flat TOML file.""" + +from __future__ import annotations + +import dataclasses +import os +import tomllib +from dataclasses import dataclass + +DEFAULT_PATH = "/etc/kernelwatch/server.toml" + + +@dataclass(frozen=True) +class Config: + # Bind to loopback by default; put a TLS reverse proxy in front. + listen_host: str = "127.0.0.1" + listen_port: int = 8080 + db_path: str = "/var/lib/kernelwatch/kernelwatch.db" + + # A host that hasn't reported for this long is shown as stale. + stale_after_hours: float = 3.0 + # Package lists older than this make "no updates" untrustworthy. + apt_stale_after_hours: float = 48.0 + report_retention_days: int = 30 + + session_hours: int = 12 + # Leave on unless you serve the dashboard over plain HTTP on a non-localhost name. + secure_cookies: bool = True + # Honour X-Forwarded-For (for login rate limiting). Enable only behind a proxy. + trust_proxy_headers: bool = False + + +def load(path: str | None = None) -> Config: + path = path or os.environ.get("KERNELWATCH_CONFIG") or DEFAULT_PATH + if not os.path.exists(path): + if path == DEFAULT_PATH: + return Config() + raise SystemExit(f"config file not found: {path}") + + with open(path, "rb") as f: + raw = tomllib.load(f) + + fields = {f.name: f for f in dataclasses.fields(Config)} + unknown = sorted(set(raw) - set(fields)) + if unknown: + raise SystemExit(f"{path}: unknown config keys: {', '.join(unknown)}") + + values = {} + for name, value in raw.items(): + expected = type(getattr(Config(), name)) + if expected is float and isinstance(value, int) and not isinstance(value, bool): + value = float(value) + if not isinstance(value, expected) or (expected is int and isinstance(value, bool)): + raise SystemExit(f"{path}: {name} must be {expected.__name__}") + values[name] = value + return Config(**values) diff --git a/server/kernelwatch/db.py b/server/kernelwatch/db.py new file mode 100644 index 0000000..2fc5792 --- /dev/null +++ b/server/kernelwatch/db.py @@ -0,0 +1,188 @@ +"""SQLite storage. One connection per thread/request; WAL keeps readers and the writer apart.""" + +from __future__ import annotations + +import json +import os +import sqlite3 +import time +from typing import Any + +SCHEMA = """ +CREATE TABLE IF NOT EXISTS hosts ( + name TEXT PRIMARY KEY, + token_hash TEXT NOT NULL UNIQUE, + created_at INTEGER NOT NULL +); +CREATE TABLE IF NOT EXISTS reports ( + id INTEGER PRIMARY KEY, + host TEXT NOT NULL REFERENCES hosts(name) ON DELETE CASCADE, + received_at INTEGER NOT NULL, + payload TEXT NOT NULL +); +CREATE INDEX IF NOT EXISTS reports_host_time ON reports(host, received_at); +CREATE TABLE IF NOT EXISTS users ( + name TEXT PRIMARY KEY, + pw_hash TEXT NOT NULL +); +CREATE TABLE IF NOT EXISTS sessions ( + id_hash TEXT PRIMARY KEY, + user TEXT NOT NULL REFERENCES users(name) ON DELETE CASCADE, + expires_at INTEGER NOT NULL +); +""" + + +def connect(path: str) -> sqlite3.Connection: + conn = sqlite3.connect(path, timeout=10, isolation_level=None) + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA foreign_keys = ON") + conn.execute("PRAGMA journal_mode = WAL") + conn.execute("PRAGMA busy_timeout = 10000") + return conn + + +def init(path: str) -> None: + directory = os.path.dirname(os.path.abspath(path)) + os.makedirs(directory, exist_ok=True) + conn = connect(path) + try: + conn.executescript(SCHEMA) + finally: + conn.close() + os.chmod(path, 0o600) + + +# --- hosts ------------------------------------------------------------------ + +def add_host(conn: sqlite3.Connection, name: str, token_hash: str) -> None: + conn.execute( + "INSERT INTO hosts (name, token_hash, created_at) VALUES (?, ?, ?)", + (name, token_hash, int(time.time())), + ) + + +def set_host_token(conn: sqlite3.Connection, name: str, token_hash: str) -> bool: + cur = conn.execute("UPDATE hosts SET token_hash = ? WHERE name = ?", (token_hash, name)) + return cur.rowcount == 1 + + +def remove_host(conn: sqlite3.Connection, name: str) -> bool: + return conn.execute("DELETE FROM hosts WHERE name = ?", (name,)).rowcount == 1 + + +def host_for_token(conn: sqlite3.Connection, token_hash: str) -> str | None: + row = conn.execute("SELECT name FROM hosts WHERE token_hash = ?", (token_hash,)).fetchone() + return row["name"] if row else None + + +def list_hosts(conn: sqlite3.Connection) -> list[sqlite3.Row]: + return conn.execute( + """ + SELECT h.name, h.created_at, MAX(r.received_at) AS last_seen + FROM hosts h LEFT JOIN reports r ON r.host = h.name + GROUP BY h.name ORDER BY h.name + """ + ).fetchall() + + +# --- reports ---------------------------------------------------------------- + +def add_report(conn: sqlite3.Connection, host: str, payload: dict[str, Any], + retention_days: int) -> None: + now = int(time.time()) + conn.execute("BEGIN IMMEDIATE") + try: + conn.execute( + "INSERT INTO reports (host, received_at, payload) VALUES (?, ?, ?)", + (host, now, json.dumps(payload, separators=(",", ":"))), + ) + conn.execute( + "DELETE FROM reports WHERE host = ? AND received_at < ?", + (host, now - retention_days * 86400), + ) + conn.execute("COMMIT") + except BaseException: + conn.execute("ROLLBACK") + raise + + +def latest_reports(conn: sqlite3.Connection) -> list[dict[str, Any]]: + """Every host with its most recent report (or None).""" + rows = conn.execute( + """ + SELECT h.name, r.received_at, r.payload + FROM hosts h + LEFT JOIN reports r ON r.id = ( + SELECT id FROM reports WHERE host = h.name ORDER BY received_at DESC, id DESC LIMIT 1 + ) + ORDER BY h.name + """ + ).fetchall() + return [ + { + "host": row["name"], + "received_at": row["received_at"], + "report": json.loads(row["payload"]) if row["payload"] else None, + } + for row in rows + ] + + +def host_history(conn: sqlite3.Connection, host: str, limit: int = 50) -> list[dict[str, Any]]: + rows = conn.execute( + "SELECT received_at, payload FROM reports WHERE host = ? " + "ORDER BY received_at DESC, id DESC LIMIT ?", + (host, limit), + ).fetchall() + return [{"received_at": r["received_at"], "report": json.loads(r["payload"])} for r in rows] + + +def host_exists(conn: sqlite3.Connection, host: str) -> bool: + return conn.execute("SELECT 1 FROM hosts WHERE name = ?", (host,)).fetchone() is not None + + +# --- users & sessions ------------------------------------------------------- + +def set_user(conn: sqlite3.Connection, name: str, pw_hash: str) -> None: + conn.execute( + "INSERT INTO users (name, pw_hash) VALUES (?, ?) " + "ON CONFLICT(name) DO UPDATE SET pw_hash = excluded.pw_hash", + (name, pw_hash), + ) + # A password change logs out existing sessions. + conn.execute("DELETE FROM sessions WHERE user = ?", (name,)) + + +def remove_user(conn: sqlite3.Connection, name: str) -> bool: + return conn.execute("DELETE FROM users WHERE name = ?", (name,)).rowcount == 1 + + +def user_pw_hash(conn: sqlite3.Connection, name: str) -> str | None: + row = conn.execute("SELECT pw_hash FROM users WHERE name = ?", (name,)).fetchone() + return row["pw_hash"] if row else None + + +def list_users(conn: sqlite3.Connection) -> list[str]: + return [r["name"] for r in conn.execute("SELECT name FROM users ORDER BY name")] + + +def create_session(conn: sqlite3.Connection, id_hash: str, user: str, ttl_seconds: int) -> None: + now = int(time.time()) + conn.execute("DELETE FROM sessions WHERE expires_at < ?", (now,)) + conn.execute( + "INSERT INTO sessions (id_hash, user, expires_at) VALUES (?, ?, ?)", + (id_hash, user, now + ttl_seconds), + ) + + +def session_user(conn: sqlite3.Connection, id_hash: str) -> str | None: + row = conn.execute( + "SELECT user FROM sessions WHERE id_hash = ? AND expires_at >= ?", + (id_hash, int(time.time())), + ).fetchone() + return row["user"] if row else None + + +def delete_session(conn: sqlite3.Connection, id_hash: str) -> None: + conn.execute("DELETE FROM sessions WHERE id_hash = ?", (id_hash,)) diff --git a/server/kernelwatch/report.py b/server/kernelwatch/report.py new file mode 100644 index 0000000..172e364 --- /dev/null +++ b/server/kernelwatch/report.py @@ -0,0 +1,66 @@ +"""Validation of agent reports. Unknown fields are dropped; known ones are type-checked.""" + +from __future__ import annotations + +from typing import Any + +MAX_BODY_BYTES = 64 * 1024 +_MAX_STR = 256 +_MAX_LIST = 200 + + +class ReportError(ValueError): + pass + + +# field -> kind. "str", "int", "bool", "strlist". All fields are optional. +FIELDS: dict[str, str] = { + "agent_version": "str", + "reported_hostname": "str", + "os_id": "str", + "os_version_id": "str", + "os_pretty_name": "str", + "kernel_running": "str", + "kernel_build": "str", + "kernels_installed": "strlist", + "kernel_newest_installed": "str", + "needrestart_ksta": "int", + "needrestart_kexp": "str", + "reboot_required": "bool", + "reboot_required_pkgs": "strlist", + "upgradable_count": "int", + "security_count": "int", + "kernel_upgradable": "strlist", + "apt_lists_age_seconds": "int", + "uptime_seconds": "int", +} + + +def _check(name: str, kind: str, value: Any) -> Any: + if value is None: + return None + if kind == "str": + if not isinstance(value, str): + raise ReportError(f"{name} must be a string") + return value[:_MAX_STR] + if kind == "int": + if not isinstance(value, int) or isinstance(value, bool): + raise ReportError(f"{name} must be an integer") + return value + if kind == "bool": + if not isinstance(value, bool): + raise ReportError(f"{name} must be a boolean") + return value + if kind == "strlist": + if not isinstance(value, list) or not all(isinstance(v, str) for v in value): + raise ReportError(f"{name} must be a list of strings") + return [v[:_MAX_STR] for v in value[:_MAX_LIST]] + raise AssertionError(kind) + + +def sanitize(raw: Any) -> dict[str, Any]: + if not isinstance(raw, dict): + raise ReportError("report must be a JSON object") + if not isinstance(raw.get("kernel_running"), str) or not raw["kernel_running"]: + raise ReportError("kernel_running is required") + return {name: _check(name, kind, raw[name]) for name, kind in FIELDS.items() if name in raw} diff --git a/server/kernelwatch/status.py b/server/kernelwatch/status.py new file mode 100644 index 0000000..2f07201 --- /dev/null +++ b/server/kernelwatch/status.py @@ -0,0 +1,89 @@ +"""Turn a host's latest report into a dashboard status. + +Levels, worst first: + stale - no report recently (or ever); nothing else can be trusted + reboot - a newer kernel (or other reboot-requiring update) is installed but not running + update - updates are waiting to be installed, or the package lists are too old to tell + ok - running the newest installed kernel, nothing pending +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any + +from .config import Config + +LEVELS = ("stale", "reboot", "update", "ok") +_RANK = {level: i for i, level in enumerate(LEVELS)} + +# needrestart's NEEDRESTART-KSTA values. +KSTA_CURRENT = 1 +KSTA_ABI_UPGRADE = 2 +KSTA_VERSION_UPGRADE = 3 + + +@dataclass +class Status: + level: str = "ok" + reasons: list[str] = field(default_factory=list) + + def raise_to(self, level: str, reason: str) -> None: + if _RANK[level] < _RANK[self.level]: + self.level = level + self.reasons.append(reason) + + @property + def rank(self) -> int: + return _RANK[self.level] + + +def kernel_reboot_pending(report: dict[str, Any]) -> str | None: + """Why the running kernel is out of date, or None if it isn't (as far as we can tell).""" + running = report.get("kernel_running") or "?" + ksta = report.get("needrestart_ksta") + if ksta == KSTA_VERSION_UPGRADE: + expected = report.get("needrestart_kexp") or report.get("kernel_newest_installed") or "?" + return f"running {running}, {expected} installed" + if ksta == KSTA_ABI_UPGRADE: + return f"running {running}, an ABI-compatible update of it is installed" + if ksta == KSTA_CURRENT: + return None + + # No usable needrestart result: compare against the newest installed image. + newest = report.get("kernel_newest_installed") + if newest and newest != running: + return f"running {running}, {newest} installed" + return None + + +def evaluate(received_at: int | None, report: dict[str, Any] | None, now: float, + cfg: Config) -> Status: + status = Status() + if received_at is None or report is None: + status.raise_to("stale", "never reported") + return status + + age_h = (now - received_at) / 3600 + if age_h > cfg.stale_after_hours: + status.raise_to("stale", f"last report {age_h:.0f}h ago") + + if why := kernel_reboot_pending(report): + status.raise_to("reboot", f"kernel: {why}") + if report.get("reboot_required"): + pkgs = report.get("reboot_required_pkgs") or [] + detail = f" ({', '.join(pkgs[:5])}{', …' if len(pkgs) > 5 else ''})" if pkgs else "" + status.raise_to("reboot", f"/run/reboot-required{detail}") + + if kernels := report.get("kernel_upgradable"): + status.raise_to("update", f"kernel update available: {', '.join(kernels)}") + if sec := report.get("security_count"): + status.raise_to("update", f"{sec} security update{'s' if sec != 1 else ''} pending") + + apt_age = report.get("apt_lists_age_seconds") + if apt_age is None: + status.raise_to("update", "package list age unknown") + elif apt_age / 3600 > cfg.apt_stale_after_hours: + status.raise_to("update", f"package lists {apt_age / 86400:.0f}d old; apt update not running?") + + return status diff --git a/server/kernelwatch/web.py b/server/kernelwatch/web.py new file mode 100644 index 0000000..fefafc8 --- /dev/null +++ b/server/kernelwatch/web.py @@ -0,0 +1,514 @@ +"""HTTP server: the agent ingest API and the authenticated dashboard. + +Meant to sit behind a TLS-terminating reverse proxy (Caddy, nginx). The +standard-library server is plenty for a fleet of tens or hundreds of hosts +reporting hourly. +""" + +from __future__ import annotations + +import html +import json +import re +import sys +import threading +import time +from http import HTTPStatus +from http.cookies import CookieError, SimpleCookie +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from typing import Any +from urllib.parse import parse_qs, quote, unquote, urlsplit + +from . import __version__, auth, db +from .config import Config +from .report import MAX_BODY_BYTES, ReportError, sanitize +from .status import LEVELS, Status, evaluate + +SESSION_COOKIE = "kw_session" +HOST_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$") + +LOGIN_MAX_FAILURES = 10 +LOGIN_WINDOW_SECONDS = 15 * 60 + +e = html.escape + + +class LoginLimiter: + """Per-client-IP failed login counter with a fixed window.""" + + def __init__(self) -> None: + self._lock = threading.Lock() + self._failures: dict[str, tuple[int, float]] = {} + + def blocked(self, ip: str) -> bool: + with self._lock: + count, start = self._failures.get(ip, (0, 0.0)) + if time.monotonic() - start > LOGIN_WINDOW_SECONDS: + self._failures.pop(ip, None) + return False + return count >= LOGIN_MAX_FAILURES + + def failed(self, ip: str) -> None: + with self._lock: + now = time.monotonic() + count, start = self._failures.get(ip, (0, now)) + if now - start > LOGIN_WINDOW_SECONDS: + count, start = 0, now + self._failures[ip] = (count + 1, start) + + def succeeded(self, ip: str) -> None: + with self._lock: + self._failures.pop(ip, None) + + +# --- formatting ------------------------------------------------------------- + +def ago(ts: float | None, now: float) -> str: + if ts is None: + return "never" + s = max(0, int(now - ts)) + for unit, size in (("d", 86400), ("h", 3600), ("m", 60)): + if s >= size: + return f"{s // size}{unit} ago" + return "just now" + + +def duration(seconds: int | None) -> str: + if seconds is None: + return "–" + d, rem = divmod(seconds, 86400) + return f"{d}d {rem // 3600}h" if d else f"{rem // 3600}h {rem % 3600 // 60}m" + + +def utc(ts: float | None) -> str: + return time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime(ts)) if ts else "" + + +def badge(level: str) -> str: + return f'{e(level)}' + + +STYLE = """ +:root { + color-scheme: light dark; + --bg: #f7f7f8; --fg: #1d1d1f; --muted: #6b6b72; --card: #fff; --line: #e2e2e6; + --ok: #1a7f37; --update: #9a6700; --reboot: #cf222e; --stale: #6e7781; +} +@media (prefers-color-scheme: dark) { + :root { + --bg: #111214; --fg: #e8e8ea; --muted: #9a9aa2; --card: #1a1b1e; --line: #2c2d31; + --ok: #3fb950; --update: #d29922; --reboot: #f85149; --stale: #8b949e; + } +} +* { box-sizing: border-box; } +body { margin: 0; background: var(--bg); color: var(--fg); + font: 14px/1.45 system-ui, -apple-system, "Segoe UI", sans-serif; } +header { display: flex; align-items: center; gap: 16px; padding: 12px 16px; + border-bottom: 1px solid var(--line); background: var(--card); } +header h1 { font-size: 16px; margin: 0; flex: 1; } +header h1 a { color: inherit; text-decoration: none; } +header form { margin: 0; } +main { padding: 16px; max-width: 1400px; margin: 0 auto; } +a { color: inherit; } +button { font: inherit; padding: 6px 12px; border: 1px solid var(--line); border-radius: 6px; + background: var(--card); color: var(--fg); cursor: pointer; } +.summary { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 16px; } +.summary div { background: var(--card); border: 1px solid var(--line); border-radius: 8px; + padding: 8px 14px; min-width: 110px; } +.summary b { display: block; font-size: 22px; } +.table-wrap { overflow-x: auto; background: var(--card); border: 1px solid var(--line); + border-radius: 8px; } +table { border-collapse: collapse; width: 100%; } +th, td { text-align: left; padding: 8px 12px; border-bottom: 1px solid var(--line); + vertical-align: top; white-space: nowrap; } +th { font-weight: 600; color: var(--muted); font-size: 12px; text-transform: uppercase; } +tr:last-child td { border-bottom: 0; } +td.reasons { white-space: normal; color: var(--muted); min-width: 260px; } +code { font: 12px ui-monospace, SFMono-Regular, Menlo, monospace; } +.muted { color: var(--muted); } +.badge { display: inline-block; padding: 1px 8px; border-radius: 999px; font-size: 12px; + font-weight: 600; color: #fff; } +.badge.ok { background: var(--ok); } .badge.update { background: var(--update); } +.badge.reboot { background: var(--reboot); } .badge.stale { background: var(--stale); } +.login { max-width: 340px; margin: 12vh auto; background: var(--card); padding: 24px; + border: 1px solid var(--line); border-radius: 10px; } +.login h1 { font-size: 18px; margin: 0 0 16px; } +.login label { display: block; margin-bottom: 12px; } +.login input { display: block; width: 100%; margin-top: 4px; padding: 8px; font: inherit; + border: 1px solid var(--line); border-radius: 6px; background: var(--bg); color: var(--fg); } +.login button { width: 100%; } +.error { color: var(--reboot); } +dl { display: grid; grid-template-columns: max-content 1fr; gap: 4px 16px; margin: 0 0 24px; } +dt { color: var(--muted); } +dd { margin: 0; overflow-wrap: anywhere; } +h2 { font-size: 15px; margin: 24px 0 8px; } +""" + + +def page(title: str, body: str, user: str | None = None, refresh: bool = False) -> str: + logout = ( + f'{e(user)}' + '
' + if user else "" + ) + header = ( + f'

kernelwatch

{logout}
' if user else "" + ) + meta_refresh = '' if refresh else "" + return f""" + + +{meta_refresh}{e(title)} + +{header}{body}""" + + +# --- handler ---------------------------------------------------------------- + +class Handler(BaseHTTPRequestHandler): + server_version = "kernelwatch/" + __version__ + sys_version = "" + cfg: Config + limiter: LoginLimiter + + # -- plumbing -- + + def log_message(self, fmt: str, *args: Any) -> None: + sys.stderr.write(f"{self.client_ip()} {fmt % args}\n") + + def client_ip(self) -> str: + if self.cfg.trust_proxy_headers: + fwd = self.headers.get("X-Forwarded-For", "") + if fwd: + return fwd.split(",")[-1].strip() + return self.client_address[0] + + def conn(self): + return db.connect(self.cfg.db_path) + + def send(self, status: int, body: str | bytes = b"", content_type: str = "text/html; charset=utf-8", + headers: dict[str, str] | None = None) -> None: + data = body.encode() if isinstance(body, str) else body + self.send_response(status) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(data))) + self.send_header("Cache-Control", "no-store") + self.send_header("X-Content-Type-Options", "nosniff") + self.send_header("Referrer-Policy", "no-referrer") + self.send_header( + "Content-Security-Policy", + "default-src 'none'; style-src 'self'; form-action 'self'; frame-ancestors 'none'", + ) + for k, v in (headers or {}).items(): + self.send_header(k, v) + self.end_headers() + if self.command != "HEAD": + self.wfile.write(data) + + def send_json(self, status: int, obj: Any) -> None: + self.send(status, json.dumps(obj), "application/json") + + def redirect(self, location: str, headers: dict[str, str] | None = None) -> None: + self.send(HTTPStatus.SEE_OTHER, b"", headers={"Location": location, **(headers or {})}) + + def read_body(self) -> bytes | None: + length = self.headers.get("Content-Length") + if length is None or not length.isdigit(): + self.send(HTTPStatus.LENGTH_REQUIRED, "Content-Length required", "text/plain") + return None + if int(length) > MAX_BODY_BYTES: + self.send(HTTPStatus.REQUEST_ENTITY_TOO_LARGE, "body too large", "text/plain") + return None + return self.rfile.read(int(length)) + + def same_origin(self) -> bool: + """Reject cross-site form posts. Browsers send Origin on POST.""" + origin = self.headers.get("Origin") + if origin is None: + return True + host = self.headers.get("Host", "") + if self.cfg.trust_proxy_headers: + host = self.headers.get("X-Forwarded-Host", host) + return urlsplit(origin).netloc == host + + def session_id(self) -> str | None: + raw = self.headers.get("Cookie") + if not raw: + return None + try: + morsel = SimpleCookie(raw).get(SESSION_COOKIE) + except CookieError: + return None + return morsel.value if morsel else None + + def current_user(self) -> str | None: + sid = self.session_id() + if not sid: + return None + conn = self.conn() + try: + return db.session_user(conn, auth.token_hash(sid)) + finally: + conn.close() + + def cookie(self, value: str, max_age: int) -> str: + parts = [f"{SESSION_COOKIE}={value}", "Path=/", "HttpOnly", "SameSite=Strict", + f"Max-Age={max_age}"] + if self.cfg.secure_cookies: + parts.append("Secure") + return "; ".join(parts) + + # -- routing -- + + def do_HEAD(self) -> None: + self.do_GET() + + def do_GET(self) -> None: + path = urlsplit(self.path).path + if path == "/healthz": + return self.send(HTTPStatus.OK, "ok\n", "text/plain") + if path == "/static/style.css": + return self.send(HTTPStatus.OK, STYLE, "text/css; charset=utf-8") + if path == "/login": + return self.login_page() + + user = self.current_user() + if user is None: + return self.redirect("/login") + if path == "/": + return self.dashboard(user) + if path.startswith("/host/"): + return self.host_page(user, unquote(path[len("/host/"):])) + self.send(HTTPStatus.NOT_FOUND, page("Not found", "

Not found.

", user)) + + def do_POST(self) -> None: + path = urlsplit(self.path).path + if path == "/api/v1/report": + return self.ingest() + if path == "/login": + return self.login() + if path == "/logout": + return self.logout() + self.send(HTTPStatus.NOT_FOUND, "not found", "text/plain") + + # -- API -- + + def ingest(self) -> None: + header = self.headers.get("Authorization", "") + scheme, _, token = header.partition(" ") + if scheme.lower() != "bearer" or not token.strip(): + return self.send_json(HTTPStatus.UNAUTHORIZED, {"error": "missing bearer token"}) + + body = self.read_body() + if body is None: + return + conn = self.conn() + try: + host = db.host_for_token(conn, auth.token_hash(token.strip())) + if host is None: + return self.send_json(HTTPStatus.UNAUTHORIZED, {"error": "unknown token"}) + try: + report = sanitize(json.loads(body)) + except (ValueError, ReportError) as exc: + return self.send_json(HTTPStatus.BAD_REQUEST, {"error": str(exc)}) + db.add_report(conn, host, report, self.cfg.report_retention_days) + finally: + conn.close() + self.send(HTTPStatus.NO_CONTENT, b"", "text/plain") + + # -- auth pages -- + + def login_page(self, error: str = "", status: int = HTTPStatus.OK) -> None: + err = f'

{e(error)}

' if error else "" + body = f"""
""" + self.send(status, page("Log in · kernelwatch", body)) + + def login(self) -> None: + if not self.same_origin(): + return self.send(HTTPStatus.FORBIDDEN, "cross-origin request refused", "text/plain") + ip = self.client_ip() + if self.limiter.blocked(ip): + return self.login_page("Too many failed attempts. Try again later.", + HTTPStatus.TOO_MANY_REQUESTS) + body = self.read_body() + if body is None: + return + form = parse_qs(body.decode("utf-8", "replace")) + username = form.get("username", [""])[0] + password = form.get("password", [""])[0] + + conn = self.conn() + try: + stored = db.user_pw_hash(conn, username) + ok = auth.verify_password(password, stored or auth.DUMMY_HASH) and stored is not None + if not ok: + self.limiter.failed(ip) + self.log_message("login failed for %r", username) + return self.login_page("Invalid username or password.", HTTPStatus.UNAUTHORIZED) + self.limiter.succeeded(ip) + sid = auth.new_token() + ttl = self.cfg.session_hours * 3600 + db.create_session(conn, auth.token_hash(sid), username, ttl) + finally: + conn.close() + self.redirect("/", {"Set-Cookie": self.cookie(sid, ttl)}) + + def logout(self) -> None: + if not self.same_origin(): + return self.send(HTTPStatus.FORBIDDEN, "cross-origin request refused", "text/plain") + sid = self.session_id() + if sid: + conn = self.conn() + try: + db.delete_session(conn, auth.token_hash(sid)) + finally: + conn.close() + self.redirect("/login", {"Set-Cookie": self.cookie("", 0)}) + + # -- dashboard -- + + def dashboard(self, user: str) -> None: + now = time.time() + conn = self.conn() + try: + hosts = db.latest_reports(conn) + finally: + conn.close() + + rows = [] + for h in hosts: + h["status"] = evaluate(h["received_at"], h["report"], now, self.cfg) + hosts.sort(key=lambda h: (h["status"].rank, h["host"])) + + counts = {level: 0 for level in LEVELS} + for h in hosts: + counts[h["status"].level] += 1 + rows.append(self.host_row(h, now)) + + summary = "".join( + f'
{counts[level]}{badge(level)}
' for level in LEVELS + ) + table = ( + "

No hosts yet. Add one with kernelwatch add-host NAME.

" + if not hosts else + '
' + "" + "" + "" + "".join(rows) + "
StatusHostOSRunning kernelNewest installedUpdatesUptimeLast seenDetails
" + ) + body = f'
{summary}
{table}
' + self.send(HTTPStatus.OK, page("Fleet · kernelwatch", body, user, refresh=True)) + + @staticmethod + def host_row(h: dict[str, Any], now: float) -> str: + r = h["report"] or {} + status: Status = h["status"] + name = h["host"] + sec = r.get("security_count") + total = r.get("upgradable_count") + updates = "–" if total is None else f"{total}" + (f" ({sec} sec)" if sec else "") + return ( + "" + f"{badge(status.level)}" + f'{e(name)}' + f"{e(r.get('os_pretty_name') or '–')}" + f"{e(r.get('kernel_running') or '–')}" + f"{e(r.get('kernel_newest_installed') or '–')}" + f"{e(updates)}" + f"{e(duration(r.get('uptime_seconds')))}" + f'{e(ago(h["received_at"], now))}' + f'{"
".join(e(x) for x in status.reasons) or "–"}' + "" + ) + + def host_page(self, user: str, name: str) -> None: + if not HOST_NAME_RE.match(name): + return self.send(HTTPStatus.NOT_FOUND, page("Not found", "

Not found.

", user)) + now = time.time() + conn = self.conn() + try: + exists = db.host_exists(conn, name) + history = db.host_history(conn, name) if exists else [] + finally: + conn.close() + if not exists: + return self.send(HTTPStatus.NOT_FOUND, page("Not found", "

Not found.

", user)) + + latest = history[0] if history else None + status = evaluate(latest and latest["received_at"], latest and latest["report"], now, self.cfg) + r = latest["report"] if latest else {} + + def field(label: str, value: Any, code: bool = False) -> str: + if value is None or value == "" or value == []: + text = "–" + elif isinstance(value, list): + text = ", ".join(str(v) for v in value) + else: + text = str(value) + inner = f"{e(text)}" if code and text != "–" else e(text) + return f"
{e(label)}
{inner}
" + + details = "".join([ + f"
Status
{badge(status.level)}
", + field("Why", "; ".join(status.reasons) or None), + field("Last report", f"{ago(latest['received_at'], now)} ({utc(latest['received_at'])})" + if latest else None), + field("Reported hostname", r.get("reported_hostname")), + field("OS", r.get("os_pretty_name")), + field("Running kernel", r.get("kernel_running"), code=True), + field("Kernel build", r.get("kernel_build"), code=True), + field("Installed kernels", r.get("kernels_installed"), code=True), + field("needrestart", None if r.get("needrestart_ksta") is None else + f"KSTA={r['needrestart_ksta']} expected={r.get('needrestart_kexp') or '?'}"), + field("Kernel packages upgradable", r.get("kernel_upgradable"), code=True), + field("Updates pending", r.get("upgradable_count")), + field("Security updates", r.get("security_count")), + field("Reboot-required packages", r.get("reboot_required_pkgs"), code=True), + field("Package lists age", duration(r.get("apt_lists_age_seconds")) + if r.get("apt_lists_age_seconds") is not None else None), + field("Uptime", duration(r.get("uptime_seconds")) if r.get("uptime_seconds") is not None else None), + field("Agent version", r.get("agent_version")), + ]) + + # History: status as it was at the time of each report (so never "stale"). + hist_rows = "".join( + "" + f'{e(ago(h["received_at"], now))}' + f"{badge(evaluate(h['received_at'], h['report'], h['received_at'], self.cfg).level)}" + f"{e(h['report'].get('kernel_running') or '–')}" + f"{e(str(h['report'].get('upgradable_count', '–')))}" + "" + for h in history + ) + history_html = ( + '

Recent reports

' + "" + f"{hist_rows}
WhenStatusRunning kernelUpdates
" + if history else "

No reports yet.

" + ) + body = f"

{e(name)}

{details}
{history_html}
" + self.send(HTTPStatus.OK, page(f"{name} · kernelwatch", body, user, refresh=True)) + + +def make_server(cfg: Config) -> ThreadingHTTPServer: + db.init(cfg.db_path) + handler = type("BoundHandler", (Handler,), {"cfg": cfg, "limiter": LoginLimiter()}) + server = ThreadingHTTPServer((cfg.listen_host, cfg.listen_port), handler) + server.daemon_threads = True + return server + + +def serve(cfg: Config) -> None: + server = make_server(cfg) + host, port = server.server_address[:2] + print(f"kernelwatch {__version__} listening on http://{host}:{port}", file=sys.stderr, flush=True) + try: + server.serve_forever() + except KeyboardInterrupt: + pass + finally: + server.server_close() diff --git a/server/server.toml.example b/server/server.toml.example new file mode 100644 index 0000000..2bb16cf --- /dev/null +++ b/server/server.toml.example @@ -0,0 +1,25 @@ +# /etc/kernelwatch/server.toml — every key is optional; defaults shown. + +# The server speaks plain HTTP; keep it on loopback behind a TLS reverse proxy. +listen_host = "127.0.0.1" +listen_port = 8080 +db_path = "/var/lib/kernelwatch/kernelwatch.db" + +# A host that hasn't reported in this long shows as "stale". +# Agents report hourly (plus up to 15 min jitter). +stale_after_hours = 3.0 + +# Package lists older than this mean "no updates" can't be trusted. +apt_stale_after_hours = 48.0 + +report_retention_days = 30 +session_hours = 12 + +# Session cookie gets the Secure flag. Leave on unless you're testing over +# plain HTTP on something other than localhost. +secure_cookies = true + +# Behind a reverse proxy, use X-Forwarded-For / X-Forwarded-Host for login +# rate limiting and origin checks. Only enable if the port isn't reachable +# directly, or clients can spoof their IP. +trust_proxy_headers = false diff --git a/tests/helpers.py b/tests/helpers.py new file mode 100644 index 0000000..67c5432 --- /dev/null +++ b/tests/helpers.py @@ -0,0 +1,25 @@ +"""Shared test setup: put server/ on sys.path and build throwaway configs.""" + +import os +import sys +import tempfile + +REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(REPO, "server")) + +from kernelwatch.config import Config # noqa: E402 + + +def temp_config(tmp: str, **overrides) -> Config: + return Config(db_path=os.path.join(tmp, "kw.db"), listen_port=0, secure_cookies=False, + **overrides) + + +def tempdir() -> tempfile.TemporaryDirectory: + return tempfile.TemporaryDirectory(prefix="kw-test-") + + +# Keep request logs out of test output. +from kernelwatch import web # noqa: E402 + +web.Handler.log_message = lambda self, *args: None diff --git a/tests/test_agent.py b/tests/test_agent.py new file mode 100644 index 0000000..efdb90f --- /dev/null +++ b/tests/test_agent.py @@ -0,0 +1,178 @@ +"""Runs the real agent script against stubbed system commands and a fake root.""" + +import json +import os +import shutil +import stat +import subprocess +import threading +import time +import unittest + +from helpers import REPO, temp_config, tempdir +from kernelwatch import auth, db, web + +AGENT = os.path.join(REPO, "agent", "kernelwatch-agent") + +DPKG_DEBIAN = """\ +ii linux-image-6.12.48+deb13-amd64 +ii linux-image-6.12.57+deb13-amd64 +rc linux-image-6.12.38+deb13-amd64 +ii linux-image-6.12.57+deb13-amd64-dbg +""" + +APT_SIM_DEBIAN = """\ +NOTE: This is only a simulation! +Reading package lists... +Inst libssl3t64 [3.5.1-1] (3.5.1-1+deb13u1 Debian-Security:13/stable-security [amd64]) +Inst linux-image-6.12.60+deb13-amd64 (6.12.60-1 Debian-Security:13/stable-security [amd64]) +Inst curl [8.14.1-2] (8.14.1-2+deb13u1 Debian:13.2/stable [amd64]) +Conf libssl3t64 (3.5.1-1+deb13u1 Debian-Security:13/stable-security [amd64]) +""" + + +def stub(bindir, name, script): + path = os.path.join(bindir, name) + with open(path, "w") as f: + f.write("#!/bin/sh\n" + script) + os.chmod(path, os.stat(path).st_mode | stat.S_IEXEC) + + +class AgentCase(unittest.TestCase): + def setUp(self): + self._tmp = tempdir() + self.tmp = self._tmp.name + self.root = os.path.join(self.tmp, "root") + self.bin = os.path.join(self.tmp, "bin") + for d in ("etc/kernelwatch", "proc", "run", "var/lib/apt/periodic", self.bin): + os.makedirs(os.path.join(self.root, d), exist_ok=True) + with open(os.path.join(self.root, "etc/os-release"), "w") as f: + f.write('PRETTY_NAME="Debian GNU/Linux 13 (trixie)"\nID=debian\nVERSION_ID="13"\n') + with open(os.path.join(self.root, "proc/uptime"), "w") as f: + f.write("93784.21 180000.00\n") + stamp = os.path.join(self.root, "var/lib/apt/periodic/update-success-stamp") + open(stamp, "w").close() + two_hours_ago = time.time() - 7200 + os.utime(stamp, (two_hours_ago, two_hours_ago)) + + stub(self.bin, "uname", 'case "$1" in -r) echo 6.12.48+deb13-amd64;; ' + '-v) echo "#1 SMP PREEMPT_DYNAMIC Debian 6.12.48-1";; esac\n') + stub(self.bin, "hostname", "echo web01.example\n") + stub(self.bin, "dpkg-query", f"cat <<'X'\n{DPKG_DEBIAN}X\n") + stub(self.bin, "apt-get", f"cat <<'X'\n{APT_SIM_DEBIAN}X\n") + + def tearDown(self): + self._tmp.cleanup() + + def run_agent(self, *args, env=None): + full_env = { + "PATH": f"{self.bin}:{os.environ['PATH']}", + "KERNELWATCH_ROOT": self.root, + **(env or {}), + } + return subprocess.run(["bash", AGENT, *args], env=full_env, capture_output=True, + text=True, timeout=30) + + def report(self): + proc = self.run_agent("--print") + self.assertEqual(proc.returncode, 0, proc.stderr) + return json.loads(proc.stdout) + + +@unittest.skipUnless(shutil.which("bash") and shutil.which("curl"), "needs bash and curl") +class AgentReportTest(AgentCase): + def test_debian_report(self): + r = self.report() + self.assertEqual(r["os_id"], "debian") + self.assertEqual(r["os_version_id"], "13") + self.assertEqual(r["os_pretty_name"], "Debian GNU/Linux 13 (trixie)") + self.assertEqual(r["reported_hostname"], "web01.example") + self.assertEqual(r["kernel_running"], "6.12.48+deb13-amd64") + self.assertEqual(r["kernels_installed"], ["6.12.48+deb13-amd64", "6.12.57+deb13-amd64"]) + self.assertEqual(r["kernel_newest_installed"], "6.12.57+deb13-amd64") + self.assertIsNone(r["needrestart_ksta"]) + self.assertFalse(r["reboot_required"]) + self.assertEqual(r["upgradable_count"], 3) + self.assertEqual(r["security_count"], 2) + self.assertEqual(r["kernel_upgradable"], ["linux-image-6.12.60+deb13-amd64"]) + self.assertAlmostEqual(r["apt_lists_age_seconds"], 7200, delta=60) + self.assertEqual(r["uptime_seconds"], 93784) + + def test_ubuntu_with_needrestart_and_reboot_required(self): + with open(os.path.join(self.root, "etc/os-release"), "w") as f: + f.write('PRETTY_NAME="Ubuntu 24.04.3 LTS"\nID=ubuntu\nVERSION_ID="24.04"\n') + stub(self.bin, "uname", 'case "$1" in -r) echo 6.8.0-85-generic;; -v) echo "#85-Ubuntu";; esac\n') + stub(self.bin, "dpkg-query", "printf 'ii linux-image-6.8.0-85-generic\\n" + "ii linux-image-unsigned-6.8.0-100-generic\\n'\n") + stub(self.bin, "apt-get", "echo 'NOTE: This is only a simulation!'\n") + stub(self.bin, "needrestart", "printf 'NEEDRESTART-VER: 3.6\\nNEEDRESTART-KCUR: 6.8.0-85-generic\\n" + "NEEDRESTART-KEXP: 6.8.0-100-generic\\nNEEDRESTART-KSTA: 3\\n'\n") + open(os.path.join(self.root, "run/reboot-required"), "w").close() + with open(os.path.join(self.root, "run/reboot-required.pkgs"), "w") as f: + f.write('linux-image-6.8.0-100-generic\nlinux-base\nlinux-base\n') + + r = self.report() + self.assertEqual(r["os_id"], "ubuntu") + self.assertEqual(r["kernel_newest_installed"], "6.8.0-100-generic", "sort -V, not lexical") + self.assertEqual(r["needrestart_ksta"], 3) + self.assertEqual(r["needrestart_kexp"], "6.8.0-100-generic") + self.assertTrue(r["reboot_required"]) + self.assertEqual(r["reboot_required_pkgs"], ["linux-base", "linux-image-6.8.0-100-generic"]) + self.assertEqual(r["upgradable_count"], 0) + self.assertEqual(r["security_count"], 0) + self.assertEqual(r["kernel_upgradable"], []) + + def test_hostile_strings_stay_valid_json(self): + stub(self.bin, "hostname", "printf 'a\"b\\\\c\\tq'\n") + self.assertEqual(self.report()["reported_hostname"], 'a"b\\cq') + + def test_missing_apt_stamps(self): + os.remove(os.path.join(self.root, "var/lib/apt/periodic/update-success-stamp")) + self.assertIsNone(self.report()["apt_lists_age_seconds"]) + + def test_send_without_config_fails_cleanly(self): + proc = self.run_agent() + self.assertNotEqual(proc.returncode, 0) + self.assertIn("SERVER_URL", proc.stderr) + + +@unittest.skipUnless(shutil.which("bash") and shutil.which("curl"), "needs bash and curl") +class AgentEndToEndTest(AgentCase): + def test_agent_reports_to_server(self): + cfg = temp_config(self.tmp) + server = web.make_server(cfg) + threading.Thread(target=server.serve_forever, daemon=True).start() + try: + token = auth.new_token() + conn = db.connect(cfg.db_path) + db.add_host(conn, "web01", auth.token_hash(token)) + conn.close() + + port = server.server_address[1] + with open(os.path.join(self.root, "etc/kernelwatch/agent.conf"), "w") as f: + f.write(f"SERVER_URL=http://127.0.0.1:{port}/\n") + creds = os.path.join(self.tmp, "creds") + os.mkdir(creds) + with open(os.path.join(creds, "token"), "w") as f: + f.write(token + "\n") + + proc = self.run_agent(env={"CREDENTIALS_DIRECTORY": creds}) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertNotIn(token, proc.stdout + proc.stderr) + + conn = db.connect(cfg.db_path) + latest = db.latest_reports(conn) + conn.close() + self.assertEqual(latest[0]["report"]["kernel_newest_installed"], "6.12.57+deb13-amd64") + + with open(os.path.join(creds, "token"), "w") as f: + f.write("wrong-token\n") + proc = self.run_agent(env={"CREDENTIALS_DIRECTORY": creds}) + self.assertNotEqual(proc.returncode, 0) + finally: + server.shutdown() + server.server_close() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_report_auth_config.py b/tests/test_report_auth_config.py new file mode 100644 index 0000000..48daa3e --- /dev/null +++ b/tests/test_report_auth_config.py @@ -0,0 +1,71 @@ +import os +import unittest + +from helpers import tempdir +from kernelwatch import auth, config +from kernelwatch.report import ReportError, sanitize + + +class SanitizeTest(unittest.TestCase): + def test_drops_unknown_and_truncates(self): + out = sanitize({"kernel_running": "6.8.0-85-generic", "evil": "x", "os_id": "u" * 1000}) + self.assertNotIn("evil", out) + self.assertEqual(len(out["os_id"]), 256) + + def test_requires_kernel_running(self): + with self.assertRaises(ReportError): + sanitize({"os_id": "debian"}) + + def test_type_checks(self): + for field, bad in (("security_count", "3"), ("security_count", True), + ("reboot_required", 1), ("kernels_installed", ["a", 2])): + with self.subTest(field=field, value=bad), self.assertRaises(ReportError): + sanitize({"kernel_running": "x", field: bad}) + + def test_nulls_allowed(self): + self.assertIsNone(sanitize({"kernel_running": "x", "needrestart_ksta": None})["needrestart_ksta"]) + + def test_not_an_object(self): + with self.assertRaises(ReportError): + sanitize([1, 2]) + + +class AuthTest(unittest.TestCase): + def test_password_roundtrip(self): + h = auth.hash_password("correct horse battery staple") + self.assertTrue(auth.verify_password("correct horse battery staple", h)) + self.assertFalse(auth.verify_password("wrong", h)) + + def test_garbage_hash(self): + self.assertFalse(auth.verify_password("x", "nonsense")) + self.assertFalse(auth.verify_password("x", "scrypt$a$b$c$d$e")) + + def test_tokens_unique(self): + self.assertNotEqual(auth.new_token(), auth.new_token()) + + +class ConfigTest(unittest.TestCase): + def write(self, tmp, text): + path = os.path.join(tmp, "server.toml") + with open(path, "w") as f: + f.write(text) + return path + + def test_load(self): + with tempdir() as tmp: + cfg = config.load(self.write(tmp, "listen_port = 9000\nstale_after_hours = 2\n")) + self.assertEqual(cfg.listen_port, 9000) + self.assertEqual(cfg.stale_after_hours, 2.0) + + def test_rejects_unknown_and_wrong_types(self): + with tempdir() as tmp: + with self.assertRaises(SystemExit): + config.load(self.write(tmp, "listen_prot = 9000\n")) + with self.assertRaises(SystemExit): + config.load(self.write(tmp, 'listen_port = "9000"\n')) + with self.assertRaises(SystemExit): + config.load(self.write(tmp, "secure_cookies = 1\n")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_status.py b/tests/test_status.py new file mode 100644 index 0000000..82103a2 --- /dev/null +++ b/tests/test_status.py @@ -0,0 +1,88 @@ +import unittest + +from helpers import Config +from kernelwatch.status import evaluate + +NOW = 1_800_000_000 +CFG = Config() + + +def report(**kw): + base = { + "kernel_running": "6.12.57+deb13-amd64", + "kernel_newest_installed": "6.12.57+deb13-amd64", + "needrestart_ksta": 1, + "reboot_required": False, + "security_count": 0, + "upgradable_count": 0, + "kernel_upgradable": [], + "apt_lists_age_seconds": 3600, + } + base.update(kw) + return base + + +class EvaluateTest(unittest.TestCase): + def level(self, rep, age=60): + return evaluate(NOW - age, rep, NOW, CFG) + + def test_ok(self): + s = self.level(report()) + self.assertEqual(s.level, "ok", s.reasons) + self.assertEqual(s.reasons, []) + + def test_never_reported(self): + self.assertEqual(evaluate(None, None, NOW, CFG).level, "stale") + + def test_stale_beats_everything(self): + s = self.level(report(needrestart_ksta=3), age=5 * 3600) + self.assertEqual(s.level, "stale") + self.assertTrue(any("kernel" in r for r in s.reasons), "still explains the kernel") + + def test_needrestart_version_upgrade(self): + s = self.level(report(needrestart_ksta=3, needrestart_kexp="6.12.60+deb13-amd64")) + self.assertEqual(s.level, "reboot") + self.assertIn("6.12.60+deb13-amd64", s.reasons[0]) + + def test_needrestart_abi_upgrade(self): + self.assertEqual(self.level(report(needrestart_ksta=2)).level, "reboot") + + def test_needrestart_current_trusted_over_name_compare(self): + rep = report(needrestart_ksta=1, kernel_newest_installed="6.12.60+deb13-amd64") + self.assertEqual(self.level(rep).level, "ok") + + def test_fallback_without_needrestart(self): + rep = report(needrestart_ksta=None, kernel_newest_installed="6.12.60+deb13-amd64") + self.assertEqual(self.level(rep).level, "reboot") + rep = report(needrestart_ksta=0) + self.assertEqual(self.level(rep).level, "ok") + + def test_reboot_required_file(self): + s = self.level(report(reboot_required=True, reboot_required_pkgs=["libc6", "dbus"])) + self.assertEqual(s.level, "reboot") + self.assertIn("libc6", s.reasons[0]) + + def test_kernel_update_available(self): + s = self.level(report(kernel_upgradable=["linux-image-6.12.60+deb13-amd64"])) + self.assertEqual(s.level, "update") + + def test_security_updates(self): + s = self.level(report(security_count=3, upgradable_count=5)) + self.assertEqual(s.level, "update") + self.assertEqual(s.reasons, ["3 security updates pending"]) + + def test_non_security_updates_are_ok(self): + self.assertEqual(self.level(report(upgradable_count=5)).level, "ok") + + def test_old_package_lists(self): + self.assertEqual(self.level(report(apt_lists_age_seconds=5 * 86400)).level, "update") + self.assertEqual(self.level(report(apt_lists_age_seconds=None)).level, "update") + + def test_reboot_outranks_update(self): + s = self.level(report(needrestart_ksta=3, security_count=2)) + self.assertEqual(s.level, "reboot") + self.assertEqual(len(s.reasons), 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_web.py b/tests/test_web.py new file mode 100644 index 0000000..9c63d8a --- /dev/null +++ b/tests/test_web.py @@ -0,0 +1,165 @@ +import json +import threading +import unittest +import urllib.error +import urllib.parse +import urllib.request + +from helpers import temp_config, tempdir +from kernelwatch import auth, db, web + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *args, **kwargs): + return None + + +OPENER = urllib.request.build_opener(NoRedirect) + + +class ServerCase(unittest.TestCase): + """Runs a real server on an ephemeral port with a temp database.""" + + def setUp(self): + self._tmp = tempdir() + self.cfg = temp_config(self._tmp.name) + self.server = web.make_server(self.cfg) + self.base = "http://127.0.0.1:%d" % self.server.server_address[1] + threading.Thread(target=self.server.serve_forever, daemon=True).start() + + def tearDown(self): + self.server.shutdown() + self.server.server_close() + self._tmp.cleanup() + + def request(self, method, path, body=None, headers=None): + req = urllib.request.Request(self.base + path, data=body, method=method, headers=headers or {}) + try: + with OPENER.open(req) as resp: + return resp.status, dict(resp.headers), resp.read().decode() + except urllib.error.HTTPError as err: + with err: + return err.code, dict(err.headers), err.read().decode() + + def add_host(self, name): + token = auth.new_token() + conn = db.connect(self.cfg.db_path) + db.add_host(conn, name, auth.token_hash(token)) + conn.close() + return token + + def add_user(self, name, password): + conn = db.connect(self.cfg.db_path) + db.set_user(conn, name, auth.hash_password(password)) + conn.close() + + def post_report(self, token, payload): + return self.request("POST", "/api/v1/report", json.dumps(payload).encode(), + {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}) + + def login(self, username, password, headers=None): + body = urllib.parse.urlencode({"username": username, "password": password}).encode() + return self.request("POST", "/login", body, + {"Content-Type": "application/x-www-form-urlencoded", **(headers or {})}) + + +class IngestTest(ServerCase): + def test_requires_valid_token(self): + self.add_host("web01") + self.assertEqual(self.post_report("", {"kernel_running": "x"})[0], 401) + self.assertEqual(self.post_report("nope", {"kernel_running": "x"})[0], 401) + + def test_accepts_report_and_binds_host_to_token(self): + token = self.add_host("web01") + status, _, _ = self.post_report(token, {"kernel_running": "6.8.0-85-generic", + "reported_hostname": "spoofed"}) + self.assertEqual(status, 204) + conn = db.connect(self.cfg.db_path) + latest = db.latest_reports(conn) + conn.close() + self.assertEqual(latest[0]["host"], "web01") + self.assertEqual(latest[0]["report"]["kernel_running"], "6.8.0-85-generic") + + def test_rejects_bad_payloads(self): + token = self.add_host("web01") + self.assertEqual(self.post_report(token, {"os_id": "debian"})[0], 400) + status, _, _ = self.request("POST", "/api/v1/report", b"{not json", + {"Authorization": f"Bearer {token}"}) + self.assertEqual(status, 400) + status, _, _ = self.request("POST", "/api/v1/report", b"x" * (70 * 1024), + {"Authorization": f"Bearer {token}"}) + self.assertEqual(status, 413) + + +class DashboardTest(ServerCase): + def test_requires_login(self): + for path in ("/", "/host/web01"): + status, headers, _ = self.request("GET", path) + self.assertEqual(status, 303) + self.assertEqual(headers["Location"], "/login") + + def test_public_endpoints(self): + self.assertEqual(self.request("GET", "/healthz")[0], 200) + self.assertEqual(self.request("GET", "/login")[0], 200) + + def test_bad_login(self): + self.add_user("admin", "a-long-password") + self.assertEqual(self.login("admin", "wrong")[0], 401) + self.assertEqual(self.login("nobody", "a-long-password")[0], 401) + + def test_login_rate_limited(self): + self.add_user("admin", "a-long-password") + for _ in range(web.LOGIN_MAX_FAILURES): + self.login("admin", "wrong") + self.assertEqual(self.login("admin", "a-long-password")[0], 429) + + def test_cross_origin_login_refused(self): + self.add_user("admin", "a-long-password") + status, _, _ = self.login("admin", "a-long-password", {"Origin": "https://evil.example"}) + self.assertEqual(status, 403) + + def test_login_dashboard_logout(self): + self.add_user("admin", "a-long-password") + token = self.add_host("web01") + self.add_host("db01") # never reports + self.post_report(token, {"kernel_running": "6.8.0-85-generic", + "kernel_newest_installed": "6.8.0-87-generic", + "os_pretty_name": "Ubuntu 24.04.3 LTS ", + "apt_lists_age_seconds": 60}) + + status, headers, _ = self.login("admin", "a-long-password") + self.assertEqual(status, 303) + cookie = headers["Set-Cookie"].split(";")[0] + self.assertIn("HttpOnly", headers["Set-Cookie"]) + self.assertIn("SameSite=Strict", headers["Set-Cookie"]) + + status, _, body = self.request("GET", "/", headers={"Cookie": cookie}) + self.assertEqual(status, 200) + self.assertIn("web01", body) + self.assertIn("db01", body) + self.assertIn("6.8.0-87-generic installed", body) + self.assertIn("never reported", body) + self.assertIn("<b>", body, "report content must be escaped") + self.assertNotIn("\n", body) + # Worst first: stale db01 before reboot web01. + self.assertLess(body.index("db01"), body.index("web01")) + + status, _, body = self.request("GET", "/host/web01", headers={"Cookie": cookie}) + self.assertEqual(status, 200) + self.assertIn("Recent reports", body) + self.assertEqual(self.request("GET", "/host/nope", headers={"Cookie": cookie})[0], 404) + + status, _, _ = self.request("POST", "/logout", b"", {"Cookie": cookie}) + self.assertEqual(status, 303) + self.assertEqual(self.request("GET", "/", headers={"Cookie": cookie})[0], 303) + + def test_password_change_ends_sessions(self): + self.add_user("admin", "a-long-password") + _, headers, _ = self.login("admin", "a-long-password") + cookie = headers["Set-Cookie"].split(";")[0] + self.add_user("admin", "another-long-password") + self.assertEqual(self.request("GET", "/", headers={"Cookie": cookie})[0], 303) + + +if __name__ == "__main__": + unittest.main()