netfilter.py

526 Zeilen · 21,7 KB · Python
Rohdatei
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
"""Netfilter: IP-Sperren nach Fehlversuchen sowie Allow-/Blocklist (IP, Netz, Hostname/DynDNS).

Funktioniert wie der Netfilter von mailcow (fail2ban), nur direkt in der App:
  * Fehlversuche (falsches Passwort, falsche PIN, unbekannter Benutzer, PIN-Login von einem nicht
    freigeschalteten Gerät, typische Angriffs-URLs wie /wp-login.php) werden pro IP gezählt.
  * Zu viele Fehlversuche in kurzer Zeit: Die IP bzw. ihr Netz wird gesperrt, bei Wiederholung
    jeweils doppelt so lange (bis zur Höchstdauer, optional danach dauerhaft).
  * Allowlist: wird nie gesperrt (Praxisnetz, VPN, DynDNS-Name des Büros …).
    Optional: Zugriff NUR aus der Allowlist.
  * Blocklist: immer gesperrt.
  * Hostnamen (DynDNS) werden alle 5 Minuten neu aufgelöst.

Notfall (ausgesperrt):
  docker compose exec app python -m app.netfilter status
  docker compose exec app python -m app.netfilter unban all
  docker compose exec app python -m app.netfilter allow 203.0.113.7
  docker compose exec app python -m app.netfilter disable
oder NETFILTER=off in der .env setzen und den Container neu starten.
"""
from __future__ import annotations

import asyncio
import html
import ipaddress
import json
import logging
import re
import socket
import sys
import threading
import time
from datetime import datetime, timedelta

from sqlalchemy import delete, func, select

from .config import settings
from .db import SessionLocal
from .models import KV, AuditLog, NetBan, NetFail

log = logging.getLogger("praxis.netfilter")
KV_KEY = "netfilter"
RESOLVE_INTERVAL = 300   # Sekunden – DynDNS-Namen neu auflösen
RELOAD_INTERVAL = 30     # Sekunden – Sperren aus der DB nachladen (abgelaufene fallen raus)
KEEP_FAILS_DAYS = 14

DEFAULTS: dict = {
    "enabled": True,
    "max_attempts": 10,     # Fehlversuche …
    "retry_window": 10,     # … innerhalb von Minuten
    "ban_time": 30,         # erste Sperre in Minuten
    "ban_increment": True,  # jede weitere Sperre doppelt so lang
    "max_ban_time": 1440,   # Höchstdauer in Minuten (24 h)
    "perm_after": 0,        # ab der n-ten Sperre dauerhaft (0 = nie)
    "netban_ipv4": 32,      # 32 = nur die einzelne IPv4-Adresse, 24 = ganzes /24-Netz
    "netban_ipv6": 64,      # IPv6: Anschlüsse bekommen meist ein /64
    "allowlist": "",
    "blocklist": "",
    "allowlist_only": False,
    "honeypot": True,
}
INT_LIMITS = {"max_attempts": (1, 1000), "retry_window": (1, 1440), "ban_time": (1, 525600),
              "max_ban_time": (1, 5256000), "perm_after": (0, 100), "netban_ipv4": (8, 32),
              "netban_ipv6": (32, 128)}

KIND_LABELS = {
    "login": "Falsches Passwort", "login_unbekannt": "Unbekannter Benutzer", "pin": "Falsche PIN",
    "kiosk_ohne_freigabe": "PIN-Login ohne freigeschaltetes Gerät", "honeypot": "Angriffs-URL aufgerufen",
    "gesperrt_versucht": "Anmeldung trotz Kontosperre",
}

# Pfade, die es in dieser App nicht gibt und die nur Scanner/Bots aufrufen.
HONEYPOT_PREFIXES = (
    "/wp-", "/wordpress", "/xmlrpc.php", "/.env", "/.git", "/.aws", "/.ssh", "/.svn", "/.htaccess",
    "/phpmyadmin", "/pma", "/myadmin", "/vendor/phpunit", "/cgi-bin", "/boaform", "/actuator",
    "/hnap1", "/server-status", "/owa", "/autodiscover", "/ecp", "/remote/login", "/solr", "/console",
    "/manager/html", "/jenkins", "/telescope", "/_ignition",
)
HONEYPOT_SUFFIXES = (".php", ".asp", ".aspx", ".jsp", ".cgi", ".env", ".sql", ".bak")

