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 <noreply@anthropic.com>
This commit is contained in:
patrickandClaude Opus 5.5 committed 2026-10-17 10:15:06 -04:00
commit 07749b01b0
27 files changed
+2406

No files matched your search

+14
View File
@@ -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
+83
View File
@@ -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 <name>` 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
+257
View File
@@ -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 <<EOF
Usage: kernelwatch-agent [--print] [--help]
Collects kernel and package update state and POSTs it to the kernelwatch server.
--print print the JSON report to stdout instead of sending it
--help show this help
Configuration is read from $CONF.
EOF
}
die() {
echo "kernelwatch-agent: $*" >&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 "$@"
+36
View File
@@ -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
+13
View File
@@ -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