acls_service.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  1. import hashlib
  2. import os
  3. import re
  4. from contextlib import nullcontext
  5. from functools import wraps
  6. from loguru import logger
  7. from database.database import get_session
  8. from database.models.models import BlacklistDomain
  9. from utils.admin import squid_config_write_lock
  10. BLOCKLIST_DIR_NAME = "blocklists"
  11. BLOCKLIST_PREFIX = "blocklist_"
  12. # These markers are owned by the dedicated Kerberos/SPNEGO screen. Keeping
  13. # the strings local avoids a dependency from the generic ACL editor back into
  14. # the configuration service, while preventing that editor from changing the
  15. # identity ACL that makes the authentication policy work.
  16. _KERBEROS_AUTH_START = "# BEGIN SquidStats Kerberos authentication"
  17. _KERBEROS_AUTH_END = "# END SquidStats Kerberos authentication"
  18. _KERBEROS_ACCESS_START = "# BEGIN SquidStats Kerberos access rule"
  19. _KERBEROS_ACCESS_END = "# END SquidStats Kerberos access rule"
  20. _KERBEROS_EXCEPTION_ACLS = frozenset({"manager", "localhost"})
  21. # ---------------------------------------------------------------------------
  22. # Domain validation regex (RFC 1123 compatible)
  23. # ---------------------------------------------------------------------------
  24. _VALID_DOMAIN_RE = re.compile(
  25. r"^(?:[a-z0-9](?:[a-z0-9\-]{0,61}[a-z0-9])?\.)+"
  26. r"[a-z]{2,63}$",
  27. re.IGNORECASE,
  28. )
  29. def _managed_kerberos_acl_names(config_manager) -> set[str]:
  30. """Return names of ACLs inside a SquidStats-managed Kerberos block.
  31. The normal ACL editor operates on ``100_acls.conf`` in modular layouts,
  32. whereas the Kerberos identity ACL intentionally lives in ``50_auth.conf``.
  33. Looking at both locations prevents adding a second, incompatible ACL with
  34. the same name or editing the managed ACL in a monolithic installation.
  35. """
  36. contents = [str(getattr(config_manager, "config_content", "") or "")]
  37. if bool(getattr(config_manager, "is_modular", False)):
  38. try:
  39. auth_content = config_manager.read_modular_config("50_auth.conf")
  40. except Exception:
  41. auth_content = None
  42. if auth_content:
  43. contents.append(auth_content)
  44. names: set[str] = set()
  45. for content in contents:
  46. in_managed_block = False
  47. for raw_line in content.splitlines():
  48. line = raw_line.strip()
  49. if line == _KERBEROS_AUTH_START:
  50. in_managed_block = True
  51. continue
  52. if line == _KERBEROS_AUTH_END:
  53. in_managed_block = False
  54. continue
  55. if not in_managed_block or line.startswith("#"):
  56. continue
  57. parts = line.split()
  58. if len(parts) >= 3 and parts[0].casefold() == "acl":
  59. names.add(parts[1].casefold())
  60. return names
  61. def _is_managed_kerberos_acl(name: str, config_manager) -> bool:
  62. return name.casefold() in _managed_kerberos_acl_names(config_manager)
  63. def _managed_kerberos_access_is_active(config_manager) -> bool:
  64. """Return whether a managed challenge relies on the manager exception.
  65. The normal HTTP rule editor permits only ``allow manager localhost``
  66. before the challenge. Those ACL definitions must therefore not be
  67. broadened through the generic ACL screen while the managed block exists.
  68. """
  69. contents = [str(getattr(config_manager, "config_content", "") or "")]
  70. active_contents = getattr(config_manager, "_active_configuration_contents", None)
  71. if callable(active_contents):
  72. try:
  73. contents.extend(active_contents())
  74. except Exception as exc:
  75. logger.debug(
  76. "No se pudieron leer includes activos para ACLs Kerberos: {}", exc
  77. )
  78. elif bool(getattr(config_manager, "is_modular", False)):
  79. try:
  80. access_content = config_manager.read_modular_config("120_http_access.conf")
  81. except Exception:
  82. access_content = None
  83. if access_content:
  84. contents.append(access_content)
  85. return any(
  86. _KERBEROS_ACCESS_START in content and _KERBEROS_ACCESS_END in content
  87. for content in contents
  88. )
  89. def _is_protected_kerberos_acl(name: str, config_manager) -> bool:
  90. return _is_managed_kerberos_acl(name, config_manager) or (
  91. name.casefold() in _KERBEROS_EXCEPTION_ACLS
  92. and _managed_kerberos_access_is_active(config_manager)
  93. )
  94. def _managed_acl_error(name: str) -> tuple[bool, str]:
  95. if name.casefold() in _KERBEROS_EXCEPTION_ACLS:
  96. return (
  97. False,
  98. "La ACL manager/localhost participa en la excepción previa a Kerberos; "
  99. "modifícala solo después de retirar o revisar Kerberos / SPNEGO.",
  100. )
  101. return (
  102. False,
  103. "La ACL Kerberos administrada se modifica desde Kerberos / SPNEGO, no desde ACLs.",
  104. )
  105. def _refresh_config_manager_for_acl_mutation(config_manager) -> None:
  106. """Reload a real config manager while its configuration lock is held.
  107. The admin application deliberately keeps a manager instance between
  108. requests. Without a refresh, an ACL request that began before a
  109. Kerberos apply could check an old configuration and subsequently broaden
  110. ``manager`` or ``localhost`` after the Kerberos transaction completed.
  111. Reloading under the shared lock makes the protection check and write one
  112. transaction. Small test/dummy managers need not implement this API.
  113. """
  114. load_config = getattr(config_manager, "load_config", None)
  115. if callable(load_config) and load_config() is False:
  116. raise RuntimeError("No se pudo recargar squid.conf antes de modificar ACLs")
  117. check_modular_config = getattr(config_manager, "_check_modular_config", None)
  118. if callable(check_modular_config):
  119. check_modular_config()
  120. def _synchronized_acl_mutation(operation):
  121. """Make ACL protection checks and writes atomic with Kerberos applies."""
  122. @wraps(operation)
  123. def wrapped(*args, **kwargs):
  124. config_manager = kwargs.get("config_manager")
  125. if config_manager is None and args:
  126. config_manager = args[-1]
  127. config_path = getattr(config_manager, "config_path", None)
  128. lock = (
  129. squid_config_write_lock(str(config_path)) if config_path else nullcontext()
  130. )
  131. try:
  132. with lock:
  133. if config_path:
  134. _refresh_config_manager_for_acl_mutation(config_manager)
  135. return operation(*args, **kwargs)
  136. except Exception:
  137. logger.exception("Error sincronizando modificación de ACL con Kerberos")
  138. return (
  139. False,
  140. "No se pudo recargar la configuración de Squid; inténtelo de nuevo.",
  141. )
  142. return wrapped
  143. def sanitize_domain_entry(raw: str) -> str | None:
  144. """Convert a raw blocklist entry to a clean domain for Squid ``dstdomain``.
  145. Handles multiple blocklist formats:
  146. **AdGuard / Adblock Plus (ABP)**:
  147. ``||example.com^`` → ``example.com``
  148. ``||example.com^$third-party`` → ``example.com``
  149. ``@@||example.com^`` → ``None`` (exception / whitelist)
  150. **Hosts file**:
  151. ``0.0.0.0 example.com`` → ``example.com``
  152. ``127.0.0.1 example.com`` → ``example.com``
  153. **Plain domain**:
  154. ``example.com`` → ``example.com``
  155. Lines that are comments, metadata, cosmetic filters, regex rules, or
  156. contain wildcards are skipped (returns ``None``).
  157. Returns:
  158. A clean lowercase domain string, or ``None`` if the line should be
  159. skipped.
  160. """
  161. line = raw.strip()
  162. # Empty or comment lines
  163. if not line or line.startswith(("!", "#", "[", "//")):
  164. return None
  165. # ABP exception rules (whitelist) — skip
  166. if line.startswith("@@"):
  167. return None
  168. # ABP cosmetic / element hiding filters — skip
  169. if "##" in line or "#@#" in line or "#?#" in line:
  170. return None
  171. # ABP/AdGuard domain rules: ||domain.com^ or ||domain.com^$options
  172. if line.startswith("||"):
  173. domain = line[2:] # strip ||
  174. # Remove trailing ^ and anything after it ($options, etc.)
  175. domain = domain.split("^")[0]
  176. # Remove any remaining $ options if no ^ was present
  177. domain = domain.split("$")[0]
  178. domain = domain.strip(".")
  179. else:
  180. # Skip lines with ABP wildcards or regex
  181. if "*" in line or line.startswith("/") or "|" in line:
  182. return None
  183. # Skip lines with $ modifier without || prefix (e.g., advanced ABP rules)
  184. if "$" in line and "=" in line:
  185. return None
  186. # Hosts file format: "0.0.0.0 example.com" or "127.0.0.1 example.com"
  187. if " " in line or "\t" in line:
  188. parts = line.split()
  189. # Take the last non-comment part
  190. domain = None
  191. for part in parts:
  192. if part.startswith("#"):
  193. break
  194. domain = part
  195. if domain is None:
  196. return None
  197. else:
  198. domain = line
  199. # Final cleanup
  200. domain = domain.lower().strip(".")
  201. # Remove port if present (e.g., "example.com:443")
  202. if ":" in domain:
  203. domain = domain.rsplit(":", 1)[0]
  204. # Must look like a valid domain
  205. if not domain or not _VALID_DOMAIN_RE.match(domain):
  206. return None
  207. # Reject IP addresses stored as domains
  208. if re.match(r"^\d{1,3}(\.\d{1,3}){3}$", domain):
  209. return None
  210. return domain
  211. def sanitize_domain_list(raw_domains: list[str]) -> list[str]:
  212. """Sanitize a list of raw domain entries for Squid compatibility.
  213. Applies :func:`sanitize_domain_entry` to each entry and returns only
  214. valid, unique domains in sorted order.
  215. """
  216. seen: set[str] = set()
  217. cleaned: list[str] = []
  218. for raw in raw_domains:
  219. domain = sanitize_domain_entry(raw)
  220. if domain and domain not in seen:
  221. seen.add(domain)
  222. cleaned.append(domain)
  223. cleaned.sort()
  224. return cleaned
  225. @_synchronized_acl_mutation
  226. def add_acl(
  227. name: str, acl_type: str, values: list, options: list, comment: str, config_manager
  228. ) -> tuple[bool, str]:
  229. if not name or not acl_type or not values:
  230. return False, "Debe proporcionar nombre, tipo y al menos un valor para la ACL"
  231. if _is_protected_kerberos_acl(name, config_manager):
  232. return _managed_acl_error(name)
  233. acl_parts = ["acl", name]
  234. if options:
  235. acl_parts.extend(options)
  236. acl_parts.append(acl_type)
  237. acl_parts.extend(values)
  238. new_acl = " ".join(acl_parts)
  239. try:
  240. if config_manager.is_modular:
  241. acl_content = config_manager.read_modular_config("100_acls.conf")
  242. if acl_content is not None:
  243. lines = acl_content.split("\n")
  244. if comment:
  245. lines.append(f"# {comment}")
  246. lines.append(new_acl)
  247. new_content = "\n".join(lines)
  248. if config_manager.save_modular_config("100_acls.conf", new_content):
  249. return True, f"ACL '{name}' agregada exitosamente"
  250. else:
  251. return False, "Error al guardar la ACL en modular"
  252. # Fallback to main config
  253. lines = config_manager.config_content.split("\n")
  254. acl_section_end = -1
  255. for i, line in enumerate(lines):
  256. if line.strip().startswith("acl "):
  257. acl_section_end = i
  258. if acl_section_end != -1:
  259. if comment:
  260. lines.insert(acl_section_end + 1, f"# {comment}")
  261. lines.insert(acl_section_end + 2, new_acl)
  262. else:
  263. lines.insert(acl_section_end + 1, new_acl)
  264. else:
  265. if comment:
  266. lines.append(f"# {comment}")
  267. lines.append(new_acl)
  268. new_content = "\n".join(lines)
  269. config_manager.save_config(new_content)
  270. return True, f"ACL '{name}' agregada exitosamente"
  271. except Exception:
  272. logger.exception("Error agregando ACL")
  273. return False, "Error interno al agregar ACL"
  274. @_synchronized_acl_mutation
  275. def edit_acl(
  276. acl_index: int,
  277. new_name: str,
  278. acl_type: str,
  279. values: list,
  280. options: list,
  281. comment: str,
  282. config_manager,
  283. ) -> tuple[bool, str]:
  284. try:
  285. acls = config_manager.get_acls()
  286. if not (0 <= acl_index < len(acls)):
  287. return False, "ACL no encontrada"
  288. target_acl = acls[acl_index]
  289. if _is_protected_kerberos_acl(target_acl["name"], config_manager):
  290. return _managed_acl_error(target_acl["name"])
  291. if _is_protected_kerberos_acl(new_name, config_manager):
  292. return _managed_acl_error(new_name)
  293. target_line = target_acl["line_number"] - 1
  294. acl_parts = ["acl", new_name]
  295. if options:
  296. acl_parts.extend(options)
  297. acl_parts.append(acl_type)
  298. acl_parts.extend(values)
  299. new_acl_line = " ".join(acl_parts)
  300. if config_manager.is_modular:
  301. acl_content = config_manager.read_modular_config("100_acls.conf")
  302. if acl_content is not None:
  303. lines = acl_content.split("\n")
  304. if 0 <= target_line < len(lines):
  305. has_comment = target_line > 0 and lines[
  306. target_line - 1
  307. ].strip().startswith("#")
  308. lines[target_line] = new_acl_line
  309. if has_comment:
  310. if comment:
  311. lines[target_line - 1] = f"# {comment}"
  312. else:
  313. lines.pop(target_line - 1)
  314. else:
  315. if comment:
  316. lines.insert(target_line, f"# {comment}")
  317. new_content = "\n".join(lines)
  318. if config_manager.save_modular_config("100_acls.conf", new_content):
  319. return True, f"ACL '{new_name}' actualizada exitosamente"
  320. else:
  321. return False, "Error guardando ACL modular"
  322. # Fallback to main config
  323. lines = config_manager.config_content.split("\n")
  324. if 0 <= target_line < len(lines):
  325. lines[target_line] = new_acl_line
  326. if target_line > 0 and lines[target_line - 1].strip().startswith("#"):
  327. if comment:
  328. lines[target_line - 1] = f"# {comment}"
  329. else:
  330. lines.pop(target_line - 1)
  331. else:
  332. if comment:
  333. lines.insert(target_line, f"# {comment}")
  334. new_content = "\n".join(lines)
  335. config_manager.save_config(new_content)
  336. return True, f"ACL '{new_name}' actualizada exitosamente"
  337. return False, "Línea de ACL no encontrada"
  338. except Exception:
  339. logger.exception("Error editando ACL")
  340. return False, "Error interno al editar ACL"
  341. @_synchronized_acl_mutation
  342. def delete_acl(acl_index: int, config_manager) -> tuple[bool, str]:
  343. try:
  344. acls = config_manager.get_acls()
  345. if not (0 <= acl_index < len(acls)):
  346. return False, "ACL no encontrada"
  347. acl_to_delete = acls[acl_index]
  348. if _is_protected_kerberos_acl(acl_to_delete["name"], config_manager):
  349. return _managed_acl_error(acl_to_delete["name"])
  350. target_line = acl_to_delete["line_number"] - 1
  351. if config_manager.is_modular:
  352. acl_content = config_manager.read_modular_config("100_acls.conf")
  353. if acl_content is not None:
  354. lines = acl_content.split("\n")
  355. comment_to_remove = None
  356. if target_line > 0 and lines[target_line - 1].strip().startswith("#"):
  357. comment_to_remove = target_line - 1
  358. new_lines = []
  359. for i, line in enumerate(lines):
  360. if i == target_line:
  361. continue
  362. if comment_to_remove is not None and i == comment_to_remove:
  363. continue
  364. new_lines.append(line)
  365. new_content = "\n".join(new_lines)
  366. if config_manager.save_modular_config("100_acls.conf", new_content):
  367. return True, f"ACL '{acl_to_delete['name']}' eliminada exitosamente"
  368. else:
  369. return False, "Error al eliminar ACL modular"
  370. lines = config_manager.config_content.split("\n")
  371. comment_to_remove = None
  372. if target_line > 0 and lines[target_line - 1].strip().startswith("#"):
  373. comment_to_remove = target_line - 1
  374. new_lines = []
  375. for i, line in enumerate(lines):
  376. if i == target_line:
  377. continue
  378. if comment_to_remove is not None and i == comment_to_remove:
  379. continue
  380. new_lines.append(line)
  381. new_content = "\n".join(new_lines)
  382. config_manager.save_config(new_content)
  383. return True, f"ACL '{acl_to_delete['name']}' eliminada exitosamente"
  384. except Exception:
  385. logger.exception("Error eliminando ACL")
  386. return False, "Error interno al eliminar ACL"
  387. def _sanitize_filename(source_url: str) -> str:
  388. """Generate a safe filename from a source URL.
  389. Uses a short hash + a sanitised portion of the URL to keep filenames
  390. unique and human-readable.
  391. """
  392. url_hash = hashlib.sha256(source_url.encode()).hexdigest()[:8]
  393. clean = re.sub(r"[^a-zA-Z0-9_-]", "_", source_url.split("//")[-1])[:60]
  394. return f"{BLOCKLIST_PREFIX}{clean}_{url_hash}.txt"
  395. def _get_blocklists_dir(config_manager) -> str:
  396. """Return (and create if needed) the blocklists subdirectory."""
  397. blocklists_dir = os.path.join(config_manager.config_dir, BLOCKLIST_DIR_NAME)
  398. os.makedirs(blocklists_dir, exist_ok=True)
  399. return blocklists_dir
  400. def _write_domains_file(
  401. filepath: str, domains: list[str], expected_dir: str
  402. ) -> tuple[bool, int]:
  403. """Write a list of domains to a flat file for Squid ``dstdomain``.
  404. Domains are sanitized through :func:`sanitize_domain_list` to ensure
  405. AdGuard/ABP format entries are converted to plain domains.
  406. The function validates that *filepath* resolves inside *expected_dir*,
  407. rejecting path-traversal attempts.
  408. Returns:
  409. ``(success, written_count)`` tuple.
  410. """
  411. try:
  412. # Resolve symlinks / relative components to prevent path traversal
  413. safe_path = os.path.realpath(filepath)
  414. safe_dir = os.path.realpath(expected_dir)
  415. if not safe_path.startswith(safe_dir + os.sep):
  416. logger.error(
  417. "Path traversal blocked: %s is outside %s",
  418. safe_path,
  419. safe_dir,
  420. )
  421. return False, 0
  422. clean = sanitize_domain_list(domains)
  423. if not clean:
  424. logger.warning(
  425. f"No valid domains remaining after sanitization for {safe_path}"
  426. )
  427. return False, 0
  428. with open(safe_path, "w", encoding="utf-8") as f:
  429. f.write("\n".join(clean) + "\n")
  430. return True, len(clean)
  431. except Exception:
  432. logger.exception(f"Error escribiendo archivo de blocklist: {filepath}")
  433. return False, 0
  434. def _remove_old_blocklist_acls(lines: list[str], acl_name: str) -> list[str]:
  435. """Remove existing blocklist ACL lines and their comments for *acl_name*."""
  436. filtered: list[str] = []
  437. for _i, line in enumerate(lines):
  438. stripped = line.strip()
  439. is_blocklist_acl = (
  440. stripped.startswith(f"acl {acl_name} ")
  441. and "dstdomain" in stripped
  442. and BLOCKLIST_PREFIX in stripped
  443. )
  444. if is_blocklist_acl:
  445. # Also remove the comment immediately above if it's ours
  446. if filtered and filtered[-1].strip().startswith("# Blocklist"):
  447. filtered.pop()
  448. continue
  449. filtered.append(line)
  450. return filtered
  451. def _build_acl_lines(
  452. acl_name: str, file_paths: list[tuple[str, str, int]]
  453. ) -> list[str]:
  454. """Build comment + acl directive lines for each blocklist file.
  455. *file_paths* is a list of ``(label, filepath, domain_count)`` tuples.
  456. """
  457. new_lines: list[str] = []
  458. for label, path, count in file_paths:
  459. new_lines.append(f"# Blocklist: {label} ({count} dominios)")
  460. new_lines.append(f'acl {acl_name} dstdomain "{path}"')
  461. return new_lines
  462. @_synchronized_acl_mutation
  463. def add_acl_blocklist(acl_name: str, config_manager) -> tuple[bool, str]:
  464. """Create dstdomain ACLs backed by files with active blacklist domains.
  465. One file is created **per source list** (``source_url``). Domains that
  466. have no ``source_url`` (e.g. custom/manual entries) are grouped into a
  467. single ``blocklist_custom.txt`` file.
  468. In Squid, multiple ``acl`` directives with the same name are merged, so
  469. all files end up being evaluated as a single logical ACL.
  470. Supports both modular (``100_acls.conf``) and monolithic squid.conf.
  471. Args:
  472. acl_name: Name for the ACL (e.g. ``blocklist``).
  473. config_manager: A :class:`SquidConfigManager` instance.
  474. Returns:
  475. ``(success, message)`` tuple.
  476. """
  477. if not acl_name:
  478. return False, "Debe proporcionar un nombre para la ACL de blocklist"
  479. if _is_protected_kerberos_acl(acl_name, config_manager):
  480. return _managed_acl_error(acl_name)
  481. # ------------------------------------------------------------------
  482. # 1. Fetch active domains grouped by source_url
  483. # ------------------------------------------------------------------
  484. session = get_session()
  485. try:
  486. rows = (
  487. session.query(BlacklistDomain.domain, BlacklistDomain.source_url)
  488. .filter(BlacklistDomain.active == 1)
  489. .order_by(BlacklistDomain.source_url, BlacklistDomain.domain)
  490. .all()
  491. )
  492. except Exception:
  493. logger.exception("Error obteniendo dominios de blacklist desde la DB")
  494. return False, "Error al obtener dominios de la base de datos"
  495. finally:
  496. session.close()
  497. if not rows:
  498. return False, "No hay dominios activos en la blacklist para agregar"
  499. # Group domains by source_url (None goes to "custom")
  500. groups: dict[str | None, list[str]] = {}
  501. for domain, source_url in rows:
  502. groups.setdefault(source_url, []).append(domain)
  503. # ------------------------------------------------------------------
  504. # 2. Write one file per source list
  505. # ------------------------------------------------------------------
  506. blocklists_dir = _get_blocklists_dir(config_manager)
  507. # file_info: list of (label, filepath, count) for building ACL lines
  508. file_info: list[tuple[str, str, int]] = []
  509. total_domains = 0
  510. for source_url, domains in groups.items():
  511. if source_url:
  512. filename = _sanitize_filename(source_url)
  513. label = source_url
  514. else:
  515. filename = f"{BLOCKLIST_PREFIX}custom.txt"
  516. label = "custom"
  517. filepath = os.path.join(blocklists_dir, filename)
  518. # Resolve to real path to prevent path traversal
  519. safe_path = os.path.realpath(filepath)
  520. safe_dir = os.path.realpath(blocklists_dir)
  521. if not safe_path.startswith(safe_dir + os.sep) and safe_path != safe_dir:
  522. logger.error("Path traversal blocked for source: %s", label)
  523. return False, f"Nombre de archivo inválido para: {label}"
  524. ok, written_count = _write_domains_file(safe_path, domains, blocklists_dir)
  525. if not ok:
  526. return False, f"Error al escribir archivo de blocklist para: {label}"
  527. file_info.append((label, safe_path, written_count))
  528. total_domains += written_count
  529. logger.info(
  530. f"Blocklist '{label}' escrita en {safe_path} con {written_count} dominios "
  531. f"({len(domains)} entradas originales)"
  532. )
  533. # ------------------------------------------------------------------
  534. # 3. Update Squid config with ACL directives
  535. # ------------------------------------------------------------------
  536. new_acl_lines = _build_acl_lines(acl_name, file_info)
  537. try:
  538. if config_manager.is_modular:
  539. acl_content = config_manager.read_modular_config("100_acls.conf")
  540. if acl_content is not None:
  541. lines = acl_content.split("\n")
  542. lines = _remove_old_blocklist_acls(lines, acl_name)
  543. lines.extend(new_acl_lines)
  544. new_content = "\n".join(lines)
  545. if config_manager.save_modular_config("100_acls.conf", new_content):
  546. return (
  547. True,
  548. f"ACL blocklist '{acl_name}' creada con {total_domains} dominios "
  549. f"en {len(file_info)} lista(s)",
  550. )
  551. else:
  552. return False, "Error al guardar la ACL blocklist en config modular"
  553. # Fallback: monolithic squid.conf
  554. lines = config_manager.config_content.split("\n")
  555. lines = _remove_old_blocklist_acls(lines, acl_name)
  556. acl_section_end = -1
  557. for i, line in enumerate(lines):
  558. if line.strip().startswith("acl "):
  559. acl_section_end = i
  560. if acl_section_end != -1:
  561. for offset, acl_line in enumerate(new_acl_lines):
  562. lines.insert(acl_section_end + 1 + offset, acl_line)
  563. else:
  564. lines.extend(new_acl_lines)
  565. new_content = "\n".join(lines)
  566. config_manager.save_config(new_content)
  567. return (
  568. True,
  569. f"ACL blocklist '{acl_name}' creada con {total_domains} dominios "
  570. f"en {len(file_info)} lista(s)",
  571. )
  572. except Exception:
  573. logger.exception("Error agregando ACL blocklist")
  574. return False, "Error interno al agregar ACL blocklist"
  575. def remove_acl_blocklist(acl_name: str, config_manager) -> tuple[bool, str]:
  576. """Remove all blocklist ACL directives and their domain files.
  577. 1. Remove all ``acl <acl_name> dstdomain …blocklist_…`` lines from Squid
  578. config (modular or monolithic).
  579. 2. Delete every ``blocklist_*.txt`` file from the blocklists directory.
  580. Args:
  581. acl_name: Name of the blocklist ACL to remove.
  582. config_manager: A :class:`SquidConfigManager` instance.
  583. Returns:
  584. ``(success, message)`` tuple.
  585. """
  586. if not acl_name:
  587. return False, "Debe proporcionar el nombre de la ACL de blocklist"
  588. errors: list[str] = []
  589. # ------------------------------------------------------------------
  590. # 1. Remove ACL directives from Squid config
  591. # ------------------------------------------------------------------
  592. try:
  593. if config_manager.is_modular:
  594. acl_content = config_manager.read_modular_config("100_acls.conf")
  595. if acl_content is not None:
  596. lines = acl_content.split("\n")
  597. cleaned = _remove_old_blocklist_acls(lines, acl_name)
  598. new_content = "\n".join(cleaned)
  599. if not config_manager.save_modular_config("100_acls.conf", new_content):
  600. errors.append("Error guardando config modular de ACLs")
  601. # Even if modular, also clean main config as a safety measure
  602. # Clean main config too
  603. lines = config_manager.config_content.split("\n")
  604. cleaned = _remove_old_blocklist_acls(lines, acl_name)
  605. new_content = "\n".join(cleaned)
  606. config_manager.save_config(new_content)
  607. except Exception:
  608. logger.exception("Error eliminando ACLs de blocklist de la config")
  609. errors.append("Error eliminando ACLs de la configuración de Squid")
  610. # ------------------------------------------------------------------
  611. # 2. Delete domain files
  612. # ------------------------------------------------------------------
  613. blocklists_dir = os.path.join(config_manager.config_dir, BLOCKLIST_DIR_NAME)
  614. deleted_files = 0
  615. if os.path.isdir(blocklists_dir):
  616. try:
  617. for fname in os.listdir(blocklists_dir):
  618. if fname.startswith(BLOCKLIST_PREFIX) and fname.endswith(".txt"):
  619. fpath = os.path.join(blocklists_dir, fname)
  620. try:
  621. os.remove(fpath)
  622. deleted_files += 1
  623. except OSError:
  624. logger.exception(f"Error eliminando archivo: {fpath}")
  625. errors.append(f"No se pudo eliminar {fname}")
  626. except OSError:
  627. logger.exception(f"Error listando directorio: {blocklists_dir}")
  628. errors.append("Error leyendo directorio de blocklists")
  629. if errors:
  630. return False, "; ".join(errors)
  631. return (
  632. True,
  633. f"ACL blocklist '{acl_name}' eliminada ({deleted_files} archivo(s) removido(s))",
  634. )