_HOST_RE = re.compile(r"^(?=.{1,253}$)([a-z0-9](-?[a-z0-9])*\.)+[a-z]{2,63}\.?$|^[a-z0-9-]{1,63}$", re.I)

Net = ipaddress.IPv4Network | ipaddress.IPv6Network


# ---------- Listen parsen ----------

def parse_list(text: str) -> tuple[list[Net], list[str], list[str]]:
    """Liefert (Netze, Hostnamen, ungültige Einträge). Trennung: Zeilen, Komma, Leerzeichen; # = Kommentar."""
    nets: list[Net] = []
    hosts: list[str] = []
    bad: list[str] = []
    for line in (text or "").splitlines():
        line = line.split("#", 1)[0]
        for entry in re.split(r"[,;\s]+", line):
            entry = entry.strip()
            if not entry:
                continue
            try:
                nets.append(ipaddress.ip_network(entry, strict=False))
                continue
            except ValueError:
                pass
            if _HOST_RE.match(entry):
                hosts.append(entry.lower().rstrip("."))
            else:
                bad.append(entry)
    return nets, hosts, bad


def resolve(host: str) -> list[Net]:
    try:
        infos = socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP)
    except OSError:
        return []
    out: list[Net] = []
    for info in infos:
        try:
            addr = ipaddress.ip_address(info[4][0].split("%", 1)[0])
        except ValueError:
            continue
        net = ipaddress.ip_network(addr)
        if net not in out:
            out.append(net)
    return out


def parse_ip(ip: str | None):
    if not ip:
        return None
    try:
        addr = ipaddress.ip_address(ip.split("%", 1)[0])
    except ValueError:
        return None
    if isinstance(addr, ipaddress.IPv6Address) and addr.ipv4_mapped:
        addr = addr.ipv4_mapped
    return addr


def _in(addr, nets) -> bool:
    return any(addr.version == n.version and addr in n for n in nets)


def _trusted_proxies() -> list[Net]:
    nets, _, _ = parse_list(settings.trusted_proxies.replace(",", " "))
    return nets


# ---------- Zustand im Speicher (schnelle Prüfung bei jeder Anfrage) ----------

class _State:
    def __init__(self) -> None:
        self.lock = threading.Lock()
        self.cfg: dict = dict(DEFAULTS)
        self.resolved: dict[str, list[Net]] = {}
        self.resolved_at: float = 0
        self.allow: list[Net] = []
        self.block: list[Net] = []
        self.bans: list[tuple[Net, datetime | None]] = []
        self.loaded_at: float = 0


STATE = _State()


def load_config(db) -> dict:
    cfg = dict(DEFAULTS)
    row = db.get(KV, KV_KEY)
    if row and row.value:
        try:
            cfg.update({k: v for k, v in json.loads(row.value).items() if k in DEFAULTS})
        except ValueError:
            log.warning("Netfilter-Einstellungen in der DB unlesbar – Standardwerte aktiv")
    return cfg


def _build(cfg: dict, resolved: dict[str, list[Net]]) -> tuple[list[Net], list[Net]]:
    lists = []
    for key in ("allowlist", "blocklist"):
        nets, hosts, _ = parse_list(cfg.get(key, ""))
        for h in hosts:
            nets.extend(resolved.get(h, []))
        lists.append(nets)
    return lists[0], lists[1]


