blocklist_enforcement.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. """
  2. Blocklist enforcement service.
  3. Contains all business logic for enabling/disabling Squid blocklists,
  4. including file management, ACL manipulation, URL validation, and
  5. enforcement state queries. Previously these were private helpers
  6. inside the admin blueprint.
  7. """
  8. import hashlib
  9. import os
  10. import re
  11. import stat
  12. from urllib.parse import urlparse
  13. from loguru import logger
  14. from database.database import get_session
  15. from database.models.models import BlacklistDomain
  16. from services.squid.acls_service import (
  17. BLOCKLIST_PREFIX,
  18. _get_blocklists_dir,
  19. _sanitize_filename,
  20. _write_domains_file,
  21. )
  22. from services.squid.http_access_service import (
  23. add_http_deny_blocklist,
  24. remove_http_deny_blocklist,
  25. )
  26. # ---------------------------------------------------------------------------
  27. # Constants
  28. # ---------------------------------------------------------------------------
  29. BLOCKLIST_ACL_NAME = "squidstats_blocklist"
  30. # ---------------------------------------------------------------------------
  31. # URL / filename validation helpers
  32. # ---------------------------------------------------------------------------
  33. def validate_source_url(source_url: str | None) -> bool:
  34. """Validate that *source_url* is a well-formed URL.
  35. ``None`` is allowed (represents the custom/manual list).
  36. """
  37. if not source_url:
  38. return True
  39. parsed = urlparse(source_url)
  40. if not (parsed.scheme and parsed.netloc):
  41. return False
  42. if ".." in source_url or source_url.startswith("/") or "\\" in source_url:
  43. return False
  44. if any(c in source_url for c in ["\x00", "\n", "\r", "\t"]):
  45. return False
  46. if len(source_url) > 2048:
  47. return False
  48. return True
  49. def is_allowed_blocklist_filename(filename: str) -> bool:
  50. """Allow only expected generated blocklist filenames."""
  51. if not filename:
  52. return False
  53. if os.path.basename(filename) != filename:
  54. return False
  55. if "/" in filename or "\\" in filename or ".." in filename:
  56. return False
  57. pattern = rf"^{re.escape(BLOCKLIST_PREFIX)}(?:custom|[a-f0-9]{{64}})\.txt$"
  58. return bool(re.fullmatch(pattern, filename))
  59. def build_blocklist_filename(source_url: str | None) -> str:
  60. """Build a deterministic safe filename for a blocklist source URL."""
  61. if source_url is None:
  62. filename = f"{BLOCKLIST_PREFIX}custom.txt"
  63. else:
  64. if not validate_source_url(source_url):
  65. raise ValueError("Invalid source URL")
  66. digest = hashlib.sha256(source_url.encode("utf-8")).hexdigest().lower()
  67. filename = f"{BLOCKLIST_PREFIX}{digest}.txt"
  68. if not is_allowed_blocklist_filename(filename):
  69. raise ValueError("Invalid blocklist filename")
  70. return filename
  71. def resolve_safe_blocklist_path(base_dir: str, filename: str) -> str | None:
  72. """Resolve and validate a blocklist file path to prevent path traversal.
  73. Returns the safe path or ``None`` if traversal is detected.
  74. """
  75. if not is_allowed_blocklist_filename(filename):
  76. return None
  77. base_dir = os.path.realpath(base_dir)
  78. candidate = os.path.realpath(os.path.join(base_dir, filename))
  79. try:
  80. if os.path.commonpath([base_dir, candidate]) != base_dir:
  81. return None
  82. except ValueError:
  83. return None
  84. return candidate
  85. # ---------------------------------------------------------------------------
  86. # Enforcement state queries
  87. # ---------------------------------------------------------------------------
  88. def get_enforced_blocklist_urls(cm) -> set[str]:
  89. """Return the set of source_url values currently enforced as Squid ACLs.
  90. Custom lists are represented by the sentinel ``__custom__``.
  91. """
  92. enforced: set[str] = set()
  93. content = _read_acl_content(cm)
  94. if not content:
  95. return enforced
  96. url_to_filename = _build_url_to_filename_map()
  97. for line in content.split("\n"):
  98. stripped = line.strip()
  99. if not _is_blocklist_acl_line(stripped):
  100. continue
  101. start = stripped.find('"')
  102. end = stripped.rfind('"')
  103. if start != -1 and end > start:
  104. filepath = stripped[start + 1 : end]
  105. fname = os.path.basename(filepath)
  106. if fname == f"{BLOCKLIST_PREFIX}custom.txt":
  107. enforced.add("__custom__")
  108. else:
  109. source_url = url_to_filename.get(fname)
  110. if source_url:
  111. enforced.add(source_url)
  112. return enforced
  113. def get_enforced_blocklist_paths(cm) -> dict[str, str]:
  114. """Return validated enforced blocklist paths keyed by filename."""
  115. enforced_paths: dict[str, str] = {}
  116. blocklists_dir = _get_blocklists_dir(cm)
  117. content = _read_acl_content(cm)
  118. if not content:
  119. return enforced_paths
  120. for line in content.split("\n"):
  121. stripped = line.strip()
  122. if not _is_blocklist_acl_line(stripped):
  123. continue
  124. match = re.search(r"""dstdomain\s+["']([^"']+)["']""", stripped)
  125. if not match:
  126. continue
  127. filepath = match.group(1)
  128. filename = os.path.basename(filepath)
  129. safe_path = resolve_safe_blocklist_path(blocklists_dir, filename)
  130. if safe_path:
  131. enforced_paths[filename] = safe_path
  132. return enforced_paths
  133. # ---------------------------------------------------------------------------
  134. # Enable / disable single blocklist
  135. # ---------------------------------------------------------------------------
  136. def enable_single_blocklist(source_url: str | None, cm) -> tuple[bool, str]:
  137. """Enable Squid enforcement for a single blocklist (by source_url).
  138. Writes the domain file, adds the ACL directive, and ensures the
  139. ``http_access deny`` rule exists.
  140. """
  141. if source_url is not None and not validate_source_url(source_url):
  142. return False, "URL de fuente inválida"
  143. label = source_url if source_url else "custom"
  144. domains = _fetch_domains_for_source(source_url)
  145. if domains is None:
  146. return False, "Error al consultar dominios"
  147. if not domains:
  148. return False, f"No hay dominios activos para '{label}'"
  149. try:
  150. filename = build_blocklist_filename(source_url)
  151. except ValueError:
  152. return False, "URL de fuente inválida"
  153. blocklists_dir = _get_blocklists_dir(cm)
  154. safe_path = resolve_safe_blocklist_path(blocklists_dir, filename)
  155. if not safe_path:
  156. logger.error("Path traversal blocked for source: %s", label)
  157. return False, f"Nombre de archivo inválido para: '{label}'"
  158. ok, written_count = _write_domains_file(safe_path, domains, blocklists_dir)
  159. if not ok:
  160. return False, f"Error escribiendo archivo para '{label}'"
  161. acl_line = f'acl {BLOCKLIST_ACL_NAME} dstdomain "{safe_path}"'
  162. comment_line = f"# Blocklist: {label} ({written_count} dominios)"
  163. try:
  164. _upsert_acl_line(cm, acl_line, comment_line)
  165. except Exception:
  166. logger.exception("Error agregando ACL para blocklist individual")
  167. return False, "Error al agregar ACL"
  168. ok, msg = add_http_deny_blocklist(BLOCKLIST_ACL_NAME, cm)
  169. if not ok:
  170. return False, msg
  171. return True, f"Blocklist '{label}' activada con {len(domains)} dominios"
  172. def disable_single_blocklist(source_url: str | None, cm) -> tuple[bool, str]:
  173. """Disable Squid enforcement for a single blocklist.
  174. Removes the ACL line, deletes the domain file, and if no blocklist
  175. ACLs remain, removes the ``http_access deny`` rule.
  176. """
  177. if source_url is not None:
  178. if not isinstance(source_url, str):
  179. return False, "Formato de URL inválido"
  180. if not validate_source_url(source_url):
  181. return False, "URL de fuente inválida"
  182. label = source_url if source_url else "custom"
  183. try:
  184. candidate_filename = build_blocklist_filename(source_url)
  185. except ValueError:
  186. return False, "URL de fuente inválida"
  187. enforced_paths = get_enforced_blocklist_paths(cm)
  188. safe_path = enforced_paths.get(candidate_filename)
  189. if not safe_path:
  190. return False, f"Blocklist '{label}' no está activada"
  191. acl_line = f'acl {BLOCKLIST_ACL_NAME} dstdomain "{safe_path}"'
  192. try:
  193. _remove_acl_line(cm, acl_line)
  194. except Exception:
  195. logger.exception("Error eliminando ACL de blocklist individual")
  196. return False, "Error al eliminar ACL"
  197. if os.path.isfile(safe_path):
  198. try:
  199. st = os.lstat(safe_path)
  200. if not stat.S_ISREG(st.st_mode):
  201. logger.error(f"Archivo no regular: {safe_path}")
  202. return False, "Archivo no regular"
  203. os.remove(safe_path)
  204. except OSError:
  205. logger.exception(f"Error eliminando archivo: {safe_path}")
  206. remaining = get_enforced_blocklist_urls(cm)
  207. if not remaining:
  208. remove_http_deny_blocklist(BLOCKLIST_ACL_NAME, cm)
  209. return True, f"Blocklist '{label}' desactivada"
  210. # ---------------------------------------------------------------------------
  211. # Internal helpers
  212. # ---------------------------------------------------------------------------
  213. def _read_acl_content(cm) -> str | None:
  214. """Read ACL content respecting modular vs monolithic config."""
  215. if cm.is_modular:
  216. return cm.read_modular_config("100_acls.conf")
  217. return cm.config_content
  218. def _is_blocklist_acl_line(stripped: str) -> bool:
  219. """Check if a stripped config line is a blocklist ACL directive."""
  220. return (
  221. stripped.startswith(f"acl {BLOCKLIST_ACL_NAME} ")
  222. and "dstdomain" in stripped
  223. and BLOCKLIST_PREFIX in stripped
  224. )
  225. def _build_url_to_filename_map() -> dict[str, str]:
  226. """Pre-fetch all source URLs from DB and map filenames -> source_url."""
  227. session = get_session()
  228. try:
  229. url_to_filename: dict[str, str] = {}
  230. urls = (
  231. session.query(BlacklistDomain.source_url)
  232. .filter(BlacklistDomain.source_url.isnot(None))
  233. .distinct()
  234. .all()
  235. )
  236. for (url,) in urls:
  237. try:
  238. url_to_filename[build_blocklist_filename(url)] = url
  239. except ValueError:
  240. logger.warning("Skipping invalid blacklist source_url in DB mapping")
  241. url_to_filename[_sanitize_filename(url)] = url
  242. return url_to_filename
  243. finally:
  244. session.close()
  245. def _fetch_domains_for_source(source_url: str | None) -> list[str] | None:
  246. """Query active domains for a given source_url (or custom if None)."""
  247. session = get_session()
  248. try:
  249. if source_url:
  250. rows = (
  251. session.query(BlacklistDomain.domain)
  252. .filter(
  253. BlacklistDomain.active == 1,
  254. BlacklistDomain.source_url == source_url,
  255. )
  256. .order_by(BlacklistDomain.domain)
  257. .all()
  258. )
  259. else:
  260. rows = (
  261. session.query(BlacklistDomain.domain)
  262. .filter(
  263. BlacklistDomain.active == 1,
  264. BlacklistDomain.source_url.is_(None),
  265. )
  266. .order_by(BlacklistDomain.domain)
  267. .all()
  268. )
  269. return [d[0] for d in rows]
  270. except Exception:
  271. logger.exception("Error consultando dominios para activar blocklist")
  272. return None
  273. finally:
  274. session.close()
  275. def _upsert_acl_line(cm, acl_line: str, comment_line: str):
  276. """Add or replace a blocklist ACL line in config (modular or monolithic)."""
  277. if cm.is_modular:
  278. acl_content = cm.read_modular_config("100_acls.conf")
  279. if acl_content is None:
  280. raise RuntimeError("No se pudo leer la config modular")
  281. lines = _filter_acl_lines(acl_content.split("\n"), acl_line, comment_line)
  282. lines.append(comment_line)
  283. lines.append(acl_line)
  284. if not cm.save_modular_config("100_acls.conf", "\n".join(lines)):
  285. raise RuntimeError("Error guardando ACL en config modular")
  286. else:
  287. lines = _filter_acl_lines(cm.config_content.split("\n"), acl_line, comment_line)
  288. acl_section_end = -1
  289. for i, line in enumerate(lines):
  290. if line.strip().startswith("acl "):
  291. acl_section_end = i
  292. if acl_section_end != -1:
  293. lines.insert(acl_section_end + 1, comment_line)
  294. lines.insert(acl_section_end + 2, acl_line)
  295. else:
  296. lines.append(comment_line)
  297. lines.append(acl_line)
  298. cm.save_config("\n".join(lines))
  299. def _remove_acl_line(cm, acl_line: str):
  300. """Remove a blocklist ACL line from config (modular or monolithic)."""
  301. if cm.is_modular:
  302. acl_content = cm.read_modular_config("100_acls.conf")
  303. if acl_content is not None:
  304. new_lines = _strip_acl_and_comment(acl_content.split("\n"), acl_line)
  305. cm.save_modular_config("100_acls.conf", "\n".join(new_lines))
  306. # In modular mode squid.conf contains only include directives generated
  307. # by SquidConfigSplitter — never write raw config content into it.
  308. return
  309. lines = cm.config_content.split("\n")
  310. new_lines = _strip_acl_and_comment(lines, acl_line)
  311. cm.save_config("\n".join(new_lines))
  312. def _filter_acl_lines(lines: list[str], acl_line: str, comment_line: str) -> list[str]:
  313. """Remove existing occurrences of an ACL line and its comment."""
  314. lines = [
  315. ln
  316. for ln in lines
  317. if not (ln.strip() == acl_line or ln.strip() == acl_line.replace('"', "'"))
  318. ]
  319. lines = [ln for ln in lines if not ln.strip() == comment_line]
  320. return lines
  321. def _strip_acl_and_comment(lines: list[str], acl_line: str) -> list[str]:
  322. """Strip an ACL line and the ``# Blocklist:`` comment above it."""
  323. new_lines: list[str] = []
  324. for ln in lines:
  325. stripped = ln.strip()
  326. if stripped == acl_line or stripped == acl_line.replace('"', "'"):
  327. if new_lines and new_lines[-1].strip().startswith("# Blocklist:"):
  328. new_lines.pop()
  329. continue
  330. new_lines.append(ln)
  331. return new_lines