admin.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909
  1. import os
  2. import re
  3. import shutil
  4. import tempfile
  5. from datetime import datetime
  6. from dotenv import load_dotenv
  7. from loguru import logger
  8. from config import Config
  9. from utils.custom_types import ACL_TYPES_INFO, PREDEFINED_ACLS
  10. load_dotenv()
  11. SQUID_CONFIG_PATH = Config.SQUID_CONFIG_PATH or "/etc/squid/squid.conf"
  12. ACL_FILES_DIR = Config.ACL_FILES_DIR or os.path.join(
  13. os.path.dirname(SQUID_CONFIG_PATH), "squid.d", ""
  14. )
  15. FALLBACK_SQUID_CONFIG_PATH = "/etc/squid/squid.conf"
  16. FALLBACK_ACL_FILES_DIRS = ["/etc/squid/acls", "/etc/squid/squid.d"]
  17. def _normalize_squid_paths(config_path: str, config_dir: str) -> tuple[str, str]:
  18. """Return effective Squid config and ACL directory paths.
  19. If configured paths do not exist, but the standard /etc/squid paths do,
  20. prefer a recognized fallback so the app can work in both container and
  21. older host environments.
  22. """
  23. config_path = os.path.abspath(os.path.expanduser(config_path))
  24. config_dir = os.path.abspath(os.path.expanduser(config_dir))
  25. if not os.path.exists(config_path) and config_path != FALLBACK_SQUID_CONFIG_PATH:
  26. if os.path.exists(FALLBACK_SQUID_CONFIG_PATH):
  27. config_path = FALLBACK_SQUID_CONFIG_PATH
  28. if not os.path.exists(config_dir):
  29. for fallback_dir in FALLBACK_ACL_FILES_DIRS:
  30. if os.path.exists(fallback_dir):
  31. config_dir = fallback_dir
  32. break
  33. return config_path, config_dir
  34. def _join_continuation_lines(content: str) -> str:
  35. """Join lines ending with a backslash with the following line."""
  36. lines = content.splitlines()
  37. result = []
  38. i = 0
  39. while i < len(lines):
  40. line = lines[i]
  41. while line.rstrip().endswith("\\"):
  42. line = line.rstrip()[:-1]
  43. i += 1
  44. if i < len(lines):
  45. line += " " + lines[i].strip()
  46. result.append(line)
  47. i += 1
  48. return "\n".join(result)
  49. def validate_paths():
  50. """Validate the squid.conf path (hard errors) and the ACL directory (warnings only).
  51. Returns a list of *hard* error strings that block SquidConfigManager
  52. initialization. Missing or inaccessible ACL directories are logged as
  53. warnings but do NOT appear in the returned list — they only disable
  54. modular-config support.
  55. """
  56. errors = []
  57. cfg = os.path.abspath(os.path.expanduser(SQUID_CONFIG_PATH))
  58. if os.path.isdir(cfg):
  59. squid_conf = os.path.join(cfg, "squid.conf")
  60. if not os.path.exists(squid_conf):
  61. errors.append(f"'squid.conf' not found in directory: {cfg}")
  62. else:
  63. if not os.path.isfile(squid_conf):
  64. errors.append(f"Found but not a regular file: {squid_conf}")
  65. else:
  66. if not os.access(squid_conf, os.R_OK):
  67. errors.append(f"No read permissions for: {squid_conf}")
  68. if not os.access(squid_conf, os.W_OK):
  69. errors.append(f"No write permissions for: {squid_conf}")
  70. else:
  71. squid_conf = cfg
  72. if not os.path.exists(squid_conf):
  73. errors.append(f"Configuration file not found: {squid_conf}")
  74. else:
  75. if not os.path.isfile(squid_conf):
  76. errors.append(f"Not a regular file: {squid_conf}")
  77. if os.path.basename(squid_conf) != "squid.conf":
  78. errors.append(
  79. f"Expected file named 'squid.conf', got: {os.path.basename(squid_conf)}"
  80. )
  81. if os.path.isfile(squid_conf):
  82. if not os.access(squid_conf, os.R_OK):
  83. errors.append(f"No read permissions for: {squid_conf}")
  84. if not os.access(squid_conf, os.W_OK):
  85. errors.append(f"No write permissions for: {squid_conf}")
  86. # ACL / modular-config directory — warnings only, never a hard error
  87. _, acl_dir = _normalize_squid_paths(SQUID_CONFIG_PATH, ACL_FILES_DIR)
  88. if not os.path.exists(acl_dir):
  89. logger.warning(
  90. f"ACL/modular config directory not found: {acl_dir} — "
  91. "modular configuration will be disabled."
  92. )
  93. elif not os.path.isdir(acl_dir):
  94. logger.warning(f"ACL path is not a directory: {acl_dir}")
  95. elif not os.access(acl_dir, os.W_OK):
  96. logger.warning(f"No write permissions in ACL directory: {acl_dir}")
  97. return errors
  98. class SquidConfigManager:
  99. def __init__(self, config_path=SQUID_CONFIG_PATH, config_dir=ACL_FILES_DIR):
  100. self.config_path, self.config_dir = _normalize_squid_paths(
  101. config_path, config_dir
  102. )
  103. self.config_content = ""
  104. self.is_valid = False
  105. self.errors = []
  106. self.is_modular = False # Flag to check if using modular configs
  107. self._validate_environment()
  108. if self.is_valid:
  109. self.load_config()
  110. self._check_modular_config()
  111. def _validate_environment(self):
  112. self.errors = validate_paths()
  113. if self.errors:
  114. for error in self.errors:
  115. logger.error(error)
  116. self.is_valid = False
  117. logger.error(
  118. "SquidConfigManager cannot be initialized due to configuration errors"
  119. )
  120. else:
  121. self.is_valid = True
  122. logger.info("SquidConfigManager initialized successfully")
  123. def _cleanup_modular_backups(self, filepath: str, suffix: str = ".bak"):
  124. """Remove old backups for a modular config file, keeping only the newest one."""
  125. base = os.path.basename(filepath)
  126. directory = os.path.dirname(filepath)
  127. prefix = base + suffix
  128. try:
  129. backups = sorted(
  130. f for f in os.listdir(directory) if f.startswith(prefix) and f != base
  131. )
  132. # Remove all but the last (newest) backup
  133. for old in backups[:-1]:
  134. try:
  135. os.remove(os.path.join(directory, old))
  136. logger.debug(f"Removed old backup: {old}")
  137. except Exception as e:
  138. logger.warning(f"Could not remove old backup {old}: {e}")
  139. except Exception as e:
  140. logger.warning(f"Error cleaning up backups for {base}: {e}")
  141. def load_config(self):
  142. if not self.is_valid:
  143. logger.error("Cannot load configuration: invalid environment")
  144. return False
  145. try:
  146. with open(self.config_path, encoding="utf-8") as f:
  147. self.config_content = f.read()
  148. logger.debug(f"Configuration loaded from: {self.config_path}")
  149. return True
  150. except FileNotFoundError:
  151. logger.error(f"Configuration file not found: {self.config_path}")
  152. self.config_content = ""
  153. return False
  154. except PermissionError:
  155. logger.error(f"No read permissions for: {self.config_path}")
  156. self.config_content = ""
  157. return False
  158. except UnicodeDecodeError as e:
  159. logger.error(f"File encoding error: {e}")
  160. self.config_content = ""
  161. return False
  162. except Exception as e:
  163. logger.error(f"Unexpected error loading configuration: {e}")
  164. self.config_content = ""
  165. return False
  166. @staticmethod
  167. def _atomic_write(path: str, content: str, encoding: str = "utf-8") -> None:
  168. """Write *content* to *path* atomically: write to a temp file then os.replace.
  169. Using open(path, 'w') truncates the file immediately; if the process is
  170. interrupted mid-write squid.conf ends up empty/corrupt. Writing to a
  171. temporary file in the same directory and calling os.replace() is atomic
  172. on POSIX — the destination is either the old file or the new file, never
  173. a partial write.
  174. """
  175. abs_path = os.path.abspath(path)
  176. dir_name = os.path.dirname(abs_path)
  177. tmp_path = None
  178. try:
  179. with tempfile.NamedTemporaryFile(
  180. mode="w",
  181. encoding=encoding,
  182. dir=dir_name,
  183. delete=False,
  184. suffix=".squidstats.tmp",
  185. ) as tmp:
  186. tmp.write(content)
  187. tmp_path = tmp.name
  188. os.replace(tmp_path, abs_path)
  189. except Exception:
  190. if tmp_path and os.path.exists(tmp_path):
  191. try:
  192. os.unlink(tmp_path)
  193. except Exception as cleanup_err:
  194. logger.warning(
  195. "Could not remove temporary file %s: %s", tmp_path, cleanup_err
  196. )
  197. raise
  198. def save_config(self, content):
  199. if not self.is_valid:
  200. logger.error("Cannot save configuration: invalid environment")
  201. return False
  202. # Guard: never blank squid.conf — an empty file would bring down Squid
  203. if not content or not content.strip():
  204. logger.error(
  205. "Refusing to save empty/whitespace-only content to squid.conf: "
  206. "this would disable the Squid proxy"
  207. )
  208. return False
  209. try:
  210. # Skip write if content hasn't changed
  211. if self.config_content == content:
  212. logger.debug("Main config unchanged, skipping write")
  213. return True
  214. backup_created = self.create_backup()
  215. if not backup_created:
  216. logger.warning("Could not create backup, but continuing with save...")
  217. self._atomic_write(self.config_path, content)
  218. self.config_content = content
  219. logger.info(f"Configuration saved successfully to: {self.config_path}")
  220. return True
  221. except PermissionError:
  222. logger.error(f"No write permissions for: {self.config_path}")
  223. return False
  224. except OSError as e:
  225. logger.error(f"System error saving configuration: {e}")
  226. return False
  227. except Exception as e:
  228. logger.error(f"Unexpected error saving configuration: {e}")
  229. return False
  230. def create_backup(self):
  231. if not self.is_valid:
  232. logger.error("Cannot create backup: invalid environment")
  233. return False
  234. try:
  235. backup_path = f"{self.config_path}.bak"
  236. shutil.copy2(self.config_path, backup_path)
  237. logger.info(f"Backup created: {backup_path}")
  238. return True
  239. except FileNotFoundError:
  240. logger.warning(f"Config file not found for backup: {self.config_path}")
  241. return False
  242. except PermissionError:
  243. logger.error(f"No permission to create backup for: {self.config_path}")
  244. return False
  245. except Exception as e:
  246. logger.error(f"Unexpected error creating backup: {e}")
  247. return False
  248. def get_acls(self):
  249. """
  250. Parse ACL definitions with enhanced information.
  251. Returns a list of ACL dictionaries with full details.
  252. Format:
  253. {
  254. 'id': 0,
  255. 'name': 'localnet',
  256. 'type': 'src',
  257. 'options': ['-i'], # ACL options like -i, -n, -m
  258. 'values': ['10.0.0.0/8', '192.168.0.0/16'], # List of values
  259. 'value_string': '10.0.0.0/8 192.168.0.0/16', # Original value string
  260. 'is_predefined': False, # True for Squid predefined ACLs
  261. 'is_slow': False, # True for slow ACL types
  262. 'category': 'network', # Category: network, time, auth, content, ssl, etc.
  263. 'description': 'RFC 1918 private networks', # Human-readable description
  264. 'line_number': 5
  265. }
  266. """
  267. if not self.is_valid:
  268. logger.error("Cannot get ACLs: invalid environment")
  269. return []
  270. # If using modular config, read from the ACLs specific file
  271. if self.is_modular:
  272. acl_content = self.read_modular_config("100_acls.conf")
  273. if not acl_content:
  274. logger.warning(
  275. "Could not read modular ACL config, falling back to main config"
  276. )
  277. config_to_parse = self.config_content
  278. else:
  279. config_to_parse = acl_content
  280. else:
  281. if not self.config_content:
  282. logger.warning("No configuration content available")
  283. return []
  284. config_to_parse = self.config_content
  285. try:
  286. acls = []
  287. lines = config_to_parse.split("\n")
  288. acl_index = 0
  289. predefined_acls = PREDEFINED_ACLS
  290. # ACL type metadata
  291. acl_types_info = ACL_TYPES_INFO
  292. last_comment = ""
  293. for line_num, line in enumerate(lines, 1):
  294. try:
  295. stripped = line.strip()
  296. # Track comments for context
  297. if stripped.startswith("#"):
  298. last_comment = stripped[1:].strip()
  299. continue
  300. if stripped.startswith("acl "):
  301. parts = stripped.split()
  302. if len(parts) >= 3:
  303. acl_name = parts[1]
  304. # Parse options and type
  305. options = []
  306. type_index = 2
  307. while type_index < len(parts) and parts[
  308. type_index
  309. ].startswith("-"):
  310. options.append(parts[type_index])
  311. type_index += 1
  312. if type_index >= len(parts):
  313. continue
  314. acl_type = parts[type_index]
  315. values = (
  316. parts[type_index + 1 :]
  317. if len(parts) > type_index + 1
  318. else []
  319. )
  320. value_string = " ".join(values)
  321. # Get type metadata
  322. type_info = acl_types_info.get(
  323. acl_type,
  324. {
  325. "category": "other",
  326. "slow": False,
  327. "desc": "Custom ACL type",
  328. },
  329. )
  330. # Check if predefined
  331. is_predefined = acl_name in predefined_acls
  332. acls.append(
  333. {
  334. "id": acl_index,
  335. "name": acl_name,
  336. "type": acl_type,
  337. "options": options,
  338. "value_list": values,
  339. "value_string": value_string,
  340. "is_predefined": is_predefined,
  341. "is_slow": type_info.get("slow", False),
  342. "category": type_info.get("category", "other"),
  343. "type_description": type_info.get("desc", ""),
  344. "comment": last_comment if last_comment else "",
  345. "line_number": line_num,
  346. "full_line": stripped,
  347. }
  348. )
  349. acl_index += 1
  350. last_comment = ""
  351. except Exception as e:
  352. logger.warning(f"Error processing ACL at line {line_num}: {e}")
  353. continue
  354. logger.debug(f"Found {len(acls)} ACLs")
  355. return acls
  356. except Exception as e:
  357. logger.error(f"Unexpected error extracting ACLs: {e}")
  358. return []
  359. def get_delay_pools(self):
  360. """
  361. Parse delay pools configuration and group by pool number.
  362. Returns a list of pool dictionaries with all related directives.
  363. Format:
  364. {
  365. 'pool_number': '1',
  366. 'class': '3',
  367. 'parameters': '8192/131072 1024/65536 256/32768',
  368. 'access_rules': [{'action': 'allow', 'acl': 'students'}]
  369. }
  370. """
  371. if not self.is_valid:
  372. logger.error("Cannot get delay pools: invalid environment")
  373. return []
  374. # If using modular config, read from the delay pools specific file
  375. if self.is_modular:
  376. delay_content = self.read_modular_config("110_delay_pools.conf")
  377. if not delay_content:
  378. logger.warning(
  379. "Could not read modular delay pools config, falling back to main config"
  380. )
  381. config_to_parse = self.config_content
  382. else:
  383. config_to_parse = delay_content
  384. else:
  385. if not self.config_content:
  386. logger.warning("No configuration content available")
  387. return []
  388. config_to_parse = self.config_content
  389. try:
  390. pools_dict = {} # Dictionary to group by pool number
  391. # total_pools = 0
  392. lines = config_to_parse.split("\n")
  393. for line_num, line in enumerate(lines, 1):
  394. try:
  395. line = line.strip()
  396. if line.startswith("delay_pools "):
  397. pass
  398. # parts = line.split()
  399. # if len(parts) >= 2:
  400. # total_pools = int(parts[1])
  401. elif line.startswith("delay_class "):
  402. parts = line.split()
  403. if len(parts) >= 3:
  404. pool_num = parts[1]
  405. if pool_num not in pools_dict:
  406. pools_dict[pool_num] = {
  407. "pool_number": pool_num,
  408. "class": parts[2],
  409. "parameters": None,
  410. "access_rules": [],
  411. }
  412. else:
  413. pools_dict[pool_num]["class"] = parts[2]
  414. elif line.startswith("delay_parameters "):
  415. parts = line.split()
  416. if len(parts) >= 3:
  417. pool_num = parts[1]
  418. if pool_num not in pools_dict:
  419. pools_dict[pool_num] = {
  420. "pool_number": pool_num,
  421. "class": None,
  422. "parameters": " ".join(parts[2:]),
  423. "access_rules": [],
  424. }
  425. else:
  426. pools_dict[pool_num]["parameters"] = " ".join(parts[2:])
  427. elif line.startswith("delay_access "):
  428. parts = line.split()
  429. if len(parts) >= 4:
  430. pool_num = parts[1]
  431. if pool_num not in pools_dict:
  432. pools_dict[pool_num] = {
  433. "pool_number": pool_num,
  434. "class": None,
  435. "parameters": None,
  436. "access_rules": [],
  437. }
  438. pools_dict[pool_num]["access_rules"].append(
  439. {"action": parts[2], "acl": " ".join(parts[3:])}
  440. )
  441. except Exception as e:
  442. logger.warning(
  443. f"Error processing delay pool at line {line_num}: {e}"
  444. )
  445. continue
  446. # Convert dictionary to sorted list
  447. delay_pools = [
  448. pools_dict[key] for key in sorted(pools_dict.keys(), key=int)
  449. ]
  450. # logger.debug(
  451. # f"Found {len(delay_pools)} delay pool configurations (total_pools={total_pools})"
  452. # )
  453. return delay_pools
  454. except Exception as e:
  455. logger.error(f"Unexpected error extracting delay pools: {e}")
  456. return []
  457. def get_http_access_rules(self):
  458. """
  459. Parse http_access rules with enhanced information.
  460. Returns a list of rule dictionaries with action, acls (list), and metadata.
  461. Format:
  462. {
  463. 'action': 'allow',
  464. 'acls': ['!Safe_ports'], # List of ACLs including negations
  465. 'acl_string': '!Safe_ports', # Original ACL string
  466. 'is_negative': True, # If it contains negation
  467. 'line_number': 5, # Original line number
  468. 'description': '' # Optional description from comments
  469. }
  470. """
  471. if not self.is_valid:
  472. logger.error("Cannot get HTTP rules: invalid environment")
  473. return []
  474. # If using modular config, read from the http_access specific file
  475. if self.is_modular:
  476. http_content = self.read_modular_config("120_http_access.conf")
  477. if not http_content:
  478. logger.warning(
  479. "Could not read modular http_access config, falling back to main config"
  480. )
  481. config_to_parse = self.config_content
  482. else:
  483. config_to_parse = http_content
  484. else:
  485. if not self.config_content:
  486. logger.warning("No configuration content available")
  487. return []
  488. config_to_parse = self.config_content
  489. try:
  490. rules = []
  491. lines = config_to_parse.split("\n")
  492. last_comment = ""
  493. for line_num, line in enumerate(lines, 1):
  494. try:
  495. stripped = line.strip()
  496. # Track comments for context
  497. if stripped.startswith("#"):
  498. last_comment = stripped[1:].strip()
  499. continue
  500. if stripped.startswith("http_access "):
  501. parts = stripped.split()
  502. if len(parts) >= 3:
  503. action = parts[1]
  504. acl_string = " ".join(parts[2:])
  505. acls = parts[2:]
  506. # Check if any ACL has negation
  507. is_negative = any(acl.startswith("!") for acl in acls)
  508. # Identify special/common ACLs
  509. special_acls = []
  510. if "localhost" in acls:
  511. special_acls.append("localhost")
  512. if "manager" in acls:
  513. special_acls.append("manager")
  514. if any("Safe_ports" in acl for acl in acls):
  515. special_acls.append("Safe_ports")
  516. if any("SSL_ports" in acl for acl in acls):
  517. special_acls.append("SSL_ports")
  518. if "CONNECT" in acls:
  519. special_acls.append("CONNECT")
  520. rules.append(
  521. {
  522. "action": action,
  523. "acls": acls,
  524. "acl_string": acl_string,
  525. "is_negative": is_negative,
  526. "line_number": line_num,
  527. "description": last_comment if last_comment else "",
  528. "special_acls": special_acls,
  529. }
  530. )
  531. last_comment = "" # Reset comment
  532. except Exception as e:
  533. logger.warning(
  534. f"Error processing HTTP rule at line {line_num}: {e}"
  535. )
  536. continue
  537. # logger.debug(f"Found {len(rules)} HTTP access rules")
  538. return rules
  539. except Exception as e:
  540. logger.error(f"Unexpected error extracting HTTP rules: {e}")
  541. return []
  542. def _check_modular_config(self):
  543. """Check if the main config file uses modular includes."""
  544. if not self.config_content:
  545. return
  546. # Check if config contains include directives pointing to squid.d
  547. self.is_modular = (
  548. "include" in self.config_content.lower()
  549. and "squid.d" in self.config_content
  550. )
  551. if self.is_modular:
  552. logger.info("Modular configuration detected")
  553. def list_modular_configs(self) -> list[dict[str, str]]:
  554. """List all modular configuration files in squid.d directory."""
  555. if not os.path.exists(self.config_dir):
  556. logger.warning(f"Config directory not found: {self.config_dir}")
  557. return []
  558. try:
  559. configs = []
  560. for filename in sorted(os.listdir(self.config_dir)):
  561. if filename.endswith(".conf"):
  562. filepath = os.path.join(self.config_dir, filename)
  563. if os.path.isfile(filepath):
  564. try:
  565. stat = os.stat(filepath)
  566. configs.append(
  567. {
  568. "filename": filename,
  569. "filepath": filepath,
  570. "size": stat.st_size,
  571. "modified": datetime.fromtimestamp(
  572. stat.st_mtime
  573. ).strftime("%Y-%m-%d %H:%M:%S"),
  574. "readable": os.access(filepath, os.R_OK),
  575. "writable": os.access(filepath, os.W_OK),
  576. }
  577. )
  578. except Exception as e:
  579. logger.warning(
  580. f"Error reading file info for {filename}: {e}"
  581. )
  582. return configs
  583. except Exception as e:
  584. logger.error(f"Error listing modular configs: {e}")
  585. return []
  586. def read_modular_config(self, filename: str) -> str | None:
  587. """Read a specific modular configuration file."""
  588. filepath = os.path.join(self.config_dir, filename)
  589. if not os.path.exists(filepath):
  590. logger.error(f"Config file not found: {filepath}")
  591. return None
  592. if not filepath.endswith(".conf"):
  593. logger.error(f"Invalid file extension: {filename}")
  594. return None
  595. try:
  596. with open(filepath, encoding="utf-8") as f:
  597. content = f.read()
  598. # logger.debug(f"Read modular config: {filename}")
  599. return content
  600. except Exception as e:
  601. logger.error(f"Error reading modular config {filename}: {e}")
  602. return None
  603. def save_modular_config(self, filename: str, content: str) -> bool:
  604. """Save content to a specific modular configuration file."""
  605. filepath = os.path.join(self.config_dir, filename)
  606. if not filename.endswith(".conf"):
  607. logger.error(f"Invalid file extension: {filename}")
  608. return False
  609. # Validate filename to prevent directory traversal
  610. if "/" in filename or "\\" in filename or ".." in filename:
  611. logger.error(f"Invalid filename (potential path traversal): {filename}")
  612. return False
  613. try:
  614. # Skip write if content hasn't changed
  615. if os.path.exists(filepath):
  616. try:
  617. with open(filepath, encoding="utf-8") as f:
  618. existing = f.read()
  619. if existing == content:
  620. # logger.debug(
  621. # f"Modular config unchanged, skipping write: {filename}"
  622. # )
  623. return True
  624. except Exception as e:
  625. logger.debug(
  626. "Could not read existing config for comparison, proceeding with write: %s",
  627. e,
  628. )
  629. # Create single backup before overwriting
  630. backup_path = f"{filepath}.bak"
  631. try:
  632. shutil.copy2(filepath, backup_path)
  633. logger.debug(f"Backup created: {backup_path}")
  634. except Exception as e:
  635. logger.warning(f"Could not create backup for {filename}: {e}")
  636. self._atomic_write(filepath, content)
  637. logger.info(f"Saved modular config: {filename}")
  638. return True
  639. except Exception as e:
  640. logger.error(f"Error saving modular config {filename}: {e}")
  641. return False
  642. def delete_modular_config(self, filename: str) -> bool:
  643. """Delete a specific modular configuration file."""
  644. filepath = os.path.join(self.config_dir, filename)
  645. if not os.path.exists(filepath):
  646. logger.error(f"Config file not found: {filepath}")
  647. return False
  648. if not filename.endswith(".conf"):
  649. logger.error(f"Invalid file extension: {filename}")
  650. return False
  651. # Validate filename to prevent directory traversal
  652. if "/" in filename or "\\" in filename or ".." in filename:
  653. logger.error(f"Invalid filename (potential path traversal): {filename}")
  654. return False
  655. try:
  656. # Keep a single .deleted backup, removing any previous one
  657. backup_path = f"{filepath}.deleted"
  658. if os.path.exists(backup_path):
  659. try:
  660. os.remove(backup_path)
  661. except Exception as e:
  662. logger.warning(f"Could not remove previous deleted backup: {e}")
  663. try:
  664. shutil.move(filepath, backup_path)
  665. logger.info(f"File moved to: {backup_path}")
  666. return True
  667. except Exception as e:
  668. logger.error(f"Error deleting file {filename}: {e}")
  669. return False
  670. except Exception as e:
  671. logger.error(f"Error handling file deletion {filename}: {e}")
  672. return False
  673. def get_modular_config_info(self) -> dict:
  674. """Get information about the modular configuration setup."""
  675. return {
  676. "is_modular": self.is_modular,
  677. "config_dir": self.config_dir,
  678. "config_dir_exists": os.path.exists(self.config_dir),
  679. "config_files_count": len(self.list_modular_configs()),
  680. "main_config_path": self.config_path,
  681. }
  682. def detect_ssl_bump(self) -> dict:
  683. """Detect whether SSL Bump is enabled in the Squid configuration.
  684. Inspects ``http_port`` directives (with backslash-continuation support),
  685. ``ssl_bump`` action rules, and ``sslcrtd_*`` directives.
  686. Returns a dict::
  687. {
  688. "enabled": bool,
  689. "mode": "peek-and-splice" | "bump-all" | "custom" | "basic" | None,
  690. "cert": str | None, # path in cert= option
  691. "generate_certs": bool,
  692. "sslcrtd_configured": bool,
  693. "sslcrtd_children": int | None,
  694. "http_port_entry": str | None,
  695. "ssl_bump_rules": list[str],
  696. "source": "main" | "modular",
  697. }
  698. """
  699. result: dict = {
  700. "enabled": False,
  701. "mode": None,
  702. "cert": None,
  703. "generate_certs": False,
  704. "sslcrtd_configured": False,
  705. "sslcrtd_children": None,
  706. "http_port_entry": None,
  707. "ssl_bump_rules": [],
  708. "source": "main",
  709. }
  710. if not self.is_valid:
  711. return result
  712. ports_content = self.config_content
  713. ssl_content = self.config_content
  714. if self.is_modular:
  715. # Use os.path.exists to avoid ERROR logs for optional modular files
  716. ports_path = os.path.join(self.config_dir, "00_ports.conf")
  717. ssl_path = os.path.join(self.config_dir, "55_ssl_bump.conf")
  718. if os.path.exists(ports_path):
  719. mc_ports = self.read_modular_config("00_ports.conf")
  720. if mc_ports:
  721. ports_content = mc_ports
  722. result["source"] = "modular"
  723. if os.path.exists(ssl_path):
  724. mc_ssl = self.read_modular_config("55_ssl_bump.conf")
  725. if mc_ssl:
  726. ssl_content = mc_ssl
  727. result["source"] = "modular"
  728. # --- http_port: join continuation lines then scan ---
  729. joined_ports = _join_continuation_lines(ports_content)
  730. for line in joined_ports.splitlines():
  731. stripped = line.strip()
  732. if not stripped or stripped.startswith("#"):
  733. continue
  734. if re.match(r"^http_port\b", stripped):
  735. tokens = stripped.split()
  736. if "ssl-bump" in tokens:
  737. result["enabled"] = True
  738. result["http_port_entry"] = stripped
  739. cert_m = re.search(r"\bcert=(\S+)", stripped)
  740. if cert_m:
  741. result["cert"] = cert_m.group(1)
  742. gen_m = re.search(
  743. r"\bgenerate-host-certificates=(on|off)\b", stripped
  744. )
  745. if gen_m:
  746. result["generate_certs"] = gen_m.group(1) == "on"
  747. break
  748. # --- ssl_bump action rules ---
  749. ssl_bump_rules = []
  750. for line in ssl_content.splitlines():
  751. stripped = line.strip()
  752. if not stripped or stripped.startswith("#"):
  753. continue
  754. if re.match(r"^ssl_bump\b", stripped):
  755. ssl_bump_rules.append(stripped)
  756. result["ssl_bump_rules"] = ssl_bump_rules
  757. # --- sslcrtd_* directives ---
  758. for line in ssl_content.splitlines():
  759. stripped = line.strip()
  760. if not stripped or stripped.startswith("#"):
  761. continue
  762. if re.match(r"^sslcrtd_program\b", stripped):
  763. result["sslcrtd_configured"] = True
  764. elif re.match(r"^sslcrtd_children\b", stripped):
  765. m = re.match(r"^sslcrtd_children\s+(\d+)", stripped)
  766. if m:
  767. result["sslcrtd_children"] = int(m.group(1))
  768. # --- determine mode ---
  769. if result["enabled"]:
  770. has_bump = any(re.match(r"^ssl_bump\s+bump\b", r) for r in ssl_bump_rules)
  771. has_peek = any(re.match(r"^ssl_bump\s+peek\b", r) for r in ssl_bump_rules)
  772. has_splice = any(
  773. re.match(r"^ssl_bump\s+splice\b", r) for r in ssl_bump_rules
  774. )
  775. if has_peek or has_splice:
  776. result["mode"] = "peek-and-splice"
  777. elif has_bump:
  778. result["mode"] = "bump-all"
  779. elif ssl_bump_rules:
  780. result["mode"] = "custom"
  781. else:
  782. result["mode"] = "basic"
  783. return result
  784. def get_status(self):
  785. return {
  786. "is_valid": self.is_valid,
  787. "errors": self.errors,
  788. "config_loaded": bool(self.config_content),
  789. "config_path": self.config_path,
  790. "config_dir": self.config_dir,
  791. "is_modular": self.is_modular,
  792. "acl_files_dir": ACL_FILES_DIR,
  793. }