|
| 1 | +"""Ban-list service — reads/clears auto-ban entries via HAProxy Runtime API. |
| 2 | +
|
| 3 | +Talks to the admin-level stats socket (`settings.haproxy_stats_socket_path`) |
| 4 | +emitted in the generated `haproxy.cfg` (see #275, #276). Each vhost with |
| 5 | +DDoS protection and auto-ban enabled owns a stick-table named |
| 6 | +`st_ban_vhost_<id>` (see `config_generator.py::_to_haproxy_context`); this |
| 7 | +module enumerates those tables' contents and can clear entries from them. |
| 8 | +""" |
| 9 | + |
| 10 | +from __future__ import annotations |
| 11 | + |
| 12 | +import ipaddress |
| 13 | +import logging |
| 14 | +import re |
| 15 | +import socket |
| 16 | +from dataclasses import dataclass |
| 17 | + |
| 18 | +from sqlalchemy.orm import Session, selectinload |
| 19 | + |
| 20 | +from app.config import settings |
| 21 | +from app.models.vhost import VHost |
| 22 | +from app.schemas.security import BannedIpResponse, UnbanResponse |
| 23 | + |
| 24 | +logger = logging.getLogger(__name__) |
| 25 | + |
| 26 | +_TABLE_ENTRY_RE = re.compile( |
| 27 | + r"key=(?P<key>\S+).*?exp=(?P<exp>\d+).*?gpc0=(?P<gpc0>\d+)" |
| 28 | +) |
| 29 | + |
| 30 | +# HAProxy's Runtime API reports failures (unknown table, permission denied, |
| 31 | +# unsupported command, ...) as plain text in the command's own response |
| 32 | +# rather than as a socket-level error, so a successful `recv()` does not |
| 33 | +# mean the command succeeded. Anchored to the start of a line, mirroring |
| 34 | +# `config_apply._RELOAD_ERROR_RE`, so a `key=...` data line or the |
| 35 | +# `# table: ...` header can never false-positive. |
| 36 | +_RUNTIME_API_ERROR_RE = re.compile( |
| 37 | + r"^\s*(unknown|no such|can't find|permission denied|invalid|error)\b", |
| 38 | + re.IGNORECASE | re.MULTILINE, |
| 39 | +) |
| 40 | + |
| 41 | + |
| 42 | +class BanListError(Exception): |
| 43 | + """Base class for ban-list domain errors.""" |
| 44 | + |
| 45 | + |
| 46 | +class InvalidIpError(BanListError): |
| 47 | + """Raised when a supplied IP address string cannot be parsed.""" |
| 48 | + |
| 49 | + def __init__(self, ip: str) -> None: |
| 50 | + self.ip = ip |
| 51 | + super().__init__(f"'{ip}' is not a valid IP address") |
| 52 | + |
| 53 | + |
| 54 | +class RuntimeApiError(BanListError): |
| 55 | + """Raised when the HAProxy Runtime API socket cannot be reached at all.""" |
| 56 | + |
| 57 | + |
| 58 | +@dataclass(frozen=True) |
| 59 | +class BanTableEntry: |
| 60 | + """One parsed row from a `show table` response.""" |
| 61 | + |
| 62 | + ip: str |
| 63 | + gpc0: int |
| 64 | + expires_in_seconds: int |
| 65 | + |
| 66 | + |
| 67 | +def _send_runtime_command(command: str) -> str: |
| 68 | + """Send one Runtime API command over the admin stats socket and return output. |
| 69 | +
|
| 70 | + Raises `RuntimeApiError` both when the socket itself is unreachable and |
| 71 | + when HAProxy accepts the connection but replies with an error message |
| 72 | + (e.g. an unknown table) — the caller cannot otherwise tell a successful |
| 73 | + `clear`/`show` from one HAProxy silently rejected. |
| 74 | + """ |
| 75 | + socket_path = settings.haproxy_stats_socket_path |
| 76 | + try: |
| 77 | + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client: |
| 78 | + client.settimeout(settings.haproxy_stats_timeout_seconds) |
| 79 | + client.connect(socket_path) |
| 80 | + client.sendall(command.encode("utf-8") + b"\n") |
| 81 | + client.shutdown(socket.SHUT_WR) |
| 82 | + output_chunks: list[bytes] = [] |
| 83 | + while True: |
| 84 | + chunk = client.recv(4096) |
| 85 | + if not chunk: |
| 86 | + break |
| 87 | + output_chunks.append(chunk) |
| 88 | + except OSError as error: |
| 89 | + raise RuntimeApiError(str(error)) from error |
| 90 | + |
| 91 | + output = b"".join(output_chunks).decode("utf-8", errors="replace") |
| 92 | + if _RUNTIME_API_ERROR_RE.search(output): |
| 93 | + raise RuntimeApiError(output.strip() or "HAProxy Runtime API returned an error") |
| 94 | + |
| 95 | + return output |
| 96 | + |
| 97 | + |
| 98 | +def _parse_show_table(raw: str) -> list[BanTableEntry]: |
| 99 | + """Parse `show table <name>` output into structured entries. |
| 100 | +
|
| 101 | + Example line: |
| 102 | + 0x...: key=192.0.2.7 use=0 exp=540000 gpc0=15 |
| 103 | + `exp` is milliseconds remaining; converted to whole seconds (rounded up |
| 104 | + so a live entry never reports 0 remaining). |
| 105 | + """ |
| 106 | + entries: list[BanTableEntry] = [] |
| 107 | + for line in raw.splitlines(): |
| 108 | + match = _TABLE_ENTRY_RE.search(line) |
| 109 | + if match is None: |
| 110 | + continue |
| 111 | + exp_ms = int(match.group("exp")) |
| 112 | + entries.append( |
| 113 | + BanTableEntry( |
| 114 | + ip=match.group("key"), |
| 115 | + gpc0=int(match.group("gpc0")), |
| 116 | + expires_in_seconds=(exp_ms + 999) // 1000, |
| 117 | + ) |
| 118 | + ) |
| 119 | + return entries |
| 120 | + |
| 121 | + |
| 122 | +class BanListService: |
| 123 | + """Reads and clears auto-ban stick-table entries via the Runtime API.""" |
| 124 | + |
| 125 | + def __init__(self, db: Session) -> None: |
| 126 | + self.db = db |
| 127 | + |
| 128 | + def list_banned(self) -> list[BannedIpResponse]: |
| 129 | + """Return every tracked/banned entry across all auto-ban-enabled vhosts. |
| 130 | +
|
| 131 | + Tolerates individual table failures (one dead table must not blank |
| 132 | + the whole list) but raises `RuntimeApiError` if every attempted |
| 133 | + table failed, so a fully unreachable Runtime API surfaces as an |
| 134 | + error instead of an empty list indistinguishable from "nothing |
| 135 | + tracked" — mirroring `unban`'s all-tables-failed handling below. |
| 136 | + """ |
| 137 | + tables = self._active_ban_tables() |
| 138 | + results: list[BannedIpResponse] = [] |
| 139 | + failures = 0 |
| 140 | + for vhost, table_name, ban_threshold in tables: |
| 141 | + try: |
| 142 | + raw = _send_runtime_command(f"show table {table_name}") |
| 143 | + entries = _parse_show_table(raw) |
| 144 | + except RuntimeApiError: |
| 145 | + logger.exception( |
| 146 | + "ban-list failed to read table %s for vhost %s", |
| 147 | + table_name, |
| 148 | + vhost.id, |
| 149 | + ) |
| 150 | + failures += 1 |
| 151 | + continue |
| 152 | + |
| 153 | + for entry in entries: |
| 154 | + results.append( |
| 155 | + BannedIpResponse( |
| 156 | + ip=entry.ip, |
| 157 | + vhost_id=vhost.id, |
| 158 | + domain=vhost.domain, |
| 159 | + gpc0=entry.gpc0, |
| 160 | + ban_threshold=ban_threshold, |
| 161 | + banned=entry.gpc0 > ban_threshold, |
| 162 | + expires_in_seconds=entry.expires_in_seconds, |
| 163 | + ) |
| 164 | + ) |
| 165 | + |
| 166 | + if tables and failures == len(tables): |
| 167 | + raise RuntimeApiError("Failed to reach HAProxy Runtime API") |
| 168 | + |
| 169 | + return results |
| 170 | + |
| 171 | + def unban(self, ip: str) -> UnbanResponse: |
| 172 | + """Clear an IP from every active ban table; return the number cleared. |
| 173 | +
|
| 174 | + `cleared` counts tables where HAProxy confirmed the `clear table` |
| 175 | + command (including a no-op when the key was already absent) — not |
| 176 | + merely tables where the socket write succeeded, since |
| 177 | + `_send_runtime_command` raises on an HAProxy-reported error too. |
| 178 | + Tolerates individual table failures (one dead table must not block |
| 179 | + clearing the others) but raises `RuntimeApiError` if every attempted |
| 180 | + table failed, so a fully unreachable Runtime API surfaces as an |
| 181 | + error instead of a silent no-op `cleared=0`. |
| 182 | + """ |
| 183 | + try: |
| 184 | + ipaddress.ip_address(ip) |
| 185 | + except ValueError as error: |
| 186 | + raise InvalidIpError(ip) from error |
| 187 | + |
| 188 | + tables = self._active_ban_tables() |
| 189 | + cleared = 0 |
| 190 | + failures = 0 |
| 191 | + for _vhost, table_name, _threshold in tables: |
| 192 | + try: |
| 193 | + _send_runtime_command(f"clear table {table_name} key {ip}") |
| 194 | + cleared += 1 |
| 195 | + except RuntimeApiError: |
| 196 | + logger.exception( |
| 197 | + "ban-list failed to clear key %s in table %s", ip, table_name |
| 198 | + ) |
| 199 | + failures += 1 |
| 200 | + |
| 201 | + if tables and failures == len(tables): |
| 202 | + raise RuntimeApiError("Failed to reach HAProxy Runtime API") |
| 203 | + |
| 204 | + return UnbanResponse(ip=ip, cleared=cleared) |
| 205 | + |
| 206 | + def _active_ban_tables(self) -> list[tuple[VHost, str, int]]: |
| 207 | + vhosts = ( |
| 208 | + self.db.query(VHost) |
| 209 | + .options(selectinload(VHost.policy)) |
| 210 | + .order_by(VHost.id.asc()) |
| 211 | + .all() |
| 212 | + ) |
| 213 | + return [ |
| 214 | + (vhost, f"st_ban_vhost_{vhost.id}", vhost.policy.ban_threshold) |
| 215 | + for vhost in vhosts |
| 216 | + if vhost.is_active |
| 217 | + and vhost.policy is not None |
| 218 | + and vhost.policy.ddos_protection_enabled |
| 219 | + and vhost.policy.auto_ban_enabled |
| 220 | + ] |
0 commit comments