admin.py 34 KB

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