admin.py 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091
  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. parts = line.split()
  592. if len(parts) >= 2:
  593. total_pools = int(parts[1])
  594. elif line.startswith("delay_class "):
  595. parts = line.split()
  596. if len(parts) >= 3:
  597. pool_num = parts[1]
  598. if pool_num not in pools_dict:
  599. pools_dict[pool_num] = {
  600. "pool_number": pool_num,
  601. "class": parts[2],
  602. "parameters": None,
  603. "access_rules": [],
  604. }
  605. else:
  606. pools_dict[pool_num]["class"] = parts[2]
  607. elif line.startswith("delay_parameters "):
  608. parts = line.split()
  609. if len(parts) >= 3:
  610. pool_num = parts[1]
  611. if pool_num not in pools_dict:
  612. pools_dict[pool_num] = {
  613. "pool_number": pool_num,
  614. "class": None,
  615. "parameters": " ".join(parts[2:]),
  616. "access_rules": [],
  617. }
  618. else:
  619. pools_dict[pool_num]["parameters"] = " ".join(parts[2:])
  620. elif line.startswith("delay_access "):
  621. parts = line.split()
  622. if len(parts) >= 4:
  623. pool_num = parts[1]
  624. if pool_num not in pools_dict:
  625. pools_dict[pool_num] = {
  626. "pool_number": pool_num,
  627. "class": None,
  628. "parameters": None,
  629. "access_rules": [],
  630. }
  631. pools_dict[pool_num]["access_rules"].append(
  632. {"action": parts[2], "acl": " ".join(parts[3:])}
  633. )
  634. except Exception as e:
  635. logger.warning(
  636. f"Error processing delay pool at line {line_num}: {e}"
  637. )
  638. continue
  639. # Convert dictionary to sorted list
  640. delay_pools = [
  641. pools_dict[key] for key in sorted(pools_dict.keys(), key=int)
  642. ]
  643. logger.debug(
  644. f"Found {len(delay_pools)} delay pool configurations (total_pools={total_pools})"
  645. )
  646. return delay_pools
  647. except Exception as e:
  648. logger.error(f"Unexpected error extracting delay pools: {e}")
  649. return []
  650. def get_http_access_rules(self):
  651. """
  652. Parse http_access rules with enhanced information.
  653. Returns a list of rule dictionaries with action, acls (list), and metadata.
  654. Format:
  655. {
  656. 'action': 'allow',
  657. 'acls': ['!Safe_ports'], # List of ACLs including negations
  658. 'acl_string': '!Safe_ports', # Original ACL string
  659. 'is_negative': True, # If it contains negation
  660. 'line_number': 5, # Original line number
  661. 'description': '' # Optional description from comments
  662. }
  663. """
  664. if not self.is_valid:
  665. logger.error("Cannot get HTTP rules: invalid environment")
  666. return []
  667. # If using modular config, read from the http_access specific file
  668. if self.is_modular:
  669. http_content = self.read_modular_config("120_http_access.conf")
  670. if not http_content:
  671. logger.warning(
  672. "Could not read modular http_access config, falling back to main config"
  673. )
  674. config_to_parse = self.config_content
  675. else:
  676. config_to_parse = http_content
  677. else:
  678. if not self.config_content:
  679. logger.warning("No configuration content available")
  680. return []
  681. config_to_parse = self.config_content
  682. try:
  683. rules = []
  684. lines = config_to_parse.split("\n")
  685. last_comment = ""
  686. for line_num, line in enumerate(lines, 1):
  687. try:
  688. stripped = line.strip()
  689. # Track comments for context
  690. if stripped.startswith("#"):
  691. last_comment = stripped[1:].strip()
  692. continue
  693. if stripped.startswith("http_access "):
  694. parts = stripped.split()
  695. if len(parts) >= 3:
  696. action = parts[1]
  697. acl_string = " ".join(parts[2:])
  698. acls = parts[2:]
  699. # Check if any ACL has negation
  700. is_negative = any(acl.startswith("!") for acl in acls)
  701. # Identify special/common ACLs
  702. special_acls = []
  703. if "localhost" in acls:
  704. special_acls.append("localhost")
  705. if "manager" in acls:
  706. special_acls.append("manager")
  707. if any("Safe_ports" in acl for acl in acls):
  708. special_acls.append("Safe_ports")
  709. if any("SSL_ports" in acl for acl in acls):
  710. special_acls.append("SSL_ports")
  711. if "CONNECT" in acls:
  712. special_acls.append("CONNECT")
  713. rules.append(
  714. {
  715. "action": action,
  716. "acls": acls,
  717. "acl_string": acl_string,
  718. "is_negative": is_negative,
  719. "line_number": line_num,
  720. "description": last_comment if last_comment else "",
  721. "special_acls": special_acls,
  722. }
  723. )
  724. last_comment = "" # Reset comment
  725. except Exception as e:
  726. logger.warning(
  727. f"Error processing HTTP rule at line {line_num}: {e}"
  728. )
  729. continue
  730. logger.debug(f"Found {len(rules)} HTTP access rules")
  731. return rules
  732. except Exception as e:
  733. logger.error(f"Unexpected error extracting HTTP rules: {e}")
  734. return []
  735. def _check_modular_config(self):
  736. """Check if the main config file uses modular includes."""
  737. if not self.config_content:
  738. return
  739. # Check if config contains include directives pointing to squid.d
  740. self.is_modular = (
  741. "include" in self.config_content.lower()
  742. and "squid.d" in self.config_content
  743. )
  744. if self.is_modular:
  745. logger.info("Modular configuration detected")
  746. def list_modular_configs(self) -> list[dict[str, str]]:
  747. """List all modular configuration files in squid.d directory."""
  748. if not os.path.exists(self.config_dir):
  749. logger.warning(f"Config directory not found: {self.config_dir}")
  750. return []
  751. try:
  752. configs = []
  753. for filename in sorted(os.listdir(self.config_dir)):
  754. if filename.endswith(".conf"):
  755. filepath = os.path.join(self.config_dir, filename)
  756. if os.path.isfile(filepath):
  757. try:
  758. stat = os.stat(filepath)
  759. configs.append(
  760. {
  761. "filename": filename,
  762. "filepath": filepath,
  763. "size": stat.st_size,
  764. "modified": datetime.fromtimestamp(
  765. stat.st_mtime
  766. ).strftime("%Y-%m-%d %H:%M:%S"),
  767. "readable": os.access(filepath, os.R_OK),
  768. "writable": os.access(filepath, os.W_OK),
  769. }
  770. )
  771. except Exception as e:
  772. logger.warning(
  773. f"Error reading file info for {filename}: {e}"
  774. )
  775. return configs
  776. except Exception as e:
  777. logger.error(f"Error listing modular configs: {e}")
  778. return []
  779. def read_modular_config(self, filename: str) -> str | None:
  780. """Read a specific modular configuration file."""
  781. filepath = os.path.join(self.config_dir, filename)
  782. if not os.path.exists(filepath):
  783. logger.error(f"Config file not found: {filepath}")
  784. return None
  785. if not filepath.endswith(".conf"):
  786. logger.error(f"Invalid file extension: {filename}")
  787. return None
  788. try:
  789. with open(filepath, encoding="utf-8") as f:
  790. content = f.read()
  791. logger.debug(f"Read modular config: {filename}")
  792. return content
  793. except Exception as e:
  794. logger.error(f"Error reading modular config {filename}: {e}")
  795. return None
  796. def save_modular_config(self, filename: str, content: str) -> bool:
  797. """Save content to a specific modular configuration file."""
  798. filepath = os.path.join(self.config_dir, filename)
  799. if not filename.endswith(".conf"):
  800. logger.error(f"Invalid file extension: {filename}")
  801. return False
  802. # Validate filename to prevent directory traversal
  803. if "/" in filename or "\\" in filename or ".." in filename:
  804. logger.error(f"Invalid filename (potential path traversal): {filename}")
  805. return False
  806. try:
  807. # Skip write if content hasn't changed
  808. if os.path.exists(filepath):
  809. try:
  810. with open(filepath, encoding="utf-8") as f:
  811. existing = f.read()
  812. if existing == content:
  813. logger.debug(
  814. f"Modular config unchanged, skipping write: {filename}"
  815. )
  816. return True
  817. except Exception:
  818. pass # If we can't read, proceed with write
  819. # Create single backup before overwriting
  820. backup_path = f"{filepath}.bak"
  821. try:
  822. shutil.copy2(filepath, backup_path)
  823. logger.debug(f"Backup created: {backup_path}")
  824. except Exception as e:
  825. logger.warning(f"Could not create backup for {filename}: {e}")
  826. with open(filepath, "w", encoding="utf-8") as f:
  827. f.write(content)
  828. logger.info(f"Saved modular config: {filename}")
  829. return True
  830. except Exception as e:
  831. logger.error(f"Error saving modular config {filename}: {e}")
  832. return False
  833. def delete_modular_config(self, filename: str) -> bool:
  834. """Delete a specific modular configuration file."""
  835. filepath = os.path.join(self.config_dir, filename)
  836. if not os.path.exists(filepath):
  837. logger.error(f"Config file not found: {filepath}")
  838. return False
  839. if not filename.endswith(".conf"):
  840. logger.error(f"Invalid file extension: {filename}")
  841. return False
  842. # Validate filename to prevent directory traversal
  843. if "/" in filename or "\\" in filename or ".." in filename:
  844. logger.error(f"Invalid filename (potential path traversal): {filename}")
  845. return False
  846. try:
  847. # Keep a single .deleted backup, removing any previous one
  848. backup_path = f"{filepath}.deleted"
  849. if os.path.exists(backup_path):
  850. try:
  851. os.remove(backup_path)
  852. except Exception as e:
  853. logger.warning(f"Could not remove previous deleted backup: {e}")
  854. try:
  855. shutil.move(filepath, backup_path)
  856. logger.info(f"File moved to: {backup_path}")
  857. return True
  858. except Exception as e:
  859. logger.error(f"Error deleting file {filename}: {e}")
  860. return False
  861. except Exception as e:
  862. logger.error(f"Error handling file deletion {filename}: {e}")
  863. return False
  864. def get_modular_config_info(self) -> dict:
  865. """Get information about the modular configuration setup."""
  866. return {
  867. "is_modular": self.is_modular,
  868. "config_dir": self.config_dir,
  869. "config_dir_exists": os.path.exists(self.config_dir),
  870. "config_files_count": len(self.list_modular_configs()),
  871. "main_config_path": self.config_path,
  872. }
  873. def detect_ssl_bump(self) -> dict:
  874. """Detect whether SSL Bump is enabled in the Squid configuration.
  875. Inspects ``http_port`` directives (with backslash-continuation support),
  876. ``ssl_bump`` action rules, and ``sslcrtd_*`` directives.
  877. Returns a dict::
  878. {
  879. "enabled": bool,
  880. "mode": "peek-and-splice" | "bump-all" | "custom" | "basic" | None,
  881. "cert": str | None, # path in cert= option
  882. "generate_certs": bool,
  883. "sslcrtd_configured": bool,
  884. "sslcrtd_children": int | None,
  885. "http_port_entry": str | None,
  886. "ssl_bump_rules": list[str],
  887. "source": "main" | "modular",
  888. }
  889. """
  890. result: dict = {
  891. "enabled": False,
  892. "mode": None,
  893. "cert": None,
  894. "generate_certs": False,
  895. "sslcrtd_configured": False,
  896. "sslcrtd_children": None,
  897. "http_port_entry": None,
  898. "ssl_bump_rules": [],
  899. "source": "main",
  900. }
  901. if not self.is_valid:
  902. return result
  903. ports_content = self.config_content
  904. ssl_content = self.config_content
  905. if self.is_modular:
  906. # Use os.path.exists to avoid ERROR logs for optional modular files
  907. ports_path = os.path.join(self.config_dir, "00_ports.conf")
  908. ssl_path = os.path.join(self.config_dir, "55_ssl_bump.conf")
  909. if os.path.exists(ports_path):
  910. mc_ports = self.read_modular_config("00_ports.conf")
  911. if mc_ports:
  912. ports_content = mc_ports
  913. result["source"] = "modular"
  914. if os.path.exists(ssl_path):
  915. mc_ssl = self.read_modular_config("55_ssl_bump.conf")
  916. if mc_ssl:
  917. ssl_content = mc_ssl
  918. result["source"] = "modular"
  919. # --- http_port: join continuation lines then scan ---
  920. joined_ports = _join_continuation_lines(ports_content)
  921. for line in joined_ports.splitlines():
  922. stripped = line.strip()
  923. if not stripped or stripped.startswith("#"):
  924. continue
  925. if re.match(r"^http_port\b", stripped):
  926. tokens = stripped.split()
  927. if "ssl-bump" in tokens:
  928. result["enabled"] = True
  929. result["http_port_entry"] = stripped
  930. cert_m = re.search(r"\bcert=(\S+)", stripped)
  931. if cert_m:
  932. result["cert"] = cert_m.group(1)
  933. gen_m = re.search(
  934. r"\bgenerate-host-certificates=(on|off)\b", stripped
  935. )
  936. if gen_m:
  937. result["generate_certs"] = gen_m.group(1) == "on"
  938. break
  939. # --- ssl_bump action rules ---
  940. ssl_bump_rules = []
  941. for line in ssl_content.splitlines():
  942. stripped = line.strip()
  943. if not stripped or stripped.startswith("#"):
  944. continue
  945. if re.match(r"^ssl_bump\b", stripped):
  946. ssl_bump_rules.append(stripped)
  947. result["ssl_bump_rules"] = ssl_bump_rules
  948. # --- sslcrtd_* directives ---
  949. for line in ssl_content.splitlines():
  950. stripped = line.strip()
  951. if not stripped or stripped.startswith("#"):
  952. continue
  953. if re.match(r"^sslcrtd_program\b", stripped):
  954. result["sslcrtd_configured"] = True
  955. elif re.match(r"^sslcrtd_children\b", stripped):
  956. m = re.match(r"^sslcrtd_children\s+(\d+)", stripped)
  957. if m:
  958. result["sslcrtd_children"] = int(m.group(1))
  959. # --- determine mode ---
  960. if result["enabled"]:
  961. has_bump = any(re.match(r"^ssl_bump\s+bump\b", r) for r in ssl_bump_rules)
  962. has_peek = any(re.match(r"^ssl_bump\s+peek\b", r) for r in ssl_bump_rules)
  963. has_splice = any(
  964. re.match(r"^ssl_bump\s+splice\b", r) for r in ssl_bump_rules
  965. )
  966. if has_peek or has_splice:
  967. result["mode"] = "peek-and-splice"
  968. elif has_bump:
  969. result["mode"] = "bump-all"
  970. elif ssl_bump_rules:
  971. result["mode"] = "custom"
  972. else:
  973. result["mode"] = "basic"
  974. return result
  975. def get_status(self):
  976. return {
  977. "is_valid": self.is_valid,
  978. "errors": self.errors,
  979. "config_loaded": bool(self.config_content),
  980. "config_path": self.config_path,
  981. "config_dir": self.config_dir,
  982. "is_modular": self.is_modular,
  983. "acl_files_dir": ACL_FILES_DIR,
  984. }