admin.py 34 KB

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