diff --git a/agent/kernelwatch-agent b/agent/kernelwatch-agent index 7e08156..40c10ea 100755 --- a/agent/kernelwatch-agent +++ b/agent/kernelwatch-agent @@ -6,7 +6,7 @@ # rules can change without redeploying agents. set -euo pipefail -AGENT_VERSION=0.8.0 +AGENT_VERSION=0.9.0 # Prefix for every file the agent reads. Only the test suite sets this. ROOT=${KERNELWATCH_ROOT:-} @@ -246,6 +246,45 @@ apt_lists_age() { printf '%s' $(($(date +%s) - newest)) } +# The release's security suite (trixie-security, noble-security) and how old, +# in seconds, apt's newest list for it is, as "SUITE AGE". The age is by the +# list's Date: field, when the repository last published as of apt's last +# successful fetch, so it grows if fetches fail even while other repositories +# refresh. AGE is empty if apt has no list for the suite: it isn't in the +# sources, and security updates can't arrive. Nothing at all without a release +# codename. Lists are matched by their Suite: (Ubuntu) or Codename: (Debian) +# field, since file names depend on the mirror; with several mirrors the newest +# counts. +APT_LISTS_DIR=$ROOT/var/lib/apt/lists +security_repo() { + local codename suite f published t newest=0 now + codename=$(os_release_field VERSION_CODENAME) + [[ -n $codename ]] || codename=$(os_release_field UBUNTU_CODENAME) + [[ $codename =~ ^[a-z]+$ ]] || return 0 + suite=$codename-security + for f in "$APT_LISTS_DIR"/*_InRelease "$APT_LISTS_DIR"/*_Release; do + [[ -f $f ]] || continue + # The fields come before the checksum lists, which can be long. + published=$(awk -v want="$suite" ' + /^(MD5Sum|SHA1|SHA256|SHA512):/ { exit } + ($1 == "Suite:" || $1 == "Codename:") && $2 == want { found = 1 } + $1 == "Date:" { sub(/^Date:[ \t]*/, ""); date = $0 } + END { if (found) print (date == "" ? "-" : date) }' "$f" 2>/dev/null) || continue + [[ -n $published ]] || continue + if [[ $published == - ]] || ! t=$(date -d "$published" +%s 2>/dev/null); then + # apt sets a list's mtime from the server's Last-Modified. + t=$(stat -c %Y "$f" 2>/dev/null) || continue + fi + ((t > newest)) && newest=$t + done + printf '%s ' "$suite" + if ((newest > 0)); then + now=$(date +%s) + printf '%s' $((now > newest ? now - newest : 0)) + fi + return 0 +} + # Size and free space of the filesystem holding /boot, in KiB, as "SIZE FREE"; # empty if df can't tell. That's the root filesystem when /boot isn't its own # mount. A full /boot makes the next kernel's postinst fail, so the host stays @@ -326,7 +365,7 @@ uptime_seconds() { build_report() { local running newest kernels sim inst sim_err rc apt_ok=1 apt_err='' reboot_file=0 reboot_pkgs= - local boot_size='' boot_free='' pro_attached='' pro_esm='' + local boot_size='' boot_free='' pro_attached='' pro_esm='' sec_suite='' sec_age='' running=$(uname -r) kernels=$(installed_kernels) @@ -352,6 +391,7 @@ build_report() { read -r boot_size boot_free <<<"$(boot_space)" || true read -r pro_attached pro_esm <<<"$(ubuntu_pro)" || true + read -r sec_suite sec_age <<<"$(security_repo)" || true [[ $pro_esm == - ]] && pro_esm= printf '{' @@ -404,6 +444,8 @@ build_report() { printf '"unattended_upgrades_kept_back":%s,' \ "$( { [[ -r $UU_KEPT_FILE ]] && tr -s ' \t' '\n' <"$UU_KEPT_FILE"; } | sort -u | json_str_array)" printf '"apt_lists_age_seconds":%s,' "$(json_int "$(apt_lists_age)")" + printf '"security_repo_suite":%s,' "$(json_str_or_null "$sec_suite")" + printf '"security_repo_age_seconds":%s,' "$(json_int "$sec_age")" printf '"uptime_seconds":%s' "$(json_int "$(uptime_seconds)")" printf '}\n' } diff --git a/docs/how-it-works.md b/docs/how-it-works.md index ac70042..488c2e0 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -10,7 +10,7 @@ Each host gets one status. When several apply, the worst one wins: |----------|---------| | `stale` | No report in `stale_after_hours` (default 3h), or never. Other data can't be trusted. | | `reboot` | A newer kernel is installed but not running, or `/run/reboot-required` exists. | -| `update` | A kernel or security update is available but not installed, services are running outdated libraries and need a restart, or apt's package lists are too old (`apt_stale_after_hours`) for "no updates" to mean anything. Also when `/boot` has less than `boot_min_free_mb` free, dpkg left packages half-installed, the OS release no longer gets security updates, or unattended-upgrades is enabled but hasn't succeeded in `unattended_upgrades_stale_after_days`. | +| `update` | A kernel or security update is available but not installed, services are running outdated libraries and need a restart, or apt's package lists are too old (`apt_stale_after_hours`) for "no updates" to mean anything. Also when `/boot` has less than `boot_min_free_mb` free, dpkg left packages half-installed, the OS release no longer gets security updates, unattended-upgrades is enabled but hasn't succeeded in `unattended_upgrades_stale_after_days`, or the release's security repository is missing from apt or hasn't refreshed in `security_repo_stale_after_days`. | | `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 @@ -134,6 +134,22 @@ How the agent works it out: `kernelwatch-apt-update.service` runs `apt-get update` just before each report, so updates show up within the hour. Either way, lists older than `apt_stale_after_hours` put the host in `update`. +- **Security repository**: security updates come from one suite, + `-security` (`trixie-security`, `noble-security`). A host whose apt + sources lack it sees "0 security updates" forever. One whose apt can't fetch + it (an expired key, a wrong URL after a release upgrade, a mirror that fell + behind) keeps the last copy while the update stamps and other lists move on. + So the agent finds apt's list for that suite by its `Suite:`/`Codename:` field + (file names depend on the mirror) and reports how old its `Date:` is, the + newest copy if there are several mirrors. No list puts the host in `update` + ("apt has no trixie-security repository"), and so does a copy older than + `security_repo_stale_after_days` (default 7; both suites publish at least + daily) while the package lists are otherwise fresh. If all the lists are old, + only "package lists N days old" is shown. ESM suites aren't checked, as they + publish rarely, and nor is a release past the end of support, whose suite has + stopped. The host page's "Security repository" row shows the suite and its + age. Set `security_repo_stale_after_days = 0` to turn this off, e.g. for a + local mirror that renames the suite. Agents before 0.9.0 don't report it. - **Phased updates** (Ubuntu only): Ubuntu rolls some updates out gradually and holds them back from a share of machines at first. apt doesn't offer these to the host yet, so they aren't counted as available updates. They appear as diff --git a/server/kernelwatch/__init__.py b/server/kernelwatch/__init__.py index f3d7612..7f1f5fa 100644 --- a/server/kernelwatch/__init__.py +++ b/server/kernelwatch/__init__.py @@ -4,4 +4,4 @@ __version__ = "0.4.0" # Version of agent/kernelwatch-agent shipped alongside this server; older agents # are noted on the dashboard. tests/test_status.py checks the two stay in sync. -AGENT_VERSION = "0.8.0" +AGENT_VERSION = "0.9.0" diff --git a/server/kernelwatch/config.py b/server/kernelwatch/config.py index 5b943c4..96653eb 100644 --- a/server/kernelwatch/config.py +++ b/server/kernelwatch/config.py @@ -40,6 +40,11 @@ class Config: # A host with unattended-upgrades enabled that hasn't had a successful run in this # long is in update. It normally runs daily. 0 disables the check. unattended_upgrades_stale_after_days: float = 3.0 + # A host whose apt lists have no repository for its release's security suite + # (e.g. trixie-security), or whose copy of it is older than this while its other + # lists refresh, is in update: security updates can't reach it. Debian and + # Ubuntu publish it at least daily. 0 disables the check. + security_repo_stale_after_days: float = 7.0 # Where `scheduled-backup` (kernelwatch-backup.timer) writes dated copies of the # database, and how many days of them it keeps; 0 keeps them all. It must stay @@ -105,6 +110,8 @@ def load(path: str | None = None) -> Config: raise SystemExit(f"{path}: report_min_interval_seconds must be zero or positive") if not math.isfinite(cfg.unattended_upgrades_stale_after_days) or cfg.unattended_upgrades_stale_after_days < 0: raise SystemExit(f"{path}: unattended_upgrades_stale_after_days must be zero or positive and finite") + if not math.isfinite(cfg.security_repo_stale_after_days) or cfg.security_repo_stale_after_days < 0: + raise SystemExit(f"{path}: security_repo_stale_after_days must be zero or positive and finite") if cfg.os_eol_warn_days < 0: raise SystemExit(f"{path}: os_eol_warn_days must be zero or positive") if cfg.boot_min_free_mb < 0: diff --git a/server/kernelwatch/report.py b/server/kernelwatch/report.py index be549c4..6fe5581 100644 --- a/server/kernelwatch/report.py +++ b/server/kernelwatch/report.py @@ -52,6 +52,8 @@ FIELDS: dict[str, str] = { "unattended_upgrades_run_age_seconds": "int", "unattended_upgrades_kept_back": "strlist", "apt_lists_age_seconds": "int", + "security_repo_suite": "str", + "security_repo_age_seconds": "int", "uptime_seconds": "int", } diff --git a/server/kernelwatch/status.py b/server/kernelwatch/status.py index a632783..0ac9911 100644 --- a/server/kernelwatch/status.py +++ b/server/kernelwatch/status.py @@ -191,6 +191,33 @@ def unattended_upgrades_problem(report: dict[str, Any], cfg: Config) -> tuple[bo "is apt-daily-upgrade.timer enabled?") +def security_repo_problem(report: dict[str, Any], cfg: Config, today: date) -> str | None: + """Why security updates may not be reaching this host from its release's security + suite, or None. Agents before 0.9.0, and releases without a codename, don't + report the suite. + + The age is of the suite's Date: field as of apt's last successful fetch of it, so + it keeps growing when fetching that repository fails, even while the update + stamps and other lists move on.""" + suite = report.get("security_repo_suite") + if not suite or not cfg.security_repo_stale_after_days: + return None + rel = support.release(report) + if rel is not None and today > rel.end: + return None # the suite has stopped publishing; support.check covers it + age = report.get("security_repo_age_seconds") + if age is None: + return (f"apt has no {suite} repository, so security updates can't arrive; " + "add it to the apt sources and run apt update") + if age <= cfg.security_repo_stale_after_days * 86400: + return None + apt_age = report.get("apt_lists_age_seconds") + if apt_age is None or apt_age / 3600 > cfg.apt_stale_after_hours: + return None # apt isn't refreshing anything; the package list reason covers it + return (f"apt's {suite} list is {_age(age)} old while apt update otherwise succeeds; " + f"run apt update and look for errors about {suite}") + + def _kernel_only_reboot_file(report: dict[str, Any]) -> bool: """/run/reboot-required exists only because of kernel packages.""" pkgs = report.get("reboot_required_pkgs") or [] @@ -295,6 +322,8 @@ def evaluate(received_at: int | None, report: dict[str, Any] | None, now: float, 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?") + if why := security_repo_problem(report, cfg, datetime.fromtimestamp(now, timezone.utc).date()): + status.raise_to("update", why) if host and (reported := hostname_mismatch(host, report)): status.note(f"registered as {host} but reports itself as {reported}; " diff --git a/server/kernelwatch/web.py b/server/kernelwatch/web.py index 7952b16..e94abcc 100644 --- a/server/kernelwatch/web.py +++ b/server/kernelwatch/web.py @@ -95,6 +95,16 @@ def unattended_upgrades_summary(report: dict[str, Any]) -> str | None: for what, age in last.items()) +def security_repo_summary(report: dict[str, Any]) -> str | None: + suite = report.get("security_repo_suite") + if not suite: + return None # agents before 0.9.0, or no release codename + age = report.get("security_repo_age_seconds") + if age is None: + return f"{suite}: not in apt's sources" + return f"{suite}, published {duration(age)} before the report" + + def phased_summary(report: dict[str, Any]) -> tuple[str, str]: """(short cell text, full description) for updates deferred by Ubuntu's phasing.""" if report.get("os_id") not in (None, "ubuntu"): @@ -527,6 +537,7 @@ class Handler(BaseHTTPRequestHandler): field("Kept back by unattended-upgrades", r.get("unattended_upgrades_kept_back"), 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("Security repository", security_repo_summary(r)), field("Uptime", duration(r.get("uptime_seconds")) if r.get("uptime_seconds") is not None else None), field("Agent version", r.get("agent_version")), ]) diff --git a/server/server.toml.example b/server/server.toml.example index 4bc1fba..1723a93 100644 --- a/server/server.toml.example +++ b/server/server.toml.example @@ -29,6 +29,12 @@ os_eol_warn_days = 90 # 0 disables the check. unattended_upgrades_stale_after_days = 3.0 +# A host with no repository for its release's security suite (trixie-security, +# noble-security) in apt's lists is in "update", and so is one whose copy is older +# than this many days while its other lists refresh (fetching it is failing). +# Both suites publish at least daily. 0 disables the check. +security_repo_stale_after_days = 7.0 + # kernelwatch-backup.timer writes a dated copy of the database here every night # and deletes copies this many days old or older (0 keeps them all). Keep the # directory under /var/lib/kernelwatch; the unit can't write elsewhere. Copy the diff --git a/tests/test_agent.py b/tests/test_agent.py index f8c1845..4cb0323 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -463,6 +463,70 @@ X os.utime(partial, (t, t)) self.assertAlmostEqual(self.report()["apt_lists_age_seconds"], 3600, delta=60) + def write_list(self, name, fields, age=3600, mtime_age=None): + """An apt list (Release or InRelease) in the fake root, its Date: `age` seconds ago.""" + body = "".join(f"{k}: {v}\n" for k, v in fields.items()) + if age is not None: + body += "Date: " + time.strftime("%a, %d %b %Y %H:%M:%S UTC", time.gmtime(time.time() - age)) + "\n" + body += "MD5Sum:\n 0123 456 main/binary-amd64/Packages\nSHA256:\n abcd 456 Suite: trixie-security\n" + if name.endswith("_InRelease"): + body = "-----BEGIN PGP SIGNED MESSAGE-----\nHash: SHA512\n\n" + body + "-----BEGIN PGP SIGNATURE-----\n" + self.write_root(f"var/lib/apt/lists/{name}", body, age=mtime_age) + + def set_os(self, text): + self.write_root("etc/os-release", text) + + def test_security_repo_debian(self): + self.write_list("deb.debian.org_debian_dists_trixie_InRelease", + {"Suite": "stable", "Codename": "trixie"}, age=60) + self.write_list("security.debian.org_debian-security_dists_trixie-security_InRelease", + {"Suite": "stable-security", "Codename": "trixie-security"}, age=5 * 3600) + self.set_os('ID=debian\nVERSION_ID="13"\nVERSION_CODENAME=trixie\n') + r = self.report() + self.assertEqual(r["security_repo_suite"], "trixie-security") + self.assertAlmostEqual(r["security_repo_age_seconds"], 5 * 3600, delta=60) + + def test_security_repo_ubuntu_newest_mirror_and_odd_file_names(self): + # Ubuntu: Suite is the pocket, Codename the release. Mirrors and mirror+file: + # sources give other file names; the newest copy counts. + self.write_list("archive.ubuntu.com_ubuntu_dists_noble-security_InRelease", + {"Suite": "noble-security", "Codename": "noble"}, age=3 * 86400) + self.write_list("_etc_apt_mirrors_ubuntu.list_dists_noble-security_InRelease", + {"Suite": "noble-security", "Codename": "noble"}, age=7200) + self.write_list("esm.ubuntu.com_infra_ubuntu_dists_noble-infra-security_InRelease", + {"Suite": "noble-infra-security", "Codename": "noble-infra-security"}, age=60) + self.set_os('ID=ubuntu\nVERSION_ID="24.04"\nVERSION_CODENAME=noble\nUBUNTU_CODENAME=noble\n') + r = self.report() + self.assertEqual(r["security_repo_suite"], "noble-security") + self.assertAlmostEqual(r["security_repo_age_seconds"], 7200, delta=60) + + def test_security_repo_missing(self): + self.write_list("deb.debian.org_debian_dists_trixie_InRelease", + {"Suite": "stable", "Codename": "trixie"}) + self.set_os('ID=debian\nVERSION_ID="13"\nVERSION_CODENAME=trixie\n') + r = self.report() + self.assertEqual(r["security_repo_suite"], "trixie-security") + self.assertIsNone(r["security_repo_age_seconds"]) + + def test_security_repo_matches_fields_not_checksum_lines(self): + # write_list puts "Suite: trixie-security" in a checksum line of every list. + self.write_list("deb.debian.org_debian_dists_trixie_Release", + {"Suite": "stable", "Codename": "trixie"}) + self.set_os('ID=debian\nVERSION_ID="13"\nVERSION_CODENAME=trixie\n') + self.assertIsNone(self.report()["security_repo_age_seconds"]) + + def test_security_repo_without_date_uses_mtime(self): + self.write_list("local_dists_trixie-security_Release", + {"Codename": "trixie-security"}, age=None, mtime_age=4 * 3600) + self.set_os('ID=debian\nVERSION_ID="13"\nVERSION_CODENAME=trixie\n') + self.assertAlmostEqual(self.report()["security_repo_age_seconds"], 4 * 3600, delta=60) + + def test_security_repo_without_codename(self): + # The default fake os-release has no VERSION_CODENAME (like Debian sid). + r = self.report() + self.assertIsNone(r["security_repo_suite"]) + self.assertIsNone(r["security_repo_age_seconds"]) + def test_send_without_config_fails_cleanly(self): proc = self.run_agent() self.assertNotEqual(proc.returncode, 0) diff --git a/tests/test_report_auth_config.py b/tests/test_report_auth_config.py index ad46509..d26291c 100644 --- a/tests/test_report_auth_config.py +++ b/tests/test_report_auth_config.py @@ -117,6 +117,15 @@ class ConfigTest(unittest.TestCase): with self.subTest(bad=bad), self.assertRaises(SystemExit): config.load(self.write(tmp, f"unattended_upgrades_stale_after_days = {bad}\n")) + def test_security_repo_stale_days_validated(self): + with tempdir() as tmp: + self.assertEqual(config.Config().security_repo_stale_after_days, 7.0) + self.assertEqual(config.load(self.write(tmp, "security_repo_stale_after_days = 0\n")) + .security_repo_stale_after_days, 0) + for bad in ("-1", "inf", "nan", '"7"'): + with self.subTest(bad=bad), self.assertRaises(SystemExit): + config.load(self.write(tmp, f"security_repo_stale_after_days = {bad}\n")) + def test_fallback_parser_matches_tomllib(self): """Python 3.10 has no tomllib; the fallback must read the same configs.""" if config.tomllib is None: diff --git a/tests/test_status.py b/tests/test_status.py index 590559b..7a7d89b 100644 --- a/tests/test_status.py +++ b/tests/test_status.py @@ -352,6 +352,59 @@ class EvaluateTest(unittest.TestCase): evaluate(NOW, rep, NOW, Config(os_eol_warn_days=200)).reasons[0]) self.assertEqual(self.level(rep).reasons, [], "outside the default 90 days") + def sec(self, age=3 * 3600, suite="trixie-security", cfg=CFG, **kw): + fields = dict(os_id="debian", os_version_id="13", security_repo_suite=suite, + security_repo_age_seconds=age) + fields.update(kw) + return evaluate(NOW - 60, report(**fields), NOW, cfg) + + def test_security_repo_fresh(self): + s = self.sec() + self.assertEqual((s.level, s.reasons), ("ok", [])) + + def test_security_repo_missing(self): + s = self.sec(age=None) + self.assertEqual(s.level, "update") + self.assertEqual(s.reasons, ["apt has no trixie-security repository, so security updates " + "can't arrive; add it to the apt sources and run apt update"]) + + def test_security_repo_stale_while_apt_update_succeeds(self): + s = self.sec(age=10 * 86400) + self.assertEqual(s.level, "update") + self.assertEqual(s.reasons, ["apt's trixie-security list is 10d old while apt update otherwise " + "succeeds; run apt update and look for errors about trixie-security"]) + self.assertEqual(self.sec(age=6 * 86400).level, "ok", "within the default 7 days") + + def test_security_repo_stale_with_all_lists_stale_reports_once(self): + s = self.sec(age=10 * 86400, apt_lists_age_seconds=10 * 86400) + self.assertEqual(s.reasons, ["package lists 10d old; apt update not running?"]) + + def test_security_repo_check_can_be_disabled(self): + cfg = Config(security_repo_stale_after_days=0) + self.assertEqual(self.sec(age=None, cfg=cfg).level, "ok") + self.assertEqual(self.sec(age=30 * 86400, cfg=cfg).level, "ok") + + def test_security_repo_not_reported(self): + # Agents before 0.9.0, and releases without a codename. + self.assertEqual(self.sec(suite=None, age=None).level, "ok") + rep = report(os_id="debian", os_version_id="13") + self.assertEqual(self.level(rep).level, "ok") + + def test_security_repo_ignored_past_end_of_support(self): + # NOW is 2027-01-15. Debian 11's LTS ended 2026-08-31, so bullseye-security no + # longer publishes; the end-of-support reason is the one that matters. + s = self.sec(age=60 * 86400, suite="bullseye-security", os_version_id="11") + self.assertEqual(len(s.reasons), 1, s.reasons) + self.assertIn("Debian 11 security support ended", s.reasons[0]) + # Ubuntu 20.04 past standard support with ESM: focal-security is frozen, but fine. + s = self.sec(age=400 * 86400, suite="focal-security", os_id="ubuntu", os_version_id="20.04", + ubuntu_esm_infra="enabled") + self.assertEqual((s.level, s.reasons), ("ok", [])) + + def test_security_repo_checked_within_standard_support(self): + s = self.sec(age=10 * 86400, suite="jammy-security", os_id="ubuntu", os_version_id="22.04") + self.assertEqual(s.level, "update") + def uu(self, success=6 * 3600, run=6 * 3600, state="enabled", **kw): return self.level(report(unattended_upgrades=state, unattended_upgrades_success_age_seconds=success, unattended_upgrades_run_age_seconds=run, **kw)) diff --git a/tests/test_web.py b/tests/test_web.py index f1d6e42..42a4fd8 100644 --- a/tests/test_web.py +++ b/tests/test_web.py @@ -221,6 +221,24 @@ class DashboardTest(ServerCase): body = self.request("GET", "/host/web01", headers={"Cookie": headers["Set-Cookie"].split(";")[0]})[2] self.assertIn("standard until 2029-05-31, ESM until 2034-04-25 (esm-infra: enabled)", body) + def test_host_page_shows_security_repo(self): + self.add_user("admin", "a-long-password") + token = self.add_host("web01") + self.post_report(token, {"kernel_running": "6.8.0-136-generic", "apt_lists_age_seconds": 60, + "security_repo_suite": "noble-security", + "security_repo_age_seconds": 14 * 3600 + 120}) + _, headers, _ = self.login("admin", "a-long-password") + cookie = {"Cookie": headers["Set-Cookie"].split(";")[0]} + body = self.request("GET", "/host/web01", headers=cookie)[2] + self.assertIn("noble-security, published 14h 2m before the report", body) + + self.post_report(self.add_host("web02"), {"kernel_running": "6.8.0-136-generic", + "apt_lists_age_seconds": 60, + "security_repo_suite": "noble-security"}) + body = self.request("GET", "/host/web02", headers=cookie)[2] + self.assertIn("noble-security: not in apt's sources", body) + self.assertIn("apt has no noble-security repository", body) + def test_login_dashboard_logout(self): self.add_user("admin", "a-long-password") token = self.add_host("web01")