py185 lines7.1 KB
| 1 | #!/usr/bin/env python3 |
| 2 | """Read-only Proxmox cluster audit using GET requests only.""" |
| 3 | |
| 4 | from __future__ import annotations |
| 5 | |
| 6 | import json |
| 7 | import os |
| 8 | import ssl |
| 9 | import sys |
| 10 | import urllib.error |
| 11 | import urllib.request |
| 12 | from typing import Any |
| 13 | |
| 14 | PVE_HOST = os.environ.get("PVE_HOST", "").strip() |
| 15 | TOKEN_ID = os.environ.get("PVE_TOKEN_ID", "") |
| 16 | TOKEN_SECRET = os.environ.get("PVE_TOKEN_SECRET", "") |
| 17 | _DENIED: list[tuple[str, str]] = [] |
| 18 | |
| 19 | |
| 20 | class AuditError(RuntimeError): |
| 21 | """An audit request could not be completed.""" |
| 22 | |
| 23 | def __init__(self, message: str, status: int | None = None) -> None: |
| 24 | super().__init__(message) |
| 25 | self.status = status |
| 26 | |
| 27 | |
| 28 | def tls_context() -> ssl.SSLContext: |
| 29 | """Build a verified TLS context after required configuration is present.""" |
| 30 | ca_file = os.environ.get("PVE_CA_FILE", "").strip() |
| 31 | try: |
| 32 | return ssl.create_default_context(cafile=ca_file or None) |
| 33 | except (OSError, ValueError, ssl.SSLError) as exc: |
| 34 | raise AuditError("PVE_CA_FILE could not be loaded") from exc |
| 35 | |
| 36 | |
| 37 | def api_url(path: str) -> str: |
| 38 | """Use the standard Proxmox port unless PVE_HOST includes an explicit port.""" |
| 39 | host = PVE_HOST |
| 40 | if host.startswith("[") and "]:" not in host: |
| 41 | host = f"{host}:8006" |
| 42 | elif not host.startswith("[") and host.count(":") != 1: |
| 43 | host = f"{host}:8006" |
| 44 | return f"https://{host}/api2/json{path}" |
| 45 | |
| 46 | |
| 47 | def tls_error(exc: BaseException) -> AuditError: |
| 48 | """Turn transport failures into a concise error without request headers.""" |
| 49 | reason = exc.reason if isinstance(exc, urllib.error.URLError) else exc |
| 50 | if isinstance(reason, ssl.SSLCertVerificationError): |
| 51 | return AuditError("TLS certificate verification failed") |
| 52 | if isinstance(reason, ssl.SSLError): |
| 53 | return AuditError("TLS connection failed") |
| 54 | return AuditError("connection failed") |
| 55 | |
| 56 | |
| 57 | def get(path: str) -> Any: |
| 58 | """The only network primitive in this file: an HTTP GET.""" |
| 59 | if not PVE_HOST: |
| 60 | raise AuditError("PVE_HOST must be set in the environment") |
| 61 | if not TOKEN_ID or not TOKEN_SECRET: |
| 62 | raise AuditError("PVE_TOKEN_ID and PVE_TOKEN_SECRET must be set in the environment") |
| 63 | request = urllib.request.Request( |
| 64 | api_url(path), method="GET", |
| 65 | headers={"Authorization": f"PVEAPIToken={TOKEN_ID}={TOKEN_SECRET}"}, |
| 66 | ) |
| 67 | try: |
| 68 | with urllib.request.urlopen(request, context=tls_context(), timeout=20) as response: |
| 69 | return json.loads(response.read().decode()).get("data") |
| 70 | except urllib.error.HTTPError as exc: |
| 71 | body = exc.read().decode(errors="replace")[:300] |
| 72 | if exc.code in (401, 403): |
| 73 | raise AuditError(f"HTTP {exc.code} on {path}: access refused", exc.code) from exc |
| 74 | raise AuditError(f"HTTP {exc.code} on {path}: {body}", exc.code) from exc |
| 75 | except (urllib.error.URLError, OSError, ValueError) as exc: |
| 76 | raise tls_error(exc) from exc |
| 77 | |
| 78 | |
| 79 | def safe(path: str, default: Any) -> Any: |
| 80 | """Read an endpoint without hiding a permission problem.""" |
| 81 | try: |
| 82 | return get(path) |
| 83 | except AuditError as exc: |
| 84 | _DENIED.append((path, str(exc).splitlines()[0][:110])) |
| 85 | return default |
| 86 | |
| 87 | |
| 88 | def section(title: str) -> None: |
| 89 | print(f"\n{'=' * 68}\n{title}\n{'=' * 68}") |
| 90 | |
| 91 | |
| 92 | def ha_rules() -> Any: |
| 93 | """Use the PVE 9 rules endpoint when the retired groups endpoint returns 500.""" |
| 94 | try: |
| 95 | return get("/cluster/ha/groups") |
| 96 | except AuditError as exc: |
| 97 | if exc.status == 500: |
| 98 | print(" HA groups moved to rules on Proxmox VE 9; reading HA rules instead.") |
| 99 | return safe("/cluster/ha/rules", []) |
| 100 | _DENIED.append(("/cluster/ha/groups", str(exc).splitlines()[0][:110])) |
| 101 | return [] |
| 102 | |
| 103 | |
| 104 | def denied_report() -> bool: |
| 105 | """Print denials so an incomplete report cannot look clean.""" |
| 106 | if not _DENIED: |
| 107 | return False |
| 108 | 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}") |
| 109 | for path, message in _DENIED: |
| 110 | print(f" DENIED {path}\n {message}") |
| 111 | return True |
| 112 | |
| 113 | |
| 114 | def gib(value: Any) -> str: |
| 115 | return f"{value / 2**30:.1f} GiB" if isinstance(value, (int, float)) else "?" |
| 116 | |
| 117 | |
| 118 | def days(seconds: Any) -> str: |
| 119 | return f"{int(seconds) // 86400}d" if isinstance(seconds, (int, float)) else "?" |
| 120 | |
| 121 | |
| 122 | def retention(job: dict) -> str: |
| 123 | keep = job.get("prune-backups", {}) |
| 124 | if isinstance(keep, str): |
| 125 | keep = dict(part.split("=", 1) for part in keep.split(",") if "=" in part) |
| 126 | order = ["keep-last", "keep-hourly", "keep-daily", "keep-weekly", "keep-monthly", "keep-yearly"] |
| 127 | ranked = sorted(keep.items(), key=lambda kv: order.index(kv[0]) if kv[0] in order else len(order)) |
| 128 | return " ".join(f"{k.removeprefix('keep-')}={v}" for k, v in ranked) or "none" |
| 129 | |
| 130 | |
| 131 | def main() -> int: |
| 132 | section("CONNECTIVITY / VERSION") |
| 133 | version = get("/version") |
| 134 | print(f" Proxmox VE {version.get('version', '?')}") |
| 135 | |
| 136 | section("CLUSTER QUORUM") |
| 137 | status = safe("/cluster/status", []) |
| 138 | for item in status: |
| 139 | if item.get("type") == "cluster": |
| 140 | state = "OK" if item.get("quorate") else "NO QUORUM" |
| 141 | print(f" cluster: {item.get('nodes')} nodes, quorum {state}") |
| 142 | for item in sorted((i for i in status if i.get("type") == "node"), key=lambda i: i.get("name", "")): |
| 143 | print(f" {item.get('name'):<8} {'online' if item.get('online') else 'OFFLINE'}") |
| 144 | |
| 145 | section("HA, REPLICATION, AND BACKUPS") |
| 146 | rules = ha_rules() |
| 147 | print(f" HA rules: {len(rules) if isinstance(rules, list) else '?'} configured") |
| 148 | for job in safe("/cluster/replication", []): |
| 149 | print(f" replication: guest {job.get('guest')} {job.get('source')} -> {job.get('target')}" |
| 150 | f" every {str(job.get('schedule', '?')).removeprefix('*/')} min") |
| 151 | for job in safe("/cluster/backup", []): |
| 152 | print(f" backup: daily {job.get('schedule')} mode={job.get('mode')} compress={job.get('compress')}" |
| 153 | f" keep {retention(job)}") |
| 154 | |
| 155 | section("STORAGE") |
| 156 | for storage in sorted(safe("/storage", []), key=lambda st: st.get("storage", "")): |
| 157 | print(f" {storage.get('storage'):<10} type={storage.get('type'):<8} shared={storage.get('shared', 0)}") |
| 158 | |
| 159 | section("NODE HEALTH") |
| 160 | for node in sorted(safe("/nodes", []), key=lambda n: n.get("node", "")): |
| 161 | name = node.get("node") |
| 162 | if not name: |
| 163 | continue |
| 164 | if node.get("status") != "online": |
| 165 | print(f" {name}: OFFLINE (skipped)") |
| 166 | continue |
| 167 | status = safe(f"/nodes/{name}/status", {}) |
| 168 | memory = status.get("memory", {}) if isinstance(status, dict) else {} |
| 169 | print(f" {name}: up {days(status.get('uptime'))}, memory {gib(memory.get('used'))} of {gib(memory.get('total'))}") |
| 170 | for pool in safe(f"/nodes/{name}/disks/zfs", []): |
| 171 | print(f" zfs {pool.get('name')}: {pool.get('health')}, {gib(pool.get('alloc'))} used of {gib(pool.get('size'))}") |
| 172 | |
| 173 | section("AUDIT COMPLETE") |
| 174 | if denied_report(): |
| 175 | return 3 |
| 176 | print(" No changes made: GET-only by construction.") |
| 177 | return 0 |
| 178 | |
| 179 | |
| 180 | if __name__ == "__main__": |
| 181 | try: |
| 182 | raise SystemExit(main()) |
| 183 | except AuditError as exc: |
| 184 | print(f"AUDIT ABORTED: {exc}", file=sys.stderr) |
| 185 | raise SystemExit(2) |