Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b59336d7e2 | ||
|
|
4fa86de11f |
No files matched your search
@@ -56,6 +56,20 @@ How the agent works it out:
|
|||||||
The agent never runs as root, and needrestart never gets network access. Fix it on the host:
|
The agent never runs as root, and needrestart never gets network access. Fix it on the host:
|
||||||
`sudo needrestart -r a` (or restart the listed services), and the next report
|
`sudo needrestart -r a` (or restart the listed services), and the next report
|
||||||
clears it.
|
clears it.
|
||||||
|
- **Ubuntu Livepatch**: with [Livepatch](https://ubuntu.com/security/livepatch)
|
||||||
|
(free for personal use with Ubuntu Pro), a newer kernel being installed doesn't
|
||||||
|
mean the running one is unpatched. If Livepatch is healthy (`applied` or
|
||||||
|
`nothing-to-apply`, checked, supported), a pending kernel reboot, or a
|
||||||
|
`/run/reboot-required` caused only by `linux-*` packages, shows as a note
|
||||||
|
instead of `reboot`, and the note gives the date by which the kernel must be
|
||||||
|
upgraded. Livepatch only fixes high and critical CVEs, and only until that
|
||||||
|
date, so cover ends 14 days before it and the host goes to `reboot` as usual.
|
||||||
|
Any other reboot reason (libc, systemd) still counts. If Livepatch is failing,
|
||||||
|
unsupported or in a state we don't know, the host gets no cover and the reason
|
||||||
|
is noted. Hosts without Livepatch are unaffected. `canonical-livepatch` needs
|
||||||
|
root and a snap cgroup, so like needrestart it runs in its own unit,
|
||||||
|
`kernelwatch-livepatch.service`, which writes `/run/kernelwatch/livepatch`
|
||||||
|
before each report. It's skipped when the snap isn't installed.
|
||||||
- **Agent version**: each report includes it. Hosts running an older agent
|
- **Agent version**: each report includes it. Hosts running an older agent
|
||||||
than the server shipped with get a note to run `agent/deploy.sh`; their status
|
than the server shipped with get a note to run `agent/deploy.sh`; their status
|
||||||
isn't changed.
|
isn't changed.
|
||||||
@@ -481,6 +495,11 @@ To restore, stop the service, put the file at `db_path` owned by `kernelwatch`
|
|||||||
database or push real history off the host page. The agent's curl waits out the
|
database or push real history off the host page. The agent's curl waits out the
|
||||||
`Retry-After` and retries, so running `systemctl start kernelwatch-agent` twice
|
`Retry-After` and retries, so running `systemctl start kernelwatch-agent` twice
|
||||||
in a row just pauses briefly. Set it to `0` to disable.
|
in a row just pauses briefly. Set it to `0` to disable.
|
||||||
|
- **Livepatch status** runs in a separate root unit with no network access and a
|
||||||
|
read-only filesystem. It has no capability bound, syscall filter or
|
||||||
|
`NoNewPrivileges`, because the snap's setuid `snap-confine` can't run under
|
||||||
|
them (tested: `NoNewPrivileges=yes` fails with "cannot change profile for the
|
||||||
|
next exec call"). It only runs `canonical-livepatch status`.
|
||||||
- **needrestart** runs in a separate root unit with `PrivateNetwork=yes`, a
|
- **needrestart** runs in a separate root unit with `PrivateNetwork=yes`, a
|
||||||
capability set of just `CAP_SYS_PTRACE` + `CAP_DAC_READ_SEARCH` (to read other
|
capability set of just `CAP_SYS_PTRACE` + `CAP_DAC_READ_SEARCH` (to read other
|
||||||
processes' memory maps), a read-only filesystem except `/run/kernelwatch`,
|
processes' memory maps), a read-only filesystem except `/run/kernelwatch`,
|
||||||
@@ -529,6 +548,5 @@ export KERNELWATCH_CONFIG=/tmp/kw.toml
|
|||||||
## Ideas for later
|
## Ideas for later
|
||||||
|
|
||||||
- Additional notification channels
|
- Additional notification channels
|
||||||
- Ubuntu Livepatch / Pro status, so live-patched hosts aren't flagged for reboot
|
|
||||||
- A JSON endpoint for scripting
|
- A JSON endpoint for scripting
|
||||||
- Grouping or tagging hosts (prod/staging, location)
|
- Grouping or tagging hosts (prod/staging, location)
|
||||||
+2
-1
@@ -19,7 +19,8 @@ here=$(cd "$(dirname "$0")" && pwd)
|
|||||||
CONF=${KERNELWATCH_DEPLOY_CONF:-$here/deploy.conf}
|
CONF=${KERNELWATCH_DEPLOY_CONF:-$here/deploy.conf}
|
||||||
HOSTS_FILE=${KERNELWATCH_HOSTS:-$here/hosts}
|
HOSTS_FILE=${KERNELWATCH_HOSTS:-$here/hosts}
|
||||||
FILES=(kernelwatch-agent kernelwatch-agent.service kernelwatch-agent.timer
|
FILES=(kernelwatch-agent kernelwatch-agent.service kernelwatch-agent.timer
|
||||||
kernelwatch-needrestart.service kernelwatch-apt-update.service install.sh)
|
kernelwatch-needrestart.service kernelwatch-livepatch kernelwatch-livepatch.service
|
||||||
|
kernelwatch-apt-update.service install.sh)
|
||||||
NAME_RE='^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$'
|
NAME_RE='^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$'
|
||||||
|
|
||||||
SERVER_URL=
|
SERVER_URL=
|
||||||
|
|||||||
+3
-2
@@ -64,9 +64,10 @@ 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
|
||||||
|
install -m 0755 "$here/kernelwatch-livepatch" /usr/local/sbin/kernelwatch-livepatch
|
||||||
install -m 0644 "$here/kernelwatch-agent.service" "$here/kernelwatch-agent.timer" \
|
install -m 0644 "$here/kernelwatch-agent.service" "$here/kernelwatch-agent.timer" \
|
||||||
"$here/kernelwatch-needrestart.service" "$here/kernelwatch-apt-update.service" \
|
"$here/kernelwatch-needrestart.service" "$here/kernelwatch-livepatch.service" \
|
||||||
/etc/systemd/system/
|
"$here/kernelwatch-apt-update.service" /etc/systemd/system/
|
||||||
|
|
||||||
case $apt_update in
|
case $apt_update in
|
||||||
on) touch /etc/kernelwatch/apt-update ;;
|
on) touch /etc/kernelwatch/apt-update ;;
|
||||||
|
|||||||
+38
-1
@@ -6,7 +6,7 @@
|
|||||||
# rules can change without redeploying agents.
|
# rules can change without redeploying agents.
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
AGENT_VERSION=0.3.2
|
AGENT_VERSION=0.4.0
|
||||||
|
|
||||||
# Prefix for every file the agent reads. Only the test suite sets this.
|
# Prefix for every file the agent reads. Only the test suite sets this.
|
||||||
ROOT=${KERNELWATCH_ROOT:-}
|
ROOT=${KERNELWATCH_ROOT:-}
|
||||||
@@ -151,6 +151,37 @@ read_needrestart() {
|
|||||||
done <"$NEEDRESTART_FILE"
|
done <"$NEEDRESTART_FILE"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Ubuntu Livepatch status, flattened by kernelwatch-livepatch.service (root; the
|
||||||
|
# Livepatch snap won't run unprivileged). Absent when Livepatch isn't enabled.
|
||||||
|
LIVEPATCH_FILE=$ROOT/run/kernelwatch/livepatch
|
||||||
|
LIVEPATCH_MAX_AGE=7200
|
||||||
|
|
||||||
|
# Sets LP_* from the file, if it's there and fresh.
|
||||||
|
LP_STATE=
|
||||||
|
LP_CHECK=
|
||||||
|
LP_SUPPORTED=
|
||||||
|
LP_UPGRADE=
|
||||||
|
LP_FIXES=
|
||||||
|
read_livepatch() {
|
||||||
|
local mtime line
|
||||||
|
mtime=$(stat -c %Y "$LIVEPATCH_FILE" 2>/dev/null) || return 0
|
||||||
|
(($(date +%s) - mtime <= LIVEPATCH_MAX_AGE)) || return 0
|
||||||
|
while IFS= read -r line; do
|
||||||
|
case $line in
|
||||||
|
LIVEPATCH-STATE:*) LP_STATE=${line#*: } ;;
|
||||||
|
LIVEPATCH-CHECK:*) LP_CHECK=${line#*: } ;;
|
||||||
|
LIVEPATCH-SUPPORTED:*) LP_SUPPORTED=${line#*: } ;;
|
||||||
|
LIVEPATCH-UPGRADE-REQUIRED:*) LP_UPGRADE=${line#*: } ;;
|
||||||
|
LIVEPATCH-FIXES:*) LP_FIXES=${line#*: } ;;
|
||||||
|
esac
|
||||||
|
done <"$LIVEPATCH_FILE"
|
||||||
|
}
|
||||||
|
|
||||||
|
# String, or null when empty.
|
||||||
|
json_str_or_null() {
|
||||||
|
if [[ -n $1 ]]; then json_str "$1"; else printf 'null'; fi
|
||||||
|
}
|
||||||
|
|
||||||
# Simulated dist-upgrade. Reads only: no locks, no cache files written.
|
# Simulated dist-upgrade. Reads only: no locks, no cache files written.
|
||||||
# dist-upgrade (not upgrade) so new-ABI kernel packages pulled in by the
|
# dist-upgrade (not upgrade) so new-ABI kernel packages pulled in by the
|
||||||
# meta-package show up. C locale because we parse apt's messages.
|
# meta-package show up. C locale because we parse apt's messages.
|
||||||
@@ -205,6 +236,7 @@ build_report() {
|
|||||||
kernels=$(installed_kernels)
|
kernels=$(installed_kernels)
|
||||||
newest=$(tail -n1 <<<"$kernels")
|
newest=$(tail -n1 <<<"$kernels")
|
||||||
read_needrestart
|
read_needrestart
|
||||||
|
read_livepatch
|
||||||
|
|
||||||
sim=$(apt_simulation)
|
sim=$(apt_simulation)
|
||||||
inst=$(grep '^Inst ' <<<"$sim" || true)
|
inst=$(grep '^Inst ' <<<"$sim" || true)
|
||||||
@@ -239,6 +271,11 @@ build_report() {
|
|||||||
printf '"security_count":%s,' "$(json_int "$(grep -ci 'security' <<<"$inst" || true)")"
|
printf '"security_count":%s,' "$(json_int "$(grep -ci 'security' <<<"$inst" || true)")"
|
||||||
printf '"phased_packages":%s,' "$(phased_packages <<<"$sim" | json_str_array)"
|
printf '"phased_packages":%s,' "$(phased_packages <<<"$sim" | json_str_array)"
|
||||||
printf '"kernel_upgradable":%s,' "$(awk '$2 ~ /^linux-image-/ { print $2 }' <<<"$inst" | json_str_array)"
|
printf '"kernel_upgradable":%s,' "$(awk '$2 ~ /^linux-image-/ { print $2 }' <<<"$inst" | json_str_array)"
|
||||||
|
printf '"livepatch_state":%s,' "$(json_str_or_null "$LP_STATE")"
|
||||||
|
printf '"livepatch_check_state":%s,' "$(json_str_or_null "$LP_CHECK")"
|
||||||
|
printf '"livepatch_supported":%s,' "$(json_str_or_null "$LP_SUPPORTED")"
|
||||||
|
printf '"livepatch_upgrade_required":%s,' "$(json_str_or_null "$LP_UPGRADE")"
|
||||||
|
printf '"livepatch_fix_count":%s,' "$(json_int "$LP_FIXES")"
|
||||||
printf '"apt_lists_age_seconds":%s,' "$(json_int "$(apt_lists_age)")"
|
printf '"apt_lists_age_seconds":%s,' "$(json_int "$(apt_lists_age)")"
|
||||||
printf '"uptime_seconds":%s' "$(json_int "$(uptime_seconds)")"
|
printf '"uptime_seconds":%s' "$(json_int "$(uptime_seconds)")"
|
||||||
printf '}\n'
|
printf '}\n'
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
[Unit]
|
[Unit]
|
||||||
Description=Report kernel and update status to kernelwatch
|
Description=Report kernel and update status to kernelwatch
|
||||||
Wants=network-online.target kernelwatch-needrestart.service kernelwatch-apt-update.service
|
Wants=network-online.target kernelwatch-needrestart.service kernelwatch-livepatch.service kernelwatch-apt-update.service
|
||||||
After=network-online.target apt-daily.service kernelwatch-needrestart.service kernelwatch-apt-update.service
|
After=network-online.target apt-daily.service kernelwatch-needrestart.service kernelwatch-livepatch.service kernelwatch-apt-update.service
|
||||||
|
|
||||||
[Service]
|
[Service]
|
||||||
Type=oneshot
|
Type=oneshot
|
||||||
|
|||||||
Executable
+38
@@ -0,0 +1,38 @@
|
|||||||
|
#!/usr/bin/python3 -I
|
||||||
|
"""Flatten `canonical-livepatch status --format json` (stdin) into KEY: value lines (stdout).
|
||||||
|
|
||||||
|
Run as root by kernelwatch-livepatch.service, whose output kernelwatch-agent reads
|
||||||
|
without needing the Livepatch snap or a shell JSON parser. Only the running
|
||||||
|
kernel's entry is used. Exits 1, printing nothing, if the input isn't Livepatch
|
||||||
|
status for a running kernel (Livepatch not enabled, or an error message)."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
|
||||||
|
|
||||||
|
def clean(value):
|
||||||
|
return " ".join(str(value).split())[:64]
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
try:
|
||||||
|
data = json.load(sys.stdin)
|
||||||
|
entry = next(e for e in data["Status"] if e.get("Running"))
|
||||||
|
except (ValueError, KeyError, TypeError, StopIteration, AttributeError):
|
||||||
|
return 1
|
||||||
|
livepatch = entry.get("Livepatch") or {}
|
||||||
|
fixes = [f for f in livepatch.get("Fixes") or [] if isinstance(f, dict) and f.get("Patched")]
|
||||||
|
for key, value in (
|
||||||
|
("STATE", livepatch.get("State")),
|
||||||
|
("CHECK", livepatch.get("CheckState")),
|
||||||
|
("SUPPORTED", entry.get("Supported")),
|
||||||
|
("UPGRADE-REQUIRED", entry.get("UpgradeRequiredDate")),
|
||||||
|
("FIXES", len(fixes)),
|
||||||
|
):
|
||||||
|
if value is not None:
|
||||||
|
print(f"LIVEPATCH-{key}: {clean(value)}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Read Ubuntu Livepatch status (for kernelwatch)
|
||||||
|
# Pulled in by kernelwatch-agent.service before each report. Skipped cleanly on
|
||||||
|
# hosts without the Livepatch snap (or python3); the dashboard then treats a
|
||||||
|
# pending kernel reboot as it always did.
|
||||||
|
ConditionPathExists=/snap/bin/canonical-livepatch
|
||||||
|
ConditionPathExists=/usr/bin/python3
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=oneshot
|
||||||
|
# `canonical-livepatch status` needs root and a snap cgroup, so it can't run in
|
||||||
|
# the agent's unprivileged unit. The helper keeps only the running kernel's
|
||||||
|
# fields. If Livepatch isn't enabled or fails, no file is written and the agent
|
||||||
|
# reports nothing for it.
|
||||||
|
ExecStart=/bin/sh -c '/snap/bin/canonical-livepatch status --format json | /usr/bin/python3 -I /usr/local/sbin/kernelwatch-livepatch > /run/kernelwatch/livepatch.new && mv /run/kernelwatch/livepatch.new /run/kernelwatch/livepatch || { rm -f /run/kernelwatch/livepatch.new; exit 1; }'
|
||||||
|
RuntimeDirectory=kernelwatch
|
||||||
|
RuntimeDirectoryMode=0755
|
||||||
|
RuntimeDirectoryPreserve=yes
|
||||||
|
UMask=0022
|
||||||
|
TimeoutStartSec=2min
|
||||||
|
|
||||||
|
# Root, no network. Snap's confinement (setuid snap-confine, mount namespaces)
|
||||||
|
# rules out NoNewPrivileges, a capability bound, RestrictNamespaces and a
|
||||||
|
# syscall filter, so the sandbox is limited to a read-only filesystem and no
|
||||||
|
# network.
|
||||||
|
User=root
|
||||||
|
PrivateNetwork=yes
|
||||||
|
ProtectSystem=strict
|
||||||
|
ProtectHome=read-only
|
||||||
|
PrivateTmp=yes
|
||||||
@@ -4,4 +4,4 @@ __version__ = "0.4.0"
|
|||||||
|
|
||||||
# Version of agent/kernelwatch-agent shipped alongside this server; older agents
|
# 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.
|
# are noted on the dashboard. tests/test_status.py checks the two stay in sync.
|
||||||
AGENT_VERSION = "0.3.2"
|
AGENT_VERSION = "0.4.0"
|
||||||
@@ -35,6 +35,11 @@ FIELDS: dict[str, str] = {
|
|||||||
"security_count": "int",
|
"security_count": "int",
|
||||||
"kernel_upgradable": "strlist",
|
"kernel_upgradable": "strlist",
|
||||||
"phased_packages": "strlist",
|
"phased_packages": "strlist",
|
||||||
|
"livepatch_state": "str",
|
||||||
|
"livepatch_check_state": "str",
|
||||||
|
"livepatch_supported": "str",
|
||||||
|
"livepatch_upgrade_required": "str",
|
||||||
|
"livepatch_fix_count": "int",
|
||||||
"apt_lists_age_seconds": "int",
|
"apt_lists_age_seconds": "int",
|
||||||
"uptime_seconds": "int",
|
"uptime_seconds": "int",
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import re
|
import re
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
|
from datetime import date, datetime, timezone
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from . import AGENT_VERSION
|
from . import AGENT_VERSION
|
||||||
@@ -19,6 +20,11 @@ from .config import Config
|
|||||||
LEVELS = ("stale", "reboot", "update", "ok")
|
LEVELS = ("stale", "reboot", "update", "ok")
|
||||||
_RANK = {level: i for i, level in enumerate(LEVELS)}
|
_RANK = {level: i for i, level in enumerate(LEVELS)}
|
||||||
|
|
||||||
|
# Ubuntu Livepatch: a pending kernel reboot stops counting this long before the
|
||||||
|
# running kernel's patch support ends (`UpgradeRequiredDate`).
|
||||||
|
LIVEPATCH_MARGIN_DAYS = 14
|
||||||
|
LIVEPATCH_HEALTHY_STATES = ("applied", "nothing-to-apply")
|
||||||
|
|
||||||
# needrestart's NEEDRESTART-KSTA values.
|
# needrestart's NEEDRESTART-KSTA values.
|
||||||
KSTA_CURRENT = 1
|
KSTA_CURRENT = 1
|
||||||
KSTA_ABI_UPGRADE = 2
|
KSTA_ABI_UPGRADE = 2
|
||||||
@@ -98,6 +104,37 @@ def kernel_reboot_pending(report: dict[str, Any]) -> str | None:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def livepatch_cover(report: dict[str, Any], now: float) -> tuple[bool, str | None]:
|
||||||
|
"""(is the running kernel kept patched by Livepatch, a note about it).
|
||||||
|
|
||||||
|
Livepatch only fixes high and critical CVEs and only until the kernel's
|
||||||
|
support ends, so cover lapses LIVEPATCH_MARGIN_DAYS before that date. Hosts
|
||||||
|
without Livepatch data, or with Livepatch in any state we don't recognise as
|
||||||
|
healthy, get no cover and are judged as before."""
|
||||||
|
state = report.get("livepatch_state")
|
||||||
|
if state is None:
|
||||||
|
return False, None
|
||||||
|
try:
|
||||||
|
deadline = date.fromisoformat(report.get("livepatch_upgrade_required") or "")
|
||||||
|
except ValueError:
|
||||||
|
deadline = None
|
||||||
|
if (state not in LIVEPATCH_HEALTHY_STATES or report.get("livepatch_check_state") != "checked"
|
||||||
|
or report.get("livepatch_supported") != "supported"):
|
||||||
|
return False, f"livepatch not healthy ({state}, {report.get('livepatch_supported') or '?'})"
|
||||||
|
if deadline is None:
|
||||||
|
return False, "livepatch end of support date unknown"
|
||||||
|
left = (deadline - datetime.fromtimestamp(now, timezone.utc).date()).days
|
||||||
|
if left <= LIVEPATCH_MARGIN_DAYS:
|
||||||
|
return False, f"livepatch support for this kernel ends {deadline}; reboot into a newer one"
|
||||||
|
return True, f"live-patched; kernel upgrade needed by {deadline}"
|
||||||
|
|
||||||
|
|
||||||
|
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 []
|
||||||
|
return bool(pkgs) and all(p.startswith("linux-") for p in pkgs)
|
||||||
|
|
||||||
|
|
||||||
def _version_tuple(v: str) -> tuple[int, ...]:
|
def _version_tuple(v: str) -> tuple[int, ...]:
|
||||||
return tuple(int(p) if p.isdigit() else 0 for p in v.split("."))
|
return tuple(int(p) if p.isdigit() else 0 for p in v.split("."))
|
||||||
|
|
||||||
@@ -128,12 +165,21 @@ def evaluate(received_at: int | None, report: dict[str, Any] | None, now: float,
|
|||||||
if age_h > cfg.stale_after_hours:
|
if age_h > cfg.stale_after_hours:
|
||||||
status.raise_to("stale", f"last report {age_h:.0f}h ago")
|
status.raise_to("stale", f"last report {age_h:.0f}h ago")
|
||||||
|
|
||||||
|
covered, livepatch_note = livepatch_cover(report, now)
|
||||||
if why := kernel_reboot_pending(report):
|
if why := kernel_reboot_pending(report):
|
||||||
|
if covered:
|
||||||
|
status.note(f"kernel: {why} ({livepatch_note})")
|
||||||
|
else:
|
||||||
status.raise_to("reboot", f"kernel: {why}")
|
status.raise_to("reboot", f"kernel: {why}")
|
||||||
if report.get("reboot_required"):
|
if report.get("reboot_required"):
|
||||||
pkgs = report.get("reboot_required_pkgs") or []
|
pkgs = report.get("reboot_required_pkgs") or []
|
||||||
detail = f" ({', '.join(pkgs[:5])}{', …' if len(pkgs) > 5 else ''})" if pkgs else ""
|
detail = f" ({', '.join(pkgs[:5])}{', …' if len(pkgs) > 5 else ''})" if pkgs else ""
|
||||||
|
if covered and _kernel_only_reboot_file(report):
|
||||||
|
status.note(f"/run/reboot-required{detail} ({livepatch_note})")
|
||||||
|
else:
|
||||||
status.raise_to("reboot", f"/run/reboot-required{detail}")
|
status.raise_to("reboot", f"/run/reboot-required{detail}")
|
||||||
|
if livepatch_note and not covered:
|
||||||
|
status.note(livepatch_note)
|
||||||
|
|
||||||
if kernels := report.get("kernel_upgradable"):
|
if kernels := report.get("kernel_upgradable"):
|
||||||
status.raise_to("update", f"kernel update available: {', '.join(kernels)}")
|
status.raise_to("update", f"kernel update available: {', '.join(kernels)}")
|
||||||
|
|||||||
@@ -496,6 +496,9 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
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 '?'}"),
|
||||||
|
field("Livepatch", None if r.get("livepatch_state") is None else
|
||||||
|
f"{r['livepatch_state']}, {r.get('livepatch_fix_count') or 0} fixes applied, "
|
||||||
|
f"{r.get('livepatch_supported') or '?'} until {r.get('livepatch_upgrade_required') or '?'}"),
|
||||||
field("Kernel packages upgradable", r.get("kernel_upgradable"), code=True),
|
field("Kernel packages upgradable", r.get("kernel_upgradable"), code=True),
|
||||||
field("Updates pending", r.get("upgradable_count")),
|
field("Updates pending", r.get("upgradable_count")),
|
||||||
field("Security updates", r.get("security_count")),
|
field("Security updates", r.get("security_count")),
|
||||||
|
|||||||
@@ -125,6 +125,46 @@ class AgentReportTest(AgentCase):
|
|||||||
self.assertEqual(r["services_need_restart"], ["nginx.service", "ssh.service"])
|
self.assertEqual(r["services_need_restart"], ["nginx.service", "ssh.service"])
|
||||||
self.assertEqual(r["sessions_need_restart"], 1)
|
self.assertEqual(r["sessions_need_restart"], 1)
|
||||||
|
|
||||||
|
def write_livepatch(self, text, age=60):
|
||||||
|
d = os.path.join(self.root, "run/kernelwatch")
|
||||||
|
os.makedirs(d, exist_ok=True)
|
||||||
|
path = os.path.join(d, "livepatch")
|
||||||
|
with open(path, "w") as f:
|
||||||
|
f.write(text)
|
||||||
|
t = time.time() - age
|
||||||
|
os.utime(path, (t, t))
|
||||||
|
|
||||||
|
def test_every_reported_field_is_accepted_by_the_server(self):
|
||||||
|
from kernelwatch.report import FIELDS
|
||||||
|
self.write_livepatch("LIVEPATCH-STATE: applied\nLIVEPATCH-FIXES: 2\n")
|
||||||
|
self.assertEqual(sorted(set(self.report()) - set(FIELDS)), [])
|
||||||
|
|
||||||
|
def test_no_livepatch_file_reports_nulls(self):
|
||||||
|
r = self.report()
|
||||||
|
for key in ("state", "check_state", "supported", "upgrade_required", "fix_count"):
|
||||||
|
self.assertIsNone(r["livepatch_" + key])
|
||||||
|
|
||||||
|
def test_livepatch_results(self):
|
||||||
|
self.write_livepatch("LIVEPATCH-STATE: applied\nLIVEPATCH-CHECK: checked\n"
|
||||||
|
"LIVEPATCH-SUPPORTED: supported\nLIVEPATCH-UPGRADE-REQUIRED: 2027-09-07\n"
|
||||||
|
"LIVEPATCH-FIXES: 2\n")
|
||||||
|
r = self.report()
|
||||||
|
self.assertEqual((r["livepatch_state"], r["livepatch_check_state"], r["livepatch_supported"]),
|
||||||
|
("applied", "checked", "supported"))
|
||||||
|
self.assertEqual((r["livepatch_upgrade_required"], r["livepatch_fix_count"]), ("2027-09-07", 2))
|
||||||
|
|
||||||
|
def test_stale_livepatch_results_ignored(self):
|
||||||
|
self.write_livepatch("LIVEPATCH-STATE: applied\nLIVEPATCH-FIXES: 2\n", age=3 * 3600)
|
||||||
|
r = self.report()
|
||||||
|
self.assertIsNone(r["livepatch_state"])
|
||||||
|
self.assertIsNone(r["livepatch_fix_count"])
|
||||||
|
|
||||||
|
def test_agent_never_runs_livepatch_itself(self):
|
||||||
|
marker = os.path.join(self.tmp, "livepatch-ran")
|
||||||
|
stub(self.bin, "canonical-livepatch", f"touch {marker}\n")
|
||||||
|
self.report()
|
||||||
|
self.assertFalse(os.path.exists(marker))
|
||||||
|
|
||||||
def test_needrestart_nothing_to_restart(self):
|
def test_needrestart_nothing_to_restart(self):
|
||||||
self.write_needrestart("NEEDRESTART-VER: 3.6\nNEEDRESTART-KSTA: 1\n")
|
self.write_needrestart("NEEDRESTART-VER: 3.6\nNEEDRESTART-KSTA: 1\n")
|
||||||
r = self.report()
|
r = self.report()
|
||||||
|
|||||||
@@ -59,6 +59,7 @@ class DeployTest(unittest.TestCase):
|
|||||||
|
|
||||||
for name in ("deploy.sh", "kernelwatch-agent", "kernelwatch-agent.service",
|
for name in ("deploy.sh", "kernelwatch-agent", "kernelwatch-agent.service",
|
||||||
"kernelwatch-agent.timer", "kernelwatch-needrestart.service",
|
"kernelwatch-agent.timer", "kernelwatch-needrestart.service",
|
||||||
|
"kernelwatch-livepatch", "kernelwatch-livepatch.service",
|
||||||
"kernelwatch-apt-update.service"):
|
"kernelwatch-apt-update.service"):
|
||||||
shutil.copy2(os.path.join(AGENT_DIR, name), self.agent)
|
shutil.copy2(os.path.join(AGENT_DIR, name), self.agent)
|
||||||
write_exec(os.path.join(self.agent, "install.sh"), FAKE_INSTALL)
|
write_exec(os.path.join(self.agent, "install.sh"), FAKE_INSTALL)
|
||||||
|
|||||||
@@ -0,0 +1,99 @@
|
|||||||
|
"""kernelwatch-livepatch: flattening real `canonical-livepatch status --format json` output."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from helpers import REPO
|
||||||
|
|
||||||
|
SCRIPT = os.path.join(REPO, "agent", "kernelwatch-livepatch")
|
||||||
|
|
||||||
|
# Captured from Ubuntu 22.04 (HWE 6.8) and 24.04 hosts, client v11.1.0.
|
||||||
|
APPLIED = {
|
||||||
|
"Client-Version": "v11.1.0",
|
||||||
|
"Status": [{
|
||||||
|
"Kernel": "6.8.0-138.138~22.04.1-generic",
|
||||||
|
"Running": True,
|
||||||
|
"Livepatch": {
|
||||||
|
"CheckState": "checked", "State": "applied", "Version": "122.1",
|
||||||
|
"Fixes": [
|
||||||
|
{"Name": "cve-2025-37944", "Description": "", "Bug": "", "Patched": True},
|
||||||
|
{"Name": "cve-2025-71089", "Description": "", "Bug": "", "Patched": True},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
"Supported": "supported",
|
||||||
|
"UpgradeRequiredDate": "2027-09-07",
|
||||||
|
}],
|
||||||
|
"tier": "updates",
|
||||||
|
"Fixed-CVEs": {"Patched-CVEs": ["UBUNTU-CVE-2025-37944", "UBUNTU-CVE-2025-71089"],
|
||||||
|
"Kernel-Upgrade": {"Status": "same-kernel"}},
|
||||||
|
}
|
||||||
|
NOTHING = {
|
||||||
|
"Status": [{
|
||||||
|
"Kernel": "7.0.0-38.38~24.04.4-generic",
|
||||||
|
"Running": True,
|
||||||
|
"Livepatch": {"CheckState": "checked", "State": "nothing-to-apply", "Version": ""},
|
||||||
|
"Supported": "supported",
|
||||||
|
"UpgradeRequiredDate": "2027-10-14",
|
||||||
|
}],
|
||||||
|
"Fixed-CVEs": {"Patched-CVEs": []},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def flatten(stdin):
|
||||||
|
if not isinstance(stdin, str):
|
||||||
|
stdin = json.dumps(stdin)
|
||||||
|
return subprocess.run([sys.executable, "-I", SCRIPT], input=stdin, capture_output=True,
|
||||||
|
text=True, timeout=30)
|
||||||
|
|
||||||
|
|
||||||
|
class LivepatchHelperTest(unittest.TestCase):
|
||||||
|
def test_applied_patches(self):
|
||||||
|
proc = flatten(APPLIED)
|
||||||
|
self.assertEqual(proc.returncode, 0, proc.stderr)
|
||||||
|
self.assertEqual(proc.stdout.splitlines(), [
|
||||||
|
"LIVEPATCH-STATE: applied",
|
||||||
|
"LIVEPATCH-CHECK: checked",
|
||||||
|
"LIVEPATCH-SUPPORTED: supported",
|
||||||
|
"LIVEPATCH-UPGRADE-REQUIRED: 2027-09-07",
|
||||||
|
"LIVEPATCH-FIXES: 2",
|
||||||
|
])
|
||||||
|
|
||||||
|
def test_nothing_to_apply_has_no_fixes_key_in_input(self):
|
||||||
|
proc = flatten(NOTHING)
|
||||||
|
self.assertEqual(proc.returncode, 0, proc.stderr)
|
||||||
|
self.assertIn("LIVEPATCH-STATE: nothing-to-apply", proc.stdout)
|
||||||
|
self.assertIn("LIVEPATCH-FIXES: 0", proc.stdout)
|
||||||
|
|
||||||
|
def test_only_the_running_kernel_counts(self):
|
||||||
|
data = json.loads(json.dumps(APPLIED))
|
||||||
|
other = json.loads(json.dumps(NOTHING["Status"][0]))
|
||||||
|
other["Running"] = False
|
||||||
|
data["Status"].insert(0, other)
|
||||||
|
self.assertIn("LIVEPATCH-STATE: applied", flatten(data).stdout)
|
||||||
|
|
||||||
|
def test_unpatched_fixes_are_not_counted(self):
|
||||||
|
data = json.loads(json.dumps(APPLIED))
|
||||||
|
data["Status"][0]["Livepatch"]["Fixes"][1]["Patched"] = False
|
||||||
|
self.assertIn("LIVEPATCH-FIXES: 1", flatten(data).stdout)
|
||||||
|
|
||||||
|
def test_not_livepatch_status_prints_nothing_and_fails(self):
|
||||||
|
no_running = {"Status": [dict(NOTHING["Status"][0], Running=False)]}
|
||||||
|
for stdin in ("", "Error: livepatch is not enabled\n", "[]", "null", '{"Status": 3}',
|
||||||
|
'{"Status": [null]}', json.dumps(no_running), '{"error": "x"}'):
|
||||||
|
with self.subTest(stdin=stdin[:30]):
|
||||||
|
proc = flatten(stdin)
|
||||||
|
self.assertEqual((proc.returncode, proc.stdout), (1, ""), proc.stderr)
|
||||||
|
|
||||||
|
def test_values_cannot_inject_lines(self):
|
||||||
|
data = json.loads(json.dumps(NOTHING))
|
||||||
|
data["Status"][0]["Supported"] = "supported\nLIVEPATCH-STATE: applied"
|
||||||
|
out = flatten(data).stdout.splitlines()
|
||||||
|
self.assertEqual([l for l in out if l.startswith("LIVEPATCH-STATE")],
|
||||||
|
["LIVEPATCH-STATE: nothing-to-apply"])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import unittest
|
import unittest
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
from helpers import REPO, Config
|
from helpers import REPO, Config
|
||||||
from kernelwatch import AGENT_VERSION
|
from kernelwatch import AGENT_VERSION
|
||||||
@@ -25,6 +26,80 @@ def report(**kw):
|
|||||||
return base
|
return base
|
||||||
|
|
||||||
|
|
||||||
|
def livepatched(days_left=300, **kw):
|
||||||
|
"""A report from an Ubuntu host with a newer kernel installed and healthy Livepatch."""
|
||||||
|
deadline = datetime.fromtimestamp(NOW, timezone.utc).date() + timedelta(days=days_left)
|
||||||
|
fields = dict(kernel_running="6.8.0-136-generic", kernel_newest_installed="6.8.0-138-generic",
|
||||||
|
needrestart_ksta=None, livepatch_state="applied", livepatch_check_state="checked",
|
||||||
|
livepatch_supported="supported", livepatch_upgrade_required=deadline.isoformat(),
|
||||||
|
livepatch_fix_count=2)
|
||||||
|
fields.update(kw)
|
||||||
|
return report(**fields)
|
||||||
|
|
||||||
|
|
||||||
|
class LivepatchTest(unittest.TestCase):
|
||||||
|
def evaluate(self, rep):
|
||||||
|
return evaluate(NOW - 60, rep, NOW, CFG)
|
||||||
|
|
||||||
|
def test_without_livepatch_a_newer_kernel_needs_a_reboot(self):
|
||||||
|
rep = livepatched()
|
||||||
|
for k in [k for k in rep if k.startswith("livepatch_")]:
|
||||||
|
del rep[k]
|
||||||
|
self.assertEqual(self.evaluate(rep).level, "reboot")
|
||||||
|
|
||||||
|
def test_healthy_livepatch_turns_pending_kernel_into_a_note(self):
|
||||||
|
s = self.evaluate(livepatched())
|
||||||
|
self.assertEqual(s.level, "ok")
|
||||||
|
self.assertEqual(len(s.reasons), 1)
|
||||||
|
self.assertIn("running 6.8.0-136-generic, 6.8.0-138-generic installed", s.reasons[0])
|
||||||
|
self.assertIn("live-patched; kernel upgrade needed by", s.reasons[0])
|
||||||
|
|
||||||
|
def test_nothing_to_apply_also_counts_as_healthy(self):
|
||||||
|
self.assertEqual(self.evaluate(livepatched(livepatch_state="nothing-to-apply")).level, "ok")
|
||||||
|
|
||||||
|
def test_cover_lapses_two_weeks_before_support_ends(self):
|
||||||
|
self.assertEqual(self.evaluate(livepatched(days_left=15)).level, "ok")
|
||||||
|
s = self.evaluate(livepatched(days_left=14))
|
||||||
|
self.assertEqual(s.level, "reboot")
|
||||||
|
self.assertTrue(any("livepatch support for this kernel ends" in r for r in s.reasons), s.reasons)
|
||||||
|
self.assertEqual(self.evaluate(livepatched(days_left=-5)).level, "reboot")
|
||||||
|
|
||||||
|
def test_unhealthy_livepatch_gives_no_cover(self):
|
||||||
|
for kw in ({"livepatch_state": "apply-failed"}, {"livepatch_state": "applying"},
|
||||||
|
{"livepatch_check_state": "check-failed"},
|
||||||
|
{"livepatch_supported": "unsupported"},
|
||||||
|
{"livepatch_upgrade_required": ""}, {"livepatch_upgrade_required": "soon"}):
|
||||||
|
with self.subTest(kw=kw):
|
||||||
|
s = self.evaluate(livepatched(**kw))
|
||||||
|
self.assertEqual(s.level, "reboot")
|
||||||
|
self.assertTrue(any("livepatch" in r for r in s.reasons), s.reasons)
|
||||||
|
|
||||||
|
def test_unhealthy_livepatch_is_noted_even_when_nothing_is_pending(self):
|
||||||
|
rep = report(livepatch_state="apply-failed", livepatch_check_state="checked",
|
||||||
|
livepatch_supported="supported", livepatch_upgrade_required="2099-01-01")
|
||||||
|
s = self.evaluate(rep)
|
||||||
|
self.assertEqual(s.level, "ok")
|
||||||
|
self.assertIn("livepatch not healthy (apply-failed, supported)", s.reasons)
|
||||||
|
|
||||||
|
def test_reboot_required_for_kernel_packages_only_is_covered(self):
|
||||||
|
rep = livepatched(reboot_required=True,
|
||||||
|
reboot_required_pkgs=["linux-image-6.8.0-138-generic", "linux-base"])
|
||||||
|
self.assertEqual(self.evaluate(rep).level, "ok")
|
||||||
|
|
||||||
|
def test_reboot_required_for_other_packages_still_counts(self):
|
||||||
|
for pkgs in (["libc6"], ["linux-image-6.8.0-138-generic", "libc6"], []):
|
||||||
|
with self.subTest(pkgs=pkgs):
|
||||||
|
rep = livepatched(reboot_required=True, reboot_required_pkgs=pkgs)
|
||||||
|
s = self.evaluate(rep)
|
||||||
|
self.assertEqual(s.level, "reboot")
|
||||||
|
self.assertTrue(any(r.startswith("/run/reboot-required") for r in s.reasons))
|
||||||
|
|
||||||
|
def test_in_place_kernel_upgrade_is_covered_too(self):
|
||||||
|
rep = livepatched(kernel_running="6.8.0-136-generic", kernel_newest_installed="6.8.0-136-generic",
|
||||||
|
kernel_build="#136-Ubuntu SMP", kernel_running_pkg_version="6.8.0-138.138")
|
||||||
|
self.assertEqual(self.evaluate(rep).level, "ok")
|
||||||
|
|
||||||
|
|
||||||
class EvaluateTest(unittest.TestCase):
|
class EvaluateTest(unittest.TestCase):
|
||||||
def level(self, rep, age=60):
|
def level(self, rep, age=60):
|
||||||
return evaluate(NOW - age, rep, NOW, CFG)
|
return evaluate(NOW - age, rep, NOW, CFG)
|
||||||
|
|||||||
@@ -174,6 +174,17 @@ class DashboardTest(ServerCase):
|
|||||||
body = self.request("GET", path, headers=cookie)[2]
|
body = self.request("GET", path, headers=cookie)[2]
|
||||||
self.assertIn("registered as web01 but reports itself as db01.example.internal <b>", body)
|
self.assertIn("registered as web01 but reports itself as db01.example.internal <b>", body)
|
||||||
|
|
||||||
|
def test_host_page_shows_livepatch(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,
|
||||||
|
"livepatch_state": "applied", "livepatch_fix_count": 2,
|
||||||
|
"livepatch_supported": "supported",
|
||||||
|
"livepatch_upgrade_required": "2099-09-07"})
|
||||||
|
_, headers, _ = self.login("admin", "a-long-password")
|
||||||
|
body = self.request("GET", "/host/web01", headers={"Cookie": headers["Set-Cookie"].split(";")[0]})[2]
|
||||||
|
self.assertIn("applied, 2 fixes applied, supported until 2099-09-07", body)
|
||||||
|
|
||||||
def test_login_dashboard_logout(self):
|
def test_login_dashboard_logout(self):
|
||||||
self.add_user("admin", "a-long-password")
|
self.add_user("admin", "a-long-password")
|
||||||
token = self.add_host("web01")
|
token = self.add_host("web01")
|
||||||
|
|||||||
Reference in new issue
Block a user