4
0

admin.py 32 KB

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