Not found.
"""HTTP server: the agent ingest API and the authenticated dashboard. Meant to sit behind a TLS-terminating reverse proxy (Caddy, nginx). The standard-library server is plenty for a fleet of tens or hundreds of hosts reporting hourly. """ from __future__ import annotations import html import json import re import sys import threading import time from http import HTTPStatus from http.cookies import CookieError, SimpleCookie from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from typing import Any from urllib.parse import parse_qs, quote, unquote, urlsplit from . import __version__, auth, db, support from .config import Config from .report import MAX_BODY_BYTES, ReportError, sanitize from .status import LEVELS, Status, evaluate, helper_failure, helper_units SESSION_COOKIE = "kw_session" HOST_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$") LOGIN_MAX_FAILURES = 10 LOGIN_WINDOW_SECONDS = 15 * 60 e = html.escape class LoginLimiter: """Per-client-IP failed login counter with a fixed window.""" def __init__(self) -> None: self._lock = threading.Lock() self._failures: dict[str, tuple[int, float]] = {} def blocked(self, ip: str) -> bool: with self._lock: count, start = self._failures.get(ip, (0, 0.0)) if time.monotonic() - start > LOGIN_WINDOW_SECONDS: self._failures.pop(ip, None) return False return count >= LOGIN_MAX_FAILURES def failed(self, ip: str) -> None: with self._lock: now = time.monotonic() count, start = self._failures.get(ip, (0, now)) if now - start > LOGIN_WINDOW_SECONDS: count, start = 0, now self._failures[ip] = (count + 1, start) def succeeded(self, ip: str) -> None: with self._lock: self._failures.pop(ip, None) # --- formatting ------------------------------------------------------------- def ago(ts: float | None, now: float) -> str: if ts is None: return "never" s = max(0, int(now - ts)) for unit, size in (("d", 86400), ("h", 3600), ("m", 60)): if s >= size: return f"{s // size}{unit} ago" return "just now" def duration(seconds: int | None) -> str: if seconds is None: return "–" d, rem = divmod(seconds, 86400) return f"{d}d {rem // 3600}h" if d else f"{rem // 3600}h {rem % 3600 // 60}m" def utc(ts: float | None) -> str: return time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime(ts)) if ts else "" def unattended_upgrades_summary(report: dict[str, Any]) -> str | None: state = report.get("unattended_upgrades") if state != "enabled": return state # "disabled", "not-installed", or None from agents before 0.8.0 last = {"success": report.get("unattended_upgrades_success_age_seconds"), "run": report.get("unattended_upgrades_run_age_seconds")} return "enabled, " + ", ".join( f"last {what} " + ("never" if age is None else f"{duration(age)} before the report") 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 upgrade_space_summary(r: dict[str, Any]) -> str | None: """Download and install size of the pending upgrades, and free space where they go.""" download, install = r.get("upgrade_download_kb"), r.get("upgrade_install_kb") if download is None or install is None: return None # agents before 0.11.0, or apt couldn't say sign = "+" if install >= 0 else "-" text = f"{-(-download // 1024)} MB to download, {sign}{-(-abs(install) // 1024)} MB installed" free: dict[str, int] = {} for prefix in ("apt_archives", "usr"): mount, kb = r.get(f"{prefix}_mount"), r.get(f"{prefix}_free_kb") if mount and kb is not None: free.setdefault(mount, kb) shown = ", ".join(f"{mount} has {kb // 1024} MB free" for mount, kb in free.items()) return f"{text}; {shown}" if shown else text def microcode_summary(report: dict[str, Any]) -> str | None: state = {1: "current", 2: "update needs a reboot"}.get(report.get("needrestart_ucsta")) if state is None: return None # unknown, a VM, or no needrestart cur, exp = report.get("needrestart_uccur"), report.get("needrestart_ucexp") revs = f" (loaded {cur}, installed {exp})" if state != "current" and cur and exp else \ f" ({cur})" if cur else "" return state + revs def helper_units_summary(report: dict[str, Any]) -> str | None: units = helper_units(report) if not units: return None # agents before 0.10.0, or nothing ran in the last two hours parts = [] for name, result, code, st, failures in units: if result == "success" or not failures: parts.append(f"{name}: ok") else: row = "" if failures == 1 else f", {failures} runs in a row" parts.append(f"{name}: failed ({helper_failure(result, code, st)}{row})") return ", ".join(parts) 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"): return "–", "this distribution doesn't phase updates" pkgs = report.get("phased_packages") if pkgs is None: return "?", "unknown: agent too old to report phased updates" if not pkgs: return "0", "none deferred" return str(len(pkgs)), ("held back by Ubuntu's phased rollout, not offered to this host " "yet (never security updates): " + ", ".join(pkgs)) def services_summary(report: dict[str, Any]) -> tuple[str, str]: """(short cell text, full description) for services needing a restart.""" services = report.get("services_need_restart") if services is None: return "?", "unknown: needrestart not installed (install.sh --with-needrestart)" if not services: return "0", "none" return str(len(services)), ", ".join(services) def badge(level: str) -> str: return f'{e(level)}' STYLE = """ :root { color-scheme: light dark; --bg: #f7f7f8; --fg: #1d1d1f; --muted: #6b6b72; --card: #fff; --line: #e2e2e6; --ok: #1a7f37; --update: #9a6700; --reboot: #cf222e; --stale: #6e7781; } @media (prefers-color-scheme: dark) { :root { --bg: #111214; --fg: #e8e8ea; --muted: #9a9aa2; --card: #1a1b1e; --line: #2c2d31; --ok: #3fb950; --update: #d29922; --reboot: #f85149; --stale: #8b949e; } } * { box-sizing: border-box; } body { margin: 0; background: var(--bg); color: var(--fg); font: 14px/1.45 system-ui, -apple-system, "Segoe UI", sans-serif; } header { display: flex; align-items: center; gap: 16px; padding: 12px 16px; border-bottom: 1px solid var(--line); background: var(--card); } header h1 { font-size: 16px; margin: 0; flex: 1; } header h1 a { color: inherit; text-decoration: none; } header form { margin: 0; } main { padding: 16px; max-width: 1400px; margin: 0 auto; } a { color: inherit; } button { font: inherit; padding: 6px 12px; border: 1px solid var(--line); border-radius: 6px; background: var(--card); color: var(--fg); cursor: pointer; } .summary { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 16px; } .summary div { background: var(--card); border: 1px solid var(--line); border-radius: 8px; padding: 8px 14px; min-width: 110px; } .summary b { display: block; font-size: 22px; } .table-wrap { overflow-x: auto; background: var(--card); border: 1px solid var(--line); border-radius: 8px; } table { border-collapse: collapse; width: 100%; } th, td { text-align: left; padding: 8px 12px; border-bottom: 1px solid var(--line); vertical-align: top; white-space: nowrap; } th { font-weight: 600; color: var(--muted); font-size: 12px; text-transform: uppercase; } tr:last-child td { border-bottom: 0; } td.reasons { white-space: normal; color: var(--muted); min-width: 260px; } code { font: 12px ui-monospace, SFMono-Regular, Menlo, monospace; } .muted { color: var(--muted); } .badge { display: inline-block; padding: 1px 8px; border-radius: 999px; font-size: 12px; font-weight: 600; color: #fff; } .badge.ok { background: var(--ok); } .badge.update { background: var(--update); } .badge.reboot { background: var(--reboot); } .badge.stale { background: var(--stale); } .login { max-width: 340px; margin: 12vh auto; background: var(--card); padding: 24px; border: 1px solid var(--line); border-radius: 10px; } .login h1 { font-size: 18px; margin: 0 0 16px; } .login label { display: block; margin-bottom: 12px; } .login input { display: block; width: 100%; margin-top: 4px; padding: 8px; font: inherit; border: 1px solid var(--line); border-radius: 6px; background: var(--bg); color: var(--fg); } .login button { width: 100%; } .error { color: var(--reboot); } dl { display: grid; grid-template-columns: max-content 1fr; gap: 4px 16px; margin: 0 0 24px; } dt { color: var(--muted); } dd { margin: 0; overflow-wrap: anywhere; } h2 { font-size: 15px; margin: 24px 0 8px; } """ def page(title: str, body: str, user: str | None = None, refresh: bool = False) -> str: logout = ( f'{e(user)}' '
' if user else "" ) header = ( f'Not found.
{e(error)}
' if error else "" body = f"""""" self.send(status, page("Log in · kernelwatch", body)) def login(self) -> None: if not self.same_origin(): return self.send(HTTPStatus.FORBIDDEN, "cross-origin request refused", "text/plain") ip = self.client_ip() if self.limiter.blocked(ip): return self.login_page("Too many failed attempts. Try again later.", HTTPStatus.TOO_MANY_REQUESTS) body = self.read_body() if body is None: return form = parse_qs(body.decode("utf-8", "replace")) username = form.get("username", [""])[0] password = form.get("password", [""])[0] conn = self.conn() try: stored = db.user_pw_hash(conn, username) ok = auth.verify_password(password, stored or auth.DUMMY_HASH) and stored is not None if not ok: self.limiter.failed(ip) self.log_message("login failed for %r", username) return self.login_page("Invalid username or password.", HTTPStatus.UNAUTHORIZED) self.limiter.succeeded(ip) sid = auth.new_token() ttl = self.cfg.session_hours * 3600 db.create_session(conn, auth.token_hash(sid), username, ttl) finally: conn.close() self.redirect("/", {"Set-Cookie": self.cookie(sid, ttl)}) def logout(self) -> None: if not self.same_origin(): return self.send(HTTPStatus.FORBIDDEN, "cross-origin request refused", "text/plain") sid = self.session_id() if sid: conn = self.conn() try: db.delete_session(conn, auth.token_hash(sid)) finally: conn.close() self.redirect("/login", {"Set-Cookie": self.cookie("", 0)}) # -- dashboard -- def dashboard(self, user: str) -> None: now = time.time() conn = self.conn() try: hosts = db.latest_reports(conn) finally: conn.close() rows = [] for h in hosts: h["status"] = evaluate(h["received_at"], h["report"], now, self.cfg, h["host"]) hosts.sort(key=lambda h: (h["status"].rank, h["host"])) counts = {level: 0 for level in LEVELS} for h in hosts: counts[h["status"].level] += 1 rows.append(self.host_row(h, now)) summary = "".join( f'No hosts yet. Add one with kernelwatch add-host NAME.
| Status | Host | OS | Running kernel | " "Newest installed | Updates | Phased | Services | Uptime | Last seen | " "Details |
|---|
{e(r.get('kernel_running') or '–')}{e(r.get('kernel_newest_installed') or '–')}Not found.
Not found.
{e(text)}" if code and text != "–" else e(text)
return f"{e(h['report'].get('kernel_running') or '–')}| When | Status | Running kernel | Updates | " f"
|---|
No reports yet.
" ) body = f"