From 195fd035e0ddb1a71740613a24c37430659d214f Mon Sep 17 00:00:00 2001 From: patrick Date: Sun, 1 Nov 2026 14:52:36 -0500 Subject: [PATCH 1/3] Fix kernelwatch-apt-update failing on apt 2.7+ With User=root, NoNewPrivileges=yes and any seccomp-based sandbox option together, apt 2.7+ (Ubuntu 24.04+, Debian 13) can't drop to _apt: E: seteuid 42 failed - seteuid (1: Operation not permitted) E: Method http has died unexpectedly! so apt-get update exited 100 on every run on 10 of 13 hosts. The '-' prefix hid it, and apt touches lists/partial even when it fails, so the agent's list age looked fresh. Only hosts with older apt (22.04, Debian 12) refreshed. On Ubuntu apt-daily kept the lists fresh regardless; a Debian 13 host relying on this unit alone had lists three days old. Root is the default, so drop User=root. Let a failed update fail the unit (the agent only Wants= it, so the report still goes), and touch /var/lib/apt/periodic/update-success-stamp, the stamp Ubuntu writes after each successful apt update, only when it succeeds. Co-Authored-By: Claude Opus 5.5 --- agent/kernelwatch-apt-update.service | 19 ++++++++++++++----- tests/test_deploy.py | 13 ++++++++++++- 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/agent/kernelwatch-apt-update.service b/agent/kernelwatch-apt-update.service index f85be08..c2ea60b 100644 --- a/agent/kernelwatch-apt-update.service +++ b/agent/kernelwatch-apt-update.service @@ -10,16 +10,25 @@ After=network-online.target [Service] Type=oneshot # Same as `apt-get update`: downloads lists, installs nothing. A failure (no -# network, lock held by an admin's apt run) mustn't stop the report; the -# dashboard flags lists that stay old. -ExecStart=-/usr/bin/apt-get -q update +# network, lock held by an admin's apt run) fails this unit but not the report, +# since kernelwatch-agent.service only Wants= it. The stamp then stops moving +# and the dashboard flags the lists as old. +ExecStart=/usr/bin/apt-get -q update +# Reached only when apt succeeded. It's the stamp Ubuntu's update-notifier hook +# writes after every successful apt update, and the agent reads it as the lists' +# age; Debian has nothing else that writes it. lists/partial, the agent's last +# resort, changes even when the update fails. +ExecStartPost=/bin/sh -c 'mkdir -p /var/lib/apt/periodic && touch /var/lib/apt/periodic/update-success-stamp' TimeoutStartSec=5min Nice=10 IOSchedulingClass=idle # apt needs root to write /var/lib/apt and drops to _apt for downloads, so this -# keeps root but loses everything apt update doesn't touch. -User=root +# runs as root (the default) but loses everything apt update doesn't touch. +# Don't add User=root: with it, NoNewPrivileges and any of the seccomp-based +# options below, apt 2.7+ (Ubuntu 24.04, Debian 13) can't switch to _apt +# ("seteuid 42 failed - seteuid (1: Operation not permitted)") and every update +# fails. NoNewPrivileges=yes ProtectHome=yes PrivateTmp=yes diff --git a/tests/test_deploy.py b/tests/test_deploy.py index c612112..917dace 100644 --- a/tests/test_deploy.py +++ b/tests/test_deploy.py @@ -310,11 +310,22 @@ class PackagingTest(unittest.TestCase): def test_apt_update_is_opt_in_and_runs_before_reports(self): unit = self.read("kernelwatch-apt-update.service") self.assertIn("ConditionPathExists=/etc/kernelwatch/apt-update", unit) - self.assertIn("ExecStart=-/usr/bin/apt-get -q update", unit, "failure mustn't block the report") + self.assertIn("\nExecStart=/usr/bin/apt-get -q update\n", unit, + "a failed update must fail the unit, so ExecStartPost doesn't mark it fresh") + post = next(l for l in unit.splitlines() if l.startswith("ExecStartPost=")) + self.assertIn("touch /var/lib/apt/periodic/update-success-stamp", post) agent = self.read("kernelwatch-agent.service") for key in ("Wants=", "After="): line = next(l for l in agent.splitlines() if l.startswith(key)) self.assertIn("kernelwatch-apt-update.service", line) + self.assertNotRegex(agent, r"(?m)^(Requires|Requisite|BindsTo)=.*kernelwatch-apt-update", + "a failed apt update mustn't stop the report") + + def test_apt_update_runs_as_root_without_user_root(self): + # User=root plus NoNewPrivileges plus any seccomp-based option stops apt 2.7+ + # dropping to _apt, so every update fails. Root is the default anyway. + unit = self.read("kernelwatch-apt-update.service") + self.assertNotRegex(unit, r"(?m)^(User|DynamicUser)=") if __name__ == "__main__": From fa6cca4f64a5d7944e648a1732b37e2e8112a770 Mon Sep 17 00:00:00 2001 From: patrick Date: Sun, 1 Nov 2026 14:53:19 -0500 Subject: [PATCH 2/3] Don't let failed apt updates make package lists look fresh apt touches /var/lib/apt/lists/partial on every update attempt, including ones that fail, and the agent took the newest of it and the two success stamps. So a host whose apt update failed hourly reported lists an hour old. Use the success stamps (update-success-stamp, update-stamp) and fall back to lists/partial only when neither exists. Co-Authored-By: Claude Opus 5.5 --- agent/kernelwatch-agent | 14 +++++++++----- docs/how-it-works.md | 11 ++++++++--- tests/test_agent.py | 17 +++++++++++++++++ 3 files changed, 34 insertions(+), 8 deletions(-) diff --git a/agent/kernelwatch-agent b/agent/kernelwatch-agent index c9b0ded..7e08156 100755 --- a/agent/kernelwatch-agent +++ b/agent/kernelwatch-agent @@ -228,18 +228,22 @@ phased_packages() { } # Seconds since apt last refreshed its package lists, or empty if unknown. +# Both stamps are touched only after a successful update: update-success-stamp by +# Ubuntu's update-notifier hook and kernelwatch-apt-update.service, update-stamp by +# apt-daily. lists/partial changes on every attempt, failed ones too, so it's only +# a last resort for hosts that have neither (Debian without either timer). 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 + "$ROOT/var/lib/apt/periodic/update-stamp"; do m=$(stat -c %Y "$f" 2>/dev/null) || continue ((m > newest)) && newest=$m done - ((newest > 0)) && printf '%s' $(($(date +%s) - newest)) - return 0 + if ((newest == 0)); then + newest=$(stat -c %Y "$ROOT/var/lib/apt/lists/partial" 2>/dev/null) || return 0 + fi + printf '%s' $(($(date +%s) - newest)) } # Size and free space of the filesystem holding /boot, in KiB, as "SIZE FREE"; diff --git a/docs/how-it-works.md b/docs/how-it-works.md index 1222850..ac70042 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -141,9 +141,14 @@ How the agent works it out: list also on the host page. They never affect status, because Ubuntu doesn't phase security updates and there's nothing to act on until apt offers them. -- **Package list freshness**: the mtime of apt's update stamps. The agent - **doesn't run `apt update`** itself; it relies on the stock `apt-daily.timer`. - If that's disabled, the host shows `update` with "package lists N days old". +- **Package list freshness**: the mtime of apt's success stamps, + `update-success-stamp` (Ubuntu, and `kernelwatch-apt-update.service`) and + `update-stamp` (`apt-daily`), both in `/var/lib/apt/periodic/` and touched + only when `apt update` succeeds. A host with neither falls back to + `/var/lib/apt/lists/partial`, which changes on failed updates too. The agent + **doesn't run `apt update`** itself; it relies on `apt-daily.timer` or + `--with-apt-update`. If the lists stop refreshing, the host shows `update` + with "package lists N days old". The agent sends raw facts and the server decides what they mean, so you can change the status rules without touching the agents. diff --git a/tests/test_agent.py b/tests/test_agent.py index c13a8c4..f8c1845 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -446,6 +446,23 @@ X os.remove(os.path.join(self.root, "var/lib/apt/periodic/update-success-stamp")) self.assertIsNone(self.report()["apt_lists_age_seconds"]) + def test_newest_success_stamp_wins(self): + self.write_root("var/lib/apt/periodic/update-stamp", age=600) + self.assertAlmostEqual(self.report()["apt_lists_age_seconds"], 600, delta=60) + + def test_failed_updates_touching_partial_dont_count_as_fresh(self): + # apt touches lists/partial even when the update fails. + os.makedirs(os.path.join(self.root, "var/lib/apt/lists/partial")) + self.assertAlmostEqual(self.report()["apt_lists_age_seconds"], 7200, delta=60) + + def test_partial_is_the_last_resort_without_stamps(self): + os.remove(os.path.join(self.root, "var/lib/apt/periodic/update-success-stamp")) + partial = os.path.join(self.root, "var/lib/apt/lists/partial") + os.makedirs(partial) + t = time.time() - 3600 + os.utime(partial, (t, t)) + self.assertAlmostEqual(self.report()["apt_lists_age_seconds"], 3600, delta=60) + def test_send_without_config_fails_cleanly(self): proc = self.run_agent() self.assertNotEqual(proc.returncode, 0) From c9912d5fbc9437cdbf8b924e4475433ae2307495 Mon Sep 17 00:00:00 2001 From: patrick Date: Sun, 1 Nov 2026 14:58:10 -0500 Subject: [PATCH 3/3] Check that the release's security repository is configured and fresh security_count is only meaningful if apt has the release's security suite. A host missing it from its sources shows 0 security updates forever, and one whose apt can't fetch it (expired key, 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 neither the simulation nor the package list age notices. The agent (0.9.0) now finds apt's list for -security by its Suite: (Ubuntu) or Codename: (Debian) field, since file names depend on the mirror (mirror+file: sources, several mirrors), and reports security_repo_suite and security_repo_age_seconds from its Date:, the newest copy winning. The server puts the host in update when there's no such list, or when it's older than security_repo_stale_after_days (default 7) while the package lists are otherwise fresh; if all of them are old, the existing "package lists N days old" reason covers it. Releases past the end of support are skipped: their suite has stopped publishing, and support.check already says so. ESM suites publish too rarely to judge by date and aren't checked. The host page gets a "Security repository" row. Co-Authored-By: Claude Opus 5.5 --- agent/kernelwatch-agent | 46 ++++++++++++++++++++++- docs/how-it-works.md | 18 ++++++++- server/kernelwatch/__init__.py | 2 +- server/kernelwatch/config.py | 7 ++++ server/kernelwatch/report.py | 2 + server/kernelwatch/status.py | 29 +++++++++++++++ server/kernelwatch/web.py | 11 ++++++ server/server.toml.example | 6 +++ tests/test_agent.py | 64 ++++++++++++++++++++++++++++++++ tests/test_report_auth_config.py | 9 +++++ tests/test_status.py | 53 ++++++++++++++++++++++++++ tests/test_web.py | 18 +++++++++ 12 files changed, 261 insertions(+), 4 deletions(-) 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")