Run the agent unprivileged; detect in-place kernel upgrades

The agent ran as (capability-less) root only so needrestart could read
Ubuntu's root-only /boot images. Switch the unit to DynamicUser=yes and
make needrestart optional.

To cover the case needrestart was catching (running kernel's package
upgraded in place, same uname -r), the agent now reports the installed
package version of the running kernel and the server compares it with
the build in uname -v: "Debian 6.12.57-1" vs 6.12.57-1 on Debian,
"#85-Ubuntu" / "#33~24.04.1-Ubuntu" vs the upload part of 6.8.0-85.85 /
6.14.0-33.33~24.04.1 on Ubuntu. Unrecognised builds fall back to
needrestart and the newest-installed comparison.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
patrickandClaude Opus 5.5 committed 2026-10-17 10:19:41 -04:00
1 parent 07749b01b0
commit 48f2d155af
9 files changed
+109 -23

No files matched your search

+14 -11
View File
@@ -35,12 +35,16 @@ its full report and recent history.
How the agent works it out: How the agent works it out:
- **Running vs. installed kernel**: if [`needrestart`](https://github.com/liske/needrestart) - **Running vs. installed kernel**, three ways:
is installed, the agent uses `needrestart -b -k`, which also catches - A newer `linux-image-*` installed than `uname -r` means a version upgrade.
ABI-compatible upgrades where the package name stays the same. Otherwise it - The build in `uname -v` (`Debian 6.12.57-1`, `#85-Ubuntu`, `#33~24.04.1-Ubuntu`)
compares `uname -r` with the newest installed `linux-image-*` package. is compared with the installed package version of the running kernel
Ubuntu 24.04 ships needrestart by default. **On Debian, install it** (`6.12.57-1`, `6.8.0-85.85`, `6.14.0-33.33~24.04.1`). A mismatch means the
(`apt install needrestart`) for accurate results. package was upgraded in place after boot; `uname -r` didn't change, but a
reboot is still needed.
- [`needrestart`](https://github.com/liske/needrestart) `-b -k`, when it's
installed and can read `/boot`. It's optional. The agent runs unprivileged, so
on Ubuntu (root-only `/boot/vmlinuz-*`) it reports "unknown" and is ignored.
- **Available updates**: a simulated `apt-get dist-upgrade`. It is read-only, takes - **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 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 packages pulled in by the meta-package show up. Lines whose origin contains
@@ -152,11 +156,10 @@ sudo kernelwatch list-users
- **Host identity comes from the token, not the payload.** A host can only - **Host identity comes from the token, not the payload.** A host can only
report as itself. Tokens are 256-bit random values; only their SHA-256 is stored. report 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 - **The agent** runs as a throwaway unprivileged user (`DynamicUser=yes`) with
read-only filesystem view and a syscall filter. It runs as uid 0 only because no capabilities, a read-only filesystem view and a syscall filter. The token
Ubuntu's `/boot/vmlinuz-*` files are root-only, and needrestart has to read reaches it through `LoadCredential=` and goes to curl on stdin, so it never
them. The token reaches it through `LoadCredential=` and goes to curl on stdin, appears in a process listing.
so it never appears in a process listing.
- **The dashboard** uses scrypt-hashed passwords, server-side sessions, - **The dashboard** uses scrypt-hashed passwords, server-side sessions,
`HttpOnly` + `Secure` + `SameSite=Strict` cookies, an Origin check on form `HttpOnly` + `Secure` + `SameSite=Strict` cookies, an Origin check on form
posts, per-IP login rate limiting, and a strict CSP. Everything a host posts, per-IP login rate limiting, and a strict CSP. Everything a host
-4
View File
@@ -33,10 +33,6 @@ esac
if ! command -v curl >/dev/null; then if ! command -v curl >/dev/null; then
apt-get install -y --no-install-recommends curl ca-certificates apt-get install -y --no-install-recommends curl ca-certificates
fi 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 -d -m 0755 /etc/kernelwatch
install -m 0755 "$here/kernelwatch-agent" /usr/local/sbin/kernelwatch-agent install -m 0755 "$here/kernelwatch-agent" /usr/local/sbin/kernelwatch-agent
+11 -1
View File
@@ -114,8 +114,17 @@ installed_kernels() {
sort -uV || true sort -uV || true
} }
# Package version of the image for the running kernel (e.g. 6.12.57-1). The
# server compares it with the build in `uname -v` to spot in-place upgrades.
running_kernel_pkg_version() {
dpkg-query -W -f='${db:Status-Abbrev} ${Version}\n' \
"linux-image-$1" "linux-image-unsigned-$1" 2>/dev/null |
awk '$1 == "ii" { print $2; exit }' || true
}
# Sets NR_KSTA / NR_KEXP from `needrestart -b`. KSTA: 0 unknown, 1 current, # Sets NR_KSTA / NR_KEXP from `needrestart -b`. KSTA: 0 unknown, 1 current,
# 2 ABI-compatible upgrade pending, 3 version upgrade pending. # 2 ABI-compatible upgrade pending, 3 version upgrade pending. Optional: as a
# normal user it can't read Ubuntu's root-only /boot images and reports 0.
NR_KSTA= NR_KSTA=
NR_KEXP= NR_KEXP=
read_needrestart() { read_needrestart() {
@@ -186,6 +195,7 @@ build_report() {
printf '"os_pretty_name":%s,' "$(json_str "$(os_release_field PRETTY_NAME)")" printf '"os_pretty_name":%s,' "$(json_str "$(os_release_field PRETTY_NAME)")"
printf '"kernel_running":%s,' "$(json_str "$running")" printf '"kernel_running":%s,' "$(json_str "$running")"
printf '"kernel_build":%s,' "$(json_str "$(uname -v)")" printf '"kernel_build":%s,' "$(json_str "$(uname -v)")"
printf '"kernel_running_pkg_version":%s,' "$(json_str "$(running_kernel_pkg_version "$running")")"
printf '"kernels_installed":%s,' "$(json_str_array <<<"$kernels")" printf '"kernels_installed":%s,' "$(json_str_array <<<"$kernels")"
printf '"kernel_newest_installed":%s,' "$(json_str "$newest")" printf '"kernel_newest_installed":%s,' "$(json_str "$newest")"
printf '"needrestart_ksta":%s,' "$(json_int "$NR_KSTA")" printf '"needrestart_ksta":%s,' "$(json_int "$NR_KSTA")"
+3 -4
View File
@@ -8,10 +8,9 @@ Type=oneshot
ExecStart=/usr/local/sbin/kernelwatch-agent ExecStart=/usr/local/sbin/kernelwatch-agent
LoadCredential=token:/etc/kernelwatch/agent.token LoadCredential=token:/etc/kernelwatch/agent.token
# Runs as root only so needrestart can read the root-only kernel images in # Everything the agent reads is world-readable, so it runs as a throwaway
# /boot (mode 0600 on Ubuntu). It holds no capabilities and sees a read-only # unprivileged user. The token credential is made readable to that user.
# filesystem. DynamicUser=yes
User=root
CapabilityBoundingSet= CapabilityBoundingSet=
AmbientCapabilities= AmbientCapabilities=
NoNewPrivileges=yes NoNewPrivileges=yes
+1
View File
@@ -22,6 +22,7 @@ FIELDS: dict[str, str] = {
"os_pretty_name": "str", "os_pretty_name": "str",
"kernel_running": "str", "kernel_running": "str",
"kernel_build": "str", "kernel_build": "str",
"kernel_running_pkg_version": "str",
"kernels_installed": "strlist", "kernels_installed": "strlist",
"kernel_newest_installed": "str", "kernel_newest_installed": "str",
"needrestart_ksta": "int", "needrestart_ksta": "int",
+30
View File
@@ -9,6 +9,7 @@ Levels, worst first:
from __future__ import annotations from __future__ import annotations
import re
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import Any from typing import Any
@@ -38,9 +39,38 @@ class Status:
return _RANK[self.level] return _RANK[self.level]
# Debian `uname -v`: "#1 SMP PREEMPT_DYNAMIC Debian 6.12.57-1 (2025-11-05)"
_DEBIAN_BUILD = re.compile(r"\bDebian (\S+)")
# Ubuntu `uname -v`: "#85-Ubuntu SMP ..." (GA) or "#33~24.04.1-Ubuntu SMP ..." (HWE)
_UBUNTU_BUILD = re.compile(r"^#(\S+)-Ubuntu\b")
# Ubuntu package version: "6.8.0-85.85" or "6.14.0-33.33~24.04.1"; upload part after "-ABI."
_UBUNTU_PKG = re.compile(r"^\d+\.\d+\.\d+-\d+\.(\S+)$")
def running_build_outdated(report: dict[str, Any]) -> tuple[str, str] | None:
"""(running build, installed package version) if the running kernel's package was
upgraded in place since boot (same `uname -r`, new build), else None.
None also means "can't tell", e.g. an unrecognised build string."""
build = report.get("kernel_build") or ""
pkg = report.get("kernel_running_pkg_version")
if not pkg:
return None
if m := _DEBIAN_BUILD.search(build):
running = m.group(1)
return (running, pkg) if running != pkg else None
if (m := _UBUNTU_BUILD.match(build)) and (p := _UBUNTU_PKG.match(pkg)):
return (m.group(1), p.group(1)) if m.group(1) != p.group(1) else None
return None
def kernel_reboot_pending(report: dict[str, Any]) -> str | None: 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).""" """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 "?" running = report.get("kernel_running") or "?"
if outdated := running_build_outdated(report):
built, installed = outdated
return f"running {running} build {built}, package upgraded in place to {installed}"
ksta = report.get("needrestart_ksta") ksta = report.get("needrestart_ksta")
if ksta == KSTA_VERSION_UPGRADE: if ksta == KSTA_VERSION_UPGRADE:
expected = report.get("needrestart_kexp") or report.get("kernel_newest_installed") or "?" expected = report.get("needrestart_kexp") or report.get("kernel_newest_installed") or "?"
+1
View File
@@ -461,6 +461,7 @@ class Handler(BaseHTTPRequestHandler):
field("OS", r.get("os_pretty_name")), field("OS", r.get("os_pretty_name")),
field("Running kernel", r.get("kernel_running"), code=True), field("Running kernel", r.get("kernel_running"), code=True),
field("Kernel build", r.get("kernel_build"), code=True), field("Kernel build", r.get("kernel_build"), code=True),
field("Running kernel package", r.get("kernel_running_pkg_version"), code=True),
field("Installed kernels", r.get("kernels_installed"), code=True), field("Installed kernels", r.get("kernels_installed"), code=True),
field("needrestart", None if r.get("needrestart_ksta") is None else field("needrestart", None if r.get("needrestart_ksta") is None else
f"KSTA={r['needrestart_ksta']} expected={r.get('needrestart_kexp') or '?'}"), f"KSTA={r['needrestart_ksta']} expected={r.get('needrestart_kexp') or '?'}"),
+12 -3
View File
@@ -11,6 +11,7 @@ import unittest
from helpers import REPO, temp_config, tempdir from helpers import REPO, temp_config, tempdir
from kernelwatch import auth, db, web from kernelwatch import auth, db, web
from kernelwatch.status import evaluate
AGENT = os.path.join(REPO, "agent", "kernelwatch-agent") AGENT = os.path.join(REPO, "agent", "kernelwatch-agent")
@@ -58,7 +59,8 @@ class AgentCase(unittest.TestCase):
stub(self.bin, "uname", 'case "$1" in -r) echo 6.12.48+deb13-amd64;; ' 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') '-v) echo "#1 SMP PREEMPT_DYNAMIC Debian 6.12.48-1";; esac\n')
stub(self.bin, "hostname", "echo web01.example\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, "dpkg-query", 'case "$*" in *Version*) echo "ii 6.12.48-2";; *) cat <<\'X\'\n'
f"{DPKG_DEBIAN}X\n;; esac\n")
stub(self.bin, "apt-get", f"cat <<'X'\n{APT_SIM_DEBIAN}X\n") stub(self.bin, "apt-get", f"cat <<'X'\n{APT_SIM_DEBIAN}X\n")
def tearDown(self): def tearDown(self):
@@ -90,6 +92,7 @@ class AgentReportTest(AgentCase):
self.assertEqual(r["kernel_running"], "6.12.48+deb13-amd64") 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["kernels_installed"], ["6.12.48+deb13-amd64", "6.12.57+deb13-amd64"])
self.assertEqual(r["kernel_newest_installed"], "6.12.57+deb13-amd64") self.assertEqual(r["kernel_newest_installed"], "6.12.57+deb13-amd64")
self.assertEqual(r["kernel_running_pkg_version"], "6.12.48-2")
self.assertIsNone(r["needrestart_ksta"]) self.assertIsNone(r["needrestart_ksta"])
self.assertFalse(r["reboot_required"]) self.assertFalse(r["reboot_required"])
self.assertEqual(r["upgradable_count"], 3) self.assertEqual(r["upgradable_count"], 3)
@@ -102,8 +105,9 @@ class AgentReportTest(AgentCase):
with open(os.path.join(self.root, "etc/os-release"), "w") as f: 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') 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, "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" stub(self.bin, "dpkg-query", 'case "$*" in *Version*) echo "ii 6.8.0-85.85";; '
"ii linux-image-unsigned-6.8.0-100-generic\\n'\n") "*) printf 'ii linux-image-6.8.0-85-generic\\n"
"ii linux-image-unsigned-6.8.0-100-generic\\n';; esac\n")
stub(self.bin, "apt-get", "echo 'NOTE: This is only a simulation!'\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" 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") "NEEDRESTART-KEXP: 6.8.0-100-generic\\nNEEDRESTART-KSTA: 3\\n'\n")
@@ -114,6 +118,7 @@ class AgentReportTest(AgentCase):
r = self.report() r = self.report()
self.assertEqual(r["os_id"], "ubuntu") self.assertEqual(r["os_id"], "ubuntu")
self.assertEqual(r["kernel_newest_installed"], "6.8.0-100-generic", "sort -V, not lexical") self.assertEqual(r["kernel_newest_installed"], "6.8.0-100-generic", "sort -V, not lexical")
self.assertEqual(r["kernel_running_pkg_version"], "6.8.0-85.85")
self.assertEqual(r["needrestart_ksta"], 3) self.assertEqual(r["needrestart_ksta"], 3)
self.assertEqual(r["needrestart_kexp"], "6.8.0-100-generic") self.assertEqual(r["needrestart_kexp"], "6.8.0-100-generic")
self.assertTrue(r["reboot_required"]) self.assertTrue(r["reboot_required"])
@@ -164,6 +169,10 @@ class AgentEndToEndTest(AgentCase):
latest = db.latest_reports(conn) latest = db.latest_reports(conn)
conn.close() conn.close()
self.assertEqual(latest[0]["report"]["kernel_newest_installed"], "6.12.57+deb13-amd64") self.assertEqual(latest[0]["report"]["kernel_newest_installed"], "6.12.57+deb13-amd64")
# Stub uname -v says build 6.12.48-1, dpkg says 6.12.48-2: upgraded in place.
status = evaluate(latest[0]["received_at"], latest[0]["report"], time.time(), cfg)
self.assertEqual(status.level, "reboot")
self.assertIn("upgraded in place to 6.12.48-2", status.reasons[0])
with open(os.path.join(creds, "token"), "w") as f: with open(os.path.join(creds, "token"), "w") as f:
f.write("wrong-token\n") f.write("wrong-token\n")
+37
View File
@@ -57,6 +57,43 @@ class EvaluateTest(unittest.TestCase):
rep = report(needrestart_ksta=0) rep = report(needrestart_ksta=0)
self.assertEqual(self.level(rep).level, "ok") self.assertEqual(self.level(rep).level, "ok")
def test_debian_in_place_upgrade(self):
build = "#1 SMP PREEMPT_DYNAMIC Debian 6.12.57-1 (2025-11-05)"
rep = report(needrestart_ksta=None, kernel_build=build, kernel_running_pkg_version="6.12.57-1")
self.assertEqual(self.level(rep).level, "ok")
rep["kernel_running_pkg_version"] = "6.12.57-2"
s = self.level(rep)
self.assertEqual(s.level, "reboot")
self.assertIn("upgraded in place to 6.12.57-2", s.reasons[0])
def test_debian_backport_build(self):
build = "#1 SMP PREEMPT_DYNAMIC Debian 6.12.9-1~bpo12+1 (2025-01-19)"
rep = report(kernel_build=build, kernel_running_pkg_version="6.12.9-1~bpo12+1")
self.assertEqual(self.level(rep).level, "ok")
def test_ubuntu_ga_in_place_upgrade(self):
build = "#85-Ubuntu SMP PREEMPT_DYNAMIC Thu Sep 18 15:26:59 UTC 2025"
rep = report(kernel_running="6.8.0-85-generic", kernel_newest_installed="6.8.0-85-generic",
needrestart_ksta=0, kernel_build=build, kernel_running_pkg_version="6.8.0-85.85")
self.assertEqual(self.level(rep).level, "ok")
rep["kernel_running_pkg_version"] = "6.8.0-85.86"
self.assertEqual(self.level(rep).level, "reboot")
def test_ubuntu_hwe_in_place_upgrade(self):
build = "#33~24.04.1-Ubuntu SMP PREEMPT_DYNAMIC Fri Sep 19 17:02:30 UTC 2025"
rep = report(kernel_running="6.14.0-33-generic", kernel_newest_installed="6.14.0-33-generic",
kernel_build=build, kernel_running_pkg_version="6.14.0-33.33~24.04.1")
self.assertEqual(self.level(rep).level, "ok")
rep["kernel_running_pkg_version"] = "6.14.0-33.34~24.04.1"
self.assertEqual(self.level(rep).level, "reboot")
def test_unrecognised_build_falls_back(self):
rep = report(needrestart_ksta=None, kernel_build="#1 SMP custom",
kernel_running_pkg_version="1.0", kernel_newest_installed="6.12.60+deb13-amd64")
self.assertIn("6.12.60+deb13-amd64 installed", self.level(rep).reasons[0])
rep["kernel_newest_installed"] = rep["kernel_running"]
self.assertEqual(self.level(rep).level, "ok")
def test_reboot_required_file(self): def test_reboot_required_file(self):
s = self.level(report(reboot_required=True, reboot_required_pkgs=["libc6", "dbus"])) s = self.level(report(reboot_required=True, reboot_required_pkgs=["libc6", "dbus"]))
self.assertEqual(s.level, "reboot") self.assertEqual(s.level, "reboot")