def reload(db=None, resolve_hosts: bool = False) -> None:
    """Einstellungen und aktive Sperren aus der DB in den Speicher laden."""
    own = db is None
    db = db or SessionLocal()
    try:
        cfg = load_config(db)
        now = datetime.now()
        bans = []
        for b in db.scalars(select(NetBan).where((NetBan.until.is_(None)) | (NetBan.until > now))).all():
            try:
                bans.append((ipaddress.ip_network(b.network, strict=False), b.until))
            except ValueError:
                continue
    finally:
        if own:
            db.close()
    resolved = dict(STATE.resolved)
    if resolve_hosts or time.monotonic() - STATE.resolved_at > RESOLVE_INTERVAL:
        hosts = set()
        for key in ("allowlist", "blocklist"):
            hosts.update(parse_list(cfg.get(key, ""))[1])
        resolved = {h: resolve(h) for h in hosts}
        for h, nets in resolved.items():
            if not nets:
                log.warning("Netfilter: Hostname %s lässt sich nicht auflösen", h)
        STATE.resolved_at = time.monotonic()
    allow, block = _build(cfg, resolved)
    with STATE.lock:
        STATE.cfg, STATE.resolved, STATE.allow, STATE.block, STATE.bans = cfg, resolved, allow, block, bans
        STATE.loaded_at = time.monotonic()


# ---------- Prüfung ----------

def verdict(ip: str | None) -> tuple[str, datetime | None]:
    """'ok' | 'allow' | 'block' | 'ban' | 'nur_allowlist' – plus Sperrende bei 'ban'."""
    if not settings.netfilter_enabled:
        return "ok", None
    addr = parse_ip(ip)
    if addr is None or addr.is_loopback:
        return "ok", None
    with STATE.lock:
        cfg, allow, block, bans = STATE.cfg, STATE.allow, STATE.block, STATE.bans
    if not cfg.get("enabled"):
        return "ok", None
    if _in(addr, allow):
        return "allow", None
    if cfg.get("allowlist_only"):
        return "nur_allowlist", None
    if _in(addr, block):
        return "block", None
    now = datetime.now()
    for net, until in bans:
        if addr.version == net.version and addr in net and (until is None or until > now):
            return "ban", until
    return "ok", None


def is_honeypot(path: str) -> bool:
    p = path.lower()
    return p.startswith(HONEYPOT_PREFIXES) or p.endswith(HONEYPOT_SUFFIXES)


def ban_network(addr, cfg: dict) -> Net:
    prefix = cfg["netban_ipv4"] if addr.version == 4 else cfg["netban_ipv6"]
    return ipaddress.ip_network(f"{addr}/{prefix}", strict=False)


def _audit(db, action: str, **details) -> None:
    db.add(AuditLog(user_id=None, username="netfilter", action=action, entity="netfilter",
                    details=json.dumps(details, ensure_ascii=False, default=str)))


def ban_duration(cfg: dict, count: int) -> int | None:
    """Minuten für die count-te Sperre, None = dauerhaft."""
    if cfg.get("perm_after") and count >= cfg["perm_after"]:
        return None
    minutes = cfg["ban_time"]
    if cfg.get("ban_increment"):
        minutes = cfg["ban_time"] * 2 ** min(count - 1, 20)
    return min(minutes, max(cfg["max_ban_time"], cfg["ban_time"]))


