captive_portal_config_service.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. """Writes/removes the captive-portal directives in Squid's configuration.
  2. Mirrors the block-marker approach used by the Kerberos module
  3. (:mod:`services.squid.kerberos_config_service`) but stays intentionally
  4. small: a single self-contained block is inserted right before the first
  5. plain ``http_access allow`` rule, so that pre-existing safety denies
  6. (``deny !Safe_ports``, ``deny CONNECT !SSL_ports``, manager exceptions...)
  7. always run first.
  8. """
  9. import os
  10. import sys
  11. from pathlib import Path
  12. from urllib.parse import urlparse
  13. from flask_babel import gettext as _
  14. from loguru import logger
  15. _BLOCK_START = "# BEGIN SquidStats Captive Portal"
  16. _BLOCK_END = "# END SquidStats Captive Portal"
  17. _EXTERNAL_ACL_NAME = "squidstats_captive_portal"
  18. _VALID_ACL_NAME = "squidstats_captive_portal_valid"
  19. _DOMAIN_ACL_NAME = "squidstats_captive_portal_domain"
  20. _HTTP_ACCESS_MODULE_FILENAME = "120_http_access.conf"
  21. _WRITE_MODE_ENV = "SQUIDSTATS_SQUID_CONFIG_WRITE_MODE"
  22. _HELPER_PYTHON_ENV = "SQUIDSTATS_HELPER_PYTHON"
  23. _HELPER_PATH_ENV = "SQUIDSTATS_HELPER_PATH"
  24. HELPER_SCRIPT_PATH = (
  25. Path(__file__).resolve().parent / "helper" / "captive_portal_helper.py"
  26. )
  27. def _portal_host(portal_public_url: str) -> str | None:
  28. if not portal_public_url:
  29. return None
  30. parsed = urlparse(portal_public_url)
  31. return parsed.hostname
  32. def render_block(
  33. *,
  34. login_url: str,
  35. portal_public_url: str,
  36. acl_ttl_seconds: int,
  37. acl_negative_ttl_seconds: int,
  38. ) -> str:
  39. """Build the Squid directive block for the captive portal."""
  40. python_exe = os.getenv(_HELPER_PYTHON_ENV, sys.executable).strip()
  41. helper_path = os.getenv(_HELPER_PATH_ENV, str(HELPER_SCRIPT_PATH)).strip()
  42. lines = [
  43. _BLOCK_START,
  44. (
  45. f"external_acl_type {_EXTERNAL_ACL_NAME} "
  46. f"ttl={int(acl_ttl_seconds)} negative_ttl={int(acl_negative_ttl_seconds)} "
  47. f"%SRC {python_exe} {helper_path}"
  48. ),
  49. f"acl {_VALID_ACL_NAME} external {_EXTERNAL_ACL_NAME}",
  50. ]
  51. portal_host = _portal_host(portal_public_url)
  52. if portal_host:
  53. lines.append(f'acl {_DOMAIN_ACL_NAME} dstdomain "{portal_host}"')
  54. lines.append(f"deny_info 302:{login_url} {_VALID_ACL_NAME}")
  55. if portal_host:
  56. lines.append(f"http_access allow {_DOMAIN_ACL_NAME}")
  57. lines.append(f"http_access deny !{_VALID_ACL_NAME}")
  58. lines.append(_BLOCK_END)
  59. return "\n".join(lines)
  60. def _find_insert_before_first_allow(lines: list[str]) -> int:
  61. """Insert after narrow manager policy but before general allow rules."""
  62. for i, line in enumerate(lines):
  63. parts = line.strip().split("#", 1)[0].split()
  64. if len(parts) >= 3 and parts[:2] == ["http_access", "allow"]:
  65. acl_names = {part.casefold() for part in parts[2:]}
  66. if acl_names == {"manager", "localhost"}:
  67. continue
  68. return i
  69. for i, line in enumerate(lines):
  70. if line.strip() == "http_access deny all":
  71. return i
  72. return len(lines)
  73. def _strip_existing_block(lines: list[str]) -> list[str]:
  74. result = []
  75. in_block = False
  76. for line in lines:
  77. stripped = line.strip()
  78. if stripped == _BLOCK_START:
  79. in_block = True
  80. continue
  81. if stripped == _BLOCK_END:
  82. in_block = False
  83. continue
  84. if not in_block:
  85. result.append(line)
  86. return result
  87. def _apply_to_content(content: str, block: str | None) -> str:
  88. lines = content.split("\n")
  89. had_managed_block = any(line.strip() == _BLOCK_START for line in lines)
  90. lines = _strip_existing_block(lines)
  91. if block is None:
  92. return "\n".join(lines)
  93. if not had_managed_block and block in content:
  94. return content
  95. insert_idx = _find_insert_before_first_allow(lines)
  96. block_lines = block.split("\n")
  97. lines[insert_idx:insert_idx] = block_lines
  98. return "\n".join(lines)
  99. def _write(cm, block: str | None) -> tuple[bool, str]:
  100. try:
  101. if os.getenv(_WRITE_MODE_ENV, "managed").strip().casefold() != "managed":
  102. return False, _(
  103. "Este despliegue usa modo manual para squid.conf. "
  104. "Copia la vista previa y aplícala mediante el procedimiento administrativo controlado."
  105. )
  106. if cm.is_modular:
  107. content = cm.read_modular_config(_HTTP_ACCESS_MODULE_FILENAME) or ""
  108. if block is None and _BLOCK_START not in content:
  109. return True, _(
  110. "La configuración del portal cautivo ya estaba deshabilitada"
  111. )
  112. new_content = _apply_to_content(content, block)
  113. if cm.save_modular_config(_HTTP_ACCESS_MODULE_FILENAME, new_content):
  114. return True, _("Configuración de portal cautivo actualizada")
  115. return False, _("Error al escribir la configuración modular")
  116. if block is None and _BLOCK_START not in cm.config_content:
  117. return True, _(
  118. "La configuración del portal cautivo ya estaba deshabilitada"
  119. )
  120. new_content = _apply_to_content(cm.config_content, block)
  121. if cm.save_config(new_content):
  122. return True, _("Configuración de portal cautivo actualizada")
  123. return False, _("Error al escribir squid.conf")
  124. except Exception:
  125. logger.exception("Error applying the captive portal Squid configuration")
  126. return False, _("Error interno al aplicar la configuración de portal cautivo")
  127. def enable_captive_portal(
  128. cm,
  129. *,
  130. login_url: str,
  131. portal_public_url: str,
  132. acl_ttl_seconds: int,
  133. acl_negative_ttl_seconds: int,
  134. ) -> tuple[bool, str]:
  135. """Write the captive portal directives into Squid's configuration."""
  136. block = render_block(
  137. login_url=login_url,
  138. portal_public_url=portal_public_url,
  139. acl_ttl_seconds=acl_ttl_seconds,
  140. acl_negative_ttl_seconds=acl_negative_ttl_seconds,
  141. )
  142. return _write(cm, block)
  143. def disable_captive_portal(cm) -> tuple[bool, str]:
  144. """Remove the captive portal directives from Squid's configuration."""
  145. return _write(cm, None)