admin.py 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237
  1. import fcntl
  2. import glob
  3. import os
  4. import re
  5. import shutil
  6. import tempfile
  7. import threading
  8. from contextlib import contextmanager
  9. from datetime import datetime
  10. from dotenv import load_dotenv
  11. from loguru import logger
  12. from config import Config
  13. from utils.custom_types import ACL_TYPES_INFO, PREDEFINED_ACLS
  14. load_dotenv()
  15. SQUID_CONFIG_PATH = Config.SQUID_CONFIG_PATH or "/etc/squid/squid.conf"
  16. ACL_FILES_DIR = Config.ACL_FILES_DIR or os.path.join(
  17. os.path.dirname(SQUID_CONFIG_PATH), "squid.d", ""
  18. )
  19. FALLBACK_SQUID_CONFIG_PATH = "/etc/squid/squid.conf"
  20. FALLBACK_ACL_FILES_DIRS = ["/etc/squid/acls", "/etc/squid/squid.d"]
  21. # All Squid configuration writers use this lock file for the short interval
  22. # between comparing a loaded snapshot and atomically replacing a file. The
  23. # in-process RLock avoids self-deadlock when a multi-file transaction invokes
  24. # ``save_config``/``save_modular_config`` while it already owns the lock; the
  25. # advisory flock coordinates separate web/scheduler worker processes.
  26. _SQUID_WRITE_LOCKS_GUARD = threading.Lock()
  27. _SQUID_WRITE_LOCKS: dict[str, threading.RLock] = {}
  28. _SQUID_WRITE_LOCK_STATE = threading.local()
  29. @contextmanager
  30. def squid_config_write_lock(config_path: str = SQUID_CONFIG_PATH):
  31. """Serialize Squid configuration read-modify-write transactions.
  32. The lock is held on the real configuration directory, which keeps it
  33. shared by app/scheduler processes using the same Squid configuration
  34. volume without creating a file that could be picked up by a wildcard
  35. ``include``. A process that cannot read that directory cannot safely
  36. inspect and replace the configuration, so failure is intentionally
  37. fail-closed.
  38. """
  39. effective_config_path = config_path
  40. if config_path == SQUID_CONFIG_PATH:
  41. effective_config_path, _unused_config_dir = _normalize_squid_paths(
  42. SQUID_CONFIG_PATH, ACL_FILES_DIR
  43. )
  44. lock_key = os.path.dirname(
  45. os.path.realpath(os.path.abspath(effective_config_path))
  46. )
  47. held = getattr(_SQUID_WRITE_LOCK_STATE, "held", None)
  48. if held is None:
  49. held = {}
  50. _SQUID_WRITE_LOCK_STATE.held = held
  51. existing = held.get(lock_key)
  52. if existing is not None:
  53. existing["depth"] += 1
  54. try:
  55. yield
  56. finally:
  57. existing["depth"] -= 1
  58. return
  59. with _SQUID_WRITE_LOCKS_GUARD:
  60. thread_lock = _SQUID_WRITE_LOCKS.setdefault(lock_key, threading.RLock())
  61. thread_lock.acquire()
  62. file_descriptor: int | None = None
  63. try:
  64. flags = os.O_RDONLY
  65. if hasattr(os, "O_DIRECTORY"):
  66. flags |= os.O_DIRECTORY
  67. file_descriptor = os.open(lock_key, flags)
  68. fcntl.flock(file_descriptor, fcntl.LOCK_EX)
  69. held[lock_key] = {"descriptor": file_descriptor, "depth": 1}
  70. yield
  71. finally:
  72. current = held.get(lock_key)
  73. if current is not None:
  74. held.pop(lock_key, None)
  75. try:
  76. fcntl.flock(current["descriptor"], fcntl.LOCK_UN)
  77. finally:
  78. os.close(current["descriptor"])
  79. elif file_descriptor is not None:
  80. os.close(file_descriptor)
  81. thread_lock.release()
  82. def _normalize_squid_paths(config_path: str, config_dir: str) -> tuple[str, str]:
  83. """Return effective Squid config and ACL directory paths.
  84. If configured paths do not exist, but the standard /etc/squid paths do,
  85. prefer a recognized fallback so the app can work in both container and
  86. older host environments.
  87. """
  88. config_path = os.path.abspath(os.path.expanduser(config_path))
  89. config_dir = os.path.abspath(os.path.expanduser(config_dir))
  90. if not os.path.exists(config_path) and config_path != FALLBACK_SQUID_CONFIG_PATH:
  91. if os.path.exists(FALLBACK_SQUID_CONFIG_PATH):
  92. config_path = FALLBACK_SQUID_CONFIG_PATH
  93. if not os.path.exists(config_dir):
  94. for fallback_dir in FALLBACK_ACL_FILES_DIRS:
  95. if os.path.exists(fallback_dir):
  96. config_dir = fallback_dir
  97. break
  98. return config_path, config_dir
  99. def _replacement_ownership(
  100. previous_metadata, *, warn: bool = True
  101. ) -> tuple[int, int]:
  102. """Return ownership that an atomic replacement can safely restore.
  103. An unprivileged service may replace a configuration file through a
  104. directory ACL even when that file is owned by root. It cannot restore
  105. root ownership afterwards. It can, however, retain a group to which it
  106. belongs, which preserves a common ``root:proxy 0640`` arrangement. Do
  107. not replace a non-world-readable file if neither guarantee is available:
  108. Squid could lose access to its configuration after an otherwise valid
  109. write.
  110. """
  111. effective_uid = os.geteuid()
  112. effective_gid = os.getegid()
  113. if effective_uid == 0:
  114. return previous_metadata.st_uid, previous_metadata.st_gid
  115. effective_groups = {effective_gid, *os.getgroups()}
  116. target_group = previous_metadata.st_gid
  117. if target_group not in effective_groups:
  118. if not (previous_metadata.st_mode & 0o004):
  119. raise PermissionError(
  120. "No se puede conservar el grupo de un squid.conf no legible "
  121. "globalmente; usa un grupo accesible para SquidStats o un "
  122. "mecanismo de administración privilegiado."
  123. )
  124. if warn:
  125. logger.warning(
  126. "Replacing Squid configuration without its original group because "
  127. "it is world-readable"
  128. )
  129. return -1, -1
  130. if warn and previous_metadata.st_uid != effective_uid:
  131. logger.warning(
  132. "Replacing root-owned Squid configuration as an unprivileged user; "
  133. "the replacement will be owned by the service account",
  134. )
  135. return -1, target_group if target_group != effective_gid else -1
  136. def can_atomically_replace_file(path: str) -> bool:
  137. """Whether this process can safely use :meth:`_atomic_write` for *path*.
  138. Replacing a file atomically needs write *and* search permission on the
  139. resolved parent directory. Testing only ``os.access(file, W_OK)`` is both
  140. misleading (a directory ACL can be sufficient) and misses a later
  141. ``NamedTemporaryFile``/``os.replace`` failure. Metadata preservation is
  142. checked here as well so the preflight does not promise a write that would
  143. make a protected Squid config unreadable.
  144. """
  145. try:
  146. target = os.path.realpath(os.path.abspath(path))
  147. directory = os.path.dirname(target)
  148. if not os.path.isfile(target) or not os.access(target, os.R_OK):
  149. return False
  150. if not os.access(directory, os.W_OK | os.X_OK):
  151. return False
  152. _replacement_ownership(os.stat(target), warn=False)
  153. except (OSError, PermissionError):
  154. return False
  155. return True
  156. def _join_continuation_lines(content: str) -> str:
  157. """Join lines ending with a backslash with the following line."""
  158. lines = content.splitlines()
  159. result = []
  160. i = 0
  161. while i < len(lines):
  162. line = lines[i]
  163. while line.rstrip().endswith("\\"):
  164. line = line.rstrip()[:-1]
  165. i += 1
  166. if i < len(lines):
  167. line += " " + lines[i].strip()
  168. result.append(line)
  169. i += 1
  170. return "\n".join(result)
  171. def validate_paths(
  172. config_path: str = SQUID_CONFIG_PATH, config_dir: str = ACL_FILES_DIR
  173. ):
  174. """Validate the squid.conf path (hard errors) and the ACL directory (warnings only).
  175. Returns a list of *hard* error strings that block SquidConfigManager
  176. initialization. Missing or inaccessible ACL directories are logged as
  177. warnings but do NOT appear in the returned list — they only disable
  178. modular-config support.
  179. """
  180. errors = []
  181. cfg = os.path.abspath(os.path.expanduser(config_path))
  182. if os.path.isdir(cfg):
  183. squid_conf = os.path.join(cfg, "squid.conf")
  184. if not os.path.exists(squid_conf):
  185. errors.append(f"'squid.conf' not found in directory: {cfg}")
  186. else:
  187. if not os.path.isfile(squid_conf):
  188. errors.append(f"Found but not a regular file: {squid_conf}")
  189. else:
  190. if not os.access(squid_conf, os.R_OK):
  191. errors.append(f"No read permissions for: {squid_conf}")
  192. if not can_atomically_replace_file(squid_conf):
  193. errors.append(
  194. "No safe atomic write permissions for Squid configuration: "
  195. f"{squid_conf}"
  196. )
  197. else:
  198. squid_conf = cfg
  199. if not os.path.exists(squid_conf):
  200. errors.append(f"Configuration file not found: {squid_conf}")
  201. else:
  202. if not os.path.isfile(squid_conf):
  203. errors.append(f"Not a regular file: {squid_conf}")
  204. if os.path.basename(squid_conf) != "squid.conf":
  205. errors.append(
  206. f"Expected file named 'squid.conf', got: {os.path.basename(squid_conf)}"
  207. )
  208. if os.path.isfile(squid_conf):
  209. if not os.access(squid_conf, os.R_OK):
  210. errors.append(f"No read permissions for: {squid_conf}")
  211. if not can_atomically_replace_file(squid_conf):
  212. errors.append(
  213. "No safe atomic write permissions for Squid configuration: "
  214. f"{squid_conf}"
  215. )
  216. # ACL / modular-config directory — warnings only, never a hard error
  217. _, acl_dir = _normalize_squid_paths(config_path, config_dir)
  218. if not os.path.exists(acl_dir):
  219. logger.warning(
  220. f"ACL/modular config directory not found: {acl_dir} — "
  221. "modular configuration will be disabled."
  222. )
  223. elif not os.path.isdir(acl_dir):
  224. logger.warning(f"ACL path is not a directory: {acl_dir}")
  225. elif not os.access(acl_dir, os.W_OK | os.X_OK):
  226. logger.warning(f"No write permissions in ACL directory: {acl_dir}")
  227. return errors
  228. class SquidConfigManager:
  229. def __init__(self, config_path=SQUID_CONFIG_PATH, config_dir=ACL_FILES_DIR):
  230. self.config_path, self.config_dir = _normalize_squid_paths(
  231. config_path, config_dir
  232. )
  233. self.config_content = ""
  234. self._modular_content_snapshots: dict[str, str | None] = {}
  235. self.is_valid = False
  236. self.errors = []
  237. self.is_modular = False # Flag to check if using modular configs
  238. self._validate_environment()
  239. if self.is_valid:
  240. self.load_config()
  241. self._check_modular_config()
  242. def _validate_environment(self):
  243. self.errors = validate_paths(self.config_path, self.config_dir)
  244. if self.errors:
  245. for error in self.errors:
  246. logger.error(error)
  247. self.is_valid = False
  248. logger.error(
  249. "SquidConfigManager cannot be initialized due to configuration errors"
  250. )
  251. else:
  252. self.is_valid = True
  253. logger.info("SquidConfigManager initialized successfully")
  254. def _cleanup_modular_backups(self, filepath: str, suffix: str = ".bak"):
  255. """Remove old backups for a modular config file, keeping only the newest one."""
  256. base = os.path.basename(filepath)
  257. directory = os.path.dirname(filepath)
  258. prefix = base + suffix
  259. try:
  260. backups = sorted(
  261. f for f in os.listdir(directory) if f.startswith(prefix) and f != base
  262. )
  263. # Remove all but the last (newest) backup
  264. for old in backups[:-1]:
  265. try:
  266. os.remove(os.path.join(directory, old))
  267. logger.debug(f"Removed old backup: {old}")
  268. except Exception as e:
  269. logger.warning(f"Could not remove old backup {old}: {e}")
  270. except Exception as e:
  271. logger.warning(f"Error cleaning up backups for {base}: {e}")
  272. def load_config(self):
  273. if not self.is_valid:
  274. logger.error("Cannot load configuration: invalid environment")
  275. return False
  276. try:
  277. with open(self.config_path, encoding="utf-8") as f:
  278. self.config_content = f.read()
  279. logger.debug(f"Configuration loaded from: {self.config_path}")
  280. return True
  281. except FileNotFoundError:
  282. logger.error(f"Configuration file not found: {self.config_path}")
  283. self.config_content = ""
  284. return False
  285. except PermissionError:
  286. logger.error(f"No read permissions for: {self.config_path}")
  287. self.config_content = ""
  288. return False
  289. except UnicodeDecodeError as e:
  290. logger.error(f"File encoding error: {e}")
  291. self.config_content = ""
  292. return False
  293. except Exception as e:
  294. logger.error(f"Unexpected error loading configuration: {e}")
  295. self.config_content = ""
  296. return False
  297. @staticmethod
  298. def _atomic_write(path: str, content: str, encoding: str = "utf-8") -> None:
  299. """Write *content* to *path* atomically: write to a temp file then os.replace.
  300. Using open(path, 'w') truncates the file immediately; if the process is
  301. interrupted mid-write squid.conf ends up empty/corrupt. Writing to a
  302. temporary file in the same directory and calling os.replace() is atomic
  303. on POSIX — the destination is either the old file or the new file, never
  304. a partial write.
  305. """
  306. # Replace the resolved target rather than a symlink itself. Squid
  307. # packages sometimes expose squid.conf through a symlink; replacing
  308. # that link would leave the daemon reading a different file after the
  309. # next restart.
  310. abs_path = os.path.realpath(os.path.abspath(path))
  311. dir_name = os.path.dirname(abs_path)
  312. tmp_path = None
  313. try:
  314. previous_metadata = os.stat(abs_path)
  315. except FileNotFoundError:
  316. previous_metadata = None
  317. try:
  318. with tempfile.NamedTemporaryFile(
  319. mode="w",
  320. encoding=encoding,
  321. dir=dir_name,
  322. delete=False,
  323. suffix=".squidstats.tmp",
  324. ) as tmp:
  325. tmp.write(content)
  326. tmp_path = tmp.name
  327. if previous_metadata is not None:
  328. # ``NamedTemporaryFile`` starts at 0600 and belongs to
  329. # SquidStats. Replacing a config file with it without
  330. # restoring metadata can make Squid unable to read its
  331. # own configuration after a successful-looking update.
  332. restore_uid, restore_gid = _replacement_ownership(
  333. previous_metadata
  334. )
  335. if restore_uid != -1 or restore_gid != -1:
  336. os.fchown(
  337. tmp.fileno(),
  338. restore_uid,
  339. restore_gid,
  340. )
  341. # Copy mode and supported ACL/xattr metadata after the
  342. # ownership change. This is important for installations
  343. # that grant the Squid account access with a POSIX ACL.
  344. shutil.copystat(abs_path, tmp_path, follow_symlinks=False)
  345. else:
  346. # Generated .conf modules contain no keytab material;
  347. # make them readable by Squid even when the web process
  348. # and Squid do not share a primary group. Existing files
  349. # keep their stricter administrator-selected mode above.
  350. os.fchmod(tmp.fileno(), 0o644)
  351. os.replace(tmp_path, abs_path)
  352. except Exception:
  353. if tmp_path and os.path.exists(tmp_path):
  354. try:
  355. os.unlink(tmp_path)
  356. except Exception as cleanup_err:
  357. logger.warning(
  358. "Could not remove temporary file %s: %s", tmp_path, cleanup_err
  359. )
  360. raise
  361. def save_config(self, content):
  362. if not self.is_valid:
  363. logger.error("Cannot save configuration: invalid environment")
  364. return False
  365. # Guard: never blank squid.conf — an empty file would bring down Squid
  366. if not content or not content.strip():
  367. logger.error(
  368. "Refusing to save empty/whitespace-only content to squid.conf: "
  369. "this would disable the Squid proxy"
  370. )
  371. return False
  372. try:
  373. with squid_config_write_lock(self.config_path):
  374. # Skip write if content hasn't changed. This deliberately
  375. # does not overwrite a newer on-disk version merely to make a
  376. # stale manager's snapshot current again.
  377. if self.config_content == content:
  378. logger.debug("Main config unchanged, skipping write")
  379. return True
  380. with open(self.config_path, encoding="utf-8") as current_file:
  381. current_content = current_file.read()
  382. if current_content != self.config_content:
  383. logger.warning(
  384. "Refusing stale write to squid.conf; reload the configuration and retry"
  385. )
  386. return False
  387. backup_created = self.create_backup()
  388. if not backup_created:
  389. logger.warning("Could not create backup, but continuing with save...")
  390. self._atomic_write(self.config_path, content)
  391. self.config_content = content
  392. logger.info(f"Configuration saved successfully to: {self.config_path}")
  393. return True
  394. except PermissionError:
  395. logger.error(f"No write permissions for: {self.config_path}")
  396. return False
  397. except OSError as e:
  398. logger.error(f"System error saving configuration: {e}")
  399. return False
  400. except Exception as e:
  401. logger.error(f"Unexpected error saving configuration: {e}")
  402. return False
  403. def create_backup(self):
  404. if not self.is_valid:
  405. logger.error("Cannot create backup: invalid environment")
  406. return False
  407. try:
  408. backup_path = f"{self.config_path}.bak"
  409. shutil.copy2(self.config_path, backup_path)
  410. logger.info(f"Backup created: {backup_path}")
  411. return True
  412. except FileNotFoundError:
  413. logger.warning(f"Config file not found for backup: {self.config_path}")
  414. return False
  415. except PermissionError:
  416. logger.error(f"No permission to create backup for: {self.config_path}")
  417. return False
  418. except Exception as e:
  419. logger.error(f"Unexpected error creating backup: {e}")
  420. return False
  421. def get_acls(self):
  422. """
  423. Parse ACL definitions with enhanced information.
  424. Returns a list of ACL dictionaries with full details.
  425. Format:
  426. {
  427. 'id': 0,
  428. 'name': 'localnet',
  429. 'type': 'src',
  430. 'options': ['-i'], # ACL options like -i, -n, -m
  431. 'values': ['10.0.0.0/8', '192.168.0.0/16'], # List of values
  432. 'value_string': '10.0.0.0/8 192.168.0.0/16', # Original value string
  433. 'is_predefined': False, # True for Squid predefined ACLs
  434. 'is_slow': False, # True for slow ACL types
  435. 'category': 'network', # Category: network, time, auth, content, ssl, etc.
  436. 'description': 'RFC 1918 private networks', # Human-readable description
  437. 'line_number': 5
  438. }
  439. """
  440. if not self.is_valid:
  441. logger.error("Cannot get ACLs: invalid environment")
  442. return []
  443. # If using modular config, read from the ACLs specific file
  444. if self.is_modular:
  445. acl_content = self.read_modular_config("100_acls.conf")
  446. if not acl_content:
  447. logger.warning(
  448. "Could not read modular ACL config, falling back to main config"
  449. )
  450. config_to_parse = self.config_content
  451. else:
  452. config_to_parse = acl_content
  453. else:
  454. if not self.config_content:
  455. logger.warning("No configuration content available")
  456. return []
  457. config_to_parse = self.config_content
  458. try:
  459. acls = []
  460. lines = config_to_parse.split("\n")
  461. acl_index = 0
  462. predefined_acls = PREDEFINED_ACLS
  463. # ACL type metadata
  464. acl_types_info = ACL_TYPES_INFO
  465. last_comment = ""
  466. for line_num, line in enumerate(lines, 1):
  467. try:
  468. stripped = line.strip()
  469. # Track comments for context
  470. if stripped.startswith("#"):
  471. last_comment = stripped[1:].strip()
  472. continue
  473. if stripped.startswith("acl "):
  474. parts = stripped.split()
  475. if len(parts) >= 3:
  476. acl_name = parts[1]
  477. # Parse options and type
  478. options = []
  479. type_index = 2
  480. while type_index < len(parts) and parts[
  481. type_index
  482. ].startswith("-"):
  483. options.append(parts[type_index])
  484. type_index += 1
  485. if type_index >= len(parts):
  486. continue
  487. acl_type = parts[type_index]
  488. values = (
  489. parts[type_index + 1 :]
  490. if len(parts) > type_index + 1
  491. else []
  492. )
  493. value_string = " ".join(values)
  494. # Get type metadata
  495. type_info = acl_types_info.get(
  496. acl_type,
  497. {
  498. "category": "other",
  499. "slow": False,
  500. "desc": "Custom ACL type",
  501. },
  502. )
  503. # Check if predefined
  504. is_predefined = acl_name in predefined_acls
  505. acls.append(
  506. {
  507. "id": acl_index,
  508. "name": acl_name,
  509. "type": acl_type,
  510. "options": options,
  511. "value_list": values,
  512. "value_string": value_string,
  513. "is_predefined": is_predefined,
  514. "is_slow": type_info.get("slow", False),
  515. "category": type_info.get("category", "other"),
  516. "type_description": type_info.get("desc", ""),
  517. "comment": last_comment if last_comment else "",
  518. "line_number": line_num,
  519. "full_line": stripped,
  520. }
  521. )
  522. acl_index += 1
  523. last_comment = ""
  524. except Exception as e:
  525. logger.warning(f"Error processing ACL at line {line_num}: {e}")
  526. continue
  527. logger.debug(f"Found {len(acls)} ACLs")
  528. return acls
  529. except Exception as e:
  530. logger.error(f"Unexpected error extracting ACLs: {e}")
  531. return []
  532. def get_delay_pools(self):
  533. """
  534. Parse delay pools configuration and group by pool number.
  535. Returns a list of pool dictionaries with all related directives.
  536. Format:
  537. {
  538. 'pool_number': '1',
  539. 'class': '3',
  540. 'parameters': '8192/131072 1024/65536 256/32768',
  541. 'access_rules': [{'action': 'allow', 'acl': 'students'}]
  542. }
  543. """
  544. if not self.is_valid:
  545. logger.error("Cannot get delay pools: invalid environment")
  546. return []
  547. # If using modular config, read from the delay pools specific file
  548. if self.is_modular:
  549. delay_content = self.read_modular_config("110_delay_pools.conf")
  550. if not delay_content:
  551. logger.warning(
  552. "Could not read modular delay pools config, falling back to main config"
  553. )
  554. config_to_parse = self.config_content
  555. else:
  556. config_to_parse = delay_content
  557. else:
  558. if not self.config_content:
  559. logger.warning("No configuration content available")
  560. return []
  561. config_to_parse = self.config_content
  562. try:
  563. pools_dict = {} # Dictionary to group by pool number
  564. # total_pools = 0
  565. lines = config_to_parse.split("\n")
  566. for line_num, line in enumerate(lines, 1):
  567. try:
  568. line = line.strip()
  569. if line.startswith("delay_pools "):
  570. pass
  571. # parts = line.split()
  572. # if len(parts) >= 2:
  573. # total_pools = int(parts[1])
  574. elif line.startswith("delay_class "):
  575. parts = line.split()
  576. if len(parts) >= 3:
  577. pool_num = parts[1]
  578. if pool_num not in pools_dict:
  579. pools_dict[pool_num] = {
  580. "pool_number": pool_num,
  581. "class": parts[2],
  582. "parameters": None,
  583. "access_rules": [],
  584. }
  585. else:
  586. pools_dict[pool_num]["class"] = parts[2]
  587. elif line.startswith("delay_parameters "):
  588. parts = line.split()
  589. if len(parts) >= 3:
  590. pool_num = parts[1]
  591. if pool_num not in pools_dict:
  592. pools_dict[pool_num] = {
  593. "pool_number": pool_num,
  594. "class": None,
  595. "parameters": " ".join(parts[2:]),
  596. "access_rules": [],
  597. }
  598. else:
  599. pools_dict[pool_num]["parameters"] = " ".join(parts[2:])
  600. elif line.startswith("delay_access "):
  601. parts = line.split()
  602. if len(parts) >= 4:
  603. pool_num = parts[1]
  604. if pool_num not in pools_dict:
  605. pools_dict[pool_num] = {
  606. "pool_number": pool_num,
  607. "class": None,
  608. "parameters": None,
  609. "access_rules": [],
  610. }
  611. pools_dict[pool_num]["access_rules"].append(
  612. {"action": parts[2], "acl": " ".join(parts[3:])}
  613. )
  614. except Exception as e:
  615. logger.warning(
  616. f"Error processing delay pool at line {line_num}: {e}"
  617. )
  618. continue
  619. # Convert dictionary to sorted list
  620. delay_pools = [
  621. pools_dict[key] for key in sorted(pools_dict.keys(), key=int)
  622. ]
  623. # logger.debug(
  624. # f"Found {len(delay_pools)} delay pool configurations (total_pools={total_pools})"
  625. # )
  626. return delay_pools
  627. except Exception as e:
  628. logger.error(f"Unexpected error extracting delay pools: {e}")
  629. return []
  630. def get_http_access_rules(self):
  631. """
  632. Parse http_access rules with enhanced information.
  633. Returns a list of rule dictionaries with action, acls (list), and metadata.
  634. Format:
  635. {
  636. 'action': 'allow',
  637. 'acls': ['!Safe_ports'], # List of ACLs including negations
  638. 'acl_string': '!Safe_ports', # Original ACL string
  639. 'is_negative': True, # If it contains negation
  640. 'line_number': 5, # Original line number
  641. 'description': '' # Optional description from comments
  642. }
  643. """
  644. if not self.is_valid:
  645. logger.error("Cannot get HTTP rules: invalid environment")
  646. return []
  647. # If using modular config, read from the http_access specific file
  648. if self.is_modular:
  649. http_content = self.read_modular_config("120_http_access.conf")
  650. if not http_content:
  651. logger.warning(
  652. "Could not read modular http_access config, falling back to main config"
  653. )
  654. config_to_parse = self.config_content
  655. else:
  656. config_to_parse = http_content
  657. else:
  658. if not self.config_content:
  659. logger.warning("No configuration content available")
  660. return []
  661. config_to_parse = self.config_content
  662. try:
  663. rules = []
  664. lines = config_to_parse.split("\n")
  665. last_comment = ""
  666. for line_num, line in enumerate(lines, 1):
  667. try:
  668. stripped = line.strip()
  669. # Track comments for context
  670. if stripped.startswith("#"):
  671. last_comment = stripped[1:].strip()
  672. continue
  673. if stripped.startswith("http_access "):
  674. parts = stripped.split()
  675. if len(parts) >= 3:
  676. action = parts[1]
  677. acl_string = " ".join(parts[2:])
  678. acls = parts[2:]
  679. # Check if any ACL has negation
  680. is_negative = any(acl.startswith("!") for acl in acls)
  681. # Identify special/common ACLs
  682. special_acls = []
  683. if "localhost" in acls:
  684. special_acls.append("localhost")
  685. if "manager" in acls:
  686. special_acls.append("manager")
  687. if any("Safe_ports" in acl for acl in acls):
  688. special_acls.append("Safe_ports")
  689. if any("SSL_ports" in acl for acl in acls):
  690. special_acls.append("SSL_ports")
  691. if "CONNECT" in acls:
  692. special_acls.append("CONNECT")
  693. rules.append(
  694. {
  695. "action": action,
  696. "acls": acls,
  697. "acl_string": acl_string,
  698. "is_negative": is_negative,
  699. "line_number": line_num,
  700. "description": last_comment if last_comment else "",
  701. "special_acls": special_acls,
  702. }
  703. )
  704. last_comment = "" # Reset comment
  705. except Exception as e:
  706. logger.warning(
  707. f"Error processing HTTP rule at line {line_num}: {e}"
  708. )
  709. continue
  710. # logger.debug(f"Found {len(rules)} HTTP access rules")
  711. return rules
  712. except Exception as e:
  713. logger.error(f"Unexpected error extracting HTTP rules: {e}")
  714. return []
  715. def _check_modular_config(self):
  716. """Check whether active includes point at the configured module directory."""
  717. if not self.config_content:
  718. return
  719. config_dir = os.path.abspath(self.config_dir)
  720. include_dirs: list[str] = []
  721. for raw_line in _join_continuation_lines(self.config_content).splitlines():
  722. line = raw_line.split("#", 1)[0].strip()
  723. match = re.match(r"^include\s+(.+)$", line, re.IGNORECASE)
  724. if not match:
  725. continue
  726. raw_include_path = os.path.expanduser(match.group(1).strip().strip('"'))
  727. include_path = os.path.abspath(
  728. raw_include_path
  729. if os.path.isabs(raw_include_path)
  730. else os.path.join(os.path.dirname(self.config_path), raw_include_path)
  731. )
  732. filename = os.path.basename(include_path)
  733. # A standalone text include may be an ACL value list. A .conf
  734. # include (including a glob) is a real configuration module.
  735. if ".conf" in filename:
  736. include_dirs.append(os.path.dirname(include_path))
  737. self.is_modular = bool(include_dirs)
  738. if self.is_modular:
  739. # Old installers sometimes leave ACL_FILES_DIR pointing at an ACL
  740. # value-list directory while squid.conf includes squid.d/conf.d.
  741. # Prefer the directory actually referenced by Squid so writes go
  742. # to active files rather than an unrelated folder.
  743. if config_dir in include_dirs:
  744. selected_dir = config_dir
  745. else:
  746. selected_dir = next(
  747. (
  748. directory
  749. for directory in include_dirs
  750. if "squid.d" in directory.casefold()
  751. ),
  752. include_dirs[0],
  753. )
  754. if selected_dir != config_dir:
  755. logger.info(
  756. "Using modular configuration directory referenced by Squid: {}",
  757. selected_dir,
  758. )
  759. self.config_dir = selected_dir
  760. logger.info("Modular configuration detected")
  761. def list_modular_configs(self) -> list[dict[str, str]]:
  762. """List all modular configuration files in squid.d directory."""
  763. if not os.path.exists(self.config_dir):
  764. logger.warning(f"Config directory not found: {self.config_dir}")
  765. return []
  766. try:
  767. configs = []
  768. for filename in sorted(os.listdir(self.config_dir)):
  769. if filename.endswith(".conf"):
  770. filepath = os.path.join(self.config_dir, filename)
  771. if os.path.isfile(filepath):
  772. try:
  773. stat = os.stat(filepath)
  774. configs.append(
  775. {
  776. "filename": filename,
  777. "filepath": filepath,
  778. "size": stat.st_size,
  779. "modified": datetime.fromtimestamp(
  780. stat.st_mtime
  781. ).strftime("%Y-%m-%d %H:%M:%S"),
  782. "readable": os.access(filepath, os.R_OK),
  783. "writable": os.access(filepath, os.W_OK),
  784. }
  785. )
  786. except Exception as e:
  787. logger.warning(
  788. f"Error reading file info for {filename}: {e}"
  789. )
  790. return configs
  791. except Exception as e:
  792. logger.error(f"Error listing modular configs: {e}")
  793. return []
  794. def read_modular_config(self, filename: str) -> str | None:
  795. """Read a specific modular configuration file."""
  796. filepath = os.path.join(self.config_dir, filename)
  797. if not hasattr(self, "_modular_content_snapshots"):
  798. self._modular_content_snapshots = {}
  799. if not os.path.exists(filepath):
  800. logger.error(f"Config file not found: {filepath}")
  801. self._modular_content_snapshots[filename] = None
  802. return None
  803. if not filepath.endswith(".conf"):
  804. logger.error(f"Invalid file extension: {filename}")
  805. return None
  806. try:
  807. with open(filepath, encoding="utf-8") as f:
  808. content = f.read()
  809. self._modular_content_snapshots[filename] = content
  810. # logger.debug(f"Read modular config: {filename}")
  811. return content
  812. except Exception as e:
  813. logger.error(f"Error reading modular config {filename}: {e}")
  814. return None
  815. def has_proxy_authentication(self) -> bool:
  816. """Return whether Squid has a usable ``proxy_auth`` identity ACL.
  817. Authentication directives may be placed in ``50_auth.conf`` after a
  818. split, in the main file, or in another active include. Consumers such
  819. as quota accounting must inspect only files Squid actually loads: a
  820. stale, unreferenced ``50_auth.conf`` must not switch quota accounting
  821. to usernames when the proxy has no active authentication helper.
  822. """
  823. if not self.is_valid:
  824. return False
  825. content = "\n".join(
  826. _join_continuation_lines(item)
  827. for item in self._active_configuration_contents()
  828. )
  829. has_helper = bool(
  830. re.search(
  831. r"^\s*auth_param\s+\S+\s+program\b",
  832. content,
  833. re.IGNORECASE | re.MULTILINE,
  834. )
  835. )
  836. has_identity_acl = bool(
  837. re.search(
  838. r"^\s*acl\s+\S+(?:\s+-\S+)*\s+proxy_auth\b",
  839. content,
  840. re.IGNORECASE | re.MULTILINE,
  841. )
  842. )
  843. return has_helper and has_identity_acl
  844. def _active_configuration_contents(self) -> list[str]:
  845. """Read active Squid include files, bounded against value-list files.
  846. This deliberately follows only actual ``include`` directives (and
  847. their globs), not every file in ``config_dir``. It is small and
  848. private because it supports configuration status checks rather than
  849. attempting to be a full Squid parser.
  850. """
  851. main_content = self.config_content or ""
  852. contents = [main_content]
  853. main_path = os.path.realpath(self.config_path)
  854. seen = {main_path}
  855. def visit(content: str, directory: str, depth: int = 0) -> None:
  856. if depth >= 8:
  857. logger.warning("Maximum Squid include depth reached")
  858. return
  859. for raw_line in _join_continuation_lines(content).splitlines():
  860. line = raw_line.split("#", 1)[0].strip()
  861. match = re.match(r"^include\s+(.+)$", line, re.IGNORECASE)
  862. if not match:
  863. continue
  864. include_path = os.path.expanduser(match.group(1).strip().strip('"'))
  865. pattern = os.path.abspath(
  866. include_path
  867. if os.path.isabs(include_path)
  868. else os.path.join(directory, include_path)
  869. )
  870. try:
  871. candidates = sorted(glob.glob(pattern))
  872. except OSError:
  873. continue
  874. for candidate in candidates:
  875. real_candidate = os.path.realpath(candidate)
  876. if (
  877. real_candidate in seen
  878. or not os.path.isfile(real_candidate)
  879. ):
  880. continue
  881. try:
  882. if os.path.getsize(real_candidate) > 1024 * 1024:
  883. continue
  884. with open(real_candidate, encoding="utf-8") as included:
  885. included_content = included.read()
  886. except (OSError, UnicodeDecodeError):
  887. continue
  888. seen.add(real_candidate)
  889. contents.append(included_content)
  890. visit(included_content, os.path.dirname(real_candidate), depth + 1)
  891. visit(main_content, os.path.dirname(main_path))
  892. return contents
  893. def save_modular_config(self, filename: str, content: str) -> bool:
  894. """Save content to a specific modular configuration file."""
  895. filepath = os.path.join(self.config_dir, filename)
  896. if not hasattr(self, "_modular_content_snapshots"):
  897. self._modular_content_snapshots = {}
  898. if not filename.endswith(".conf"):
  899. logger.error(f"Invalid file extension: {filename}")
  900. return False
  901. # Validate filename to prevent directory traversal
  902. if "/" in filename or "\\" in filename or ".." in filename:
  903. logger.error(f"Invalid filename (potential path traversal): {filename}")
  904. return False
  905. try:
  906. with squid_config_write_lock(self.config_path):
  907. try:
  908. with open(filepath, encoding="utf-8") as current_file:
  909. current_content: str | None = current_file.read()
  910. except FileNotFoundError:
  911. current_content = None
  912. snapshot_known = filename in self._modular_content_snapshots
  913. expected_content = self._modular_content_snapshots.get(filename)
  914. if snapshot_known and current_content != expected_content:
  915. logger.warning(
  916. "Refusing stale write to modular config %s; reload it and retry",
  917. filename,
  918. )
  919. return False
  920. if not snapshot_known and current_content is not None and current_content != content:
  921. logger.warning(
  922. "Refusing to overwrite modular config %s without a loaded snapshot",
  923. filename,
  924. )
  925. return False
  926. if current_content == content:
  927. self._modular_content_snapshots[filename] = content
  928. return True
  929. if current_content is not None:
  930. # Create single backup before overwriting
  931. backup_path = f"{filepath}.bak"
  932. try:
  933. shutil.copy2(filepath, backup_path)
  934. logger.debug(f"Backup created: {backup_path}")
  935. except Exception as e:
  936. logger.warning(f"Could not create backup for {filename}: {e}")
  937. self._atomic_write(filepath, content)
  938. self._modular_content_snapshots[filename] = content
  939. logger.info(f"Saved modular config: {filename}")
  940. return True
  941. except Exception as e:
  942. logger.error(f"Error saving modular config {filename}: {e}")
  943. return False
  944. def delete_modular_config(self, filename: str) -> bool:
  945. """Delete a specific modular configuration file."""
  946. filepath = os.path.join(self.config_dir, filename)
  947. if not os.path.exists(filepath):
  948. logger.error(f"Config file not found: {filepath}")
  949. return False
  950. if not filename.endswith(".conf"):
  951. logger.error(f"Invalid file extension: {filename}")
  952. return False
  953. # Validate filename to prevent directory traversal
  954. if "/" in filename or "\\" in filename or ".." in filename:
  955. logger.error(f"Invalid filename (potential path traversal): {filename}")
  956. return False
  957. try:
  958. # Keep a single .deleted backup, removing any previous one
  959. backup_path = f"{filepath}.deleted"
  960. if os.path.exists(backup_path):
  961. try:
  962. os.remove(backup_path)
  963. except Exception as e:
  964. logger.warning(f"Could not remove previous deleted backup: {e}")
  965. try:
  966. shutil.move(filepath, backup_path)
  967. logger.info(f"File moved to: {backup_path}")
  968. return True
  969. except Exception as e:
  970. logger.error(f"Error deleting file {filename}: {e}")
  971. return False
  972. except Exception as e:
  973. logger.error(f"Error handling file deletion {filename}: {e}")
  974. return False
  975. def get_modular_config_info(self) -> dict:
  976. """Get information about the modular configuration setup."""
  977. return {
  978. "is_modular": self.is_modular,
  979. "config_dir": self.config_dir,
  980. "config_dir_exists": os.path.exists(self.config_dir),
  981. "config_files_count": len(self.list_modular_configs()),
  982. "main_config_path": self.config_path,
  983. }
  984. def detect_ssl_bump(self) -> dict:
  985. """Detect whether SSL Bump is enabled in the Squid configuration.
  986. Inspects ``http_port`` directives (with backslash-continuation support),
  987. ``ssl_bump`` action rules, and ``sslcrtd_*`` directives.
  988. Returns a dict::
  989. {
  990. "enabled": bool,
  991. "mode": "peek-and-splice" | "bump-all" | "custom" | "basic" | None,
  992. "cert": str | None, # path in cert= option
  993. "generate_certs": bool,
  994. "sslcrtd_configured": bool,
  995. "sslcrtd_children": int | None,
  996. "http_port_entry": str | None,
  997. "ssl_bump_rules": list[str],
  998. "source": "main" | "modular",
  999. }
  1000. """
  1001. result: dict = {
  1002. "enabled": False,
  1003. "mode": None,
  1004. "cert": None,
  1005. "generate_certs": False,
  1006. "sslcrtd_configured": False,
  1007. "sslcrtd_children": None,
  1008. "http_port_entry": None,
  1009. "ssl_bump_rules": [],
  1010. "source": "main",
  1011. }
  1012. if not self.is_valid:
  1013. return result
  1014. ports_content = self.config_content
  1015. ssl_content = self.config_content
  1016. if self.is_modular:
  1017. # Use os.path.exists to avoid ERROR logs for optional modular files
  1018. ports_path = os.path.join(self.config_dir, "00_ports.conf")
  1019. ssl_path = os.path.join(self.config_dir, "55_ssl_bump.conf")
  1020. if os.path.exists(ports_path):
  1021. mc_ports = self.read_modular_config("00_ports.conf")
  1022. if mc_ports:
  1023. ports_content = mc_ports
  1024. result["source"] = "modular"
  1025. if os.path.exists(ssl_path):
  1026. mc_ssl = self.read_modular_config("55_ssl_bump.conf")
  1027. if mc_ssl:
  1028. ssl_content = mc_ssl
  1029. result["source"] = "modular"
  1030. # --- http_port: join continuation lines then scan ---
  1031. joined_ports = _join_continuation_lines(ports_content)
  1032. for line in joined_ports.splitlines():
  1033. stripped = line.strip()
  1034. if not stripped or stripped.startswith("#"):
  1035. continue
  1036. if re.match(r"^http_port\b", stripped):
  1037. tokens = stripped.split()
  1038. if "ssl-bump" in tokens:
  1039. result["enabled"] = True
  1040. result["http_port_entry"] = stripped
  1041. cert_m = re.search(r"\bcert=(\S+)", stripped)
  1042. if cert_m:
  1043. result["cert"] = cert_m.group(1)
  1044. gen_m = re.search(
  1045. r"\bgenerate-host-certificates=(on|off)\b", stripped
  1046. )
  1047. if gen_m:
  1048. result["generate_certs"] = gen_m.group(1) == "on"
  1049. break
  1050. # --- ssl_bump action rules ---
  1051. ssl_bump_rules = []
  1052. for line in ssl_content.splitlines():
  1053. stripped = line.strip()
  1054. if not stripped or stripped.startswith("#"):
  1055. continue
  1056. if re.match(r"^ssl_bump\b", stripped):
  1057. ssl_bump_rules.append(stripped)
  1058. result["ssl_bump_rules"] = ssl_bump_rules
  1059. # --- sslcrtd_* directives ---
  1060. for line in ssl_content.splitlines():
  1061. stripped = line.strip()
  1062. if not stripped or stripped.startswith("#"):
  1063. continue
  1064. if re.match(r"^sslcrtd_program\b", stripped):
  1065. result["sslcrtd_configured"] = True
  1066. elif re.match(r"^sslcrtd_children\b", stripped):
  1067. m = re.match(r"^sslcrtd_children\s+(\d+)", stripped)
  1068. if m:
  1069. result["sslcrtd_children"] = int(m.group(1))
  1070. # --- determine mode ---
  1071. if result["enabled"]:
  1072. has_bump = any(re.match(r"^ssl_bump\s+bump\b", r) for r in ssl_bump_rules)
  1073. has_peek = any(re.match(r"^ssl_bump\s+peek\b", r) for r in ssl_bump_rules)
  1074. has_splice = any(
  1075. re.match(r"^ssl_bump\s+splice\b", r) for r in ssl_bump_rules
  1076. )
  1077. if has_peek or has_splice:
  1078. result["mode"] = "peek-and-splice"
  1079. elif has_bump:
  1080. result["mode"] = "bump-all"
  1081. elif ssl_bump_rules:
  1082. result["mode"] = "custom"
  1083. else:
  1084. result["mode"] = "basic"
  1085. return result
  1086. def get_status(self):
  1087. return {
  1088. "is_valid": self.is_valid,
  1089. "errors": self.errors,
  1090. "config_loaded": bool(self.config_content),
  1091. "config_path": self.config_path,
  1092. "config_dir": self.config_dir,
  1093. "is_modular": self.is_modular,
  1094. "acl_files_dir": ACL_FILES_DIR,
  1095. }