def record_failure(ip: str | None, kind: str, detail: str | None = None) -> bool:
    """Fehlversuch speichern; sperrt bei Überschreiten der Grenze. Rückgabe: jetzt gesperrt."""
    if not settings.netfilter_enabled:
        return False
    addr = parse_ip(ip)
    if addr is None or addr.is_loopback:
        return False
    with STATE.lock:
        cfg, allow = STATE.cfg, STATE.allow
    if not cfg.get("enabled") or _in(addr, allow) or _in(addr, _trusted_proxies()):
        # Proxy nie sperren – sonst wären alle Nutzer dahinter ausgesperrt
        return False
    now = datetime.now()
    net = ban_network(addr, cfg)
    with SessionLocal() as db:
        db.add(NetFail(ts=now, ip=str(addr), kind=kind[:30], detail=(detail or "")[:150] or None))
        db.flush()
        existing = db.scalar(select(NetBan).where(NetBan.network == str(net)))
        if existing and (existing.until is None or existing.until > now):
            db.commit()
            return True
        since = now - timedelta(minutes=cfg["retry_window"])
        if existing and existing.banned_at > since:
            since = existing.banned_at  # nach einer Sperre wieder bei null anfangen
        ips = [str(a) for a in _net_ips(db, net, since)]
        count = db.scalar(select(func.count(NetFail.id)).where(NetFail.ts >= since, NetFail.ip.in_(ips))) or 0
        if count < cfg["max_attempts"]:
            db.commit()
            return False
        n = 1
        if existing and existing.banned_at > now - timedelta(days=30):
            n = (existing.ban_count or 0) + 1
        minutes = ban_duration(cfg, n)
        until = None if minutes is None else now + timedelta(minutes=minutes)
        reason = f"{count} Fehlversuche in {cfg['retry_window']} Min. (zuletzt: {KIND_LABELS.get(kind, kind)})"
        if existing:
            existing.banned_at, existing.until, existing.ban_count, existing.reason, existing.manual = (
                now, until, n, reason, False)
        else:
            db.add(NetBan(network=str(net), banned_at=now, until=until, ban_count=n, reason=reason, manual=False))
        _audit(db, "netfilter.gesperrt", netz=str(net), bis=until or "dauerhaft", sperre_nr=n, grund=reason)
        db.commit()
        log.warning("Netfilter: %s gesperrt bis %s (%s)", net, until or "dauerhaft", reason)
    reload()
    return True


def _net_ips(db, net: Net, since: datetime) -> list[str]:
    """Alle IPs mit Fehlversuchen seit `since`, die im Netz liegen (bei /32 nur die IP selbst)."""
    if net.num_addresses == 1:
        return [str(net.network_address)]
    out = []
    for ip in db.scalars(select(NetFail.ip).where(NetFail.ts >= since).distinct()).all():
        a = parse_ip(ip)
        if a is not None and a.version == net.version and a in net:
            out.append(ip)
    return out


# ---------- Verwaltung (Admin-Seite / CLI) ----------

def save_config(db, new: dict, actor=None) -> dict:
    cfg = load_config(db)
    cfg.update({k: v for k, v in new.items() if k in DEFAULTS})
    for k, (lo, hi) in INT_LIMITS.items():
        cfg[k] = max(lo, min(hi, int(cfg[k])))
    row = db.get(KV, KV_KEY) or KV(key=KV_KEY)
    row.value = json.dumps(cfg, ensure_ascii=False)
    db.add(row)
    changed = {k: v for k, v in new.items() if k in DEFAULTS}
    db.add(AuditLog(user_id=getattr(actor, "id", None), username=getattr(actor, "username", "cli"),
                    action="netfilter.einstellungen", entity="netfilter",
                    details=json.dumps(changed, ensure_ascii=False, default=str)))
    db.commit()
    reload(db, resolve_hosts=True)
    return cfg


def would_allow(cfg: dict, ip: str | None) -> tuple[bool, str]:
    """Prüft, ob `ip` mit den Einstellungen `cfg` noch Zugriff hätte (Aussperr-Schutz)."""
    addr = parse_ip(ip)
    if addr is None or addr.is_loopback or not cfg.get("enabled"):
        return True, ""
    allow_nets, allow_hosts, _ = parse_list(cfg.get("allowlist", ""))
    block_nets, block_hosts, _ = parse_list(cfg.get("blocklist", ""))
    for h in allow_hosts:
        allow_nets += resolve(h)
    if _in(addr, allow_nets):
        return True, ""
    if cfg.get("allowlist_only"):
        return False, (f"Mit „nur Allowlist“ würdest du dich selbst aussperren: deine Adresse {addr} steht "
                       "nicht in der Allowlist.")
    for h in block_hosts:
        block_nets += resolve(h)
    if _in(addr, block_nets):
        return False, f"Deine eigene Adresse {addr} steht in der Blocklist."
    return True, ""


