#!/usr/bin/env python3 """Read-only Proxmox cluster audit using GET requests only.""" from __future__ import annotations import json import os import ssl import sys import urllib.error import urllib.request from typing import Any PVE_HOST = os.environ.get("PVE_HOST", "").strip() TOKEN_ID = os.environ.get("PVE_TOKEN_ID", "") TOKEN_SECRET = os.environ.get("PVE_TOKEN_SECRET", "") _DENIED: list[tuple[str, str]] = [] class AuditError(RuntimeError): """An audit request could not be completed.""" def __init__(self, message: str, status: int | None = None) -> None: super().__init__(message) self.status = status def tls_context() -> ssl.SSLContext: """Build a verified TLS context after required configuration is present.""" ca_file = os.environ.get("PVE_CA_FILE", "").strip() try: return ssl.create_default_context(cafile=ca_file or None) except (OSError, ValueError, ssl.SSLError) as exc: raise AuditError("PVE_CA_FILE could not be loaded") from exc def api_url(path: str) -> str: """Use the standard Proxmox port unless PVE_HOST includes an explicit port.""" host = PVE_HOST if host.startswith("[") and "]:" not in host: host = f"{host}:8006" elif not host.startswith("[") and host.count(":") != 1: host = f"{host}:8006" return f"https://{host}/api2/json{path}" def tls_error(exc: BaseException) -> AuditError: """Turn transport failures into a concise error without request headers.""" reason = exc.reason if isinstance(exc, urllib.error.URLError) else exc if isinstance(reason, ssl.SSLCertVerificationError): return AuditError("TLS certificate verification failed") if isinstance(reason, ssl.SSLError): return AuditError("TLS connection failed") return AuditError("connection failed") def get(path: str) -> Any: """The only network primitive in this file: an HTTP GET.""" if not PVE_HOST: raise AuditError("PVE_HOST must be set in the environment") if not TOKEN_ID or not TOKEN_SECRET: raise AuditError("PVE_TOKEN_ID and PVE_TOKEN_SECRET must be set in the environment") request = urllib.request.Request( api_url(path), method="GET", headers={"Authorization": f"PVEAPIToken={TOKEN_ID}={TOKEN_SECRET}"}, ) try: with urllib.request.urlopen(request, context=tls_context(), timeout=20) as response: return json.loads(response.read().decode()).get("data") except urllib.error.HTTPError as exc: body = exc.read().decode(errors="replace")[:300] if exc.code in (401, 403): raise AuditError(f"HTTP {exc.code} on {path}: access refused", exc.code) from exc raise AuditError(f"HTTP {exc.code} on {path}: {body}", exc.code) from exc except (urllib.error.URLError, OSError, ValueError) as exc: raise tls_error(exc) from exc def safe(path: str, default: Any) -> Any: """Read an endpoint without hiding a permission problem.""" try: return get(path) except AuditError as exc: _DENIED.append((path, str(exc).splitlines()[0][:110])) return default def section(title: str) -> None: print(f"\n{'=' * 68}\n{title}\n{'=' * 68}") def ha_rules() -> Any: """Use the PVE 9 rules endpoint when the retired groups endpoint returns 500.""" try: return get("/cluster/ha/groups") except AuditError as exc: if exc.status == 500: print(" HA groups moved to rules on Proxmox VE 9; reading HA rules instead.") return safe("/cluster/ha/rules", []) _DENIED.append(("/cluster/ha/groups", str(exc).splitlines()[0][:110])) return [] def denied_report() -> bool: """Print denials so an incomplete report cannot look clean.""" if not _DENIED: return False print(f"\n{'!' * 68}\nINCOMPLETE AUDIT: {len(_DENIED)} endpoint(s) DENIED.\nSections may look empty because access was refused, not because no configuration exists.\n{'!' * 68}") for path, message in _DENIED: print(f" DENIED {path}\n {message}") return True def gib(value: Any) -> str: return f"{value / 2**30:.1f} GiB" if isinstance(value, (int, float)) else "?" def days(seconds: Any) -> str: return f"{int(seconds) // 86400}d" if isinstance(seconds, (int, float)) else "?" def retention(job: dict) -> str: keep = job.get("prune-backups", {}) if isinstance(keep, str): keep = dict(part.split("=", 1) for part in keep.split(",") if "=" in part) order = ["keep-last", "keep-hourly", "keep-daily", "keep-weekly", "keep-monthly", "keep-yearly"] ranked = sorted(keep.items(), key=lambda kv: order.index(kv[0]) if kv[0] in order else len(order)) return " ".join(f"{k.removeprefix('keep-')}={v}" for k, v in ranked) or "none" def main() -> int: section("CONNECTIVITY / VERSION") version = get("/version") print(f" Proxmox VE {version.get('version', '?')}") section("CLUSTER QUORUM") status = safe("/cluster/status", []) for item in status: if item.get("type") == "cluster": state = "OK" if item.get("quorate") else "NO QUORUM" print(f" cluster: {item.get('nodes')} nodes, quorum {state}") for item in sorted((i for i in status if i.get("type") == "node"), key=lambda i: i.get("name", "")): print(f" {item.get('name'):<8} {'online' if item.get('online') else 'OFFLINE'}") section("HA, REPLICATION, AND BACKUPS") rules = ha_rules() print(f" HA rules: {len(rules) if isinstance(rules, list) else '?'} configured") for job in safe("/cluster/replication", []): print(f" replication: guest {job.get('guest')} {job.get('source')} -> {job.get('target')}" f" every {str(job.get('schedule', '?')).removeprefix('*/')} min") for job in safe("/cluster/backup", []): print(f" backup: daily {job.get('schedule')} mode={job.get('mode')} compress={job.get('compress')}" f" keep {retention(job)}") section("STORAGE") for storage in sorted(safe("/storage", []), key=lambda st: st.get("storage", "")): print(f" {storage.get('storage'):<10} type={storage.get('type'):<8} shared={storage.get('shared', 0)}") section("NODE HEALTH") for node in sorted(safe("/nodes", []), key=lambda n: n.get("node", "")): name = node.get("node") if not name: continue if node.get("status") != "online": print(f" {name}: OFFLINE (skipped)") continue status = safe(f"/nodes/{name}/status", {}) memory = status.get("memory", {}) if isinstance(status, dict) else {} print(f" {name}: up {days(status.get('uptime'))}, memory {gib(memory.get('used'))} of {gib(memory.get('total'))}") for pool in safe(f"/nodes/{name}/disks/zfs", []): print(f" zfs {pool.get('name')}: {pool.get('health')}, {gib(pool.get('alloc'))} used of {gib(pool.get('size'))}") section("AUDIT COMPLETE") if denied_report(): return 3 print(" No changes made: GET-only by construction.") return 0 if __name__ == "__main__": try: raise SystemExit(main()) except AuditError as exc: print(f"AUDIT ABORTED: {exc}", file=sys.stderr) raise SystemExit(2)