http_access_service.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. import re
  2. from loguru import logger
  3. _KERBEROS_ACCESS_START = "# BEGIN SquidStats Kerberos access rule"
  4. _KERBEROS_ACCESS_END = "# END SquidStats Kerberos access rule"
  5. _KERBEROS_CHALLENGE_RE = re.compile(r"^http_access\s+deny\s+!\S+\s*$", re.I)
  6. def _is_local_cache_manager_allow(parts: list[str]) -> bool:
  7. """Recognise either conventional order of the local manager exception.
  8. Squid evaluates ACLs in an access rule as a conjunction, so both
  9. ``allow manager localhost`` and ``allow localhost manager`` are the
  10. conventional narrow exception. Do not accept extra/negated ACLs here:
  11. generic edits must not gain a way to place a client allow before the
  12. Kerberos challenge.
  13. """
  14. lowered = [part.casefold() for part in parts]
  15. return (
  16. len(lowered) == 4
  17. and lowered[:2] == ["http_access", "allow"]
  18. and set(lowered[2:]) == {"manager", "localhost"}
  19. )
  20. def _find_http_lines(lines):
  21. return [
  22. i
  23. for i, line in enumerate(lines)
  24. if line.strip().startswith("http_access ") and not line.strip().startswith("#")
  25. ]
  26. def _is_managed_kerberos_access_line(lines: list[str], line_index: int) -> bool:
  27. """Return whether an HTTP rule belongs to the Kerberos managed block."""
  28. in_kerberos_block = False
  29. for index, line in enumerate(lines):
  30. marker = line.strip()
  31. if marker == _KERBEROS_ACCESS_START:
  32. in_kerberos_block = True
  33. elif marker == _KERBEROS_ACCESS_END:
  34. in_kerberos_block = False
  35. if index == line_index:
  36. return in_kerberos_block
  37. return False
  38. def _editable_http_line(
  39. lines: list[str], http_lines_indices: list[int], rule_index: int
  40. ) -> tuple[int | None, str | None]:
  41. """Resolve a UI index while preserving the dedicated Kerberos rule."""
  42. if rule_index < 0 or rule_index >= len(http_lines_indices):
  43. return None, "Índice de regla inválido"
  44. line_index = http_lines_indices[rule_index]
  45. if _is_managed_kerberos_access_line(lines, line_index):
  46. return (
  47. None,
  48. "La regla Kerberos administrada se modifica desde Kerberos / SPNEGO, no desde HTTP Access.",
  49. )
  50. return line_index, None
  51. def _kerberos_policy_error(lines: list[str]) -> str | None:
  52. """Reject an edit that would put a normal allow before Kerberos.
  53. The dedicated screen owns the challenge line, but changing a neighboring
  54. rule through the generic editor can be equally dangerous. A narrow local
  55. Cache Manager exception is the only positive allow permitted beforehand.
  56. """
  57. starts = [
  58. index
  59. for index, line in enumerate(lines)
  60. if line.strip() == _KERBEROS_ACCESS_START
  61. ]
  62. ends = [
  63. index
  64. for index, line in enumerate(lines)
  65. if line.strip() == _KERBEROS_ACCESS_END
  66. ]
  67. if not starts and not ends:
  68. return None
  69. if len(starts) != 1 or len(ends) != 1 or ends[0] <= starts[0]:
  70. return (
  71. "El bloque Kerberos administrado está incompleto; revísalo desde "
  72. "Kerberos / SPNEGO antes de modificar reglas HTTP Access."
  73. )
  74. challenge_indices = [
  75. index
  76. for index in range(starts[0] + 1, ends[0])
  77. if _KERBEROS_CHALLENGE_RE.fullmatch(
  78. lines[index].strip().split("#", 1)[0].strip()
  79. )
  80. ]
  81. if len(challenge_indices) != 1:
  82. return (
  83. "No se pudo verificar el desafío Kerberos administrado; modifica "
  84. "la política desde Kerberos / SPNEGO."
  85. )
  86. for line in lines[: challenge_indices[0]]:
  87. parts = line.strip().split("#", 1)[0].strip().split()
  88. lowered = [part.casefold() for part in parts]
  89. if lowered[:2] != ["http_access", "allow"]:
  90. continue
  91. if _is_local_cache_manager_allow(parts):
  92. continue
  93. return (
  94. "La regla dejaría un allow antes del desafío Kerberos. Modifica la "
  95. "política desde Kerberos / SPNEGO o conserva solo la excepción local del manager."
  96. )
  97. return None
  98. def delete_http_access(rule_index: int, config_manager) -> tuple[bool, str]:
  99. try:
  100. if config_manager.is_modular:
  101. http_content = config_manager.read_modular_config("120_http_access.conf")
  102. if http_content is not None:
  103. lines = http_content.split("\n")
  104. http_lines_indices = _find_http_lines(lines)
  105. line_index, error = _editable_http_line(
  106. lines, http_lines_indices, rule_index
  107. )
  108. if error:
  109. return False, error
  110. # remove the line
  111. del lines[line_index]
  112. new_content = "\n".join(lines)
  113. if config_manager.save_modular_config(
  114. "120_http_access.conf", new_content
  115. ):
  116. return True, "Regla HTTP Access eliminada exitosamente"
  117. else:
  118. return False, "Error al eliminar la regla modular"
  119. # Fallback to main config
  120. lines = config_manager.config_content.split("\n")
  121. http_lines_indices = _find_http_lines(lines)
  122. line_index, error = _editable_http_line(lines, http_lines_indices, rule_index)
  123. if error:
  124. return False, error
  125. del lines[line_index]
  126. new_content = "\n".join(lines)
  127. if config_manager.save_config(new_content):
  128. return True, "Regla HTTP Access eliminada exitosamente"
  129. return False, "Error al eliminar la regla HTTP Access"
  130. except Exception:
  131. logger.exception("Error eliminando http_access")
  132. return False, "Error interno al eliminar regla http_access"
  133. def edit_http_access(
  134. rule_index: int, action: str, acls: list, description: str, config_manager
  135. ) -> tuple[bool, str]:
  136. try:
  137. acl_string = " ".join([acl.strip() for acl in acls if acl.strip()])
  138. if not acl_string:
  139. return False, "Debe especificar al menos una ACL"
  140. new_rule = f"http_access {action} {acl_string}"
  141. if config_manager.is_modular:
  142. http_content = config_manager.read_modular_config("120_http_access.conf")
  143. if http_content is not None:
  144. lines = http_content.split("\n")
  145. http_lines_indices = _find_http_lines(lines)
  146. i, error = _editable_http_line(lines, http_lines_indices, rule_index)
  147. if error:
  148. return False, error
  149. if description:
  150. if i > 0 and lines[i - 1].strip().startswith("#"):
  151. lines[i - 1] = f"# {description}"
  152. else:
  153. lines.insert(i, f"# {description}")
  154. i += 1
  155. lines[i] = new_rule
  156. if error := _kerberos_policy_error(lines):
  157. return False, error
  158. new_content = "\n".join(lines)
  159. if config_manager.save_modular_config(
  160. "120_http_access.conf", new_content
  161. ):
  162. return True, "Regla HTTP Access actualizada exitosamente"
  163. else:
  164. return False, "Error al guardar regla modular"
  165. # Fallback to main config
  166. lines = config_manager.config_content.split("\n")
  167. http_lines_indices = _find_http_lines(lines)
  168. i, error = _editable_http_line(lines, http_lines_indices, rule_index)
  169. if error:
  170. return False, error
  171. if description:
  172. if i > 0 and lines[i - 1].strip().startswith("#"):
  173. lines[i - 1] = f"# {description}"
  174. else:
  175. lines.insert(i, f"# {description}")
  176. i += 1
  177. lines[i] = new_rule
  178. if error := _kerberos_policy_error(lines):
  179. return False, error
  180. new_content = "\n".join(lines)
  181. if config_manager.save_config(new_content):
  182. return True, "Regla HTTP Access actualizada exitosamente"
  183. return False, "Error al guardar la regla HTTP Access"
  184. except Exception:
  185. logger.exception("Error actualizando http_access")
  186. return False, "Error interno al actualizar regla http_access"
  187. def add_http_access(
  188. action: str, acls: list, description: str, config_manager
  189. ) -> tuple[bool, str]:
  190. try:
  191. acl_string = " ".join([acl.strip() for acl in acls if acl.strip()])
  192. if not acl_string:
  193. return False, "Debe especificar al menos una ACL"
  194. new_rule = f"http_access {action} {acl_string}"
  195. lines_to_add = []
  196. if description:
  197. lines_to_add.append(f"# {description}")
  198. lines_to_add.append(new_rule)
  199. if config_manager.is_modular:
  200. http_content = config_manager.read_modular_config("120_http_access.conf")
  201. if http_content is not None:
  202. lines = http_content.split("\n")
  203. lines.extend(lines_to_add)
  204. new_content = "\n".join(lines)
  205. if config_manager.save_modular_config(
  206. "120_http_access.conf", new_content
  207. ):
  208. return True, "Regla HTTP Access agregada exitosamente"
  209. else:
  210. return False, "Error al guardar regla modular"
  211. lines = config_manager.config_content.split("\n")
  212. lines.extend(lines_to_add)
  213. new_content = "\n".join(lines)
  214. if config_manager.save_config(new_content):
  215. return True, "Regla HTTP Access agregada exitosamente"
  216. return False, "Error al guardar la regla HTTP Access"
  217. except Exception:
  218. logger.exception("Error agregando http_access")
  219. return False, "Error interno al agregar regla http_access"
  220. def add_http_deny_blocklist(acl_name: str, config_manager) -> tuple[bool, str]:
  221. """Add an ``http_access deny <acl_name>`` rule for the blocklist.
  222. The deny rule is inserted **before** the first ``http_access allow`` rule
  223. so that blocked domains are rejected before any allow rule can match.
  224. If a deny rule for this ACL already exists, it is not duplicated.
  225. Args:
  226. acl_name: Name of the blocklist ACL (must match the ACL created by
  227. :func:`add_acl_blocklist`).
  228. config_manager: A :class:`SquidConfigManager` instance.
  229. Returns:
  230. ``(success, message)`` tuple.
  231. """
  232. if not acl_name:
  233. return False, "Debe proporcionar el nombre de la ACL de blocklist"
  234. deny_rule = f"http_access deny {acl_name}"
  235. comment = f"# Deny blocklist gestionada por SquidStats ({acl_name})"
  236. try:
  237. if config_manager.is_modular:
  238. http_content = config_manager.read_modular_config("120_http_access.conf")
  239. if http_content is not None:
  240. lines = http_content.split("\n")
  241. # Check if the deny rule already exists
  242. for line in lines:
  243. if line.strip() == deny_rule:
  244. return True, f"La regla deny para '{acl_name}' ya existe"
  245. # Find the first http_access allow to insert before it
  246. insert_idx = len(lines)
  247. for i, line in enumerate(lines):
  248. stripped = line.strip()
  249. if stripped.startswith("http_access allow"):
  250. insert_idx = i
  251. break
  252. lines.insert(insert_idx, comment)
  253. lines.insert(insert_idx + 1, deny_rule)
  254. new_content = "\n".join(lines)
  255. if config_manager.save_modular_config(
  256. "120_http_access.conf", new_content
  257. ):
  258. return (
  259. True,
  260. f"Regla 'http_access deny {acl_name}' agregada exitosamente",
  261. )
  262. else:
  263. return False, "Error al guardar regla deny modular"
  264. # Fallback to main config
  265. lines = config_manager.config_content.split("\n")
  266. for line in lines:
  267. if line.strip() == deny_rule:
  268. return True, f"La regla deny para '{acl_name}' ya existe"
  269. insert_idx = len(lines)
  270. for i, line in enumerate(lines):
  271. stripped = line.strip()
  272. if stripped.startswith("http_access allow"):
  273. insert_idx = i
  274. break
  275. lines.insert(insert_idx, comment)
  276. lines.insert(insert_idx + 1, deny_rule)
  277. new_content = "\n".join(lines)
  278. if config_manager.save_config(new_content):
  279. return (
  280. True,
  281. f"Regla 'http_access deny {acl_name}' agregada exitosamente",
  282. )
  283. return False, "Error al guardar la regla deny"
  284. except Exception:
  285. logger.exception("Error agregando http_access deny para blocklist")
  286. return False, "Error interno al agregar regla http_access deny"
  287. def remove_http_deny_blocklist(acl_name: str, config_manager) -> tuple[bool, str]:
  288. """Remove the ``http_access deny <acl_name>`` rule and its comment.
  289. Supports both modular (``120_http_access.conf``) and monolithic config.
  290. Args:
  291. acl_name: Name of the blocklist ACL whose deny rule should be removed.
  292. config_manager: A :class:`SquidConfigManager` instance.
  293. Returns:
  294. ``(success, message)`` tuple.
  295. """
  296. if not acl_name:
  297. return False, "Debe proporcionar el nombre de la ACL de blocklist"
  298. deny_rule = f"http_access deny {acl_name}"
  299. def _strip_deny(lines: list[str]) -> list[str]:
  300. """Return lines without the deny rule and its preceding comment."""
  301. result: list[str] = []
  302. # skip_next = False
  303. i = 0
  304. while i < len(lines):
  305. stripped = lines[i].strip()
  306. # Check if this is our deny rule
  307. if stripped == deny_rule:
  308. # Also remove the comment immediately above if it belongs to us
  309. if result and result[-1].strip().startswith(
  310. "# Deny blocklist gestionada por SquidStats"
  311. ):
  312. result.pop()
  313. i += 1
  314. continue
  315. result.append(lines[i])
  316. i += 1
  317. return result
  318. try:
  319. removed = False
  320. if config_manager.is_modular:
  321. http_content = config_manager.read_modular_config("120_http_access.conf")
  322. if http_content is not None:
  323. lines = http_content.split("\n")
  324. cleaned = _strip_deny(lines)
  325. if len(cleaned) != len(lines):
  326. removed = True
  327. new_content = "\n".join(cleaned)
  328. if not config_manager.save_modular_config(
  329. "120_http_access.conf", new_content
  330. ):
  331. return False, "Error guardando config modular de http_access"
  332. # Also clean main config
  333. lines = config_manager.config_content.split("\n")
  334. cleaned = _strip_deny(lines)
  335. if len(cleaned) != len(lines):
  336. removed = True
  337. new_content = "\n".join(cleaned)
  338. if not config_manager.save_config(new_content):
  339. return False, "Error guardando config principal de http_access"
  340. if removed:
  341. return (
  342. True,
  343. f"Regla 'http_access deny {acl_name}' eliminada exitosamente",
  344. )
  345. return True, f"No se encontró regla deny para '{acl_name}' (ya eliminada)"
  346. except Exception:
  347. logger.exception("Error eliminando http_access deny para blocklist")
  348. return False, "Error interno al eliminar regla http_access deny"
  349. def move_http_access(
  350. rule_index: int, direction: str, config_manager
  351. ) -> tuple[bool, str]:
  352. try:
  353. if config_manager.is_modular:
  354. http_content = config_manager.read_modular_config("120_http_access.conf")
  355. if http_content is not None:
  356. lines = http_content.split("\n")
  357. http_lines_indices = _find_http_lines(lines)
  358. current, error = _editable_http_line(
  359. lines, http_lines_indices, rule_index
  360. )
  361. if error:
  362. return False, error
  363. if direction == "up" and rule_index > 0:
  364. target = http_lines_indices[rule_index - 1]
  365. if _is_managed_kerberos_access_line(lines, target):
  366. return (
  367. False,
  368. "No se puede mover una regla a través del bloque Kerberos administrado.",
  369. )
  370. lines[current], lines[target] = lines[target], lines[current]
  371. elif direction == "down" and rule_index < len(http_lines_indices) - 1:
  372. target = http_lines_indices[rule_index + 1]
  373. if _is_managed_kerberos_access_line(lines, target):
  374. return (
  375. False,
  376. "No se puede mover una regla a través del bloque Kerberos administrado.",
  377. )
  378. lines[current], lines[target] = lines[target], lines[current]
  379. new_content = "\n".join(lines)
  380. if config_manager.save_modular_config(
  381. "120_http_access.conf", new_content
  382. ):
  383. return True, "Regla movida exitosamente"
  384. return False, "Error al guardar regla modular"
  385. lines = config_manager.config_content.split("\n")
  386. http_lines_indices = _find_http_lines(lines)
  387. current, error = _editable_http_line(lines, http_lines_indices, rule_index)
  388. if error:
  389. return False, error
  390. if direction == "up" and rule_index > 0:
  391. target = http_lines_indices[rule_index - 1]
  392. if _is_managed_kerberos_access_line(lines, target):
  393. return (
  394. False,
  395. "No se puede mover una regla a través del bloque Kerberos administrado.",
  396. )
  397. lines[current], lines[target] = lines[target], lines[current]
  398. elif direction == "down" and rule_index < len(http_lines_indices) - 1:
  399. target = http_lines_indices[rule_index + 1]
  400. if _is_managed_kerberos_access_line(lines, target):
  401. return (
  402. False,
  403. "No se puede mover una regla a través del bloque Kerberos administrado.",
  404. )
  405. lines[current], lines[target] = lines[target], lines[current]
  406. new_content = "\n".join(lines)
  407. if config_manager.save_config(new_content):
  408. return True, "Regla movida exitosamente"
  409. return False, "Error al guardar la regla HTTP Access"
  410. except Exception:
  411. logger.exception("Error moviendo http_access")
  412. return False, "Error interno al mover regla http_access"