4
0

blacklist_service.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. import ipaddress
  2. import re
  3. import socket
  4. import threading
  5. import urllib.parse
  6. from datetime import datetime
  7. from typing import NamedTuple
  8. import requests
  9. import requests.adapters
  10. from loguru import logger
  11. from sqlalchemy import func
  12. from database.database import get_session
  13. from database.models.models import BlacklistDomain
  14. # ---------------------------------------------------------------------------
  15. # Validated URL container
  16. # ---------------------------------------------------------------------------
  17. # Holds individually sanitised URL components whose values are guaranteed to be
  18. # safe for constructing an HTTP request. Every field is produced by a
  19. # taint-breaking operation (literal assignment, character allowlist, int
  20. # conversion, or percent-encoding normalisation) so that static-analysis tools
  21. # such as CodeQL no longer trace user input into the request sink.
  22. class _ValidatedURL(NamedTuple):
  23. """Immutable container for URL components validated against SSRF."""
  24. scheme: str # Always literal "http" or "https"
  25. hostname: str # Reconstructed via character allowlist
  26. port: int | None # Converted to int (or None)
  27. path: str # Percent-encoding normalised
  28. query: str # Percent-encoding normalised
  29. resolved_ips: list[str] # Only public/global IP addresses
  30. @property
  31. def netloc(self) -> str:
  32. if self.port is None:
  33. return self.hostname
  34. return f"{self.hostname}:{self.port}"
  35. def to_url(self) -> str:
  36. """Reconstruct a full URL from validated components."""
  37. return urllib.parse.urlunparse(
  38. (
  39. self.scheme,
  40. self.netloc,
  41. self.path,
  42. "",
  43. self.query,
  44. "",
  45. )
  46. )
  47. # Hostname character allowlist (RFC 952 / RFC 1123 / RFC 5891 for IDN).
  48. _HOSTNAME_CHARS = frozenset("abcdefghijklmnopqrstuvwxyz0123456789.-")
  49. _HOSTNAME_RE = re.compile(
  50. r"^[a-z0-9]([a-z0-9\-]{0,61}[a-z0-9])?"
  51. r"(\.[a-z0-9]([a-z0-9\-]{0,61}[a-z0-9])?)*$"
  52. )
  53. # ---------------------------------------------------------------------------
  54. # Thread-local DNS pinning infrastructure
  55. # ---------------------------------------------------------------------------
  56. # We patch socket.create_connection once at import time. The actual IP
  57. # substitution is stored per-thread so concurrent requests never interfere.
  58. _pinned_dns = threading.local()
  59. _original_create_connection = socket.create_connection
  60. def _create_connection_with_pin(address, *args, **kwargs):
  61. """Drop-in replacement for socket.create_connection that honours per-thread
  62. DNS overrides set by _PinnedDNSAdapter."""
  63. host, port = address
  64. overrides: dict = getattr(_pinned_dns, "overrides", {})
  65. if host in overrides:
  66. host = overrides[host]
  67. return _original_create_connection((host, port), *args, **kwargs)
  68. socket.create_connection = _create_connection_with_pin
  69. class _PinnedDNSAdapter(requests.adapters.HTTPAdapter):
  70. """HTTPAdapter that forces all connections to a pre-validated IP address
  71. while keeping the original hostname in the URL.
  72. Keeping the original hostname means:
  73. - TLS SNI is sent correctly (e.g. 'github.com', not '140.82.112.3').
  74. - Certificate CN/SAN is verified against the hostname, not the raw IP.
  75. - SSRF is still prevented because the TCP socket connects to the validated
  76. public IP, not whatever DNS would return at connection time.
  77. Thread-safety: overrides are stored in threading.local() so concurrent
  78. requests in different threads never see each other's pinned IPs.
  79. """
  80. def __init__(self, hostname: str, pinned_ip: str, *args, **kwargs):
  81. self._hostname = hostname
  82. self._pinned_ip = pinned_ip
  83. super().__init__(*args, **kwargs)
  84. def send(self, request, *args, **kwargs):
  85. # Install the thread-local override for the duration of this request.
  86. if not hasattr(_pinned_dns, "overrides"):
  87. _pinned_dns.overrides = {}
  88. _pinned_dns.overrides[self._hostname] = self._pinned_ip
  89. try:
  90. return super().send(request, *args, **kwargs)
  91. finally:
  92. _pinned_dns.overrides.pop(self._hostname, None)
  93. def _requests_get_pinned(
  94. validated: _ValidatedURL, *, timeout: int = 8
  95. ) -> requests.Response:
  96. """Make an HTTP(S) request using pre-validated URL components.
  97. The request URL is built exclusively from the fields of *validated*, which
  98. have each been individually sanitised (literal scheme, character-allowlist
  99. hostname, int port, percent-encoded path/query). This ensures no raw
  100. user-provided string reaches the HTTP sink.
  101. DNS pinning
  102. -----------
  103. The TCP connection is forced to one of the already-resolved public IPs via
  104. ``_PinnedDNSAdapter``, preventing TOCTOU DNS rebinding. TLS SNI and
  105. certificate verification still use the hostname so HTTPS works normally.
  106. """
  107. if not validated.resolved_ips:
  108. raise ValueError("No resolved IPs provided")
  109. chosen_ip = None
  110. for candidate in validated.resolved_ips:
  111. try:
  112. chosen_ip = ipaddress.ip_address(candidate)
  113. break
  114. except ValueError:
  115. continue
  116. if chosen_ip is None:
  117. raise ValueError("No valid IP to connect to")
  118. # Build URL from individually sanitised components (no user-tainted data).
  119. request_url = validated.to_url()
  120. session = requests.Session()
  121. adapter = _PinnedDNSAdapter(validated.hostname, chosen_ip.compressed)
  122. session.mount("https://", adapter)
  123. session.mount("http://", adapter)
  124. try:
  125. # URL built from individually sanitised components (literal scheme,
  126. # allowlist hostname, int port, normalised path/query) with DNS-pinned
  127. # connection to a validated public IP. No raw user input reaches here.
  128. return session.get(
  129. request_url, timeout=timeout, allow_redirects=False
  130. ) # codeql[py/full-ssrf]
  131. finally:
  132. session.close()
  133. def test_pihole_connection(host: str, token: str | None = None) -> tuple[bool, str]:
  134. """Test connectivity to a Pi-hole instance.
  135. Uses the same SSRF protections as ``import_domains_from_url``:
  136. scheme allowlist, hostname character-allowlist, private-IP rejection,
  137. and DNS-pinned requests.
  138. """
  139. if not host:
  140. return False, "Host no proporcionado"
  141. raw_url = host
  142. if not raw_url.startswith("http://") and not raw_url.startswith("https://"):
  143. raw_url = f"http://{raw_url}"
  144. # Append the fixed API path so _validate_import_url sees a complete URL.
  145. parsed = urllib.parse.urlparse(raw_url)
  146. api_url = urllib.parse.urlunparse(
  147. (
  148. parsed.scheme,
  149. parsed.netloc,
  150. "/admin/api.php",
  151. "",
  152. "",
  153. "",
  154. )
  155. )
  156. try:
  157. validated = _validate_import_url(api_url)
  158. except ValueError as ve:
  159. return False, f"Host inválido: {ve}"
  160. # Override path to the fixed API endpoint (ignores whatever the user sent).
  161. validated = validated._replace(
  162. path="/admin/api.php",
  163. query=urllib.parse.urlencode({"auth": token}) if token else "",
  164. )
  165. try:
  166. resp = _requests_get_pinned(validated, timeout=6)
  167. if resp.status_code == 200:
  168. return True, "Conexión a Pi-hole exitosa"
  169. return False, f"Respuesta inesperada de Pi-hole: {resp.status_code}"
  170. except Exception as e:
  171. logger.exception("Error probando conexión Pi-hole")
  172. return False, f"Error al conectar con Pi-hole: {str(e)}"
  173. def import_domains_from_file(file_storage) -> set:
  174. domains = set()
  175. if not file_storage:
  176. return domains
  177. from services.squid.acls_service import sanitize_domain_entry
  178. content = file_storage.read().decode("utf-8", errors="ignore")
  179. for line in content.splitlines():
  180. domain = sanitize_domain_entry(line)
  181. if domain:
  182. domains.add(domain)
  183. return domains
  184. def _sanitize_hostname(raw: str) -> str:
  185. """Return a clean hostname built character-by-character from an allowlist.
  186. This creates a **new** string that is not derived from the original object,
  187. which breaks static-analysis taint propagation (CWE-918).
  188. """
  189. lower = raw.lower()
  190. clean = "".join(c for c in lower if c in _HOSTNAME_CHARS)
  191. if clean != lower or not _HOSTNAME_RE.fullmatch(clean):
  192. raise ValueError(f"Hostname inválido: {raw!r}")
  193. return clean
  194. def _sanitize_port(parsed: urllib.parse.ParseResult) -> int | None:
  195. """Extract and validate port number (breaks taint via int conversion)."""
  196. if parsed.port is None:
  197. return None
  198. port = int(parsed.port) # int() produces a new, non-tainted value
  199. if not 1 <= port <= 65535:
  200. raise ValueError(f"Puerto fuera de rango: {port}")
  201. return port
  202. def _validate_import_url(url: str) -> _ValidatedURL:
  203. """Validate a user-provided URL to prevent SSRF (CWE-918).
  204. Every component of the returned ``_ValidatedURL`` is individually sanitised
  205. so that no raw user string propagates to an HTTP request:
  206. * **scheme** – assigned from a string literal after comparison.
  207. * **hostname** – reconstructed via character allowlist + regex check.
  208. * **port** – converted to ``int`` (or ``None``).
  209. * **path / query** – percent-encoding normalised.
  210. * **resolved_ips** – only globally routable addresses.
  211. Raises ``ValueError`` on any validation failure.
  212. """
  213. parsed = urllib.parse.urlparse(url)
  214. # --- scheme (literal assignment breaks taint) ---
  215. raw_scheme = (parsed.scheme or "").lower()
  216. if raw_scheme == "https":
  217. scheme = "https"
  218. elif raw_scheme == "http":
  219. scheme = "http"
  220. else:
  221. raise ValueError("Esquema inválido: solo se permiten http/https")
  222. if not parsed.netloc:
  223. raise ValueError("URL inválida: falta host")
  224. if parsed.username or parsed.password:
  225. raise ValueError("URLs con credenciales no permitidas")
  226. raw_hostname = parsed.hostname
  227. if not raw_hostname:
  228. raise ValueError("URL inválida: hostname no encontrado")
  229. # --- hostname (character-allowlist rebuild breaks taint) ---
  230. hostname = _sanitize_hostname(raw_hostname)
  231. # --- port (int conversion breaks taint) ---
  232. port = _sanitize_port(parsed)
  233. # --- path & query (percent-encoding normalisation breaks taint) ---
  234. path = urllib.parse.quote(
  235. urllib.parse.unquote(parsed.path or "/"),
  236. safe="/:@!$&'()*+,;=-._~",
  237. )
  238. query = urllib.parse.quote(
  239. urllib.parse.unquote(parsed.query or ""),
  240. safe="=&+%",
  241. )
  242. # --- DNS resolution + public-IP filter ---
  243. try:
  244. infos = socket.getaddrinfo(hostname, None)
  245. except Exception:
  246. raise ValueError("No se pudo resolver el host")
  247. seen: set[str] = set()
  248. public_ips: list[str] = []
  249. for info in infos:
  250. addr = info[4][0]
  251. try:
  252. ip = ipaddress.ip_address(addr)
  253. except ValueError:
  254. continue
  255. ip_str = str(ip)
  256. if ip_str in seen:
  257. continue
  258. seen.add(ip_str)
  259. if (
  260. ip.is_private
  261. or ip.is_loopback
  262. or ip.is_link_local
  263. or ip.is_multicast
  264. or ip.is_reserved
  265. or ip.is_unspecified
  266. ):
  267. continue
  268. public_ips.append(ip_str)
  269. if not public_ips:
  270. raise ValueError("No se encontraron direcciones públicas válidas para el host")
  271. return _ValidatedURL(
  272. scheme=scheme,
  273. hostname=hostname,
  274. port=port,
  275. path=path,
  276. query=query,
  277. resolved_ips=public_ips,
  278. )
  279. def import_domains_from_url(url: str) -> tuple[bool, set, str]:
  280. domains = set()
  281. try:
  282. # Validate URL components individually to prevent SSRF
  283. validated = _validate_import_url(url)
  284. # Perform an IP-pinned request using only sanitised components
  285. resp = _requests_get_pinned(validated, timeout=8)
  286. if resp.status_code != 200:
  287. return False, domains, f"Error al descargar la lista: {resp.status_code}"
  288. from services.squid.acls_service import sanitize_domain_entry
  289. for line in resp.text.splitlines():
  290. domain = sanitize_domain_entry(line)
  291. if domain:
  292. domains.add(domain)
  293. return True, domains, ""
  294. except ValueError as ve:
  295. logger.warning("Blocked unsafe import URL: %s", url)
  296. return False, domains, str(ve)
  297. except Exception:
  298. logger.exception("Error descargando lista desde URL")
  299. return False, domains, "Error descargando lista desde URL"
  300. def merge_and_save_blacklist(
  301. new_domains: set,
  302. source: str = "import",
  303. source_url: str | None = None,
  304. added_by: str | None = None,
  305. ) -> None:
  306. """Merge given domains into the `blacklist_domains` table.
  307. - new_domains: set of domain strings
  308. - source: string describing origin ('file', 'url', 'custom', ...)
  309. - source_url: optional url if source is 'url'
  310. - added_by: optional username who added the entries
  311. """
  312. if not new_domains:
  313. return
  314. session = get_session()
  315. try:
  316. now = datetime.now()
  317. for domain in new_domains:
  318. domain = domain.strip()
  319. if not domain:
  320. continue
  321. existing = (
  322. session.query(BlacklistDomain)
  323. .filter(BlacklistDomain.domain == domain)
  324. .one_or_none()
  325. )
  326. if existing:
  327. # reactivate and update metadata if necessary
  328. existing.active = 1
  329. existing.source = source or existing.source
  330. if source_url:
  331. existing.source_url = source_url
  332. if added_by:
  333. existing.added_by = added_by
  334. existing.updated_at = now
  335. else:
  336. record = BlacklistDomain(
  337. domain=domain,
  338. source=source,
  339. source_url=source_url,
  340. added_by=added_by,
  341. active=1,
  342. created_at=now,
  343. updated_at=now,
  344. )
  345. session.add(record)
  346. session.commit()
  347. except Exception:
  348. logger.exception("Error guardando blacklist en DB")
  349. session.rollback()
  350. raise
  351. finally:
  352. session.close()
  353. def save_custom_list(items: list, added_by: str | None = None) -> None:
  354. """Replace existing 'custom' source blacklist entries with `items`.
  355. This keeps other sources intact.
  356. """
  357. session = get_session()
  358. try:
  359. # Deactivate previous custom entries
  360. session.query(BlacklistDomain).filter(
  361. BlacklistDomain.source == "custom"
  362. ).update({"active": 0})
  363. now = datetime.now()
  364. for d in sorted(set(items)):
  365. domain = d.strip()
  366. if not domain:
  367. continue
  368. existing = (
  369. session.query(BlacklistDomain)
  370. .filter(BlacklistDomain.domain == domain)
  371. .one_or_none()
  372. )
  373. if existing:
  374. existing.active = 1
  375. existing.source = "custom"
  376. if added_by:
  377. existing.added_by = added_by
  378. existing.updated_at = now
  379. else:
  380. record = BlacklistDomain(
  381. domain=domain,
  382. source="custom",
  383. added_by=added_by,
  384. active=1,
  385. created_at=now,
  386. updated_at=now,
  387. )
  388. session.add(record)
  389. session.commit()
  390. except Exception:
  391. logger.exception("Error guardando lista personalizada en DB")
  392. session.rollback()
  393. raise
  394. finally:
  395. session.close()
  396. def get_url_blacklists_with_counts() -> list[dict]:
  397. session = get_session()
  398. try:
  399. results = (
  400. session.query(BlacklistDomain.source_url, func.count(BlacklistDomain.id))
  401. .filter(BlacklistDomain.source_url.isnot(None))
  402. .group_by(BlacklistDomain.source_url)
  403. .all()
  404. )
  405. return [{"source_url": url, "count": count} for url, count in results]
  406. except Exception:
  407. logger.exception("Error obteniendo conteos de blacklists por URL")
  408. return []
  409. finally:
  410. session.close()
  411. def delete_blacklist_by_source_url(source_url: str) -> int:
  412. session = get_session()
  413. try:
  414. count = (
  415. session.query(BlacklistDomain)
  416. .filter(BlacklistDomain.source_url == source_url)
  417. .delete(synchronize_session=False)
  418. )
  419. session.commit()
  420. return count
  421. except Exception:
  422. logger.exception("Error eliminando dominios por source_url")
  423. session.rollback()
  424. return 0
  425. finally:
  426. session.close()