4
0

admin.py 50 KB

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