def manual_ban(db, network: str, minutes: int | None, reason: str, actor) -> Net:
    net = ipaddress.ip_network(network.strip(), strict=False)
    now = datetime.now()
    until = None if not minutes else now + timedelta(minutes=minutes)
    b = db.scalar(select(NetBan).where(NetBan.network == str(net)))
    if b:
        b.banned_at, b.until, b.reason, b.manual = now, until, reason, True
        b.ban_count = (b.ban_count or 0) + 1
    else:
        db.add(NetBan(network=str(net), banned_at=now, until=until, reason=reason, manual=True, ban_count=1))
    db.add(AuditLog(user_id=actor.id, username=actor.username, action="netfilter.manuell_gesperrt",
                    entity="netfilter", details=json.dumps({"netz": str(net), "bis": str(until or "dauerhaft"),
                                                            "grund": reason}, ensure_ascii=False)))
    db.commit()
    reload(db)
    return net


def unban(db, ban: NetBan, actor=None) -> None:
    """Sperre aufheben und Zähler zurücksetzen (nächste Sperre beginnt wieder mit der Grunddauer)."""
    net = ban.network
    ips = _net_ips(db, ipaddress.ip_network(net, strict=False), datetime.now() - timedelta(days=KEEP_FAILS_DAYS))
    if ips:
        db.execute(delete(NetFail).where(NetFail.ip.in_(ips)))
    db.delete(ban)
    db.add(AuditLog(user_id=getattr(actor, "id", None), username=getattr(actor, "username", "cli"),
                    action="netfilter.entsperrt", entity="netfilter", details=json.dumps({"netz": net})))
    db.commit()
    reload(db)


def purge(db) -> None:
    db.execute(delete(NetFail).where(NetFail.ts < datetime.now() - timedelta(days=KEEP_FAILS_DAYS)))
    db.execute(delete(NetBan).where(NetBan.until.is_not(None),
                                    NetBan.until < datetime.now() - timedelta(days=30)))
    db.commit()


async def netfilter_loop() -> None:
    last_purge = 0.0
    while True:
        await asyncio.sleep(RELOAD_INTERVAL)
        try:
            await asyncio.to_thread(reload)
            if time.monotonic() - last_purge > 3600:
                with SessionLocal() as db:
                    await asyncio.to_thread(purge, db)
                last_purge = time.monotonic()
        except Exception:  # noqa: BLE001
            log.exception("Netfilter: Aktualisierung fehlgeschlagen")


# ---------- ASGI-Middleware ----------

_PAGE = """<!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport"
content="width=device-width,initial-scale=1"><title>Zugriff gesperrt</title><style>body{{font-family:system-ui,sans-serif;
background:#f4f6f8;color:#1d2733;display:grid;place-items:center;min-height:100vh;margin:0}}div{{background:#fff;
max-width:30rem;padding:2rem;border-radius:12px;box-shadow:0 2px 12px #0001}}h1{{font-size:1.3rem;margin-top:0}}
code{{background:#eef1f4;padding:.1rem .3rem;border-radius:4px}}</style></head><body><div><h1>{title}</h1><p>{text}</p>
<p><small>Deine Adresse: <code>{ip}</code></small></p></div></body></html>"""


def _blocked_page(kind: str, ip: str, until: datetime | None) -> bytes:
    if kind == "ban":
        title = "Vorübergehend gesperrt"
        text = ("Nach zu vielen fehlgeschlagenen Anmeldeversuchen ist der Zugriff von dieser Adresse "
                + (f"bis {until:%d.%m.%Y %H:%M} Uhr gesperrt." if until else "dauerhaft gesperrt.")
                + " Bei Fragen bitte an die Praxisleitung bzw. den Administrator wenden.")
    elif kind == "nur_allowlist":
        title = "Kein Zugriff von hier"
        text = "Der Praxisplaner ist nur aus dem Praxisnetz bzw. von freigegebenen Adressen erreichbar."
    else:
        title = "Zugriff gesperrt"
        text = "Der Zugriff von dieser Adresse ist gesperrt."
    return _PAGE.format(title=title, text=text, ip=html.escape(ip)).encode()


