py56 lines2.0 KB
| 1 | #!/usr/bin/env python3 |
| 2 | """Sanitize Proxmox audit output into a terminal-replay transcript.""" |
| 3 | |
| 4 | from __future__ import annotations |
| 5 | |
| 6 | import json |
| 7 | import os |
| 8 | import re |
| 9 | import sys |
| 10 | from collections.abc import Callable |
| 11 | |
| 12 | IP = re.compile(r"\b(?:192\.168|10|100)\.\d{1,3}\.\d{1,3}\b") |
| 13 | MAC = re.compile(r"\b(?:[0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}\b") |
| 14 | UUID = re.compile(r"\b[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}\b") |
| 15 | DISK = re.compile(r"\b(?:eui\.[A-Za-z0-9._-]+|nvme-[A-Za-z0-9._-]+|wwn-[A-Za-z0-9._-]+)\b", re.I) |
| 16 | SERIAL = re.compile(r"(?i)\b(serial(?:_number)?\s*[=:]\s*)[^\s,]+") |
| 17 | COMMENT = re.compile(r"""(?i)(["']?(?:comment|notes|description)["']?\s*[:=]\s*)(["'])(.*?)\2""") |
| 18 | REPOID = re.compile(r"\s*\(repoid [0-9a-f]+\)") |
| 19 | |
| 20 | |
| 21 | def replacement(prefix: str) -> Callable[[re.Match[str]], str]: |
| 22 | values: dict[str, str] = {} |
| 23 | |
| 24 | def replace(match: re.Match[str]) -> str: |
| 25 | value = match.group(0) |
| 26 | if value not in values: |
| 27 | values[value] = f"[{prefix}-{len(values) + 1}]" |
| 28 | return values[value] |
| 29 | |
| 30 | return replace |
| 31 | |
| 32 | |
| 33 | def sanitize(text: str) -> str: |
| 34 | """Replace network and machine identifiers while retaining audit meaning.""" |
| 35 | text = IP.sub(replacement("address"), text) |
| 36 | text = MAC.sub(replacement("mac"), text) |
| 37 | text = UUID.sub(replacement("uuid"), text) |
| 38 | text = DISK.sub(replacement("disk-id"), text) |
| 39 | text = SERIAL.sub(r"\1[serial]", text) |
| 40 | text = COMMENT.sub(r"\1\2[note]\2", text) |
| 41 | text = REPOID.sub("", text) |
| 42 | for word in filter(None, (w.strip() for w in os.environ.get("SANITIZE_EXTRA", "").split(","))): |
| 43 | text = re.sub(re.escape(word), "[name]", text, flags=re.I) |
| 44 | return text |
| 45 | |
| 46 | |
| 47 | def main() -> int: |
| 48 | output = sanitize(sys.stdin.read()) |
| 49 | transcript = {"title": "Proxmox cluster audit", "prompt": "$ ", "type_ms": 28, "line_ms": 30, "steps": [{"cmd": "PVE_HOST=[address] python pve_audit.py", "out": output, "pause": 900}]} |
| 50 | json.dump(transcript, sys.stdout, indent=2) |
| 51 | sys.stdout.write("\n") |
| 52 | return 0 |
| 53 | |
| 54 | |
| 55 | if __name__ == "__main__": |
| 56 | raise SystemExit(main()) |