diff --git a/backend/app/auth.py b/backend/app/auth.py index 8f8a082..ef3f537 100644 --- a/backend/app/auth.py +++ b/backend/app/auth.py @@ -363,8 +363,8 @@ def pfad_rolle(methode: str, pfad: str) -> str: methode = (methode or "").upper() if pfad in FREIE_PFADE or pfad.startswith("/api/auth/"): return "" # freie Pfade bzw. der Router prueft selbst - if pfad == "/api/notifications/export": - return "admin" # der Export enthaelt die Konfiguration + if pfad in ("/api/notifications/export", "/api/logs/export"): + return "admin" # der Export enthaelt Konfiguration bzw. System-Logs if methode in ("GET", "HEAD", "OPTIONS"): return "betrachter" for erlaubt in _BETRACHTER_PFADE: diff --git a/backend/app/log_bundle.py b/backend/app/log_bundle.py new file mode 100644 index 0000000..66be379 --- /dev/null +++ b/backend/app/log_bundle.py @@ -0,0 +1,242 @@ +"""Zentrale Log-Erfassung und bereinigter Diagnose-Export ("Alle Logs herunterladen"). + +Sammelt Laufzeit-Logs (Ring-Buffer + rotierende Datei im Datenverzeichnis), +Scan-Logs aus SQLite, Provider-/Docker-Status, Subnetz-/Asset-Uebersicht und +Systeminfos in eine einzelne Text- oder JSON-Datei - mit automatischer +Maskierung moeglicher Geheimnisse, damit die Datei direkt geteilt werden kann. +""" +from __future__ import annotations + +import json +import logging +import re +import threading +from collections import deque +from datetime import datetime, timezone +from logging.handlers import RotatingFileHandler +from pathlib import Path +from typing import Any + +from .scanner import detect_providers +from .scanner.docker_scanner import check_docker_connection + +_LOCK = threading.Lock() +_RING_BUFFER: deque[str] = deque(maxlen=2500) +_INSTALLED_DIR: str = "" + +_SECRET_PATTERNS: list[tuple[re.Pattern[str], str]] = [ + (re.compile(r"(?i)(Authorization\s*:\s*(?:Bearer|Basic|PVEAPIToken)\s+)[^\s\"']+"), r"\1***"), + (re.compile(r"(?i)(X-Pingognito-Token\s*:\s*)[^\s\"']+"), r"\1***"), + (re.compile(r"(?i)(PVEAPIToken=)[^\s\"']+"), r"\1***"), + (re.compile(r"(?i)(\b(?:password|passwort|passwd|api[_-]?key|token|secret|community|auth_pass|priv_pass)\b\s*[:=]\s*)([^\s,;\"']+)"), r"\1***"), + (re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----"), "[PRIVATE-KEY-MASKIERT]"), +] + + +class _RingLogHandler(logging.Handler): + """Haelt die letzten Laufzeit-Logzeilen fuer den Sofort-Export im Speicher.""" + + def emit(self, record: logging.LogRecord) -> None: + try: + msg = self.format(record) + with _LOCK: + _RING_BUFFER.append(msg) + except Exception: + pass + + +def redact_secrets(text: str) -> str: + """Maskiert bekannte Token-, Passwort- und Private-Key-Muster in Log-Text.""" + out = text or "" + for pattern, repl in _SECRET_PATTERNS: + out = pattern.sub(repl, out) + return out + + +def install_log_capture(data_dir: Path) -> Path: + """Richtet Ring-Buffer und rotierende Logdatei (/pingognito.log) ein.""" + global _INSTALLED_DIR + log_path = Path(data_dir) / "pingognito.log" + key = str(Path(data_dir).resolve()) + with _LOCK: + if _INSTALLED_DIR == key: + return log_path + Path(data_dir).mkdir(parents=True, exist_ok=True) + root = logging.getLogger() + fmt = logging.Formatter("%(asctime)s %(levelname)-7s %(name)s: %(message)s") + + # Vorhandene eigene Handler bei Pfadwechsel sauber abbauen + for existing in list(root.handlers): + if getattr(existing, "_pingognito_capture", False): + root.removeHandler(existing) + try: + existing.close() + except Exception: + pass + + ring = _RingLogHandler() + ring.setFormatter(fmt) + ring.setLevel(logging.INFO) + ring._pingognito_capture = True # type: ignore[attr-defined] + root.addHandler(ring) + + try: + file_handler = RotatingFileHandler( + str(log_path), maxBytes=2 * 1024 * 1024, backupCount=2, encoding="utf-8", + ) + file_handler.setFormatter(fmt) + file_handler.setLevel(logging.INFO) + file_handler._pingognito_capture = True # type: ignore[attr-defined] + root.addHandler(file_handler) + except OSError: + pass + + _INSTALLED_DIR = key + return log_path + + +def _read_runtime_logs(data_dir: Path, max_lines: int = 2500) -> list[str]: + log_path = Path(data_dir) / "pingognito.log" + lines: list[str] = [] + if log_path.exists(): + try: + raw = log_path.read_text(encoding="utf-8", errors="replace").splitlines() + lines = raw[-max_lines:] + except OSError: + lines = [] + if not lines: + with _LOCK: + lines = list(_RING_BUFFER)[-max_lines:] + return [redact_secrets(line) for line in lines] + + +def collect_log_bundle(db: Any, settings: Any, scope: Any) -> dict[str, Any]: + """Erstellt ein vollstaendiges, bereinigtes Diagnose- und Log-Paket.""" + docker_ok, docker_detail = check_docker_connection(getattr(settings, "docker_host", "")) + scans = db.list_scans(limit=25) + scan_entries: list[dict[str, Any]] = [] + for s in scans: + logs = db.get_logs(s.id, limit=500) + scan_entries.append({ + "id": s.id, + "name": s.name, + "mode": s.mode.value, + "status": s.status.value, + "targets": s.targets, + "project_paths": s.project_paths, + "subnets": s.subnets, + "created_at": s.created_at, + "started_at": s.started_at, + "finished_at": s.finished_at, + "duration_seconds": s.duration_seconds, + "counts": s.counts, + "error": redact_secrets(s.error), + "logs": [ + {"ts": entry.get("ts", ""), "message": redact_secrets(entry.get("message", ""))} + for entry in logs + ], + }) + + subnets = [s.model_dump(mode="json") for s in db.list_subnets()] + assets = db.list_assets(limit=500) + creds = [ + { + "id": c.id, + "name": c.name, + "kind": c.kind.value, + "host_pattern": c.host_pattern, + "port": c.port, + "enabled": c.enabled, + "secret_set": c.secret_set, + } + for c in db.list_credentials() + ] + audit_entries = db.audit_abfrage(limit=200) + for item in audit_entries: + item["detail"] = redact_secrets(str(item.get("detail", ""))) + + return { + "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"), + "version": "1.0.0", + "settings": settings.public_dict(), + "scope": scope.config.model_dump(mode="json"), + "providers": detect_providers(), + "docker": {"available": docker_ok, "detail": docker_detail}, + "subnets": subnets, + "credentials_summary": creds, + "assets_count": len(assets), + "assets": [a.model_dump(mode="json") for a in assets], + "scans": scan_entries, + "audit_recent": audit_entries, + "runtime_logs": _read_runtime_logs(Path(settings.data_dir)), + } + + +def build_log_bundle(db: Any, settings: Any, scope: Any, fmt: str = "txt") -> tuple[bytes, str, str]: + """Liefert (daten, mimetype, dateiendung) fuer den Log-Download.""" + bundle = collect_log_bundle(db, settings, scope) + kind = (fmt or "txt").strip().lower() + if kind == "json": + payload = json.dumps(bundle, indent=2, ensure_ascii=False).encode("utf-8") + return payload, "application/json; charset=utf-8", "json" + + lines: list[str] = [ + "======================================================================", + f"Pingognito Diagnose- & Log-Export ({bundle['generated_at']})", + "======================================================================", + "", + "--- [1] SYSTEM & SCANNER-PROVIDER ---", + f"Docker: {bundle['docker']['available']} - {bundle['docker']['detail']}", + ] + for pname, pinfo in (bundle.get("providers") or {}).items(): + st = f"OK ({pinfo.get('version') or pinfo.get('path')})" if pinfo.get("available") else "nicht installiert" + lines.append(f" - {pname}: {st}") + + lines.extend(["", "--- [2] SUBNETZE / SCOPE ---"]) + lines.append(f"Allowlist Hosts: {bundle['scope'].get('allowed_hosts')}") + lines.append(f"Allowlist CIDRs: {bundle['scope'].get('allowed_cidrs')}") + lines.append(f"Private Netze erlaubt: {bundle['scope'].get('allow_private_networks')}") + for sub in bundle.get("subnets") or []: + lines.append( + f" - {sub['cidr']} | {sub.get('label', '')} | gw={sub.get('gateway', '-')} | " + f"freigegeben={sub.get('approved')}" + ) + + lines.extend(["", f"--- [3] ZUGANGSPROFILE ({len(bundle['credentials_summary'])}) ---"]) + for c in bundle.get("credentials_summary") or []: + lines.append( + f" - {c['name']} [{c['kind']}] -> {c['host_pattern']} (port={c['port']}, enabled={c['enabled']})" + ) + + lines.extend(["", f"--- [4] INVENTARISIERTE ASSETS ({bundle['assets_count']}) ---"]) + for a in bundle.get("assets") or []: + ports = ",".join(str(p.get("port")) for p in (a.get("ports") or []) if p.get("port")) + lines.append( + f" - [{a.get('device_type')}] {a.get('ip') or a.get('asset_key')} " + f"({a.get('hostname') or '-'}) | MAC={a.get('mac') or '-'} ({a.get('vendor') or '-'}) | " + f"OS={a.get('os_info') or '-'} | Ports=[{ports}] | Befunde={a.get('open_findings', 0)}" + ) + + lines.extend(["", f"--- [5] SCAN-LOGS (letzte {len(bundle['scans'])} Scans) ---"]) + for s in bundle.get("scans") or []: + lines.append( + f"\n>>> Scan {s['id']} | '{s['name']}' | mode={s['mode']} | status={s['status']} | " + f"dauer={s['duration_seconds']}s | counts={s['counts']}" + ) + if s.get("error"): + lines.append(f" FEHLER: {s['error']}") + for entry in s.get("logs") or []: + lines.append(f" [{entry.get('ts', '')}] {entry.get('message', '')}") + + lines.extend(["", f"--- [6] HISTORIE / AUDIT (letzte {len(bundle['audit_recent'])}) ---"]) + for a in bundle.get("audit_recent") or []: + lines.append( + f" [{a.get('ts', '')}] {a.get('username', '-') or '-'} ({a.get('role', '-') or '-'}) " + f"{a.get('action', '')} | {a.get('result', '')} | {a.get('detail', '')}" + ) + + lines.extend(["", f"--- [7] BACKEND RUNTIME-LOGS ({len(bundle['runtime_logs'])} Zeilen) ---"]) + lines.extend(bundle.get("runtime_logs") or ["(keine Laufzeit-Logs im Puffer)"]) + + text = "\n".join(lines) + "\n" + return text.encode("utf-8"), "text/plain; charset=utf-8", "txt" diff --git a/backend/app/main.py b/backend/app/main.py index ee28e57..eae4802 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -21,6 +21,7 @@ from .config import get_settings from .db import Database from .diff import compare_scans from .jobs import JobManager +from .log_bundle import build_log_bundle, install_log_capture from .models import KnownFalsePositive, ScanRecord, ScanRequest, Schedule, ScopeConfig, utcnow from .reports import build_report from .scanner import detect_providers @@ -38,6 +39,7 @@ FRONTEND_DIR = BASE_DIR.parent.parent / "frontend" settings = get_settings() settings.ensure_dirs() +install_log_capture(Path(settings.data_dir)) db = Database(settings.db_path) db.mark_stale_running() @@ -895,6 +897,26 @@ def scan_logs(scan_id: str) -> dict[str, Any]: return {"logs": db.get_logs(scan_id)} +@app.get("/api/logs/export") +def export_all_logs( + http_request: Request, + fmt: str = Query(default="txt", pattern="^(txt|json)$"), +) -> Response: + """Exportiert alle Laufzeit-, Scan-, System- und Asset-Logs als eine Datei.""" + from datetime import datetime + + data, mimetype, ext = build_log_bundle(db, settings, scope, fmt=fmt) + stamp = datetime.now().strftime("%Y%m%d-%H%M%S") + filename = f"pingognito-logs-{stamp}.{ext}" + protokoll(http_request, "logs.exported", "admin", + detail=f"Komplettes Log-Paket als {ext} heruntergeladen") + return Response( + content=data, + media_type=mimetype, + headers={"Content-Disposition": f'attachment; filename="{filename}"'}, + ) + + @app.get("/api/scans/{scan_id}/report/{fmt}") def scan_report(scan_id: str, fmt: str) -> Response: scan = db.get_scan(scan_id) diff --git a/backend/selftest.py b/backend/selftest.py index 29a8e12..5d80f80 100644 --- a/backend/selftest.py +++ b/backend/selftest.py @@ -2341,6 +2341,39 @@ def _(): assert c_adm.delete("/api/infra/subnets?cidr=10.99.0.0/24").status_code == 200 +@check("Kompletter Log-Export maskiert Geheimnisse und liefert txt/json") +def _(): + import logging + from app.log_bundle import install_log_capture, redact_secrets + from app.main import app, settings + from fastapi.testclient import TestClient + + install_log_capture(Path(settings.data_dir)) + sample = "Authorization: Bearer geheim123 X-Pingognito-Token: tok999 password=Geheim! -----BEGIN RSA PRIVATE KEY-----\nABC\n-----END RSA PRIVATE KEY-----" + redacted = redact_secrets(sample) + assert "geheim123" not in redacted + assert "tok999" not in redacted + assert "Geheim!" not in redacted + assert "ABC" not in redacted + + logging.getLogger("pingognito.test").info("Log-Capture-Test token=SuperGeheimToken42") + with _benutzer_anlegen(("log_user", "nutzer"), ("log_admin", "admin")): + c_user = _anmelden(app, "log_user") + assert c_user.get("/api/logs/export?fmt=txt").status_code == 403 + + c_adm = _anmelden(app, "log_admin") + r_txt = c_adm.get("/api/logs/export?fmt=txt") + assert r_txt.status_code == 200, r_txt.text + assert "attachment;" in r_txt.headers.get("content-disposition", "") + assert "Pingognito Diagnose- & Log-Export" in r_txt.text + assert "SuperGeheimToken42" not in r_txt.text + + r_json = c_adm.get("/api/logs/export?fmt=json") + assert r_json.status_code == 200 + body = r_json.json() + assert "runtime_logs" in body and "scans" in body and "providers" in body + + # ---------------------------------------------------------------------- # bestanden = sum(1 for _, ok, _ in RESULTS if ok) gesamt = len(RESULTS) diff --git a/frontend/app.js b/frontend/app.js index 64c28bc..ce12508 100644 --- a/frontend/app.js +++ b/frontend/app.js @@ -325,6 +325,17 @@ async function exportAudit(fmt) { } } +async function exportAllLogs(fmt) { + const f = fmt || 'txt'; + try { + await downloadAuthFile('/api/logs/export?fmt=' + encodeURIComponent(f), + 'pingognito-logs.' + f); + setConn(true, 'Alle Logs als .' + f + ' heruntergeladen'); + } catch (err) { + setConn(false, 'Log-Export fehlgeschlagen: ' + err.message); + } +} + async function clearAudit() { if (!confirm('Wirklich die gesamte Historie loeschen?')) return; try { @@ -1950,6 +1961,9 @@ async function init() { $('#histReload').addEventListener('click', loadAudit); $('#histExportJson').addEventListener('click', () => exportAudit('json')); $('#histExportCsv').addEventListener('click', () => exportAudit('csv')); + if ($('#histExportAllLogs')) $('#histExportAllLogs').addEventListener('click', () => exportAllLogs('txt')); + if ($('#histExportAllLogsJson')) $('#histExportAllLogsJson').addEventListener('click', () => exportAllLogs('json')); + if ($('#newscanDownloadLogs')) $('#newscanDownloadLogs').addEventListener('click', () => exportAllLogs('txt')); $('#histClear').addEventListener('click', clearAudit); $('#histModus').addEventListener('change', setAuditModus); $('#histCat').addEventListener('change', loadAudit); diff --git a/frontend/index.html b/frontend/index.html index 30fe1a1..3218ebc 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -131,7 +131,11 @@
-

Verlauf des aktuellen Scans

+
+

Verlauf des aktuellen Scans

+ + +