class NetfilterMiddleware:
    def __init__(self, app) -> None:
        self.app = app

    async def __call__(self, scope, receive, send):
        if scope["type"] != "http" or not settings.netfilter_enabled or scope.get("path") == "/health":
            return await self.app(scope, receive, send)
        ip = (scope.get("client") or (None,))[0] or ""
        kind, until = verdict(ip)
        if kind in ("block", "ban", "nur_allowlist"):
            body = _blocked_page(kind, ip, until)
            headers = [(b"content-type", b"text/html; charset=utf-8"), (b"cache-control", b"no-store"),
                       (b"content-length", str(len(body)).encode())]
            if kind == "ban" and until:
                headers.append((b"retry-after", str(max(1, int((until - datetime.now()).total_seconds()))).encode()))
            await send({"type": "http.response.start", "status": 403, "headers": headers})
            await send({"type": "http.response.body", "body": body})
            return
        if kind == "ok" and STATE.cfg.get("honeypot") and is_honeypot(scope.get("path", "")):
            await asyncio.to_thread(record_failure, ip, "honeypot", scope.get("path", "")[:150])
            body = b"Not Found"
            await send({"type": "http.response.start", "status": 404,
                        "headers": [(b"content-type", b"text/plain"), (b"content-length", b"9")]})
            await send({"type": "http.response.body", "body": body})
            return
        return await self.app(scope, receive, send)


# ---------- Kommandozeile (Notfall) ----------

def _cli(argv: list[str]) -> int:
    from .seed import init_db
    logging.basicConfig(level=logging.WARNING)
    init_db()
    cmd = argv[0] if argv else "status"
    with SessionLocal() as db:
        cfg = load_config(db)
        if cmd == "status":
            print(f"Netfilter: {'AN' if cfg['enabled'] and settings.netfilter_enabled else 'AUS'}"
                  f"{' (NETFILTER=off in .env)' if not settings.netfilter_enabled else ''}"
                  f"{' – NUR ALLOWLIST' if cfg['allowlist_only'] else ''}")
            print(f"Grenze: {cfg['max_attempts']} Fehlversuche in {cfg['retry_window']} Min.")
            now = datetime.now()
            bans = db.scalars(select(NetBan).where((NetBan.until.is_(None)) | (NetBan.until > now))
                              .order_by(NetBan.banned_at.desc())).all()
            print(f"Aktive Sperren: {len(bans)}")
            for b in bans:
                print(f"  {b.network:<22} bis {b.until:%d.%m.%Y %H:%M}" if b.until else f"  {b.network:<22} dauerhaft",
                      "-", b.reason or "")
            nets, hosts, _ = parse_list(cfg["allowlist"])
            print("Allowlist:", ", ".join([str(n) for n in nets] + hosts) or "–")
        elif cmd == "unban" and len(argv) > 1:
            target = argv[1]
            bans = db.scalars(select(NetBan)).all()
            hit = 0
            for b in bans:
                net = ipaddress.ip_network(b.network, strict=False)
                addr = parse_ip(target)
                if target == "all" or b.network == target or (addr and addr.version == net.version and addr in net):
                    unban(db, b)
                    hit += 1
            print(f"{hit} Sperre(n) aufgehoben.")
        elif cmd == "allow" and len(argv) > 1:
            entries = "\n".join(argv[1:])
            _, _, bad = parse_list(entries)
            if bad:
                print("Ungültig:", ", ".join(bad))
                return 1
            save_config(db, {"allowlist": (cfg["allowlist"].rstrip() + "\n" + entries).strip()})
            print("Zur Allowlist hinzugefügt:", entries.replace("\n", ", "))
        elif cmd in ("disable", "enable"):
            save_config(db, {"enabled": cmd == "enable", **({"allowlist_only": False} if cmd == "disable" else {})})
            print("Netfilter", "eingeschaltet." if cmd == "enable" else "ausgeschaltet (auch „nur Allowlist“ aus).")
        else:
            print(__doc__)
            return 1
    print("Hinweis: Die laufende App übernimmt Änderungen innerhalb von 30 Sekunden.")
    return 0


if __name__ == "__main__":
    sys.exit(_cli(sys.argv[1:]))