Files
Pingognito/backend/app/scope.py
T

494 lines
18 KiB
Python

"""Scope-Gate, Rate-Limiting und abgesicherter HTTP-Zugriff.
Kernregel: Ein aktiver Request gegen ein Ziel ist nur erlaubt, wenn der Host
explizit in der Allowlist steht. Die Allowlist wird bei jeder Weiterleitung
erneut geprüft, damit ein Redirect nicht aus dem Scope führt.
"""
from __future__ import annotations
import ipaddress
import json
import socket
import threading
import time
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Iterable, Optional
from urllib.parse import urlparse, urlunparse
import httpx
from .models import ScopeConfig
@dataclass
class Decision:
allowed: bool
reason: str = ""
host: str = ""
ip: str = ""
def _normalize_host(host: str) -> str:
host = (host or "").strip().lower()
if host.startswith("[") and host.endswith("]"):
host = host[1:-1]
return host
def host_matches(pattern: str, host: str) -> bool:
"""Exact-, Wildcard- und IP-Match gegen ein Allowlist-Eintrag.
Wildcards gelten strikt für Subdomains: '*.example.test' trifft
'app.example.test', aber nicht 'example.test' - dafür braucht es einen
eigenen Eintrag.
"""
pattern = _normalize_host(pattern)
host = _normalize_host(host)
if not pattern or not host:
return False
if pattern.startswith("*."):
suffix = pattern[1:] # ".example.test"
return host.endswith(suffix) and len(host) > len(suffix)
return pattern == host
def is_private_ip(ip: str) -> bool:
try:
addr = ipaddress.ip_address(ip)
except ValueError:
return False
return (
addr.is_private
or addr.is_loopback
or addr.is_link_local
or addr.is_reserved
or addr.is_multicast
or addr.is_unspecified
)
def resolve_host(host: str) -> list[str]:
"""Löst einen Hostnamen auf. Leere Liste bei Fehlern."""
try:
socket.inet_pton(socket.AF_INET, host)
return [host]
except OSError:
pass
try:
socket.inet_pton(socket.AF_INET6, host)
return [host]
except OSError:
pass
try:
infos = socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP)
except socket.gaierror:
return []
return list({info[4][0] for info in infos})
class Scope:
"""Prüft URLs gegen die Allowlist."""
def __init__(self, config: ScopeConfig | None = None):
self.config = config or ScopeConfig()
self._lock = threading.Lock()
# ------------------------------------------------------------------ #
@classmethod
def load(cls, path: str | Path) -> "Scope":
p = Path(path)
if p.exists():
try:
data = json.loads(p.read_text(encoding="utf-8"))
return cls(ScopeConfig(**data))
except (OSError, ValueError, TypeError):
pass
return cls(ScopeConfig())
def save(self, path: str | Path) -> None:
p = Path(path)
p.parent.mkdir(parents=True, exist_ok=True)
tmp = p.with_suffix(p.suffix + ".tmp")
tmp.write_text(self.config.model_dump_json(indent=2), encoding="utf-8")
tmp.replace(p)
def update(self, config: ScopeConfig) -> None:
with self._lock:
self.config = config
# ------------------------------------------------------------------ #
def check_url(self, url: str) -> Decision:
"""Prüft eine URL gegen die Allowlist. Blockiert standardmäßig."""
try:
parsed = urlparse(url if "://" in url else "http://" + url)
except ValueError as exc:
return Decision(False, f"Ungültige URL: {exc}")
scheme = (parsed.scheme or "http").lower()
if scheme not in ("http", "https"):
return Decision(False, f"Schema '{scheme}' ist nicht erlaubt (nur http/https)")
if not parsed.hostname:
return Decision(False, "URL ohne Hostnamen")
host = _normalize_host(parsed.hostname)
cfg = self.config
# 1) Deny-Liste hat Vorrang.
for denied in cfg.denied_hosts:
if host_matches(denied, host):
return Decision(False, f"Host '{host}' steht auf der Deny-Liste", host)
# 2) Allowlist muss den Host explizit nennen.
allowed = any(host_matches(pattern, host) for pattern in cfg.allowed_hosts)
if not allowed:
ips = resolve_host(host)
for cidr in cfg.allowed_cidrs:
try:
network = ipaddress.ip_network(cidr, strict=False)
except ValueError:
continue
for ip in ips:
try:
if ipaddress.ip_address(ip) in network:
allowed = True
break
except ValueError:
continue
if allowed:
break
if not allowed:
return Decision(
False,
f"Host '{host}' steht nicht in der Allowlist - aktiver Scan für '{url}' verweigert",
host,
)
# 3) Private Adressen nur mit entsprechender Freigabe.
ips = resolve_host(host)
ip = ips[0] if ips else ""
if ips and not cfg.allow_private_networks:
if any(is_private_ip(ip) for ip in ips):
return Decision(False, f"Host '{host}' zeigt auf ein privates Netz - nicht freigegeben", host, ip)
return Decision(True, "in Scope", host, ip)
def check_ip(self, ip_or_host: str, approved_cidrs: Optional[Iterable[str]] = None) -> Decision:
"""Prüft eine IP-Adresse oder einen Hostnamen gegen Scope + freigegebene Subnetze."""
host = _normalize_host(ip_or_host)
if not host:
return Decision(False, "Leerer Host")
cfg = self.config
for denied in cfg.denied_hosts:
if host_matches(denied, host):
return Decision(False, f"Host '{host}' steht auf der Deny-Liste", host)
ips = resolve_host(host)
if not ips:
try:
ipaddress.ip_address(host)
ips = [host]
except ValueError:
pass
if ips and not cfg.allow_private_networks and any(is_private_ip(ip) for ip in ips):
return Decision(False, f"Host '{host}' ist privat und nicht freigegeben", host, ips[0])
allowed = any(host_matches(pattern, host) for pattern in cfg.allowed_hosts)
all_cidrs = list(cfg.allowed_cidrs) + list(approved_cidrs or [])
if not allowed and ips:
for cidr in all_cidrs:
try:
net = ipaddress.ip_network(cidr, strict=False)
except ValueError:
continue
if any(ipaddress.ip_address(ip) in net for ip in ips):
allowed = True
break
if not allowed:
return Decision(False, f"Ziel '{host}' liegt nicht in Allowlist oder freigegebenen Subnetzen", host)
return Decision(True, "in Scope", host, ips[0] if ips else "")
def check_cidr(self, cidr: str, approved_cidrs: Optional[Iterable[str]] = None) -> Decision:
"""Prüft, ob ein Subnetz (CIDR) für den aktiven Scan freigegeben ist."""
try:
net = ipaddress.ip_network(str(cidr).strip(), strict=False)
except ValueError as exc:
return Decision(False, f"Ungültiges Subnetz '{cidr}': {exc}")
cfg = self.config
if not cfg.allow_private_networks and (net.is_private or net.is_loopback or net.is_link_local):
return Decision(False, f"Privates Subnetz '{net}' ist nicht freigegeben")
all_cidrs = list(cfg.allowed_cidrs) + list(approved_cidrs or [])
for entry in all_cidrs:
try:
allowed_net = ipaddress.ip_network(str(entry).strip(), strict=False)
except ValueError:
continue
if net.subnet_of(allowed_net) if net.version == allowed_net.version else False:
return Decision(True, "Subnetz freigegeben", str(net))
return Decision(False, f"Subnetz '{net}' ist noch nicht freigegeben")
class TokenBucket:
"""Token-Bucket je Host, begrenzt Requests pro Sekunde."""
def __init__(self, rate: float, burst: int):
self.rate = max(0.1, rate)
self.burst = max(1, burst)
self._tokens = float(self.burst)
self._last = time.monotonic()
self._lock = threading.Lock()
def acquire(self) -> None:
while True:
with self._lock:
now = time.monotonic()
self._tokens = min(self.burst, self._tokens + (now - self._last) * self.rate)
self._last = now
if self._tokens >= 1.0:
self._tokens -= 1.0
return
wait = (1.0 - self._tokens) / self.rate
time.sleep(min(wait, 5.0))
class RateLimiter:
"""Verteilt Token-Buckets und Semaphoren pro Host."""
def __init__(self, rate: float = 5.0, burst: int = 10, per_host_concurrency: int = 4):
self.rate = rate
self.burst = burst
self.per_host_concurrency = per_host_concurrency
self._buckets: dict[str, TokenBucket] = {}
self._sems: dict[str, threading.BoundedSemaphore] = {}
self._lock = threading.Lock()
def _bucket(self, host: str) -> TokenBucket:
with self._lock:
if host not in self._buckets:
self._buckets[host] = TokenBucket(self.rate, self.burst)
return self._buckets[host]
def _sem(self, host: str) -> threading.BoundedSemaphore:
with self._lock:
if host not in self._sems:
self._sems[host] = threading.BoundedSemaphore(self.per_host_concurrency)
return self._sems[host]
def host_slot(self, host: str) -> threading.BoundedSemaphore:
return self._sem(host)
def wait(self, host: str) -> None:
self._bucket(host).acquire()
def configure(self, rate: float | None = None, burst: int | None = None, per_host: int | None = None) -> None:
with self._lock:
if rate is not None:
self.rate = max(0.1, rate)
if burst is not None:
self.burst = max(1, burst)
if per_host is not None:
self.per_host_concurrency = max(1, per_host)
self._buckets.clear()
self._sems.clear()
@dataclass
class HttpResult:
url: str = ""
final_url: str = ""
status: int = 0
headers: dict[str, str] = field(default_factory=dict)
set_cookies: list[str] = field(default_factory=list)
body: str = ""
body_length: int = 0
redirects: list[str] = field(default_factory=list)
error: str = ""
elapsed_ms: float = 0.0
method: str = "GET"
@property
def ok(self) -> bool:
return not self.error and 0 < self.status < 600
def header(self, name: str, default: str = "") -> str:
return self.headers.get(name.lower(), default)
class SafeHttp:
"""HTTP-Client, der jeden Request durch das Scope-Gate schickt."""
MAX_REDIRECTS = 6
MAX_BODY = 512 * 1024
def __init__(self, scope: Scope, limiter: RateLimiter, timeout: float = 15.0,
user_agent: str = "Pingognito/1.0 (authorisierter Sicherheitsscan)"):
self.scope = scope
self.limiter = limiter
self.timeout = timeout
self.user_agent = user_agent
self._client = httpx.Client(
timeout=timeout,
follow_redirects=False,
verify=False, # TLS-Probleme werden separat bewertet, nicht geworfen
headers={"User-Agent": user_agent, "Accept": "*/*"},
)
def close(self) -> None:
self._client.close()
# ------------------------------------------------------------------ #
def request(
self,
url: str,
method: str = "GET",
headers: Optional[dict[str, str]] = None,
max_redirects: int = MAX_REDIRECTS,
allow_body: bool = True,
read_body: bool = True,
) -> HttpResult:
result = HttpResult(url=url, method=method)
current = url
started = time.monotonic()
for _ in range(max_redirects + 1):
decision = self.scope.check_url(current)
if not decision.allowed:
result.error = decision.reason
result.final_url = current
result.elapsed_ms = (time.monotonic() - started) * 1000
return result
host = decision.host
sem = self.limiter.host_slot(host)
sem.acquire()
try:
self.limiter.wait(host)
response = self._client.request(method, current, headers=headers or {})
except httpx.TooManyRedirects as exc:
result.error = f"Redirect-Schleife: {exc}"
break
except httpx.HTTPError as exc:
result.error = f"{type(exc).__name__}: {exc}"
break
except Exception as exc: # pragma: no cover - defensiver Schutz
result.error = f"{type(exc).__name__}: {exc}"
break
finally:
sem.release()
result.status = response.status_code
result.headers = {k.lower(): v for k, v in response.headers.items()}
result.set_cookies = response.headers.get_list("set-cookie")
result.final_url = str(response.url)
if response.status_code in (301, 302, 303, 307, 308):
location = response.headers.get("location", "")
if not location:
break
next_url = str(httpx.URL(current).join(location))
result.redirects.append(f"{response.status_code} -> {next_url}")
current = next_url
if response.status_code == 303:
method = "GET"
continue
if read_body:
try:
body = response.content[: self.MAX_BODY]
result.body = body.decode(response.encoding or "utf-8", errors="replace")
result.body_length = len(response.content)
except (UnicodeError, ValueError):
result.body = ""
break
result.elapsed_ms = (time.monotonic() - started) * 1000
if not result.error and not result.final_url:
result.final_url = current
return result
# ------------------------------------------------------------------ #
def get(self, url: str, **kwargs: Any) -> HttpResult:
return self.request(url, method="GET", **kwargs)
def head(self, url: str, **kwargs: Any) -> HttpResult:
return self.request(url, method="HEAD", **kwargs)
def options(self, url: str, headers: Optional[dict[str, str]] = None, **kwargs: Any) -> HttpResult:
return self.request(url, method="OPTIONS", headers=headers, **kwargs)
def tls_info(host: str, port: int = 443, timeout: float = 10.0) -> dict[str, Any]:
"""Liest TLS-Zertifikatsdaten und prüft unterstützte Protokollversionen."""
import ssl
info: dict[str, Any] = {"host": host, "port": port}
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
try:
with socket.create_connection((host, port), timeout=timeout) as sock:
with context.wrap_socket(sock, server_hostname=host) as tls:
info["tls_version"] = tls.version() or ""
cipher = tls.cipher()
info["cipher"] = cipher[0] if cipher else ""
cert = tls.getpeercert()
if cert:
info["not_before"] = cert.get("notBefore", "")
info["not_after"] = cert.get("notAfter", "")
info["issuer"] = dict(x[0] for x in cert.get("issuer", [])).get("organizationName", "")
info["subject"] = dict(x[0] for x in cert.get("subject", [])).get("commonName", "")
info["san"] = [v for k, v in cert.get("subjectAltName", []) if k == "DNS"]
info["self_signed"] = bool(cert.get("issuer")) and cert.get("issuer") == cert.get("subject")
info["expired"] = False
info["days_left"] = None
if cert.get("notAfter"):
try:
expiry = time.strptime(cert["notAfter"], "%b %d %H:%M:%S %Y %Z")
days = int((time.mktime(expiry) - time.time()) / 86400)
info["days_left"] = days
info["expired"] = days < 0
except (ValueError, OverflowError):
pass
except (socket.timeout, OSError, ssl.SSLError) as exc:
info["error"] = f"{type(exc).__name__}: {exc}"
# Protokollversionen einzeln testen (aktiv, aber harmlos - nur Handshake).
versions: dict[str, str] = {}
for label, proto in (("TLSv1.0", ssl.TLSVersion.TLSv1), ("TLSv1.1", ssl.TLSVersion.TLSv1_1),
("TLSv1.2", ssl.TLSVersion.TLSv1_2), ("TLSv1.3", ssl.TLSVersion.TLSv1_3)):
try:
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
try:
ctx.minimum_version = proto
ctx.maximum_version = proto
except (ValueError, AttributeError):
versions[label] = "nicht unterstützt"
continue
with socket.create_connection((host, port), timeout=timeout) as sock:
with ctx.wrap_socket(sock, server_hostname=host):
versions[label] = "aktiv"
except (ssl.SSLError, OSError):
versions[label] = "abgelehnt"
except Exception: # pragma: no cover
versions[label] = "unbekannt"
info["protocols"] = versions
return info
def normalize_base_url(raw: str) -> str:
"""Macht aus 'example.com' ein 'https://example.com'."""
raw = (raw or "").strip()
if not raw:
return ""
if "://" not in raw:
raw = "https://" + raw
parsed = urlparse(raw)
if not parsed.path:
parsed = parsed._replace(path="/")
return urlunparse(parsed)