243 lines
9.7 KiB
Python
243 lines
9.7 KiB
Python
"""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-Übersicht und
|
|
Systeminfos in eine einzelne Text- oder JSON-Datei - mit automatischer
|
|
Maskierung möglicher 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):
|
|
"""Hält die letzten Laufzeit-Logzeilen für 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 (<data_dir>/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 vollständiges, 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) für 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"
|