user_restrictions_service.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. """
  2. User restrictions service.
  3. Provides block/unblock and throttle/unthrottle operations for active proxy
  4. users. Each operation persists to the database and updates the corresponding
  5. Squid config file so that the restriction survives restarts.
  6. Block mechanism:
  7. - Writes active blocked IPs to: <config_dir>/squidstats_restrictions/squidstats_blocked_ips.txt
  8. - ACL: acl squidstats_blocked src "<file>"
  9. - HTTP access: http_access deny squidstats_blocked (inserted before first allow)
  10. Throttle mechanism (per delay pool):
  11. - Writes active throttled IPs to: <config_dir>/squidstats_restrictions/squidstats_throttle_pool_<N>.txt
  12. - ACL: acl squidstats_throttle_<N> src "<file>"
  13. - Delay access: delay_access <N> allow squidstats_throttle_<N> (inserted before deny all)
  14. """
  15. import ipaddress
  16. import os
  17. import re
  18. from loguru import logger
  19. from database.models.models import BlockedUser, ThrottledUser
  20. from services.squid.http_access_service import (
  21. add_http_deny_blocklist,
  22. remove_http_deny_blocklist,
  23. )
  24. # ---------------------------------------------------------------------------
  25. # Constants
  26. # ---------------------------------------------------------------------------
  27. BLOCKED_ACL_NAME = "squidstats_blocked"
  28. BLOCKED_IPS_FILENAME = "squidstats_blocked_ips.txt"
  29. THROTTLE_ACL_PREFIX = "squidstats_throttle_"
  30. THROTTLE_IPS_PREFIX = "squidstats_throttle_pool_"
  31. RESTRICTIONS_DIR_NAME = "squidstats_restrictions"
  32. # Allowed filename pattern for restrictions files (path traversal prevention)
  33. _SAFE_FILENAME_RE = re.compile(r"^squidstats_[a-z0-9_]+\.txt$")
  34. # ---------------------------------------------------------------------------
  35. # Helpers
  36. # ---------------------------------------------------------------------------
  37. def _validate_ip(ip: str) -> bool:
  38. """Return True only if *ip* is a valid IPv4 or IPv6 address."""
  39. if not ip or len(ip) > 45:
  40. return False
  41. try:
  42. ipaddress.ip_address(ip)
  43. return True
  44. except ValueError:
  45. return False
  46. def _validate_filename(filename: str) -> bool:
  47. return bool(_SAFE_FILENAME_RE.fullmatch(filename))
  48. def _get_restrictions_dir(cm) -> str:
  49. """Return (and create if needed) the restrictions subdirectory."""
  50. restrictions_dir = os.path.join(cm.config_dir, RESTRICTIONS_DIR_NAME)
  51. os.makedirs(restrictions_dir, exist_ok=True)
  52. return restrictions_dir
  53. def _safe_path(directory: str, filename: str) -> str | None:
  54. """Resolve path under directory, rejecting traversal attempts."""
  55. if not _validate_filename(filename):
  56. logger.error("Invalid restrictions filename: %s", filename)
  57. return None
  58. safe_dir = os.path.realpath(directory)
  59. candidate = os.path.realpath(os.path.join(directory, filename))
  60. if not candidate.startswith(safe_dir + os.sep):
  61. logger.error("Path traversal blocked: %s is outside %s", candidate, safe_dir)
  62. return None
  63. return candidate
  64. def _write_ip_file(filepath: str, ips: list[str], expected_dir: str) -> bool:
  65. """Write a list of IPs to a flat file (one per line), with path-traversal protection."""
  66. safe_dir = os.path.realpath(expected_dir)
  67. safe_path = os.path.realpath(filepath)
  68. if not safe_path.startswith(safe_dir + os.sep):
  69. logger.error("Path traversal blocked writing IP file: %s", filepath)
  70. return False
  71. try:
  72. with open(safe_path, "w", encoding="utf-8") as f:
  73. for ip in ips:
  74. f.write(ip + "\n")
  75. return True
  76. except Exception:
  77. logger.exception("Error writing IP file: %s", filepath)
  78. return False
  79. def _blocked_ips_filepath(cm) -> str:
  80. return os.path.join(_get_restrictions_dir(cm), BLOCKED_IPS_FILENAME)
  81. def _throttled_ips_filepath(cm, pool_number: int) -> str:
  82. return os.path.join(
  83. _get_restrictions_dir(cm), f"{THROTTLE_IPS_PREFIX}{pool_number}.txt"
  84. )
  85. # ---------------------------------------------------------------------------
  86. # ACL helpers
  87. # ---------------------------------------------------------------------------
  88. def _find_acl_insert_index(lines: list[str]) -> int:
  89. """Return the index where a new ACL should be inserted.
  90. Prefer inserting after the last existing ACL block.
  91. If no ACLs exist, insert before the first access/delay rule.
  92. Otherwise append to the end.
  93. """
  94. last_acl_idx = -1
  95. first_access_idx = len(lines)
  96. for i, line in enumerate(lines):
  97. stripped = line.strip()
  98. if stripped.startswith("acl "):
  99. last_acl_idx = i
  100. elif (
  101. stripped.startswith("http_access ") or stripped.startswith("delay_access ")
  102. ) and first_access_idx == len(lines):
  103. first_access_idx = i
  104. if last_acl_idx != -1:
  105. return last_acl_idx + 1
  106. return first_access_idx
  107. def _add_acl_src_file(acl_name: str, filepath: str, cm) -> bool:
  108. """Add `acl <acl_name> src "<filepath>"` idempotently."""
  109. acl_line = f'acl {acl_name} src "{filepath}"'
  110. comment = f"# SquidStats managed: {acl_name}"
  111. try:
  112. if cm.is_modular:
  113. content = cm.read_modular_config("100_acls.conf")
  114. if content is not None:
  115. if acl_line in content:
  116. return True
  117. lines = content.split("\n")
  118. lines.append(comment)
  119. lines.append(acl_line)
  120. return bool(cm.save_modular_config("100_acls.conf", "\n".join(lines)))
  121. if acl_line in cm.config_content:
  122. return True
  123. lines = cm.config_content.split("\n")
  124. insert_idx = _find_acl_insert_index(lines)
  125. lines.insert(insert_idx, comment)
  126. lines.insert(insert_idx + 1, acl_line)
  127. return bool(cm.save_config("\n".join(lines)))
  128. except Exception:
  129. logger.exception("Error adding ACL src: %s", acl_name)
  130. return False
  131. def _remove_acl_src(acl_name: str, cm) -> bool:
  132. """Remove the ACL src directive for *acl_name*."""
  133. comment = f"# SquidStats managed: {acl_name}"
  134. try:
  135. if cm.is_modular:
  136. content = cm.read_modular_config("100_acls.conf")
  137. if content is not None:
  138. lines = content.split("\n")
  139. new_lines = _filter_acl_lines(lines, acl_name, comment)
  140. return bool(
  141. cm.save_modular_config("100_acls.conf", "\n".join(new_lines))
  142. )
  143. lines = cm.config_content.split("\n")
  144. new_lines = _filter_acl_lines(lines, acl_name, comment)
  145. return bool(cm.save_config("\n".join(new_lines)))
  146. except Exception:
  147. logger.exception("Error removing ACL src: %s", acl_name)
  148. return False
  149. def _filter_acl_lines(lines: list[str], acl_name: str, comment: str) -> list[str]:
  150. """Strip the ACL line and its preceding comment from *lines*."""
  151. result = []
  152. skip_comment = False
  153. for line in lines:
  154. stripped = line.strip()
  155. if stripped == comment:
  156. skip_comment = True
  157. continue
  158. if skip_comment and stripped.startswith(f"acl {acl_name} src"):
  159. skip_comment = False
  160. continue
  161. skip_comment = False
  162. result.append(line)
  163. return result
  164. # ---------------------------------------------------------------------------
  165. # Delay-access helpers
  166. # ---------------------------------------------------------------------------
  167. def _add_delay_access(pool_number: int, acl_name: str, cm) -> bool:
  168. """Add `delay_access <N> allow <acl_name>` before any existing deny all for pool N."""
  169. rule = f"delay_access {pool_number} allow {acl_name}"
  170. deny_all = f"delay_access {pool_number} deny all"
  171. comment = f"# SquidStats managed: throttle pool {pool_number}"
  172. try:
  173. if cm.is_modular:
  174. content = cm.read_modular_config("110_delay_pools.conf")
  175. if content is not None:
  176. if rule in content:
  177. return True
  178. lines = content.split("\n")
  179. insert_idx = _find_delay_insert_index(lines, pool_number, deny_all)
  180. lines.insert(insert_idx, rule)
  181. lines.insert(insert_idx, comment)
  182. return bool(
  183. cm.save_modular_config("110_delay_pools.conf", "\n".join(lines))
  184. )
  185. if rule in cm.config_content:
  186. return True
  187. lines = cm.config_content.split("\n")
  188. insert_idx = _find_delay_insert_index(lines, pool_number, deny_all)
  189. lines.insert(insert_idx, rule)
  190. lines.insert(insert_idx, comment)
  191. return bool(cm.save_config("\n".join(lines)))
  192. except Exception:
  193. logger.exception("Error adding delay_access for pool %s", pool_number)
  194. return False
  195. def _find_delay_insert_index(lines: list[str], pool_number: int, deny_all: str) -> int:
  196. """Find the index to insert the new delay_access rule.
  197. Prefers inserting before the pool's existing `deny all`.
  198. Falls back to inserting after the pool's `delay_parameters` line.
  199. Falls back to end of file.
  200. """
  201. after_params = len(lines)
  202. for i, line in enumerate(lines):
  203. stripped = line.strip()
  204. if stripped == deny_all:
  205. return i
  206. if stripped.startswith(
  207. f"delay_parameters {pool_number} "
  208. ) and after_params == len(lines):
  209. after_params = i + 1
  210. return after_params
  211. # ---------------------------------------------------------------------------
  212. # Sync helpers (file reconstruction from DB)
  213. # ---------------------------------------------------------------------------
  214. def _sync_blocked_file(db, cm) -> bool:
  215. active_ips = [r.ip for r in db.query(BlockedUser).filter_by(active=1).all()]
  216. filepath = _blocked_ips_filepath(cm)
  217. restrictions_dir = _get_restrictions_dir(cm)
  218. return _write_ip_file(filepath, active_ips, restrictions_dir)
  219. def _sync_throttled_file(db, cm, pool_number: int) -> bool:
  220. active_ips = [
  221. r.ip
  222. for r in db.query(ThrottledUser)
  223. .filter_by(pool_number=pool_number, active=1)
  224. .all()
  225. ]
  226. filepath = _throttled_ips_filepath(cm, pool_number)
  227. restrictions_dir = _get_restrictions_dir(cm)
  228. return _write_ip_file(filepath, active_ips, restrictions_dir)
  229. def _cleanup_blocked_rules_if_empty(db, cm) -> None:
  230. """Remove SquidStats blocklist rules when no active blocked IPs remain."""
  231. active_blocked = db.query(BlockedUser).filter_by(active=1).count()
  232. if active_blocked == 0:
  233. _remove_acl_src(BLOCKED_ACL_NAME, cm)
  234. remove_http_deny_blocklist(BLOCKED_ACL_NAME, cm)
  235. # ---------------------------------------------------------------------------
  236. # Public API: Block / Unblock
  237. # ---------------------------------------------------------------------------
  238. def block_user(username: str, ip: str, db, cm) -> tuple[bool, str]:
  239. """Block *ip* in Squid and persist to DB.
  240. Idempotent ACL/http_access additions ensure the Squid directives are
  241. only written once regardless of how many users are blocked.
  242. """
  243. if not _validate_ip(ip):
  244. return False, "Dirección IP inválida"
  245. existing = db.query(BlockedUser).filter_by(ip=ip, active=1).first()
  246. if existing:
  247. return False, f"La IP {ip} ya está bloqueada"
  248. record = BlockedUser(username=username, ip=ip, active=1)
  249. try:
  250. db.add(record)
  251. db.commit()
  252. except Exception:
  253. db.rollback()
  254. logger.exception("Error saving BlockedUser to DB")
  255. return False, "Error al guardar en la base de datos"
  256. if not _sync_blocked_file(db, cm):
  257. db.delete(record)
  258. db.commit()
  259. return False, "Error al escribir el archivo de IPs bloqueadas"
  260. filepath = _blocked_ips_filepath(cm)
  261. if not _add_acl_src_file(BLOCKED_ACL_NAME, filepath, cm):
  262. logger.warning("Could not add squidstats_blocked ACL; DB entry saved")
  263. if not add_http_deny_blocklist(BLOCKED_ACL_NAME, cm):
  264. logger.warning(
  265. "Could not add http_access deny squidstats_blocked; DB entry saved"
  266. )
  267. return True, f"Usuario {username} ({ip}) bloqueado"
  268. def unblock_user(username: str, ip: str, db, cm) -> tuple[bool, str]:
  269. """Remove the block for *ip*."""
  270. if not _validate_ip(ip):
  271. return False, "Dirección IP inválida"
  272. record = db.query(BlockedUser).filter_by(ip=ip, active=1).first()
  273. if not record:
  274. return False, f"No se encontró bloqueo activo para IP {ip}"
  275. record.active = 0
  276. try:
  277. db.commit()
  278. except Exception:
  279. db.rollback()
  280. logger.exception("Error updating BlockedUser in DB")
  281. return False, "Error al actualizar la base de datos"
  282. _sync_blocked_file(db, cm)
  283. _cleanup_blocked_rules_if_empty(db, cm)
  284. return True, f"Usuario {username} ({ip}) desbloqueado"
  285. # ---------------------------------------------------------------------------
  286. # Public API: Throttle / Unthrottle
  287. # ---------------------------------------------------------------------------
  288. def throttle_user(username: str, ip: str, pool_number: int, db, cm) -> tuple[bool, str]:
  289. """Assign *ip* to *pool_number* to apply bandwidth throttling.
  290. Requires the delay pool to already exist in the Squid configuration.
  291. """
  292. if not _validate_ip(ip):
  293. return False, "Dirección IP inválida"
  294. pools = cm.get_delay_pools()
  295. pool_numbers = {int(p["pool_number"]) for p in pools if "pool_number" in p}
  296. if pool_number not in pool_numbers:
  297. return False, f"El delay pool #{pool_number} no existe en la configuración"
  298. existing = db.query(ThrottledUser).filter_by(ip=ip, active=1).first()
  299. if existing:
  300. return (
  301. False,
  302. f"La IP {ip} ya tiene velocidad reducida (pool #{existing.pool_number})",
  303. )
  304. record = ThrottledUser(username=username, ip=ip, pool_number=pool_number, active=1)
  305. try:
  306. db.add(record)
  307. db.commit()
  308. except Exception:
  309. db.rollback()
  310. logger.exception("Error saving ThrottledUser to DB")
  311. return False, "Error al guardar en la base de datos"
  312. if not _sync_throttled_file(db, cm, pool_number):
  313. db.delete(record)
  314. db.commit()
  315. return False, "Error al escribir el archivo de IPs con velocidad reducida"
  316. acl_name = f"{THROTTLE_ACL_PREFIX}{pool_number}"
  317. filepath = _throttled_ips_filepath(cm, pool_number)
  318. if not _add_acl_src_file(acl_name, filepath, cm):
  319. logger.warning("Could not add throttle ACL; DB entry saved")
  320. if not _add_delay_access(pool_number, acl_name, cm):
  321. logger.warning("Could not add delay_access rule; DB entry saved")
  322. return True, f"Velocidad reducida para {username} ({ip}) en pool #{pool_number}"
  323. def unthrottle_user(username: str, ip: str, db, cm) -> tuple[bool, str]:
  324. """Remove the throttle for *ip*."""
  325. if not _validate_ip(ip):
  326. return False, "Dirección IP inválida"
  327. record = db.query(ThrottledUser).filter_by(ip=ip, active=1).first()
  328. if not record:
  329. return False, f"No se encontró throttle activo para IP {ip}"
  330. pool_number = record.pool_number
  331. record.active = 0
  332. try:
  333. db.commit()
  334. except Exception:
  335. db.rollback()
  336. logger.exception("Error updating ThrottledUser in DB")
  337. return False, "Error al actualizar la base de datos"
  338. _sync_throttled_file(db, cm, pool_number)
  339. return True, f"Velocidad restaurada para {username} ({ip})"
  340. # ---------------------------------------------------------------------------
  341. # Startup sync
  342. # ---------------------------------------------------------------------------
  343. def sync_restrictions(db, cm) -> None:
  344. """Rebuild restriction files from DB on startup.
  345. Ensures Squid config ACLs and files are consistent with DB records even
  346. after a server restart or manual file deletion.
  347. """
  348. # Blocked users
  349. _sync_blocked_file(db, cm)
  350. active_blocked = db.query(BlockedUser).filter_by(active=1).count()
  351. if active_blocked > 0:
  352. filepath = _blocked_ips_filepath(cm)
  353. _add_acl_src_file(BLOCKED_ACL_NAME, filepath, cm)
  354. add_http_deny_blocklist(BLOCKED_ACL_NAME, cm)
  355. else:
  356. _remove_acl_src(BLOCKED_ACL_NAME, cm)
  357. remove_http_deny_blocklist(BLOCKED_ACL_NAME, cm)
  358. # Throttled users (per pool)
  359. rows = db.query(ThrottledUser.pool_number).filter_by(active=1).distinct().all()
  360. for (pool_number,) in rows:
  361. _sync_throttled_file(db, cm, pool_number)
  362. acl_name = f"{THROTTLE_ACL_PREFIX}{pool_number}"
  363. filepath = _throttled_ips_filepath(cm, pool_number)
  364. _add_acl_src_file(acl_name, filepath, cm)
  365. _add_delay_access(pool_number, acl_name, cm)
  366. logger.info("User restrictions synchronized to Squid config")
  367. # ---------------------------------------------------------------------------
  368. # Status queries
  369. # ---------------------------------------------------------------------------
  370. def get_user_status(ip: str, db) -> dict:
  371. """Return current block/throttle status for *ip*."""
  372. blocked = db.query(BlockedUser).filter_by(ip=ip, active=1).first()
  373. throttled = db.query(ThrottledUser).filter_by(ip=ip, active=1).first()
  374. return {
  375. "ip": ip,
  376. "blocked": blocked is not None,
  377. "throttled": throttled is not None,
  378. "pool_number": throttled.pool_number if throttled else None,
  379. }