Scaffold kernelwatch: fleet kernel status agent and dashboard
Agent: bash script run hourly by a hardened systemd timer on Debian 12/13 and Ubuntu 24.04. Collects running vs installed kernel (needrestart when available), pending/security updates via a read-only apt simulation, reboot-required state and apt list freshness, and POSTs them as JSON. Server: stdlib-only Python + SQLite (system python3 >= 3.11). Token-bound ingest API, login-protected dashboard with per-host status (stale/reboot/update/ok) and history, admin CLI, systemd unit and installer. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
07749b01b0
27 files changed
+2406
No files matched your search
Executable
+51
@@ -0,0 +1,51 @@
|
||||
#!/usr/bin/env bash
|
||||
# Install or upgrade the kernelwatch server on Debian 12/13 or Ubuntu 24.04.
|
||||
#
|
||||
# sudo ./install.sh
|
||||
#
|
||||
# Installs to /opt/kernelwatch, config in /etc/kernelwatch/server.toml (kept
|
||||
# on upgrade), data in /var/lib/kernelwatch. Then put a TLS reverse proxy in
|
||||
# front (see README) and create a dashboard user: sudo kernelwatch set-password admin
|
||||
set -euo pipefail
|
||||
|
||||
here=$(cd "$(dirname "$0")" && pwd)
|
||||
[[ $(id -u) == 0 ]] || { echo "run as root" >&2; exit 1; }
|
||||
|
||||
if ! /usr/bin/python3 -c 'import sys; sys.exit(sys.version_info < (3, 11))' 2>/dev/null; then
|
||||
echo "kernelwatch needs /usr/bin/python3 >= 3.11 (Debian 12+, Ubuntu 24.04)" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! id kernelwatch >/dev/null 2>&1; then
|
||||
useradd --system --home-dir /var/lib/kernelwatch --no-create-home \
|
||||
--shell /usr/sbin/nologin kernelwatch
|
||||
fi
|
||||
|
||||
rm -rf /opt/kernelwatch.new
|
||||
install -d -m 0755 /opt/kernelwatch.new/kernelwatch
|
||||
install -m 0755 "$here/kernelwatch-server" /opt/kernelwatch.new/
|
||||
install -m 0644 "$here"/kernelwatch/*.py /opt/kernelwatch.new/kernelwatch/
|
||||
rm -rf /opt/kernelwatch.old
|
||||
[[ -d /opt/kernelwatch ]] && mv /opt/kernelwatch /opt/kernelwatch.old
|
||||
mv /opt/kernelwatch.new /opt/kernelwatch
|
||||
rm -rf /opt/kernelwatch.old
|
||||
|
||||
install -m 0755 "$here/kernelwatch.sh" /usr/local/bin/kernelwatch
|
||||
|
||||
install -d -m 0755 /etc/kernelwatch
|
||||
if [[ ! -e /etc/kernelwatch/server.toml ]]; then
|
||||
install -m 0640 -g kernelwatch "$here/server.toml.example" /etc/kernelwatch/server.toml
|
||||
fi
|
||||
install -d -m 0750 -o kernelwatch -g kernelwatch /var/lib/kernelwatch
|
||||
|
||||
install -m 0644 "$here/kernelwatch.service" /etc/systemd/system/
|
||||
systemctl daemon-reload
|
||||
systemctl enable kernelwatch.service
|
||||
systemctl restart kernelwatch.service
|
||||
|
||||
echo
|
||||
echo "kernelwatch is running on $(grep -E '^listen_' /etc/kernelwatch/server.toml | tr '\n' ' ')"
|
||||
if [[ -z $(kernelwatch list-users) ]]; then
|
||||
echo "Create a dashboard login: sudo kernelwatch set-password admin"
|
||||
fi
|
||||
echo "Register a host: sudo kernelwatch add-host <name>"
|
||||
Executable
+11
@@ -0,0 +1,11 @@
|
||||
#!/usr/bin/python3 -I
|
||||
"""Entry point. Runs from a checkout or /opt/kernelwatch with the system python3 (3.11+)."""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
|
||||
|
||||
from kernelwatch.cli import main # noqa: E402
|
||||
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,40 @@
|
||||
[Unit]
|
||||
Description=kernelwatch fleet kernel dashboard
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
User=kernelwatch
|
||||
Group=kernelwatch
|
||||
Environment=KERNELWATCH_CONFIG=/etc/kernelwatch/server.toml
|
||||
ExecStart=/usr/bin/python3 -I /opt/kernelwatch/kernelwatch-server serve
|
||||
Restart=on-failure
|
||||
RestartSec=5s
|
||||
StateDirectory=kernelwatch
|
||||
StateDirectoryMode=0750
|
||||
|
||||
CapabilityBoundingSet=
|
||||
AmbientCapabilities=
|
||||
NoNewPrivileges=yes
|
||||
ProtectSystem=strict
|
||||
ProtectHome=yes
|
||||
PrivateTmp=yes
|
||||
PrivateDevices=yes
|
||||
ProtectKernelTunables=yes
|
||||
ProtectKernelModules=yes
|
||||
ProtectKernelLogs=yes
|
||||
ProtectControlGroups=yes
|
||||
ProtectClock=yes
|
||||
ProtectHostname=yes
|
||||
ProtectProc=invisible
|
||||
RestrictNamespaces=yes
|
||||
RestrictRealtime=yes
|
||||
RestrictSUIDSGID=yes
|
||||
LockPersonality=yes
|
||||
MemoryDenyWriteExecute=yes
|
||||
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
|
||||
SystemCallArchitectures=native
|
||||
SystemCallFilter=@system-service
|
||||
UMask=0077
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,14 @@
|
||||
#!/bin/sh
|
||||
# /usr/local/bin/kernelwatch — admin CLI wrapper. Runs as the service user so
|
||||
# the database stays owned by it.
|
||||
set -e
|
||||
if [ "$(id -u)" = 0 ]; then
|
||||
exec runuser -u kernelwatch -- env KERNELWATCH_CONFIG=/etc/kernelwatch/server.toml \
|
||||
/usr/bin/python3 -I /opt/kernelwatch/kernelwatch-server "$@"
|
||||
fi
|
||||
if [ "$(id -un)" = kernelwatch ]; then
|
||||
exec env KERNELWATCH_CONFIG=/etc/kernelwatch/server.toml \
|
||||
/usr/bin/python3 -I /opt/kernelwatch/kernelwatch-server "$@"
|
||||
fi
|
||||
echo "kernelwatch: run with sudo" >&2
|
||||
exit 1
|
||||
@@ -0,0 +1,3 @@
|
||||
"""kernelwatch: fleet kernel and reboot status dashboard."""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
@@ -0,0 +1,5 @@
|
||||
import sys
|
||||
|
||||
from .cli import main
|
||||
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,55 @@
|
||||
"""Password hashing and token helpers. Standard library only."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import secrets
|
||||
|
||||
# scrypt parameters: ~16 MiB memory, tens of milliseconds per hash.
|
||||
_N, _R, _P = 2**14, 8, 1
|
||||
_DKLEN = 32
|
||||
|
||||
|
||||
def _b64(b: bytes) -> str:
|
||||
return base64.urlsafe_b64encode(b).decode().rstrip("=")
|
||||
|
||||
|
||||
def _unb64(s: str) -> bytes:
|
||||
return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
salt = secrets.token_bytes(16)
|
||||
dk = hashlib.scrypt(password.encode(), salt=salt, n=_N, r=_R, p=_P, dklen=_DKLEN)
|
||||
return f"scrypt${_N}${_R}${_P}${_b64(salt)}${_b64(dk)}"
|
||||
|
||||
|
||||
def verify_password(password: str, stored: str) -> bool:
|
||||
try:
|
||||
scheme, n, r, p, salt, dk = stored.split("$")
|
||||
if scheme != "scrypt":
|
||||
return False
|
||||
expected = _unb64(dk)
|
||||
actual = hashlib.scrypt(
|
||||
password.encode(), salt=_unb64(salt), n=int(n), r=int(r), p=int(p),
|
||||
dklen=len(expected),
|
||||
)
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
return hmac.compare_digest(actual, expected)
|
||||
|
||||
|
||||
# Used to equalise timing when a login names a user that doesn't exist.
|
||||
DUMMY_HASH = hash_password(secrets.token_urlsafe(16))
|
||||
|
||||
|
||||
def new_token() -> str:
|
||||
"""A high-entropy secret for host tokens and session IDs."""
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def token_hash(token: str) -> str:
|
||||
# Tokens are 256-bit random, so a fast hash is fine; we only store this.
|
||||
return hashlib.sha256(token.encode()).hexdigest()
|
||||
@@ -0,0 +1,153 @@
|
||||
"""Command-line interface: run the server and manage hosts and users."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import getpass
|
||||
import sqlite3
|
||||
import sys
|
||||
import time
|
||||
|
||||
from . import __version__, auth, db, web
|
||||
from .config import load
|
||||
|
||||
|
||||
def _conn(cfg):
|
||||
db.init(cfg.db_path)
|
||||
return db.connect(cfg.db_path)
|
||||
|
||||
|
||||
def _valid_host(name: str) -> str:
|
||||
if not web.HOST_NAME_RE.match(name):
|
||||
raise argparse.ArgumentTypeError("host names may contain letters, digits, '.', '_' and '-'")
|
||||
return name
|
||||
|
||||
|
||||
def cmd_serve(cfg, args) -> int:
|
||||
web.serve(cfg)
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_add_host(cfg, args) -> int:
|
||||
token = auth.new_token()
|
||||
conn = _conn(cfg)
|
||||
try:
|
||||
db.add_host(conn, args.name, auth.token_hash(token))
|
||||
except sqlite3.IntegrityError:
|
||||
print(f"host {args.name!r} already exists (use rotate-token)", file=sys.stderr)
|
||||
return 1
|
||||
finally:
|
||||
conn.close()
|
||||
print(f"Added {args.name}. Its token (shown once):\n\n {token}\n")
|
||||
print("On the host, run: sudo ./agent/install.sh --server <URL> and paste the token.")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_rotate_token(cfg, args) -> int:
|
||||
token = auth.new_token()
|
||||
conn = _conn(cfg)
|
||||
try:
|
||||
if not db.set_host_token(conn, args.name, auth.token_hash(token)):
|
||||
print(f"no such host {args.name!r}", file=sys.stderr)
|
||||
return 1
|
||||
finally:
|
||||
conn.close()
|
||||
print(f"New token for {args.name} (the old one no longer works):\n\n {token}\n")
|
||||
print("On the host, run: sudo KERNELWATCH_TOKEN=... ./agent/install.sh or edit /etc/kernelwatch/agent.token")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_remove_host(cfg, args) -> int:
|
||||
conn = _conn(cfg)
|
||||
try:
|
||||
if not db.remove_host(conn, args.name):
|
||||
print(f"no such host {args.name!r}", file=sys.stderr)
|
||||
return 1
|
||||
finally:
|
||||
conn.close()
|
||||
print(f"Removed {args.name} and its reports.")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_list_hosts(cfg, args) -> int:
|
||||
conn = _conn(cfg)
|
||||
try:
|
||||
hosts = db.list_hosts(conn)
|
||||
finally:
|
||||
conn.close()
|
||||
now = time.time()
|
||||
for h in hosts:
|
||||
print(f"{h['name']:<32} last seen {web.ago(h['last_seen'], now)}")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_set_password(cfg, args) -> int:
|
||||
password = getpass.getpass(f"Password for {args.name}: ")
|
||||
if len(password) < 12:
|
||||
print("use at least 12 characters", file=sys.stderr)
|
||||
return 1
|
||||
if getpass.getpass("Again: ") != password:
|
||||
print("passwords don't match", file=sys.stderr)
|
||||
return 1
|
||||
conn = _conn(cfg)
|
||||
try:
|
||||
db.set_user(conn, args.name, auth.hash_password(password))
|
||||
finally:
|
||||
conn.close()
|
||||
print(f"Password set for {args.name}.")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_remove_user(cfg, args) -> int:
|
||||
conn = _conn(cfg)
|
||||
try:
|
||||
if not db.remove_user(conn, args.name):
|
||||
print(f"no such user {args.name!r}", file=sys.stderr)
|
||||
return 1
|
||||
finally:
|
||||
conn.close()
|
||||
print(f"Removed user {args.name}.")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_list_users(cfg, args) -> int:
|
||||
conn = _conn(cfg)
|
||||
try:
|
||||
for name in db.list_users(conn):
|
||||
print(name)
|
||||
finally:
|
||||
conn.close()
|
||||
return 0
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(prog="kernelwatch", description="Fleet kernel status dashboard.")
|
||||
parser.add_argument("-c", "--config", help="config file (default: $KERNELWATCH_CONFIG or "
|
||||
"/etc/kernelwatch/server.toml)")
|
||||
parser.add_argument("--version", action="version", version=f"kernelwatch {__version__}")
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
sub.add_parser("serve", help="run the HTTP server").set_defaults(func=cmd_serve)
|
||||
|
||||
for name, func, help_ in (
|
||||
("add-host", cmd_add_host, "register a host and print its token"),
|
||||
("rotate-token", cmd_rotate_token, "issue a new token for a host"),
|
||||
("remove-host", cmd_remove_host, "delete a host and its reports"),
|
||||
):
|
||||
p = sub.add_parser(name, help=help_)
|
||||
p.add_argument("name", type=_valid_host)
|
||||
p.set_defaults(func=func)
|
||||
sub.add_parser("list-hosts", help="list hosts and when they last reported").set_defaults(
|
||||
func=cmd_list_hosts)
|
||||
|
||||
for name, func, help_ in (
|
||||
("set-password", cmd_set_password, "create a dashboard user or change their password"),
|
||||
("remove-user", cmd_remove_user, "delete a dashboard user"),
|
||||
):
|
||||
p = sub.add_parser(name, help=help_)
|
||||
p.add_argument("name")
|
||||
p.set_defaults(func=func)
|
||||
sub.add_parser("list-users", help="list dashboard users").set_defaults(func=cmd_list_users)
|
||||
|
||||
args = parser.parse_args(argv)
|
||||
return args.func(load(args.config), args)
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Server configuration, loaded from a flat TOML file."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import dataclasses
|
||||
import os
|
||||
import tomllib
|
||||
from dataclasses import dataclass
|
||||
|
||||
DEFAULT_PATH = "/etc/kernelwatch/server.toml"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Config:
|
||||
# Bind to loopback by default; put a TLS reverse proxy in front.
|
||||
listen_host: str = "127.0.0.1"
|
||||
listen_port: int = 8080
|
||||
db_path: str = "/var/lib/kernelwatch/kernelwatch.db"
|
||||
|
||||
# A host that hasn't reported for this long is shown as stale.
|
||||
stale_after_hours: float = 3.0
|
||||
# Package lists older than this make "no updates" untrustworthy.
|
||||
apt_stale_after_hours: float = 48.0
|
||||
report_retention_days: int = 30
|
||||
|
||||
session_hours: int = 12
|
||||
# Leave on unless you serve the dashboard over plain HTTP on a non-localhost name.
|
||||
secure_cookies: bool = True
|
||||
# Honour X-Forwarded-For (for login rate limiting). Enable only behind a proxy.
|
||||
trust_proxy_headers: bool = False
|
||||
|
||||
|
||||
def load(path: str | None = None) -> Config:
|
||||
path = path or os.environ.get("KERNELWATCH_CONFIG") or DEFAULT_PATH
|
||||
if not os.path.exists(path):
|
||||
if path == DEFAULT_PATH:
|
||||
return Config()
|
||||
raise SystemExit(f"config file not found: {path}")
|
||||
|
||||
with open(path, "rb") as f:
|
||||
raw = tomllib.load(f)
|
||||
|
||||
fields = {f.name: f for f in dataclasses.fields(Config)}
|
||||
unknown = sorted(set(raw) - set(fields))
|
||||
if unknown:
|
||||
raise SystemExit(f"{path}: unknown config keys: {', '.join(unknown)}")
|
||||
|
||||
values = {}
|
||||
for name, value in raw.items():
|
||||
expected = type(getattr(Config(), name))
|
||||
if expected is float and isinstance(value, int) and not isinstance(value, bool):
|
||||
value = float(value)
|
||||
if not isinstance(value, expected) or (expected is int and isinstance(value, bool)):
|
||||
raise SystemExit(f"{path}: {name} must be {expected.__name__}")
|
||||
values[name] = value
|
||||
return Config(**values)
|
||||
@@ -0,0 +1,188 @@
|
||||
"""SQLite storage. One connection per thread/request; WAL keeps readers and the writer apart."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS hosts (
|
||||
name TEXT PRIMARY KEY,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS reports (
|
||||
id INTEGER PRIMARY KEY,
|
||||
host TEXT NOT NULL REFERENCES hosts(name) ON DELETE CASCADE,
|
||||
received_at INTEGER NOT NULL,
|
||||
payload TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS reports_host_time ON reports(host, received_at);
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
name TEXT PRIMARY KEY,
|
||||
pw_hash TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
id_hash TEXT PRIMARY KEY,
|
||||
user TEXT NOT NULL REFERENCES users(name) ON DELETE CASCADE,
|
||||
expires_at INTEGER NOT NULL
|
||||
);
|
||||
"""
|
||||
|
||||
|
||||
def connect(path: str) -> sqlite3.Connection:
|
||||
conn = sqlite3.connect(path, timeout=10, isolation_level=None)
|
||||
conn.row_factory = sqlite3.Row
|
||||
conn.execute("PRAGMA foreign_keys = ON")
|
||||
conn.execute("PRAGMA journal_mode = WAL")
|
||||
conn.execute("PRAGMA busy_timeout = 10000")
|
||||
return conn
|
||||
|
||||
|
||||
def init(path: str) -> None:
|
||||
directory = os.path.dirname(os.path.abspath(path))
|
||||
os.makedirs(directory, exist_ok=True)
|
||||
conn = connect(path)
|
||||
try:
|
||||
conn.executescript(SCHEMA)
|
||||
finally:
|
||||
conn.close()
|
||||
os.chmod(path, 0o600)
|
||||
|
||||
|
||||
# --- hosts ------------------------------------------------------------------
|
||||
|
||||
def add_host(conn: sqlite3.Connection, name: str, token_hash: str) -> None:
|
||||
conn.execute(
|
||||
"INSERT INTO hosts (name, token_hash, created_at) VALUES (?, ?, ?)",
|
||||
(name, token_hash, int(time.time())),
|
||||
)
|
||||
|
||||
|
||||
def set_host_token(conn: sqlite3.Connection, name: str, token_hash: str) -> bool:
|
||||
cur = conn.execute("UPDATE hosts SET token_hash = ? WHERE name = ?", (token_hash, name))
|
||||
return cur.rowcount == 1
|
||||
|
||||
|
||||
def remove_host(conn: sqlite3.Connection, name: str) -> bool:
|
||||
return conn.execute("DELETE FROM hosts WHERE name = ?", (name,)).rowcount == 1
|
||||
|
||||
|
||||
def host_for_token(conn: sqlite3.Connection, token_hash: str) -> str | None:
|
||||
row = conn.execute("SELECT name FROM hosts WHERE token_hash = ?", (token_hash,)).fetchone()
|
||||
return row["name"] if row else None
|
||||
|
||||
|
||||
def list_hosts(conn: sqlite3.Connection) -> list[sqlite3.Row]:
|
||||
return conn.execute(
|
||||
"""
|
||||
SELECT h.name, h.created_at, MAX(r.received_at) AS last_seen
|
||||
FROM hosts h LEFT JOIN reports r ON r.host = h.name
|
||||
GROUP BY h.name ORDER BY h.name
|
||||
"""
|
||||
).fetchall()
|
||||
|
||||
|
||||
# --- reports ----------------------------------------------------------------
|
||||
|
||||
def add_report(conn: sqlite3.Connection, host: str, payload: dict[str, Any],
|
||||
retention_days: int) -> None:
|
||||
now = int(time.time())
|
||||
conn.execute("BEGIN IMMEDIATE")
|
||||
try:
|
||||
conn.execute(
|
||||
"INSERT INTO reports (host, received_at, payload) VALUES (?, ?, ?)",
|
||||
(host, now, json.dumps(payload, separators=(",", ":"))),
|
||||
)
|
||||
conn.execute(
|
||||
"DELETE FROM reports WHERE host = ? AND received_at < ?",
|
||||
(host, now - retention_days * 86400),
|
||||
)
|
||||
conn.execute("COMMIT")
|
||||
except BaseException:
|
||||
conn.execute("ROLLBACK")
|
||||
raise
|
||||
|
||||
|
||||
def latest_reports(conn: sqlite3.Connection) -> list[dict[str, Any]]:
|
||||
"""Every host with its most recent report (or None)."""
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT h.name, r.received_at, r.payload
|
||||
FROM hosts h
|
||||
LEFT JOIN reports r ON r.id = (
|
||||
SELECT id FROM reports WHERE host = h.name ORDER BY received_at DESC, id DESC LIMIT 1
|
||||
)
|
||||
ORDER BY h.name
|
||||
"""
|
||||
).fetchall()
|
||||
return [
|
||||
{
|
||||
"host": row["name"],
|
||||
"received_at": row["received_at"],
|
||||
"report": json.loads(row["payload"]) if row["payload"] else None,
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
|
||||
|
||||
def host_history(conn: sqlite3.Connection, host: str, limit: int = 50) -> list[dict[str, Any]]:
|
||||
rows = conn.execute(
|
||||
"SELECT received_at, payload FROM reports WHERE host = ? "
|
||||
"ORDER BY received_at DESC, id DESC LIMIT ?",
|
||||
(host, limit),
|
||||
).fetchall()
|
||||
return [{"received_at": r["received_at"], "report": json.loads(r["payload"])} for r in rows]
|
||||
|
||||
|
||||
def host_exists(conn: sqlite3.Connection, host: str) -> bool:
|
||||
return conn.execute("SELECT 1 FROM hosts WHERE name = ?", (host,)).fetchone() is not None
|
||||
|
||||
|
||||
# --- users & sessions -------------------------------------------------------
|
||||
|
||||
def set_user(conn: sqlite3.Connection, name: str, pw_hash: str) -> None:
|
||||
conn.execute(
|
||||
"INSERT INTO users (name, pw_hash) VALUES (?, ?) "
|
||||
"ON CONFLICT(name) DO UPDATE SET pw_hash = excluded.pw_hash",
|
||||
(name, pw_hash),
|
||||
)
|
||||
# A password change logs out existing sessions.
|
||||
conn.execute("DELETE FROM sessions WHERE user = ?", (name,))
|
||||
|
||||
|
||||
def remove_user(conn: sqlite3.Connection, name: str) -> bool:
|
||||
return conn.execute("DELETE FROM users WHERE name = ?", (name,)).rowcount == 1
|
||||
|
||||
|
||||
def user_pw_hash(conn: sqlite3.Connection, name: str) -> str | None:
|
||||
row = conn.execute("SELECT pw_hash FROM users WHERE name = ?", (name,)).fetchone()
|
||||
return row["pw_hash"] if row else None
|
||||
|
||||
|
||||
def list_users(conn: sqlite3.Connection) -> list[str]:
|
||||
return [r["name"] for r in conn.execute("SELECT name FROM users ORDER BY name")]
|
||||
|
||||
|
||||
def create_session(conn: sqlite3.Connection, id_hash: str, user: str, ttl_seconds: int) -> None:
|
||||
now = int(time.time())
|
||||
conn.execute("DELETE FROM sessions WHERE expires_at < ?", (now,))
|
||||
conn.execute(
|
||||
"INSERT INTO sessions (id_hash, user, expires_at) VALUES (?, ?, ?)",
|
||||
(id_hash, user, now + ttl_seconds),
|
||||
)
|
||||
|
||||
|
||||
def session_user(conn: sqlite3.Connection, id_hash: str) -> str | None:
|
||||
row = conn.execute(
|
||||
"SELECT user FROM sessions WHERE id_hash = ? AND expires_at >= ?",
|
||||
(id_hash, int(time.time())),
|
||||
).fetchone()
|
||||
return row["user"] if row else None
|
||||
|
||||
|
||||
def delete_session(conn: sqlite3.Connection, id_hash: str) -> None:
|
||||
conn.execute("DELETE FROM sessions WHERE id_hash = ?", (id_hash,))
|
||||
@@ -0,0 +1,66 @@
|
||||
"""Validation of agent reports. Unknown fields are dropped; known ones are type-checked."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
MAX_BODY_BYTES = 64 * 1024
|
||||
_MAX_STR = 256
|
||||
_MAX_LIST = 200
|
||||
|
||||
|
||||
class ReportError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
# field -> kind. "str", "int", "bool", "strlist". All fields are optional.
|
||||
FIELDS: dict[str, str] = {
|
||||
"agent_version": "str",
|
||||
"reported_hostname": "str",
|
||||
"os_id": "str",
|
||||
"os_version_id": "str",
|
||||
"os_pretty_name": "str",
|
||||
"kernel_running": "str",
|
||||
"kernel_build": "str",
|
||||
"kernels_installed": "strlist",
|
||||
"kernel_newest_installed": "str",
|
||||
"needrestart_ksta": "int",
|
||||
"needrestart_kexp": "str",
|
||||
"reboot_required": "bool",
|
||||
"reboot_required_pkgs": "strlist",
|
||||
"upgradable_count": "int",
|
||||
"security_count": "int",
|
||||
"kernel_upgradable": "strlist",
|
||||
"apt_lists_age_seconds": "int",
|
||||
"uptime_seconds": "int",
|
||||
}
|
||||
|
||||
|
||||
def _check(name: str, kind: str, value: Any) -> Any:
|
||||
if value is None:
|
||||
return None
|
||||
if kind == "str":
|
||||
if not isinstance(value, str):
|
||||
raise ReportError(f"{name} must be a string")
|
||||
return value[:_MAX_STR]
|
||||
if kind == "int":
|
||||
if not isinstance(value, int) or isinstance(value, bool):
|
||||
raise ReportError(f"{name} must be an integer")
|
||||
return value
|
||||
if kind == "bool":
|
||||
if not isinstance(value, bool):
|
||||
raise ReportError(f"{name} must be a boolean")
|
||||
return value
|
||||
if kind == "strlist":
|
||||
if not isinstance(value, list) or not all(isinstance(v, str) for v in value):
|
||||
raise ReportError(f"{name} must be a list of strings")
|
||||
return [v[:_MAX_STR] for v in value[:_MAX_LIST]]
|
||||
raise AssertionError(kind)
|
||||
|
||||
|
||||
def sanitize(raw: Any) -> dict[str, Any]:
|
||||
if not isinstance(raw, dict):
|
||||
raise ReportError("report must be a JSON object")
|
||||
if not isinstance(raw.get("kernel_running"), str) or not raw["kernel_running"]:
|
||||
raise ReportError("kernel_running is required")
|
||||
return {name: _check(name, kind, raw[name]) for name, kind in FIELDS.items() if name in raw}
|
||||
@@ -0,0 +1,89 @@
|
||||
"""Turn a host's latest report into a dashboard status.
|
||||
|
||||
Levels, worst first:
|
||||
stale - no report recently (or ever); nothing else can be trusted
|
||||
reboot - a newer kernel (or other reboot-requiring update) is installed but not running
|
||||
update - updates are waiting to be installed, or the package lists are too old to tell
|
||||
ok - running the newest installed kernel, nothing pending
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from .config import Config
|
||||
|
||||
LEVELS = ("stale", "reboot", "update", "ok")
|
||||
_RANK = {level: i for i, level in enumerate(LEVELS)}
|
||||
|
||||
# needrestart's NEEDRESTART-KSTA values.
|
||||
KSTA_CURRENT = 1
|
||||
KSTA_ABI_UPGRADE = 2
|
||||
KSTA_VERSION_UPGRADE = 3
|
||||
|
||||
|
||||
@dataclass
|
||||
class Status:
|
||||
level: str = "ok"
|
||||
reasons: list[str] = field(default_factory=list)
|
||||
|
||||
def raise_to(self, level: str, reason: str) -> None:
|
||||
if _RANK[level] < _RANK[self.level]:
|
||||
self.level = level
|
||||
self.reasons.append(reason)
|
||||
|
||||
@property
|
||||
def rank(self) -> int:
|
||||
return _RANK[self.level]
|
||||
|
||||
|
||||
def kernel_reboot_pending(report: dict[str, Any]) -> str | None:
|
||||
"""Why the running kernel is out of date, or None if it isn't (as far as we can tell)."""
|
||||
running = report.get("kernel_running") or "?"
|
||||
ksta = report.get("needrestart_ksta")
|
||||
if ksta == KSTA_VERSION_UPGRADE:
|
||||
expected = report.get("needrestart_kexp") or report.get("kernel_newest_installed") or "?"
|
||||
return f"running {running}, {expected} installed"
|
||||
if ksta == KSTA_ABI_UPGRADE:
|
||||
return f"running {running}, an ABI-compatible update of it is installed"
|
||||
if ksta == KSTA_CURRENT:
|
||||
return None
|
||||
|
||||
# No usable needrestart result: compare against the newest installed image.
|
||||
newest = report.get("kernel_newest_installed")
|
||||
if newest and newest != running:
|
||||
return f"running {running}, {newest} installed"
|
||||
return None
|
||||
|
||||
|
||||
def evaluate(received_at: int | None, report: dict[str, Any] | None, now: float,
|
||||
cfg: Config) -> Status:
|
||||
status = Status()
|
||||
if received_at is None or report is None:
|
||||
status.raise_to("stale", "never reported")
|
||||
return status
|
||||
|
||||
age_h = (now - received_at) / 3600
|
||||
if age_h > cfg.stale_after_hours:
|
||||
status.raise_to("stale", f"last report {age_h:.0f}h ago")
|
||||
|
||||
if why := kernel_reboot_pending(report):
|
||||
status.raise_to("reboot", f"kernel: {why}")
|
||||
if report.get("reboot_required"):
|
||||
pkgs = report.get("reboot_required_pkgs") or []
|
||||
detail = f" ({', '.join(pkgs[:5])}{', …' if len(pkgs) > 5 else ''})" if pkgs else ""
|
||||
status.raise_to("reboot", f"/run/reboot-required{detail}")
|
||||
|
||||
if kernels := report.get("kernel_upgradable"):
|
||||
status.raise_to("update", f"kernel update available: {', '.join(kernels)}")
|
||||
if sec := report.get("security_count"):
|
||||
status.raise_to("update", f"{sec} security update{'s' if sec != 1 else ''} pending")
|
||||
|
||||
apt_age = report.get("apt_lists_age_seconds")
|
||||
if apt_age is None:
|
||||
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?")
|
||||
|
||||
return status
|
||||
@@ -0,0 +1,514 @@
|
||||
"""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
|
||||
from .config import Config
|
||||
from .report import MAX_BODY_BYTES, ReportError, sanitize
|
||||
from .status import LEVELS, Status, evaluate
|
||||
|
||||
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 badge(level: str) -> str:
|
||||
return f'<span class="badge {e(level)}">{e(level)}</span>'
|
||||
|
||||
|
||||
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'<span class="muted">{e(user)}</span>'
|
||||
'<form method="post" action="/logout"><button type="submit">Log out</button></form>'
|
||||
if user else ""
|
||||
)
|
||||
header = (
|
||||
f'<header><h1><a href="/">kernelwatch</a></h1>{logout}</header>' if user else ""
|
||||
)
|
||||
meta_refresh = '<meta http-equiv="refresh" content="60">' if refresh else ""
|
||||
return f"""<!doctype html>
|
||||
<html lang="en"><head><meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
{meta_refresh}<title>{e(title)}</title>
|
||||
<link rel="stylesheet" href="/static/style.css"></head>
|
||||
<body>{header}{body}</body></html>"""
|
||||
|
||||
|
||||
# --- handler ----------------------------------------------------------------
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
server_version = "kernelwatch/" + __version__
|
||||
sys_version = ""
|
||||
cfg: Config
|
||||
limiter: LoginLimiter
|
||||
|
||||
# -- plumbing --
|
||||
|
||||
def log_message(self, fmt: str, *args: Any) -> None:
|
||||
sys.stderr.write(f"{self.client_ip()} {fmt % args}\n")
|
||||
|
||||
def client_ip(self) -> str:
|
||||
if self.cfg.trust_proxy_headers:
|
||||
fwd = self.headers.get("X-Forwarded-For", "")
|
||||
if fwd:
|
||||
return fwd.split(",")[-1].strip()
|
||||
return self.client_address[0]
|
||||
|
||||
def conn(self):
|
||||
return db.connect(self.cfg.db_path)
|
||||
|
||||
def send(self, status: int, body: str | bytes = b"", content_type: str = "text/html; charset=utf-8",
|
||||
headers: dict[str, str] | None = None) -> None:
|
||||
data = body.encode() if isinstance(body, str) else body
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.send_header("X-Content-Type-Options", "nosniff")
|
||||
self.send_header("Referrer-Policy", "no-referrer")
|
||||
self.send_header(
|
||||
"Content-Security-Policy",
|
||||
"default-src 'none'; style-src 'self'; form-action 'self'; frame-ancestors 'none'",
|
||||
)
|
||||
for k, v in (headers or {}).items():
|
||||
self.send_header(k, v)
|
||||
self.end_headers()
|
||||
if self.command != "HEAD":
|
||||
self.wfile.write(data)
|
||||
|
||||
def send_json(self, status: int, obj: Any) -> None:
|
||||
self.send(status, json.dumps(obj), "application/json")
|
||||
|
||||
def redirect(self, location: str, headers: dict[str, str] | None = None) -> None:
|
||||
self.send(HTTPStatus.SEE_OTHER, b"", headers={"Location": location, **(headers or {})})
|
||||
|
||||
def read_body(self) -> bytes | None:
|
||||
length = self.headers.get("Content-Length")
|
||||
if length is None or not length.isdigit():
|
||||
self.send(HTTPStatus.LENGTH_REQUIRED, "Content-Length required", "text/plain")
|
||||
return None
|
||||
if int(length) > MAX_BODY_BYTES:
|
||||
self.send(HTTPStatus.REQUEST_ENTITY_TOO_LARGE, "body too large", "text/plain")
|
||||
return None
|
||||
return self.rfile.read(int(length))
|
||||
|
||||
def same_origin(self) -> bool:
|
||||
"""Reject cross-site form posts. Browsers send Origin on POST."""
|
||||
origin = self.headers.get("Origin")
|
||||
if origin is None:
|
||||
return True
|
||||
host = self.headers.get("Host", "")
|
||||
if self.cfg.trust_proxy_headers:
|
||||
host = self.headers.get("X-Forwarded-Host", host)
|
||||
return urlsplit(origin).netloc == host
|
||||
|
||||
def session_id(self) -> str | None:
|
||||
raw = self.headers.get("Cookie")
|
||||
if not raw:
|
||||
return None
|
||||
try:
|
||||
morsel = SimpleCookie(raw).get(SESSION_COOKIE)
|
||||
except CookieError:
|
||||
return None
|
||||
return morsel.value if morsel else None
|
||||
|
||||
def current_user(self) -> str | None:
|
||||
sid = self.session_id()
|
||||
if not sid:
|
||||
return None
|
||||
conn = self.conn()
|
||||
try:
|
||||
return db.session_user(conn, auth.token_hash(sid))
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def cookie(self, value: str, max_age: int) -> str:
|
||||
parts = [f"{SESSION_COOKIE}={value}", "Path=/", "HttpOnly", "SameSite=Strict",
|
||||
f"Max-Age={max_age}"]
|
||||
if self.cfg.secure_cookies:
|
||||
parts.append("Secure")
|
||||
return "; ".join(parts)
|
||||
|
||||
# -- routing --
|
||||
|
||||
def do_HEAD(self) -> None:
|
||||
self.do_GET()
|
||||
|
||||
def do_GET(self) -> None:
|
||||
path = urlsplit(self.path).path
|
||||
if path == "/healthz":
|
||||
return self.send(HTTPStatus.OK, "ok\n", "text/plain")
|
||||
if path == "/static/style.css":
|
||||
return self.send(HTTPStatus.OK, STYLE, "text/css; charset=utf-8")
|
||||
if path == "/login":
|
||||
return self.login_page()
|
||||
|
||||
user = self.current_user()
|
||||
if user is None:
|
||||
return self.redirect("/login")
|
||||
if path == "/":
|
||||
return self.dashboard(user)
|
||||
if path.startswith("/host/"):
|
||||
return self.host_page(user, unquote(path[len("/host/"):]))
|
||||
self.send(HTTPStatus.NOT_FOUND, page("Not found", "<main><p>Not found.</p></main>", user))
|
||||
|
||||
def do_POST(self) -> None:
|
||||
path = urlsplit(self.path).path
|
||||
if path == "/api/v1/report":
|
||||
return self.ingest()
|
||||
if path == "/login":
|
||||
return self.login()
|
||||
if path == "/logout":
|
||||
return self.logout()
|
||||
self.send(HTTPStatus.NOT_FOUND, "not found", "text/plain")
|
||||
|
||||
# -- API --
|
||||
|
||||
def ingest(self) -> None:
|
||||
header = self.headers.get("Authorization", "")
|
||||
scheme, _, token = header.partition(" ")
|
||||
if scheme.lower() != "bearer" or not token.strip():
|
||||
return self.send_json(HTTPStatus.UNAUTHORIZED, {"error": "missing bearer token"})
|
||||
|
||||
body = self.read_body()
|
||||
if body is None:
|
||||
return
|
||||
conn = self.conn()
|
||||
try:
|
||||
host = db.host_for_token(conn, auth.token_hash(token.strip()))
|
||||
if host is None:
|
||||
return self.send_json(HTTPStatus.UNAUTHORIZED, {"error": "unknown token"})
|
||||
try:
|
||||
report = sanitize(json.loads(body))
|
||||
except (ValueError, ReportError) as exc:
|
||||
return self.send_json(HTTPStatus.BAD_REQUEST, {"error": str(exc)})
|
||||
db.add_report(conn, host, report, self.cfg.report_retention_days)
|
||||
finally:
|
||||
conn.close()
|
||||
self.send(HTTPStatus.NO_CONTENT, b"", "text/plain")
|
||||
|
||||
# -- auth pages --
|
||||
|
||||
def login_page(self, error: str = "", status: int = HTTPStatus.OK) -> None:
|
||||
err = f'<p class="error">{e(error)}</p>' if error else ""
|
||||
body = f"""<main><form class="login" method="post" action="/login">
|
||||
<h1>kernelwatch</h1>{err}
|
||||
<label>Username<input name="username" autocomplete="username" required autofocus></label>
|
||||
<label>Password<input name="password" type="password" autocomplete="current-password" required></label>
|
||||
<button type="submit">Log in</button></form></main>"""
|
||||
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)
|
||||
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'<div><b>{counts[level]}</b>{badge(level)}</div>' for level in LEVELS
|
||||
)
|
||||
table = (
|
||||
"<p class=muted>No hosts yet. Add one with <code>kernelwatch add-host NAME</code>.</p>"
|
||||
if not hosts else
|
||||
'<div class="table-wrap"><table><thead><tr>'
|
||||
"<th>Status</th><th>Host</th><th>OS</th><th>Running kernel</th>"
|
||||
"<th>Newest installed</th><th>Updates</th><th>Uptime</th><th>Last seen</th>"
|
||||
"<th>Details</th></tr></thead><tbody>" + "".join(rows) + "</tbody></table></div>"
|
||||
)
|
||||
body = f'<main><div class="summary">{summary}</div>{table}</main>'
|
||||
self.send(HTTPStatus.OK, page("Fleet · kernelwatch", body, user, refresh=True))
|
||||
|
||||
@staticmethod
|
||||
def host_row(h: dict[str, Any], now: float) -> str:
|
||||
r = h["report"] or {}
|
||||
status: Status = h["status"]
|
||||
name = h["host"]
|
||||
sec = r.get("security_count")
|
||||
total = r.get("upgradable_count")
|
||||
updates = "–" if total is None else f"{total}" + (f" ({sec} sec)" if sec else "")
|
||||
return (
|
||||
"<tr>"
|
||||
f"<td>{badge(status.level)}</td>"
|
||||
f'<td><a href="/host/{quote(name)}">{e(name)}</a></td>'
|
||||
f"<td>{e(r.get('os_pretty_name') or '–')}</td>"
|
||||
f"<td><code>{e(r.get('kernel_running') or '–')}</code></td>"
|
||||
f"<td><code>{e(r.get('kernel_newest_installed') or '–')}</code></td>"
|
||||
f"<td>{e(updates)}</td>"
|
||||
f"<td>{e(duration(r.get('uptime_seconds')))}</td>"
|
||||
f'<td title="{e(utc(h["received_at"]))}">{e(ago(h["received_at"], now))}</td>'
|
||||
f'<td class="reasons">{"<br>".join(e(x) for x in status.reasons) or "–"}</td>'
|
||||
"</tr>"
|
||||
)
|
||||
|
||||
def host_page(self, user: str, name: str) -> None:
|
||||
if not HOST_NAME_RE.match(name):
|
||||
return self.send(HTTPStatus.NOT_FOUND, page("Not found", "<main><p>Not found.</p></main>", user))
|
||||
now = time.time()
|
||||
conn = self.conn()
|
||||
try:
|
||||
exists = db.host_exists(conn, name)
|
||||
history = db.host_history(conn, name) if exists else []
|
||||
finally:
|
||||
conn.close()
|
||||
if not exists:
|
||||
return self.send(HTTPStatus.NOT_FOUND, page("Not found", "<main><p>Not found.</p></main>", user))
|
||||
|
||||
latest = history[0] if history else None
|
||||
status = evaluate(latest and latest["received_at"], latest and latest["report"], now, self.cfg)
|
||||
r = latest["report"] if latest else {}
|
||||
|
||||
def field(label: str, value: Any, code: bool = False) -> str:
|
||||
if value is None or value == "" or value == []:
|
||||
text = "–"
|
||||
elif isinstance(value, list):
|
||||
text = ", ".join(str(v) for v in value)
|
||||
else:
|
||||
text = str(value)
|
||||
inner = f"<code>{e(text)}</code>" if code and text != "–" else e(text)
|
||||
return f"<dt>{e(label)}</dt><dd>{inner}</dd>"
|
||||
|
||||
details = "".join([
|
||||
f"<dt>Status</dt><dd>{badge(status.level)}</dd>",
|
||||
field("Why", "; ".join(status.reasons) or None),
|
||||
field("Last report", f"{ago(latest['received_at'], now)} ({utc(latest['received_at'])})"
|
||||
if latest else None),
|
||||
field("Reported hostname", r.get("reported_hostname")),
|
||||
field("OS", r.get("os_pretty_name")),
|
||||
field("Running kernel", r.get("kernel_running"), code=True),
|
||||
field("Kernel build", r.get("kernel_build"), code=True),
|
||||
field("Installed kernels", r.get("kernels_installed"), code=True),
|
||||
field("needrestart", None if r.get("needrestart_ksta") is None else
|
||||
f"KSTA={r['needrestart_ksta']} expected={r.get('needrestart_kexp') or '?'}"),
|
||||
field("Kernel packages upgradable", r.get("kernel_upgradable"), code=True),
|
||||
field("Updates pending", r.get("upgradable_count")),
|
||||
field("Security updates", r.get("security_count")),
|
||||
field("Reboot-required packages", r.get("reboot_required_pkgs"), 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("Uptime", duration(r.get("uptime_seconds")) if r.get("uptime_seconds") is not None else None),
|
||||
field("Agent version", r.get("agent_version")),
|
||||
])
|
||||
|
||||
# History: status as it was at the time of each report (so never "stale").
|
||||
hist_rows = "".join(
|
||||
"<tr>"
|
||||
f'<td title="{e(utc(h["received_at"]))}">{e(ago(h["received_at"], now))}</td>'
|
||||
f"<td>{badge(evaluate(h['received_at'], h['report'], h['received_at'], self.cfg).level)}</td>"
|
||||
f"<td><code>{e(h['report'].get('kernel_running') or '–')}</code></td>"
|
||||
f"<td>{e(str(h['report'].get('upgradable_count', '–')))}</td>"
|
||||
"</tr>"
|
||||
for h in history
|
||||
)
|
||||
history_html = (
|
||||
'<h2>Recent reports</h2><div class="table-wrap"><table><thead><tr>'
|
||||
"<th>When</th><th>Status</th><th>Running kernel</th><th>Updates</th>"
|
||||
f"</tr></thead><tbody>{hist_rows}</tbody></table></div>"
|
||||
if history else "<p class=muted>No reports yet.</p>"
|
||||
)
|
||||
body = f"<main><h2>{e(name)}</h2><dl>{details}</dl>{history_html}</main>"
|
||||
self.send(HTTPStatus.OK, page(f"{name} · kernelwatch", body, user, refresh=True))
|
||||
|
||||
|
||||
def make_server(cfg: Config) -> ThreadingHTTPServer:
|
||||
db.init(cfg.db_path)
|
||||
handler = type("BoundHandler", (Handler,), {"cfg": cfg, "limiter": LoginLimiter()})
|
||||
server = ThreadingHTTPServer((cfg.listen_host, cfg.listen_port), handler)
|
||||
server.daemon_threads = True
|
||||
return server
|
||||
|
||||
|
||||
def serve(cfg: Config) -> None:
|
||||
server = make_server(cfg)
|
||||
host, port = server.server_address[:2]
|
||||
print(f"kernelwatch {__version__} listening on http://{host}:{port}", file=sys.stderr, flush=True)
|
||||
try:
|
||||
server.serve_forever()
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
server.server_close()
|
||||
@@ -0,0 +1,25 @@
|
||||
# /etc/kernelwatch/server.toml — every key is optional; defaults shown.
|
||||
|
||||
# The server speaks plain HTTP; keep it on loopback behind a TLS reverse proxy.
|
||||
listen_host = "127.0.0.1"
|
||||
listen_port = 8080
|
||||
db_path = "/var/lib/kernelwatch/kernelwatch.db"
|
||||
|
||||
# A host that hasn't reported in this long shows as "stale".
|
||||
# Agents report hourly (plus up to 15 min jitter).
|
||||
stale_after_hours = 3.0
|
||||
|
||||
# Package lists older than this mean "no updates" can't be trusted.
|
||||
apt_stale_after_hours = 48.0
|
||||
|
||||
report_retention_days = 30
|
||||
session_hours = 12
|
||||
|
||||
# Session cookie gets the Secure flag. Leave on unless you're testing over
|
||||
# plain HTTP on something other than localhost.
|
||||
secure_cookies = true
|
||||
|
||||
# Behind a reverse proxy, use X-Forwarded-For / X-Forwarded-Host for login
|
||||
# rate limiting and origin checks. Only enable if the port isn't reachable
|
||||
# directly, or clients can spoof their IP.
|
||||
trust_proxy_headers = false
|
||||
Reference in new issue
Block a user