acls_service.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. import hashlib
  2. import os
  3. import re
  4. from loguru import logger
  5. from database.database import get_session
  6. from database.models.models import BlacklistDomain
  7. BLOCKLIST_DIR_NAME = "blocklists"
  8. BLOCKLIST_PREFIX = "blocklist_"
  9. # ---------------------------------------------------------------------------
  10. # Domain validation regex (RFC 1123 compatible)
  11. # ---------------------------------------------------------------------------
  12. _VALID_DOMAIN_RE = re.compile(
  13. r"^(?:[a-z0-9](?:[a-z0-9\-]{0,61}[a-z0-9])?\.)+"
  14. r"[a-z]{2,63}$",
  15. re.IGNORECASE,
  16. )
  17. def sanitize_domain_entry(raw: str) -> str | None:
  18. """Convert a raw blocklist entry to a clean domain for Squid ``dstdomain``.
  19. Handles multiple blocklist formats:
  20. **AdGuard / Adblock Plus (ABP)**:
  21. ``||example.com^`` → ``example.com``
  22. ``||example.com^$third-party`` → ``example.com``
  23. ``@@||example.com^`` → ``None`` (exception / whitelist)
  24. **Hosts file**:
  25. ``0.0.0.0 example.com`` → ``example.com``
  26. ``127.0.0.1 example.com`` → ``example.com``
  27. **Plain domain**:
  28. ``example.com`` → ``example.com``
  29. Lines that are comments, metadata, cosmetic filters, regex rules, or
  30. contain wildcards are skipped (returns ``None``).
  31. Returns:
  32. A clean lowercase domain string, or ``None`` if the line should be
  33. skipped.
  34. """
  35. line = raw.strip()
  36. # Empty or comment lines
  37. if not line or line.startswith(("!", "#", "[", "//")):
  38. return None
  39. # ABP exception rules (whitelist) — skip
  40. if line.startswith("@@"):
  41. return None
  42. # ABP cosmetic / element hiding filters — skip
  43. if "##" in line or "#@#" in line or "#?#" in line:
  44. return None
  45. # ABP/AdGuard domain rules: ||domain.com^ or ||domain.com^$options
  46. if line.startswith("||"):
  47. domain = line[2:] # strip ||
  48. # Remove trailing ^ and anything after it ($options, etc.)
  49. domain = domain.split("^")[0]
  50. # Remove any remaining $ options if no ^ was present
  51. domain = domain.split("$")[0]
  52. domain = domain.strip(".")
  53. else:
  54. # Skip lines with ABP wildcards or regex
  55. if "*" in line or line.startswith("/") or "|" in line:
  56. return None
  57. # Skip lines with $ modifier without || prefix (e.g., advanced ABP rules)
  58. if "$" in line and "=" in line:
  59. return None
  60. # Hosts file format: "0.0.0.0 example.com" or "127.0.0.1 example.com"
  61. if " " in line or "\t" in line:
  62. parts = line.split()
  63. # Take the last non-comment part
  64. domain = None
  65. for part in parts:
  66. if part.startswith("#"):
  67. break
  68. domain = part
  69. if domain is None:
  70. return None
  71. else:
  72. domain = line
  73. # Final cleanup
  74. domain = domain.lower().strip(".")
  75. # Remove port if present (e.g., "example.com:443")
  76. if ":" in domain:
  77. domain = domain.rsplit(":", 1)[0]
  78. # Must look like a valid domain
  79. if not domain or not _VALID_DOMAIN_RE.match(domain):
  80. return None
  81. # Reject IP addresses stored as domains
  82. if re.match(r"^\d{1,3}(\.\d{1,3}){3}$", domain):
  83. return None
  84. return domain
  85. def sanitize_domain_list(raw_domains: list[str]) -> list[str]:
  86. """Sanitize a list of raw domain entries for Squid compatibility.
  87. Applies :func:`sanitize_domain_entry` to each entry and returns only
  88. valid, unique domains in sorted order.
  89. """
  90. seen: set[str] = set()
  91. cleaned: list[str] = []
  92. for raw in raw_domains:
  93. domain = sanitize_domain_entry(raw)
  94. if domain and domain not in seen:
  95. seen.add(domain)
  96. cleaned.append(domain)
  97. cleaned.sort()
  98. return cleaned
  99. def add_acl(
  100. name: str, acl_type: str, values: list, options: list, comment: str, config_manager
  101. ) -> tuple[bool, str]:
  102. if not name or not acl_type or not values:
  103. return False, "Debe proporcionar nombre, tipo y al menos un valor para la ACL"
  104. acl_parts = ["acl", name]
  105. if options:
  106. acl_parts.extend(options)
  107. acl_parts.append(acl_type)
  108. acl_parts.extend(values)
  109. new_acl = " ".join(acl_parts)
  110. try:
  111. if config_manager.is_modular:
  112. acl_content = config_manager.read_modular_config("100_acls.conf")
  113. if acl_content is not None:
  114. lines = acl_content.split("\n")
  115. if comment:
  116. lines.append(f"# {comment}")
  117. lines.append(new_acl)
  118. new_content = "\n".join(lines)
  119. if config_manager.save_modular_config("100_acls.conf", new_content):
  120. return True, f"ACL '{name}' agregada exitosamente"
  121. else:
  122. return False, "Error al guardar la ACL en modular"
  123. # Fallback to main config
  124. lines = config_manager.config_content.split("\n")
  125. acl_section_end = -1
  126. for i, line in enumerate(lines):
  127. if line.strip().startswith("acl "):
  128. acl_section_end = i
  129. if acl_section_end != -1:
  130. if comment:
  131. lines.insert(acl_section_end + 1, f"# {comment}")
  132. lines.insert(acl_section_end + 2, new_acl)
  133. else:
  134. lines.insert(acl_section_end + 1, new_acl)
  135. else:
  136. if comment:
  137. lines.append(f"# {comment}")
  138. lines.append(new_acl)
  139. new_content = "\n".join(lines)
  140. config_manager.save_config(new_content)
  141. return True, f"ACL '{name}' agregada exitosamente"
  142. except Exception:
  143. logger.exception("Error agregando ACL")
  144. return False, "Error interno al agregar ACL"
  145. def edit_acl(
  146. acl_index: int,
  147. new_name: str,
  148. acl_type: str,
  149. values: list,
  150. options: list,
  151. comment: str,
  152. config_manager,
  153. ) -> tuple[bool, str]:
  154. try:
  155. acls = config_manager.get_acls()
  156. if not (0 <= acl_index < len(acls)):
  157. return False, "ACL no encontrada"
  158. target_acl = acls[acl_index]
  159. target_line = target_acl["line_number"] - 1
  160. acl_parts = ["acl", new_name]
  161. if options:
  162. acl_parts.extend(options)
  163. acl_parts.append(acl_type)
  164. acl_parts.extend(values)
  165. new_acl_line = " ".join(acl_parts)
  166. if config_manager.is_modular:
  167. acl_content = config_manager.read_modular_config("100_acls.conf")
  168. if acl_content is not None:
  169. lines = acl_content.split("\n")
  170. if 0 <= target_line < len(lines):
  171. has_comment = target_line > 0 and lines[
  172. target_line - 1
  173. ].strip().startswith("#")
  174. lines[target_line] = new_acl_line
  175. if has_comment:
  176. if comment:
  177. lines[target_line - 1] = f"# {comment}"
  178. else:
  179. lines.pop(target_line - 1)
  180. else:
  181. if comment:
  182. lines.insert(target_line, f"# {comment}")
  183. new_content = "\n".join(lines)
  184. if config_manager.save_modular_config("100_acls.conf", new_content):
  185. return True, f"ACL '{new_name}' actualizada exitosamente"
  186. else:
  187. return False, "Error guardando ACL modular"
  188. # Fallback to main config
  189. lines = config_manager.config_content.split("\n")
  190. if 0 <= target_line < len(lines):
  191. lines[target_line] = new_acl_line
  192. if target_line > 0 and lines[target_line - 1].strip().startswith("#"):
  193. if comment:
  194. lines[target_line - 1] = f"# {comment}"
  195. else:
  196. lines.pop(target_line - 1)
  197. else:
  198. if comment:
  199. lines.insert(target_line, f"# {comment}")
  200. new_content = "\n".join(lines)
  201. config_manager.save_config(new_content)
  202. return True, f"ACL '{new_name}' actualizada exitosamente"
  203. return False, "Línea de ACL no encontrada"
  204. except Exception:
  205. logger.exception("Error editando ACL")
  206. return False, "Error interno al editar ACL"
  207. def delete_acl(acl_index: int, config_manager) -> tuple[bool, str]:
  208. try:
  209. acls = config_manager.get_acls()
  210. if not (0 <= acl_index < len(acls)):
  211. return False, "ACL no encontrada"
  212. acl_to_delete = acls[acl_index]
  213. target_line = acl_to_delete["line_number"] - 1
  214. if config_manager.is_modular:
  215. acl_content = config_manager.read_modular_config("100_acls.conf")
  216. if acl_content is not None:
  217. lines = acl_content.split("\n")
  218. comment_to_remove = None
  219. if target_line > 0 and lines[target_line - 1].strip().startswith("#"):
  220. comment_to_remove = target_line - 1
  221. new_lines = []
  222. for i, line in enumerate(lines):
  223. if i == target_line:
  224. continue
  225. if comment_to_remove is not None and i == comment_to_remove:
  226. continue
  227. new_lines.append(line)
  228. new_content = "\n".join(new_lines)
  229. if config_manager.save_modular_config("100_acls.conf", new_content):
  230. return True, f"ACL '{acl_to_delete['name']}' eliminada exitosamente"
  231. else:
  232. return False, "Error al eliminar ACL modular"
  233. lines = config_manager.config_content.split("\n")
  234. comment_to_remove = None
  235. if target_line > 0 and lines[target_line - 1].strip().startswith("#"):
  236. comment_to_remove = target_line - 1
  237. new_lines = []
  238. for i, line in enumerate(lines):
  239. if i == target_line:
  240. continue
  241. if comment_to_remove is not None and i == comment_to_remove:
  242. continue
  243. new_lines.append(line)
  244. new_content = "\n".join(new_lines)
  245. config_manager.save_config(new_content)
  246. return True, f"ACL '{acl_to_delete['name']}' eliminada exitosamente"
  247. except Exception:
  248. logger.exception("Error eliminando ACL")
  249. return False, "Error interno al eliminar ACL"
  250. def _sanitize_filename(source_url: str) -> str:
  251. """Generate a safe filename from a source URL.
  252. Uses a short hash + a sanitised portion of the URL to keep filenames
  253. unique and human-readable.
  254. """
  255. url_hash = hashlib.sha256(source_url.encode()).hexdigest()[:8]
  256. clean = re.sub(r"[^a-zA-Z0-9_-]", "_", source_url.split("//")[-1])[:60]
  257. return f"{BLOCKLIST_PREFIX}{clean}_{url_hash}.txt"
  258. def _get_blocklists_dir(config_manager) -> str:
  259. """Return (and create if needed) the blocklists subdirectory."""
  260. blocklists_dir = os.path.join(config_manager.config_dir, BLOCKLIST_DIR_NAME)
  261. os.makedirs(blocklists_dir, exist_ok=True)
  262. return blocklists_dir
  263. def _write_domains_file(
  264. filepath: str, domains: list[str], expected_dir: str
  265. ) -> tuple[bool, int]:
  266. """Write a list of domains to a flat file for Squid ``dstdomain``.
  267. Domains are sanitized through :func:`sanitize_domain_list` to ensure
  268. AdGuard/ABP format entries are converted to plain domains.
  269. The function validates that *filepath* resolves inside *expected_dir*,
  270. rejecting path-traversal attempts.
  271. Returns:
  272. ``(success, written_count)`` tuple.
  273. """
  274. try:
  275. # Resolve symlinks / relative components to prevent path traversal
  276. safe_path = os.path.realpath(filepath)
  277. safe_dir = os.path.realpath(expected_dir)
  278. if not safe_path.startswith(safe_dir + os.sep):
  279. logger.error(
  280. "Path traversal blocked: %s is outside %s",
  281. safe_path,
  282. safe_dir,
  283. )
  284. return False, 0
  285. clean = sanitize_domain_list(domains)
  286. if not clean:
  287. logger.warning(
  288. f"No valid domains remaining after sanitization for {safe_path}"
  289. )
  290. return False, 0
  291. with open(safe_path, "w", encoding="utf-8") as f:
  292. f.write("\n".join(clean) + "\n")
  293. return True, len(clean)
  294. except Exception:
  295. logger.exception(f"Error escribiendo archivo de blocklist: {filepath}")
  296. return False, 0
  297. def _remove_old_blocklist_acls(lines: list[str], acl_name: str) -> list[str]:
  298. """Remove existing blocklist ACL lines and their comments for *acl_name*."""
  299. filtered: list[str] = []
  300. for _i, line in enumerate(lines):
  301. stripped = line.strip()
  302. is_blocklist_acl = (
  303. stripped.startswith(f"acl {acl_name} ")
  304. and "dstdomain" in stripped
  305. and BLOCKLIST_PREFIX in stripped
  306. )
  307. if is_blocklist_acl:
  308. # Also remove the comment immediately above if it's ours
  309. if filtered and filtered[-1].strip().startswith("# Blocklist"):
  310. filtered.pop()
  311. continue
  312. filtered.append(line)
  313. return filtered
  314. def _build_acl_lines(
  315. acl_name: str, file_paths: list[tuple[str, str, int]]
  316. ) -> list[str]:
  317. """Build comment + acl directive lines for each blocklist file.
  318. *file_paths* is a list of ``(label, filepath, domain_count)`` tuples.
  319. """
  320. new_lines: list[str] = []
  321. for label, path, count in file_paths:
  322. new_lines.append(f"# Blocklist: {label} ({count} dominios)")
  323. new_lines.append(f'acl {acl_name} dstdomain "{path}"')
  324. return new_lines
  325. def add_acl_blocklist(acl_name: str, config_manager) -> tuple[bool, str]:
  326. """Create dstdomain ACLs backed by files with active blacklist domains.
  327. One file is created **per source list** (``source_url``). Domains that
  328. have no ``source_url`` (e.g. custom/manual entries) are grouped into a
  329. single ``blocklist_custom.txt`` file.
  330. In Squid, multiple ``acl`` directives with the same name are merged, so
  331. all files end up being evaluated as a single logical ACL.
  332. Supports both modular (``100_acls.conf``) and monolithic squid.conf.
  333. Args:
  334. acl_name: Name for the ACL (e.g. ``blocklist``).
  335. config_manager: A :class:`SquidConfigManager` instance.
  336. Returns:
  337. ``(success, message)`` tuple.
  338. """
  339. if not acl_name:
  340. return False, "Debe proporcionar un nombre para la ACL de blocklist"
  341. # ------------------------------------------------------------------
  342. # 1. Fetch active domains grouped by source_url
  343. # ------------------------------------------------------------------
  344. session = get_session()
  345. try:
  346. rows = (
  347. session.query(BlacklistDomain.domain, BlacklistDomain.source_url)
  348. .filter(BlacklistDomain.active == 1)
  349. .order_by(BlacklistDomain.source_url, BlacklistDomain.domain)
  350. .all()
  351. )
  352. except Exception:
  353. logger.exception("Error obteniendo dominios de blacklist desde la DB")
  354. return False, "Error al obtener dominios de la base de datos"
  355. finally:
  356. session.close()
  357. if not rows:
  358. return False, "No hay dominios activos en la blacklist para agregar"
  359. # Group domains by source_url (None goes to "custom")
  360. groups: dict[str | None, list[str]] = {}
  361. for domain, source_url in rows:
  362. groups.setdefault(source_url, []).append(domain)
  363. # ------------------------------------------------------------------
  364. # 2. Write one file per source list
  365. # ------------------------------------------------------------------
  366. blocklists_dir = _get_blocklists_dir(config_manager)
  367. # file_info: list of (label, filepath, count) for building ACL lines
  368. file_info: list[tuple[str, str, int]] = []
  369. total_domains = 0
  370. for source_url, domains in groups.items():
  371. if source_url:
  372. filename = _sanitize_filename(source_url)
  373. label = source_url
  374. else:
  375. filename = f"{BLOCKLIST_PREFIX}custom.txt"
  376. label = "custom"
  377. filepath = os.path.join(blocklists_dir, filename)
  378. # Resolve to real path to prevent path traversal
  379. safe_path = os.path.realpath(filepath)
  380. safe_dir = os.path.realpath(blocklists_dir)
  381. if not safe_path.startswith(safe_dir + os.sep) and safe_path != safe_dir:
  382. logger.error("Path traversal blocked for source: %s", label)
  383. return False, f"Nombre de archivo inválido para: {label}"
  384. ok, written_count = _write_domains_file(safe_path, domains, blocklists_dir)
  385. if not ok:
  386. return False, f"Error al escribir archivo de blocklist para: {label}"
  387. file_info.append((label, safe_path, written_count))
  388. total_domains += written_count
  389. logger.info(
  390. f"Blocklist '{label}' escrita en {safe_path} con {written_count} dominios "
  391. f"({len(domains)} entradas originales)"
  392. )
  393. # ------------------------------------------------------------------
  394. # 3. Update Squid config with ACL directives
  395. # ------------------------------------------------------------------
  396. new_acl_lines = _build_acl_lines(acl_name, file_info)
  397. try:
  398. if config_manager.is_modular:
  399. acl_content = config_manager.read_modular_config("100_acls.conf")
  400. if acl_content is not None:
  401. lines = acl_content.split("\n")
  402. lines = _remove_old_blocklist_acls(lines, acl_name)
  403. lines.extend(new_acl_lines)
  404. new_content = "\n".join(lines)
  405. if config_manager.save_modular_config("100_acls.conf", new_content):
  406. return (
  407. True,
  408. f"ACL blocklist '{acl_name}' creada con {total_domains} dominios "
  409. f"en {len(file_info)} lista(s)",
  410. )
  411. else:
  412. return False, "Error al guardar la ACL blocklist en config modular"
  413. # Fallback: monolithic squid.conf
  414. lines = config_manager.config_content.split("\n")
  415. lines = _remove_old_blocklist_acls(lines, acl_name)
  416. acl_section_end = -1
  417. for i, line in enumerate(lines):
  418. if line.strip().startswith("acl "):
  419. acl_section_end = i
  420. if acl_section_end != -1:
  421. for offset, acl_line in enumerate(new_acl_lines):
  422. lines.insert(acl_section_end + 1 + offset, acl_line)
  423. else:
  424. lines.extend(new_acl_lines)
  425. new_content = "\n".join(lines)
  426. config_manager.save_config(new_content)
  427. return (
  428. True,
  429. f"ACL blocklist '{acl_name}' creada con {total_domains} dominios "
  430. f"en {len(file_info)} lista(s)",
  431. )
  432. except Exception:
  433. logger.exception("Error agregando ACL blocklist")
  434. return False, "Error interno al agregar ACL blocklist"
  435. def remove_acl_blocklist(acl_name: str, config_manager) -> tuple[bool, str]:
  436. """Remove all blocklist ACL directives and their domain files.
  437. 1. Remove all ``acl <acl_name> dstdomain …blocklist_…`` lines from Squid
  438. config (modular or monolithic).
  439. 2. Delete every ``blocklist_*.txt`` file from the blocklists directory.
  440. Args:
  441. acl_name: Name of the blocklist ACL to remove.
  442. config_manager: A :class:`SquidConfigManager` instance.
  443. Returns:
  444. ``(success, message)`` tuple.
  445. """
  446. if not acl_name:
  447. return False, "Debe proporcionar el nombre de la ACL de blocklist"
  448. errors: list[str] = []
  449. # ------------------------------------------------------------------
  450. # 1. Remove ACL directives from Squid config
  451. # ------------------------------------------------------------------
  452. try:
  453. if config_manager.is_modular:
  454. acl_content = config_manager.read_modular_config("100_acls.conf")
  455. if acl_content is not None:
  456. lines = acl_content.split("\n")
  457. cleaned = _remove_old_blocklist_acls(lines, acl_name)
  458. new_content = "\n".join(cleaned)
  459. if not config_manager.save_modular_config("100_acls.conf", new_content):
  460. errors.append("Error guardando config modular de ACLs")
  461. # Even if modular, also clean main config as a safety measure
  462. # Clean main config too
  463. lines = config_manager.config_content.split("\n")
  464. cleaned = _remove_old_blocklist_acls(lines, acl_name)
  465. new_content = "\n".join(cleaned)
  466. config_manager.save_config(new_content)
  467. except Exception:
  468. logger.exception("Error eliminando ACLs de blocklist de la config")
  469. errors.append("Error eliminando ACLs de la configuración de Squid")
  470. # ------------------------------------------------------------------
  471. # 2. Delete domain files
  472. # ------------------------------------------------------------------
  473. blocklists_dir = os.path.join(config_manager.config_dir, BLOCKLIST_DIR_NAME)
  474. deleted_files = 0
  475. if os.path.isdir(blocklists_dir):
  476. try:
  477. for fname in os.listdir(blocklists_dir):
  478. if fname.startswith(BLOCKLIST_PREFIX) and fname.endswith(".txt"):
  479. fpath = os.path.join(blocklists_dir, fname)
  480. try:
  481. os.remove(fpath)
  482. deleted_files += 1
  483. except OSError:
  484. logger.exception(f"Error eliminando archivo: {fpath}")
  485. errors.append(f"No se pudo eliminar {fname}")
  486. except OSError:
  487. logger.exception(f"Error listando directorio: {blocklists_dir}")
  488. errors.append("Error leyendo directorio de blocklists")
  489. if errors:
  490. return False, "; ".join(errors)
  491. return (
  492. True,
  493. f"ACL blocklist '{acl_name}' eliminada ({deleted_files} archivo(s) removido(s))",
  494. )