admin.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059
  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. load_dotenv()
  9. SQUID_CONFIG_PATH = Config.SQUID_CONFIG_PATH or "/etc/squid/squid.conf"
  10. ACL_FILES_DIR = (
  11. os.getenv("ACL_FILES_DIR") or
  12. os.path.join(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 load_config(self):
  103. if not self.is_valid:
  104. logger.error("Cannot load configuration: invalid environment")
  105. return False
  106. try:
  107. with open(self.config_path, encoding="utf-8") as f:
  108. self.config_content = f.read()
  109. logger.debug(f"Configuration loaded from: {self.config_path}")
  110. return True
  111. except FileNotFoundError:
  112. logger.error(f"Configuration file not found: {self.config_path}")
  113. self.config_content = ""
  114. return False
  115. except PermissionError:
  116. logger.error(f"No read permissions for: {self.config_path}")
  117. self.config_content = ""
  118. return False
  119. except UnicodeDecodeError as e:
  120. logger.error(f"File encoding error: {e}")
  121. self.config_content = ""
  122. return False
  123. except Exception as e:
  124. logger.error(f"Unexpected error loading configuration: {e}")
  125. self.config_content = ""
  126. return False
  127. def save_config(self, content):
  128. if not self.is_valid:
  129. logger.error("Cannot save configuration: invalid environment")
  130. return False
  131. try:
  132. backup_created = self.create_backup()
  133. if not backup_created:
  134. logger.warning("Could not create backup, but continuing with save...")
  135. with open(self.config_path, "w", encoding="utf-8") as f:
  136. f.write(content)
  137. self.config_content = content
  138. logger.info(f"Configuration saved successfully to: {self.config_path}")
  139. return True
  140. except PermissionError:
  141. logger.error(f"No write permissions for: {self.config_path}")
  142. return False
  143. except OSError as e:
  144. logger.error(f"System error saving configuration: {e}")
  145. return False
  146. except Exception as e:
  147. logger.error(f"Unexpected error saving configuration: {e}")
  148. return False
  149. def create_backup(self):
  150. if not self.is_valid:
  151. logger.error("Cannot create backup: invalid environment")
  152. return False
  153. def get_acls(self):
  154. """
  155. Parse ACL definitions with enhanced information.
  156. Returns a list of ACL dictionaries with full details.
  157. Format:
  158. {
  159. 'id': 0,
  160. 'name': 'localnet',
  161. 'type': 'src',
  162. 'options': ['-i'], # ACL options like -i, -n, -m
  163. 'values': ['10.0.0.0/8', '192.168.0.0/16'], # List of values
  164. 'value_string': '10.0.0.0/8 192.168.0.0/16', # Original value string
  165. 'is_predefined': False, # True for Squid predefined ACLs
  166. 'is_slow': False, # True for slow ACL types
  167. 'category': 'network', # Category: network, time, auth, content, ssl, etc.
  168. 'description': 'RFC 1918 private networks', # Human-readable description
  169. 'line_number': 5
  170. }
  171. """
  172. if not self.is_valid:
  173. logger.error("Cannot get ACLs: invalid environment")
  174. return []
  175. # If using modular config, read from the ACLs specific file
  176. if self.is_modular:
  177. acl_content = self.read_modular_config("100_acls.conf")
  178. if not acl_content:
  179. logger.warning(
  180. "Could not read modular ACL config, falling back to main config"
  181. )
  182. config_to_parse = self.config_content
  183. else:
  184. config_to_parse = acl_content
  185. else:
  186. if not self.config_content:
  187. logger.warning("No configuration content available")
  188. return []
  189. config_to_parse = self.config_content
  190. try:
  191. acls = []
  192. lines = config_to_parse.split("\n")
  193. acl_index = 0
  194. # Predefined ACLs in Squid
  195. predefined_acls = [
  196. "all",
  197. "manager",
  198. "localhost",
  199. "to_localhost",
  200. "to_linklocal",
  201. "CONNECT",
  202. ]
  203. # ACL type metadata
  204. acl_types_info = {
  205. # Network ACLs
  206. "src": {
  207. "category": "network",
  208. "slow": False,
  209. "desc": "Source IP address",
  210. },
  211. "dst": {
  212. "category": "network",
  213. "slow": True,
  214. "desc": "Destination IP address",
  215. },
  216. "localip": {
  217. "category": "network",
  218. "slow": False,
  219. "desc": "Local IP client connected to",
  220. },
  221. "arp": {
  222. "category": "network",
  223. "slow": False,
  224. "desc": "MAC address (EUI-48)",
  225. },
  226. "eui64": {
  227. "category": "network",
  228. "slow": False,
  229. "desc": "EUI-64 address",
  230. },
  231. "client_connection_mark": {
  232. "category": "network",
  233. "slow": False,
  234. "desc": "CONNMARK of connection",
  235. },
  236. # Domain ACLs
  237. "srcdomain": {
  238. "category": "domain",
  239. "slow": True,
  240. "desc": "Reverse DNS lookup of client IP",
  241. },
  242. "dstdomain": {
  243. "category": "domain",
  244. "slow": False,
  245. "desc": "Destination domain from URL",
  246. },
  247. "srcdom_regex": {
  248. "category": "domain",
  249. "slow": True,
  250. "desc": "Regex match on client name",
  251. },
  252. "dstdom_regex": {
  253. "category": "domain",
  254. "slow": False,
  255. "desc": "Regex match on server domain",
  256. },
  257. # AS Number ACLs
  258. "src_as": {
  259. "category": "network",
  260. "slow": False,
  261. "desc": "Source Autonomous System number",
  262. },
  263. "dst_as": {
  264. "category": "network",
  265. "slow": False,
  266. "desc": "Destination AS number",
  267. },
  268. # Time ACLs
  269. "time": {
  270. "category": "time",
  271. "slow": False,
  272. "desc": "Time of day and day of week",
  273. },
  274. # URL ACLs
  275. "url_regex": {
  276. "category": "url",
  277. "slow": False,
  278. "desc": "Regex match on full URL",
  279. },
  280. "urllogin": {
  281. "category": "url",
  282. "slow": False,
  283. "desc": "Regex match on URL login field",
  284. },
  285. "urlpath_regex": {
  286. "category": "url",
  287. "slow": False,
  288. "desc": "Regex match on URL path",
  289. },
  290. # Port ACLs
  291. "port": {
  292. "category": "port",
  293. "slow": False,
  294. "desc": "Destination TCP port",
  295. },
  296. "localport": {
  297. "category": "port",
  298. "slow": False,
  299. "desc": "TCP port client connected to",
  300. },
  301. "myportname": {
  302. "category": "port",
  303. "slow": False,
  304. "desc": "Port name from *_port directive",
  305. },
  306. # Protocol & Method ACLs
  307. "proto": {
  308. "category": "protocol",
  309. "slow": False,
  310. "desc": "Request protocol (HTTP, FTP, etc)",
  311. },
  312. "method": {
  313. "category": "protocol",
  314. "slow": False,
  315. "desc": "HTTP request method",
  316. },
  317. "http_status": {
  318. "category": "protocol",
  319. "slow": False,
  320. "desc": "HTTP status code in reply",
  321. },
  322. # Header ACLs
  323. "browser": {
  324. "category": "content",
  325. "slow": False,
  326. "desc": "User-Agent header pattern",
  327. },
  328. "referer_regex": {
  329. "category": "content",
  330. "slow": False,
  331. "desc": "Referer header pattern",
  332. },
  333. "req_header": {
  334. "category": "content",
  335. "slow": False,
  336. "desc": "Request header pattern",
  337. },
  338. "rep_header": {
  339. "category": "content",
  340. "slow": False,
  341. "desc": "Reply header pattern",
  342. },
  343. # Authentication ACLs
  344. "proxy_auth": {
  345. "category": "auth",
  346. "slow": True,
  347. "desc": "Proxy authentication username",
  348. },
  349. "proxy_auth_regex": {
  350. "category": "auth",
  351. "slow": True,
  352. "desc": "Proxy auth username regex",
  353. },
  354. "ext_user": {
  355. "category": "auth",
  356. "slow": True,
  357. "desc": "External ACL helper username",
  358. },
  359. "ext_user_regex": {
  360. "category": "auth",
  361. "slow": True,
  362. "desc": "External ACL helper username regex",
  363. },
  364. # MIME Type ACLs
  365. "req_mime_type": {
  366. "category": "content",
  367. "slow": False,
  368. "desc": "Request MIME type",
  369. },
  370. "rep_mime_type": {
  371. "category": "content",
  372. "slow": False,
  373. "desc": "Reply MIME type",
  374. },
  375. # Connection ACLs
  376. "maxconn": {
  377. "category": "connection",
  378. "slow": False,
  379. "desc": "Max TCP connections from IP",
  380. },
  381. "max_user_ip": {
  382. "category": "connection",
  383. "slow": False,
  384. "desc": "Max IPs per user",
  385. },
  386. # SSL/TLS ACLs
  387. "ssl_error": {
  388. "category": "ssl",
  389. "slow": False,
  390. "desc": "SSL certificate validation error",
  391. },
  392. "server_cert_fingerprint": {
  393. "category": "ssl",
  394. "slow": False,
  395. "desc": "Server cert fingerprint",
  396. },
  397. "ssl::server_name": {
  398. "category": "ssl",
  399. "slow": False,
  400. "desc": "TLS SNI server name",
  401. },
  402. "ssl::server_name_regex": {
  403. "category": "ssl",
  404. "slow": False,
  405. "desc": "TLS SNI regex match",
  406. },
  407. "connections_encrypted": {
  408. "category": "ssl",
  409. "slow": False,
  410. "desc": "All connections over TLS",
  411. },
  412. # Advanced ACLs
  413. "external": {
  414. "category": "advanced",
  415. "slow": True,
  416. "desc": "External ACL helper lookup",
  417. },
  418. "random": {
  419. "category": "advanced",
  420. "slow": False,
  421. "desc": "Random probability match",
  422. },
  423. "note": {
  424. "category": "advanced",
  425. "slow": False,
  426. "desc": "Transaction annotation",
  427. },
  428. "annotate_transaction": {
  429. "category": "advanced",
  430. "slow": False,
  431. "desc": "Add transaction annotation",
  432. },
  433. "annotate_client": {
  434. "category": "advanced",
  435. "slow": False,
  436. "desc": "Add client annotation",
  437. },
  438. "peername": {
  439. "category": "advanced",
  440. "slow": False,
  441. "desc": "Cache peer name",
  442. },
  443. "peername_regex": {
  444. "category": "advanced",
  445. "slow": False,
  446. "desc": "Cache peer name regex",
  447. },
  448. "hier_code": {
  449. "category": "advanced",
  450. "slow": False,
  451. "desc": "Squid hierarchy code",
  452. },
  453. # Group ACLs
  454. "any-of": {
  455. "category": "group",
  456. "slow": False,
  457. "desc": "Match any of the ACLs",
  458. },
  459. "all-of": {
  460. "category": "group",
  461. "slow": False,
  462. "desc": "Match all of the ACLs",
  463. },
  464. }
  465. last_comment = ""
  466. for line_num, line in enumerate(lines, 1):
  467. try:
  468. stripped = line.strip()
  469. # Track comments for context
  470. if stripped.startswith("#"):
  471. last_comment = stripped[1:].strip()
  472. continue
  473. if stripped.startswith("acl "):
  474. parts = stripped.split()
  475. if len(parts) >= 3:
  476. acl_name = parts[1]
  477. # Parse options and type
  478. options = []
  479. type_index = 2
  480. while type_index < len(parts) and parts[
  481. type_index
  482. ].startswith("-"):
  483. options.append(parts[type_index])
  484. type_index += 1
  485. if type_index >= len(parts):
  486. continue
  487. acl_type = parts[type_index]
  488. values = (
  489. parts[type_index + 1 :]
  490. if len(parts) > type_index + 1
  491. else []
  492. )
  493. value_string = " ".join(values)
  494. # Get type metadata
  495. type_info = acl_types_info.get(
  496. acl_type,
  497. {
  498. "category": "other",
  499. "slow": False,
  500. "desc": "Custom ACL type",
  501. },
  502. )
  503. # Check if predefined
  504. is_predefined = acl_name in predefined_acls
  505. acls.append(
  506. {
  507. "id": acl_index,
  508. "name": acl_name,
  509. "type": acl_type,
  510. "options": options,
  511. "value_list": values,
  512. "value_string": value_string,
  513. "is_predefined": is_predefined,
  514. "is_slow": type_info.get("slow", False),
  515. "category": type_info.get("category", "other"),
  516. "type_description": type_info.get("desc", ""),
  517. "comment": last_comment if last_comment else "",
  518. "line_number": line_num,
  519. "full_line": stripped,
  520. }
  521. )
  522. acl_index += 1
  523. last_comment = ""
  524. except Exception as e:
  525. logger.warning(f"Error processing ACL at line {line_num}: {e}")
  526. continue
  527. logger.debug(f"Found {len(acls)} ACLs")
  528. return acls
  529. except Exception as e:
  530. logger.error(f"Unexpected error extracting ACLs: {e}")
  531. return []
  532. def get_delay_pools(self):
  533. """
  534. Parse delay pools configuration and group by pool number.
  535. Returns a list of pool dictionaries with all related directives.
  536. Format:
  537. {
  538. 'pool_number': '1',
  539. 'class': '3',
  540. 'parameters': '8192/131072 1024/65536 256/32768',
  541. 'access_rules': [{'action': 'allow', 'acl': 'students'}]
  542. }
  543. """
  544. if not self.is_valid:
  545. logger.error("Cannot get delay pools: invalid environment")
  546. return []
  547. # If using modular config, read from the delay pools specific file
  548. if self.is_modular:
  549. delay_content = self.read_modular_config("110_delay_pools.conf")
  550. if not delay_content:
  551. logger.warning(
  552. "Could not read modular delay pools config, falling back to main config"
  553. )
  554. config_to_parse = self.config_content
  555. else:
  556. config_to_parse = delay_content
  557. else:
  558. if not self.config_content:
  559. logger.warning("No configuration content available")
  560. return []
  561. config_to_parse = self.config_content
  562. try:
  563. pools_dict = {} # Dictionary to group by pool number
  564. total_pools = 0
  565. lines = config_to_parse.split("\n")
  566. for line_num, line in enumerate(lines, 1):
  567. try:
  568. line = line.strip()
  569. if line.startswith("delay_pools "):
  570. parts = line.split()
  571. if len(parts) >= 2:
  572. total_pools = int(parts[1])
  573. elif line.startswith("delay_class "):
  574. parts = line.split()
  575. if len(parts) >= 3:
  576. pool_num = parts[1]
  577. if pool_num not in pools_dict:
  578. pools_dict[pool_num] = {
  579. "pool_number": pool_num,
  580. "class": parts[2],
  581. "parameters": None,
  582. "access_rules": [],
  583. }
  584. else:
  585. pools_dict[pool_num]["class"] = parts[2]
  586. elif line.startswith("delay_parameters "):
  587. parts = line.split()
  588. if len(parts) >= 3:
  589. pool_num = parts[1]
  590. if pool_num not in pools_dict:
  591. pools_dict[pool_num] = {
  592. "pool_number": pool_num,
  593. "class": None,
  594. "parameters": " ".join(parts[2:]),
  595. "access_rules": [],
  596. }
  597. else:
  598. pools_dict[pool_num]["parameters"] = " ".join(parts[2:])
  599. elif line.startswith("delay_access "):
  600. parts = line.split()
  601. if len(parts) >= 4:
  602. pool_num = parts[1]
  603. if pool_num not in pools_dict:
  604. pools_dict[pool_num] = {
  605. "pool_number": pool_num,
  606. "class": None,
  607. "parameters": None,
  608. "access_rules": [],
  609. }
  610. pools_dict[pool_num]["access_rules"].append(
  611. {"action": parts[2], "acl": " ".join(parts[3:])}
  612. )
  613. except Exception as e:
  614. logger.warning(
  615. f"Error processing delay pool at line {line_num}: {e}"
  616. )
  617. continue
  618. # Convert dictionary to sorted list
  619. delay_pools = [
  620. pools_dict[key] for key in sorted(pools_dict.keys(), key=int)
  621. ]
  622. logger.debug(
  623. f"Found {len(delay_pools)} delay pool configurations (total_pools={total_pools})"
  624. )
  625. return delay_pools
  626. except Exception as e:
  627. logger.error(f"Unexpected error extracting delay pools: {e}")
  628. return []
  629. def get_http_access_rules(self):
  630. """
  631. Parse http_access rules with enhanced information.
  632. Returns a list of rule dictionaries with action, acls (list), and metadata.
  633. Format:
  634. {
  635. 'action': 'allow',
  636. 'acls': ['!Safe_ports'], # List of ACLs including negations
  637. 'acl_string': '!Safe_ports', # Original ACL string
  638. 'is_negative': True, # If it contains negation
  639. 'line_number': 5, # Original line number
  640. 'description': '' # Optional description from comments
  641. }
  642. """
  643. if not self.is_valid:
  644. logger.error("Cannot get HTTP rules: invalid environment")
  645. return []
  646. # If using modular config, read from the http_access specific file
  647. if self.is_modular:
  648. http_content = self.read_modular_config("120_http_access.conf")
  649. if not http_content:
  650. logger.warning(
  651. "Could not read modular http_access config, falling back to main config"
  652. )
  653. config_to_parse = self.config_content
  654. else:
  655. config_to_parse = http_content
  656. else:
  657. if not self.config_content:
  658. logger.warning("No configuration content available")
  659. return []
  660. config_to_parse = self.config_content
  661. try:
  662. rules = []
  663. lines = config_to_parse.split("\n")
  664. last_comment = ""
  665. for line_num, line in enumerate(lines, 1):
  666. try:
  667. stripped = line.strip()
  668. # Track comments for context
  669. if stripped.startswith("#"):
  670. last_comment = stripped[1:].strip()
  671. continue
  672. if stripped.startswith("http_access "):
  673. parts = stripped.split()
  674. if len(parts) >= 3:
  675. action = parts[1]
  676. acl_string = " ".join(parts[2:])
  677. acls = parts[2:]
  678. # Check if any ACL has negation
  679. is_negative = any(acl.startswith("!") for acl in acls)
  680. # Identify special/common ACLs
  681. special_acls = []
  682. if "localhost" in acls:
  683. special_acls.append("localhost")
  684. if "manager" in acls:
  685. special_acls.append("manager")
  686. if any("Safe_ports" in acl for acl in acls):
  687. special_acls.append("Safe_ports")
  688. if any("SSL_ports" in acl for acl in acls):
  689. special_acls.append("SSL_ports")
  690. if "CONNECT" in acls:
  691. special_acls.append("CONNECT")
  692. rules.append(
  693. {
  694. "action": action,
  695. "acls": acls,
  696. "acl_string": acl_string,
  697. "is_negative": is_negative,
  698. "line_number": line_num,
  699. "description": last_comment if last_comment else "",
  700. "special_acls": special_acls,
  701. }
  702. )
  703. last_comment = "" # Reset comment
  704. except Exception as e:
  705. logger.warning(
  706. f"Error processing HTTP rule at line {line_num}: {e}"
  707. )
  708. continue
  709. logger.debug(f"Found {len(rules)} HTTP access rules")
  710. return rules
  711. except Exception as e:
  712. logger.error(f"Unexpected error extracting HTTP rules: {e}")
  713. return []
  714. def _check_modular_config(self):
  715. """Check if the main config file uses modular includes."""
  716. if not self.config_content:
  717. return
  718. # Check if config contains include directives pointing to squid.d
  719. self.is_modular = (
  720. "include" in self.config_content.lower()
  721. and "squid.d" in self.config_content
  722. )
  723. if self.is_modular:
  724. logger.info("Modular configuration detected")
  725. def list_modular_configs(self) -> list[dict[str, str]]:
  726. """List all modular configuration files in squid.d directory."""
  727. if not os.path.exists(self.config_dir):
  728. logger.warning(f"Config directory not found: {self.config_dir}")
  729. return []
  730. try:
  731. configs = []
  732. for filename in sorted(os.listdir(self.config_dir)):
  733. if filename.endswith(".conf"):
  734. filepath = os.path.join(self.config_dir, filename)
  735. if os.path.isfile(filepath):
  736. try:
  737. stat = os.stat(filepath)
  738. configs.append(
  739. {
  740. "filename": filename,
  741. "filepath": filepath,
  742. "size": stat.st_size,
  743. "modified": datetime.fromtimestamp(
  744. stat.st_mtime
  745. ).strftime("%Y-%m-%d %H:%M:%S"),
  746. "readable": os.access(filepath, os.R_OK),
  747. "writable": os.access(filepath, os.W_OK),
  748. }
  749. )
  750. except Exception as e:
  751. logger.warning(
  752. f"Error reading file info for {filename}: {e}"
  753. )
  754. return configs
  755. except Exception as e:
  756. logger.error(f"Error listing modular configs: {e}")
  757. return []
  758. def read_modular_config(self, filename: str) -> str | None:
  759. """Read a specific modular configuration file."""
  760. filepath = os.path.join(self.config_dir, filename)
  761. if not os.path.exists(filepath):
  762. logger.error(f"Config file not found: {filepath}")
  763. return None
  764. if not filepath.endswith(".conf"):
  765. logger.error(f"Invalid file extension: {filename}")
  766. return None
  767. try:
  768. with open(filepath, encoding="utf-8") as f:
  769. content = f.read()
  770. logger.debug(f"Read modular config: {filename}")
  771. return content
  772. except Exception as e:
  773. logger.error(f"Error reading modular config {filename}: {e}")
  774. return None
  775. def save_modular_config(self, filename: str, content: str) -> bool:
  776. """Save content to a specific modular configuration file."""
  777. filepath = os.path.join(self.config_dir, filename)
  778. if not filename.endswith(".conf"):
  779. logger.error(f"Invalid file extension: {filename}")
  780. return False
  781. # Validate filename to prevent directory traversal
  782. if "/" in filename or "\\" in filename or ".." in filename:
  783. logger.error(f"Invalid filename (potential path traversal): {filename}")
  784. return False
  785. try:
  786. # Create backup before saving
  787. if os.path.exists(filepath):
  788. backup_path = (
  789. f"{filepath}.bak{datetime.now().strftime('%Y%m%d_%H%M%S')}"
  790. )
  791. try:
  792. shutil.copy2(filepath, backup_path)
  793. logger.info(f"Backup created: {backup_path}")
  794. except Exception as e:
  795. logger.warning(f"Could not create backup: {e}")
  796. with open(filepath, "w", encoding="utf-8") as f:
  797. f.write(content)
  798. logger.info(f"Saved modular config: {filename}")
  799. return True
  800. except Exception as e:
  801. logger.error(f"Error saving modular config {filename}: {e}")
  802. return False
  803. def delete_modular_config(self, filename: str) -> bool:
  804. """Delete a specific modular configuration file."""
  805. filepath = os.path.join(self.config_dir, filename)
  806. if not os.path.exists(filepath):
  807. logger.error(f"Config file not found: {filepath}")
  808. return False
  809. if not filename.endswith(".conf"):
  810. logger.error(f"Invalid file extension: {filename}")
  811. return False
  812. # Validate filename to prevent directory traversal
  813. if "/" in filename or "\\" in filename or ".." in filename:
  814. logger.error(f"Invalid filename (potential path traversal): {filename}")
  815. return False
  816. try:
  817. # Create backup before deleting
  818. backup_path = (
  819. f"{filepath}.deleted{datetime.now().strftime('%Y%m%d_%H%M%S')}"
  820. )
  821. try:
  822. shutil.move(filepath, backup_path)
  823. logger.info(f"File moved to: {backup_path}")
  824. return True
  825. except Exception as e:
  826. logger.error(f"Error deleting file {filename}: {e}")
  827. return False
  828. except Exception as e:
  829. logger.error(f"Error handling file deletion {filename}: {e}")
  830. return False
  831. def get_modular_config_info(self) -> dict:
  832. """Get information about the modular configuration setup."""
  833. return {
  834. "is_modular": self.is_modular,
  835. "config_dir": self.config_dir,
  836. "config_dir_exists": os.path.exists(self.config_dir),
  837. "config_files_count": len(self.list_modular_configs()),
  838. "main_config_path": self.config_path,
  839. }
  840. def detect_ssl_bump(self) -> dict:
  841. """Detect whether SSL Bump is enabled in the Squid configuration.
  842. Inspects ``http_port`` directives (with backslash-continuation support),
  843. ``ssl_bump`` action rules, and ``sslcrtd_*`` directives.
  844. Returns a dict::
  845. {
  846. "enabled": bool,
  847. "mode": "peek-and-splice" | "bump-all" | "custom" | "basic" | None,
  848. "cert": str | None, # path in cert= option
  849. "generate_certs": bool,
  850. "sslcrtd_configured": bool,
  851. "sslcrtd_children": int | None,
  852. "http_port_entry": str | None,
  853. "ssl_bump_rules": list[str],
  854. "source": "main" | "modular",
  855. }
  856. """
  857. result: dict = {
  858. "enabled": False,
  859. "mode": None,
  860. "cert": None,
  861. "generate_certs": False,
  862. "sslcrtd_configured": False,
  863. "sslcrtd_children": None,
  864. "http_port_entry": None,
  865. "ssl_bump_rules": [],
  866. "source": "main",
  867. }
  868. if not self.is_valid:
  869. return result
  870. ports_content = self.config_content
  871. ssl_content = self.config_content
  872. if self.is_modular:
  873. # Use os.path.exists to avoid ERROR logs for optional modular files
  874. ports_path = os.path.join(self.config_dir, "00_ports.conf")
  875. ssl_path = os.path.join(self.config_dir, "55_ssl_bump.conf")
  876. if os.path.exists(ports_path):
  877. mc_ports = self.read_modular_config("00_ports.conf")
  878. if mc_ports:
  879. ports_content = mc_ports
  880. result["source"] = "modular"
  881. if os.path.exists(ssl_path):
  882. mc_ssl = self.read_modular_config("55_ssl_bump.conf")
  883. if mc_ssl:
  884. ssl_content = mc_ssl
  885. result["source"] = "modular"
  886. # --- http_port: join continuation lines then scan ---
  887. joined_ports = _join_continuation_lines(ports_content)
  888. for line in joined_ports.splitlines():
  889. stripped = line.strip()
  890. if not stripped or stripped.startswith("#"):
  891. continue
  892. if re.match(r"^http_port\b", stripped):
  893. tokens = stripped.split()
  894. if "ssl-bump" in tokens:
  895. result["enabled"] = True
  896. result["http_port_entry"] = stripped
  897. cert_m = re.search(r"\bcert=(\S+)", stripped)
  898. if cert_m:
  899. result["cert"] = cert_m.group(1)
  900. gen_m = re.search(
  901. r"\bgenerate-host-certificates=(on|off)\b", stripped
  902. )
  903. if gen_m:
  904. result["generate_certs"] = gen_m.group(1) == "on"
  905. break
  906. # --- ssl_bump action rules ---
  907. ssl_bump_rules = []
  908. for line in ssl_content.splitlines():
  909. stripped = line.strip()
  910. if not stripped or stripped.startswith("#"):
  911. continue
  912. if re.match(r"^ssl_bump\b", stripped):
  913. ssl_bump_rules.append(stripped)
  914. result["ssl_bump_rules"] = ssl_bump_rules
  915. # --- sslcrtd_* directives ---
  916. for line in ssl_content.splitlines():
  917. stripped = line.strip()
  918. if not stripped or stripped.startswith("#"):
  919. continue
  920. if re.match(r"^sslcrtd_program\b", stripped):
  921. result["sslcrtd_configured"] = True
  922. elif re.match(r"^sslcrtd_children\b", stripped):
  923. m = re.match(r"^sslcrtd_children\s+(\d+)", stripped)
  924. if m:
  925. result["sslcrtd_children"] = int(m.group(1))
  926. # --- determine mode ---
  927. if result["enabled"]:
  928. has_bump = any(
  929. re.match(r"^ssl_bump\s+bump\b", r) for r in ssl_bump_rules
  930. )
  931. has_peek = any(
  932. re.match(r"^ssl_bump\s+peek\b", r) for r in ssl_bump_rules
  933. )
  934. has_splice = any(
  935. re.match(r"^ssl_bump\s+splice\b", r) for r in ssl_bump_rules
  936. )
  937. if has_peek or has_splice:
  938. result["mode"] = "peek-and-splice"
  939. elif has_bump:
  940. result["mode"] = "bump-all"
  941. elif ssl_bump_rules:
  942. result["mode"] = "custom"
  943. else:
  944. result["mode"] = "basic"
  945. return result
  946. def get_status(self):
  947. return {
  948. "is_valid": self.is_valid,
  949. "errors": self.errors,
  950. "config_loaded": bool(self.config_content),
  951. "config_path": self.config_path,
  952. "config_dir": self.config_dir,
  953. "is_modular": self.is_modular,
  954. "acl_files_dir": ACL_FILES_DIR,
  955. }