connection_reset_service.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. """Terminate tracked network states belonging to a client IP.
  2. This is intentionally a host-level capability. Squid does not expose a
  3. portable API for closing only one client's active sockets, so unsupported
  4. platforms must report that fact instead of claiming the reset succeeded.
  5. """
  6. import ipaddress
  7. import platform
  8. import shutil
  9. import subprocess # nosec B404
  10. from loguru import logger
  11. def _validate_ip(client_ip: str) -> str:
  12. """Return a normalized IP address or raise ValueError."""
  13. value = str(client_ip or "").strip()
  14. if not value:
  15. raise ValueError("Se requiere una dirección IP")
  16. try:
  17. return str(ipaddress.ip_address(value))
  18. except ValueError as exc:
  19. raise ValueError("La dirección IP no es válida") from exc
  20. def _run_reset(command: list[str], backend: str) -> tuple[bool, str, str | None]:
  21. try:
  22. result = subprocess.run( # nosec B603 # noqa: S603
  23. command,
  24. check=False,
  25. capture_output=True,
  26. text=True,
  27. timeout=30,
  28. )
  29. except subprocess.TimeoutExpired:
  30. return False, "El reseteo de conexiones agotó el tiempo de espera", None
  31. except OSError as exc:
  32. logger.warning("No se pudo ejecutar %s: %s", backend, exc)
  33. return False, f"No se pudo ejecutar {backend}", str(exc)
  34. if result.returncode == 0:
  35. return (
  36. True,
  37. f"Conexiones activas de {command[-1]} reseteadas mediante {backend}",
  38. None,
  39. )
  40. details = (result.stderr or result.stdout).strip() or None
  41. logger.warning("%s falló con estado %s: %s", backend, result.returncode, details)
  42. if details and any(
  43. marker in details.lower()
  44. for marker in ("permission denied", "operation not permitted", "must be root")
  45. ):
  46. return (
  47. False,
  48. "Se requieren privilegios del sistema para resetear conexiones",
  49. details,
  50. )
  51. return False, f"{backend} no pudo resetear las conexiones", details
  52. def reset_client_connections(client_ip: str) -> tuple[bool, str, str | None]:
  53. """Reset tracked states for *client_ip* using the host's native firewall.
  54. Linux uses conntrack and macOS/BSD uses pfctl. Both require the SquidStats
  55. process to have the corresponding system privileges (normally root or a
  56. narrowly scoped sudo policy).
  57. """
  58. try:
  59. normalized_ip = _validate_ip(client_ip)
  60. except ValueError as exc:
  61. return False, str(exc), None
  62. system = platform.system().lower()
  63. if system == "linux":
  64. binary = shutil.which("conntrack")
  65. if not binary:
  66. return (
  67. False,
  68. "No se encontró conntrack. Instálalo en el host para resetear conexiones.",
  69. None,
  70. )
  71. return _run_reset([binary, "-D", "-s", normalized_ip], "conntrack")
  72. if system in {"darwin", "freebsd", "openbsd", "netbsd"}:
  73. binary = shutil.which("pfctl")
  74. if not binary:
  75. return False, "No se encontró pfctl para resetear conexiones", None
  76. return _run_reset([binary, "-k", normalized_ip], "pfctl")
  77. return (
  78. False,
  79. f"El reseteo de conexiones no está soportado en {platform.system() or 'este sistema'}",
  80. None,
  81. )