4
0

admin.py 40 KB

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