admin.py 42 KB

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