| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091 |
- import os
- import re
- import shutil
- from datetime import datetime
- from dotenv import load_dotenv
- from loguru import logger
- from config import Config
- load_dotenv()
- SQUID_CONFIG_PATH = Config.SQUID_CONFIG_PATH or "/etc/squid/squid.conf"
- ACL_FILES_DIR = os.getenv("ACL_FILES_DIR") or os.path.join(
- os.path.dirname(SQUID_CONFIG_PATH), "squid.d", ""
- )
- def _join_continuation_lines(content: str) -> str:
- """Join lines ending with a backslash with the following line."""
- lines = content.splitlines()
- result = []
- i = 0
- while i < len(lines):
- line = lines[i]
- while line.rstrip().endswith("\\"):
- line = line.rstrip()[:-1]
- i += 1
- if i < len(lines):
- line += " " + lines[i].strip()
- result.append(line)
- i += 1
- return "\n".join(result)
- def validate_paths():
- """Validate the squid.conf path (hard errors) and the ACL directory (warnings only).
- Returns a list of *hard* error strings that block SquidConfigManager
- initialization. Missing or inaccessible ACL directories are logged as
- warnings but do NOT appear in the returned list — they only disable
- modular-config support.
- """
- errors = []
- cfg = os.path.abspath(os.path.expanduser(SQUID_CONFIG_PATH))
- if os.path.isdir(cfg):
- squid_conf = os.path.join(cfg, "squid.conf")
- if not os.path.exists(squid_conf):
- errors.append(f"'squid.conf' not found in directory: {cfg}")
- else:
- if not os.path.isfile(squid_conf):
- errors.append(f"Found but not a regular file: {squid_conf}")
- else:
- if not os.access(squid_conf, os.R_OK):
- errors.append(f"No read permissions for: {squid_conf}")
- if not os.access(squid_conf, os.W_OK):
- errors.append(f"No write permissions for: {squid_conf}")
- else:
- squid_conf = cfg
- if not os.path.exists(squid_conf):
- errors.append(f"Configuration file not found: {squid_conf}")
- else:
- if not os.path.isfile(squid_conf):
- errors.append(f"Not a regular file: {squid_conf}")
- if os.path.basename(squid_conf) != "squid.conf":
- errors.append(
- f"Expected file named 'squid.conf', got: {os.path.basename(squid_conf)}"
- )
- if os.path.isfile(squid_conf):
- if not os.access(squid_conf, os.R_OK):
- errors.append(f"No read permissions for: {squid_conf}")
- if not os.access(squid_conf, os.W_OK):
- errors.append(f"No write permissions for: {squid_conf}")
- # ACL / modular-config directory — warnings only, never a hard error
- acl_dir = os.path.abspath(os.path.expanduser(ACL_FILES_DIR))
- if not os.path.exists(acl_dir):
- logger.warning(
- f"ACL/modular config directory not found: {acl_dir} — "
- "modular configuration will be disabled."
- )
- elif not os.path.isdir(acl_dir):
- logger.warning(f"ACL path is not a directory: {acl_dir}")
- elif not os.access(acl_dir, os.W_OK):
- logger.warning(f"No write permissions in ACL directory: {acl_dir}")
- return errors
- class SquidConfigManager:
- def __init__(self, config_path=SQUID_CONFIG_PATH, config_dir=ACL_FILES_DIR):
- self.config_path = config_path
- self.config_dir = config_dir
- self.config_content = ""
- self.is_valid = False
- self.errors = []
- self.is_modular = False # Flag to check if using modular configs
- self._validate_environment()
- if self.is_valid:
- self.load_config()
- self._check_modular_config()
- def _validate_environment(self):
- self.errors = validate_paths()
- if self.errors:
- for error in self.errors:
- logger.error(error)
- self.is_valid = False
- logger.error(
- "SquidConfigManager cannot be initialized due to configuration errors"
- )
- else:
- self.is_valid = True
- logger.info("SquidConfigManager initialized successfully")
- def _cleanup_modular_backups(self, filepath: str, suffix: str = ".bak"):
- """Remove old backups for a modular config file, keeping only the newest one."""
- base = os.path.basename(filepath)
- directory = os.path.dirname(filepath)
- prefix = base + suffix
- try:
- backups = sorted(
- f for f in os.listdir(directory) if f.startswith(prefix) and f != base
- )
- # Remove all but the last (newest) backup
- for old in backups[:-1]:
- try:
- os.remove(os.path.join(directory, old))
- logger.debug(f"Removed old backup: {old}")
- except Exception as e:
- logger.warning(f"Could not remove old backup {old}: {e}")
- except Exception as e:
- logger.warning(f"Error cleaning up backups for {base}: {e}")
- def load_config(self):
- if not self.is_valid:
- logger.error("Cannot load configuration: invalid environment")
- return False
- try:
- with open(self.config_path, encoding="utf-8") as f:
- self.config_content = f.read()
- logger.debug(f"Configuration loaded from: {self.config_path}")
- return True
- except FileNotFoundError:
- logger.error(f"Configuration file not found: {self.config_path}")
- self.config_content = ""
- return False
- except PermissionError:
- logger.error(f"No read permissions for: {self.config_path}")
- self.config_content = ""
- return False
- except UnicodeDecodeError as e:
- logger.error(f"File encoding error: {e}")
- self.config_content = ""
- return False
- except Exception as e:
- logger.error(f"Unexpected error loading configuration: {e}")
- self.config_content = ""
- return False
- def save_config(self, content):
- if not self.is_valid:
- logger.error("Cannot save configuration: invalid environment")
- return False
- try:
- # Skip write if content hasn't changed
- if self.config_content == content:
- logger.debug("Main config unchanged, skipping write")
- return True
- backup_created = self.create_backup()
- if not backup_created:
- logger.warning("Could not create backup, but continuing with save...")
- with open(self.config_path, "w", encoding="utf-8") as f:
- f.write(content)
- self.config_content = content
- logger.info(f"Configuration saved successfully to: {self.config_path}")
- return True
- except PermissionError:
- logger.error(f"No write permissions for: {self.config_path}")
- return False
- except OSError as e:
- logger.error(f"System error saving configuration: {e}")
- return False
- except Exception as e:
- logger.error(f"Unexpected error saving configuration: {e}")
- return False
- def create_backup(self):
- if not self.is_valid:
- logger.error("Cannot create backup: invalid environment")
- return False
- def get_acls(self):
- """
- Parse ACL definitions with enhanced information.
- Returns a list of ACL dictionaries with full details.
- Format:
- {
- 'id': 0,
- 'name': 'localnet',
- 'type': 'src',
- 'options': ['-i'], # ACL options like -i, -n, -m
- 'values': ['10.0.0.0/8', '192.168.0.0/16'], # List of values
- 'value_string': '10.0.0.0/8 192.168.0.0/16', # Original value string
- 'is_predefined': False, # True for Squid predefined ACLs
- 'is_slow': False, # True for slow ACL types
- 'category': 'network', # Category: network, time, auth, content, ssl, etc.
- 'description': 'RFC 1918 private networks', # Human-readable description
- 'line_number': 5
- }
- """
- if not self.is_valid:
- logger.error("Cannot get ACLs: invalid environment")
- return []
- # If using modular config, read from the ACLs specific file
- if self.is_modular:
- acl_content = self.read_modular_config("100_acls.conf")
- if not acl_content:
- logger.warning(
- "Could not read modular ACL config, falling back to main config"
- )
- config_to_parse = self.config_content
- else:
- config_to_parse = acl_content
- else:
- if not self.config_content:
- logger.warning("No configuration content available")
- return []
- config_to_parse = self.config_content
- try:
- acls = []
- lines = config_to_parse.split("\n")
- acl_index = 0
- # Predefined ACLs in Squid
- predefined_acls = [
- "all",
- "manager",
- "localhost",
- "to_localhost",
- "to_linklocal",
- "CONNECT",
- ]
- # ACL type metadata
- acl_types_info = {
- # Network ACLs
- "src": {
- "category": "network",
- "slow": False,
- "desc": "Source IP address",
- },
- "dst": {
- "category": "network",
- "slow": True,
- "desc": "Destination IP address",
- },
- "localip": {
- "category": "network",
- "slow": False,
- "desc": "Local IP client connected to",
- },
- "arp": {
- "category": "network",
- "slow": False,
- "desc": "MAC address (EUI-48)",
- },
- "eui64": {
- "category": "network",
- "slow": False,
- "desc": "EUI-64 address",
- },
- "client_connection_mark": {
- "category": "network",
- "slow": False,
- "desc": "CONNMARK of connection",
- },
- # Domain ACLs
- "srcdomain": {
- "category": "domain",
- "slow": True,
- "desc": "Reverse DNS lookup of client IP",
- },
- "dstdomain": {
- "category": "domain",
- "slow": False,
- "desc": "Destination domain from URL",
- },
- "srcdom_regex": {
- "category": "domain",
- "slow": True,
- "desc": "Regex match on client name",
- },
- "dstdom_regex": {
- "category": "domain",
- "slow": False,
- "desc": "Regex match on server domain",
- },
- # AS Number ACLs
- "src_as": {
- "category": "network",
- "slow": False,
- "desc": "Source Autonomous System number",
- },
- "dst_as": {
- "category": "network",
- "slow": False,
- "desc": "Destination AS number",
- },
- # Time ACLs
- "time": {
- "category": "time",
- "slow": False,
- "desc": "Time of day and day of week",
- },
- # URL ACLs
- "url_regex": {
- "category": "url",
- "slow": False,
- "desc": "Regex match on full URL",
- },
- "urllogin": {
- "category": "url",
- "slow": False,
- "desc": "Regex match on URL login field",
- },
- "urlpath_regex": {
- "category": "url",
- "slow": False,
- "desc": "Regex match on URL path",
- },
- # Port ACLs
- "port": {
- "category": "port",
- "slow": False,
- "desc": "Destination TCP port",
- },
- "localport": {
- "category": "port",
- "slow": False,
- "desc": "TCP port client connected to",
- },
- "myportname": {
- "category": "port",
- "slow": False,
- "desc": "Port name from *_port directive",
- },
- # Protocol & Method ACLs
- "proto": {
- "category": "protocol",
- "slow": False,
- "desc": "Request protocol (HTTP, FTP, etc)",
- },
- "method": {
- "category": "protocol",
- "slow": False,
- "desc": "HTTP request method",
- },
- "http_status": {
- "category": "protocol",
- "slow": False,
- "desc": "HTTP status code in reply",
- },
- # Header ACLs
- "browser": {
- "category": "content",
- "slow": False,
- "desc": "User-Agent header pattern",
- },
- "referer_regex": {
- "category": "content",
- "slow": False,
- "desc": "Referer header pattern",
- },
- "req_header": {
- "category": "content",
- "slow": False,
- "desc": "Request header pattern",
- },
- "rep_header": {
- "category": "content",
- "slow": False,
- "desc": "Reply header pattern",
- },
- # Authentication ACLs
- "proxy_auth": {
- "category": "auth",
- "slow": True,
- "desc": "Proxy authentication username",
- },
- "proxy_auth_regex": {
- "category": "auth",
- "slow": True,
- "desc": "Proxy auth username regex",
- },
- "ext_user": {
- "category": "auth",
- "slow": True,
- "desc": "External ACL helper username",
- },
- "ext_user_regex": {
- "category": "auth",
- "slow": True,
- "desc": "External ACL helper username regex",
- },
- # MIME Type ACLs
- "req_mime_type": {
- "category": "content",
- "slow": False,
- "desc": "Request MIME type",
- },
- "rep_mime_type": {
- "category": "content",
- "slow": False,
- "desc": "Reply MIME type",
- },
- # Connection ACLs
- "maxconn": {
- "category": "connection",
- "slow": False,
- "desc": "Max TCP connections from IP",
- },
- "max_user_ip": {
- "category": "connection",
- "slow": False,
- "desc": "Max IPs per user",
- },
- # SSL/TLS ACLs
- "ssl_error": {
- "category": "ssl",
- "slow": False,
- "desc": "SSL certificate validation error",
- },
- "server_cert_fingerprint": {
- "category": "ssl",
- "slow": False,
- "desc": "Server cert fingerprint",
- },
- "ssl::server_name": {
- "category": "ssl",
- "slow": False,
- "desc": "TLS SNI server name",
- },
- "ssl::server_name_regex": {
- "category": "ssl",
- "slow": False,
- "desc": "TLS SNI regex match",
- },
- "connections_encrypted": {
- "category": "ssl",
- "slow": False,
- "desc": "All connections over TLS",
- },
- # Advanced ACLs
- "external": {
- "category": "advanced",
- "slow": True,
- "desc": "External ACL helper lookup",
- },
- "random": {
- "category": "advanced",
- "slow": False,
- "desc": "Random probability match",
- },
- "note": {
- "category": "advanced",
- "slow": False,
- "desc": "Transaction annotation",
- },
- "annotate_transaction": {
- "category": "advanced",
- "slow": False,
- "desc": "Add transaction annotation",
- },
- "annotate_client": {
- "category": "advanced",
- "slow": False,
- "desc": "Add client annotation",
- },
- "peername": {
- "category": "advanced",
- "slow": False,
- "desc": "Cache peer name",
- },
- "peername_regex": {
- "category": "advanced",
- "slow": False,
- "desc": "Cache peer name regex",
- },
- "hier_code": {
- "category": "advanced",
- "slow": False,
- "desc": "Squid hierarchy code",
- },
- # Group ACLs
- "any-of": {
- "category": "group",
- "slow": False,
- "desc": "Match any of the ACLs",
- },
- "all-of": {
- "category": "group",
- "slow": False,
- "desc": "Match all of the ACLs",
- },
- }
- last_comment = ""
- for line_num, line in enumerate(lines, 1):
- try:
- stripped = line.strip()
- # Track comments for context
- if stripped.startswith("#"):
- last_comment = stripped[1:].strip()
- continue
- if stripped.startswith("acl "):
- parts = stripped.split()
- if len(parts) >= 3:
- acl_name = parts[1]
- # Parse options and type
- options = []
- type_index = 2
- while type_index < len(parts) and parts[
- type_index
- ].startswith("-"):
- options.append(parts[type_index])
- type_index += 1
- if type_index >= len(parts):
- continue
- acl_type = parts[type_index]
- values = (
- parts[type_index + 1 :]
- if len(parts) > type_index + 1
- else []
- )
- value_string = " ".join(values)
- # Get type metadata
- type_info = acl_types_info.get(
- acl_type,
- {
- "category": "other",
- "slow": False,
- "desc": "Custom ACL type",
- },
- )
- # Check if predefined
- is_predefined = acl_name in predefined_acls
- acls.append(
- {
- "id": acl_index,
- "name": acl_name,
- "type": acl_type,
- "options": options,
- "value_list": values,
- "value_string": value_string,
- "is_predefined": is_predefined,
- "is_slow": type_info.get("slow", False),
- "category": type_info.get("category", "other"),
- "type_description": type_info.get("desc", ""),
- "comment": last_comment if last_comment else "",
- "line_number": line_num,
- "full_line": stripped,
- }
- )
- acl_index += 1
- last_comment = ""
- except Exception as e:
- logger.warning(f"Error processing ACL at line {line_num}: {e}")
- continue
- logger.debug(f"Found {len(acls)} ACLs")
- return acls
- except Exception as e:
- logger.error(f"Unexpected error extracting ACLs: {e}")
- return []
- def get_delay_pools(self):
- """
- Parse delay pools configuration and group by pool number.
- Returns a list of pool dictionaries with all related directives.
- Format:
- {
- 'pool_number': '1',
- 'class': '3',
- 'parameters': '8192/131072 1024/65536 256/32768',
- 'access_rules': [{'action': 'allow', 'acl': 'students'}]
- }
- """
- if not self.is_valid:
- logger.error("Cannot get delay pools: invalid environment")
- return []
- # If using modular config, read from the delay pools specific file
- if self.is_modular:
- delay_content = self.read_modular_config("110_delay_pools.conf")
- if not delay_content:
- logger.warning(
- "Could not read modular delay pools config, falling back to main config"
- )
- config_to_parse = self.config_content
- else:
- config_to_parse = delay_content
- else:
- if not self.config_content:
- logger.warning("No configuration content available")
- return []
- config_to_parse = self.config_content
- try:
- pools_dict = {} # Dictionary to group by pool number
- total_pools = 0
- lines = config_to_parse.split("\n")
- for line_num, line in enumerate(lines, 1):
- try:
- line = line.strip()
- if line.startswith("delay_pools "):
- parts = line.split()
- if len(parts) >= 2:
- total_pools = int(parts[1])
- elif line.startswith("delay_class "):
- parts = line.split()
- if len(parts) >= 3:
- pool_num = parts[1]
- if pool_num not in pools_dict:
- pools_dict[pool_num] = {
- "pool_number": pool_num,
- "class": parts[2],
- "parameters": None,
- "access_rules": [],
- }
- else:
- pools_dict[pool_num]["class"] = parts[2]
- elif line.startswith("delay_parameters "):
- parts = line.split()
- if len(parts) >= 3:
- pool_num = parts[1]
- if pool_num not in pools_dict:
- pools_dict[pool_num] = {
- "pool_number": pool_num,
- "class": None,
- "parameters": " ".join(parts[2:]),
- "access_rules": [],
- }
- else:
- pools_dict[pool_num]["parameters"] = " ".join(parts[2:])
- elif line.startswith("delay_access "):
- parts = line.split()
- if len(parts) >= 4:
- pool_num = parts[1]
- if pool_num not in pools_dict:
- pools_dict[pool_num] = {
- "pool_number": pool_num,
- "class": None,
- "parameters": None,
- "access_rules": [],
- }
- pools_dict[pool_num]["access_rules"].append(
- {"action": parts[2], "acl": " ".join(parts[3:])}
- )
- except Exception as e:
- logger.warning(
- f"Error processing delay pool at line {line_num}: {e}"
- )
- continue
- # Convert dictionary to sorted list
- delay_pools = [
- pools_dict[key] for key in sorted(pools_dict.keys(), key=int)
- ]
- logger.debug(
- f"Found {len(delay_pools)} delay pool configurations (total_pools={total_pools})"
- )
- return delay_pools
- except Exception as e:
- logger.error(f"Unexpected error extracting delay pools: {e}")
- return []
- def get_http_access_rules(self):
- """
- Parse http_access rules with enhanced information.
- Returns a list of rule dictionaries with action, acls (list), and metadata.
- Format:
- {
- 'action': 'allow',
- 'acls': ['!Safe_ports'], # List of ACLs including negations
- 'acl_string': '!Safe_ports', # Original ACL string
- 'is_negative': True, # If it contains negation
- 'line_number': 5, # Original line number
- 'description': '' # Optional description from comments
- }
- """
- if not self.is_valid:
- logger.error("Cannot get HTTP rules: invalid environment")
- return []
- # If using modular config, read from the http_access specific file
- if self.is_modular:
- http_content = self.read_modular_config("120_http_access.conf")
- if not http_content:
- logger.warning(
- "Could not read modular http_access config, falling back to main config"
- )
- config_to_parse = self.config_content
- else:
- config_to_parse = http_content
- else:
- if not self.config_content:
- logger.warning("No configuration content available")
- return []
- config_to_parse = self.config_content
- try:
- rules = []
- lines = config_to_parse.split("\n")
- last_comment = ""
- for line_num, line in enumerate(lines, 1):
- try:
- stripped = line.strip()
- # Track comments for context
- if stripped.startswith("#"):
- last_comment = stripped[1:].strip()
- continue
- if stripped.startswith("http_access "):
- parts = stripped.split()
- if len(parts) >= 3:
- action = parts[1]
- acl_string = " ".join(parts[2:])
- acls = parts[2:]
- # Check if any ACL has negation
- is_negative = any(acl.startswith("!") for acl in acls)
- # Identify special/common ACLs
- special_acls = []
- if "localhost" in acls:
- special_acls.append("localhost")
- if "manager" in acls:
- special_acls.append("manager")
- if any("Safe_ports" in acl for acl in acls):
- special_acls.append("Safe_ports")
- if any("SSL_ports" in acl for acl in acls):
- special_acls.append("SSL_ports")
- if "CONNECT" in acls:
- special_acls.append("CONNECT")
- rules.append(
- {
- "action": action,
- "acls": acls,
- "acl_string": acl_string,
- "is_negative": is_negative,
- "line_number": line_num,
- "description": last_comment if last_comment else "",
- "special_acls": special_acls,
- }
- )
- last_comment = "" # Reset comment
- except Exception as e:
- logger.warning(
- f"Error processing HTTP rule at line {line_num}: {e}"
- )
- continue
- logger.debug(f"Found {len(rules)} HTTP access rules")
- return rules
- except Exception as e:
- logger.error(f"Unexpected error extracting HTTP rules: {e}")
- return []
- def _check_modular_config(self):
- """Check if the main config file uses modular includes."""
- if not self.config_content:
- return
- # Check if config contains include directives pointing to squid.d
- self.is_modular = (
- "include" in self.config_content.lower()
- and "squid.d" in self.config_content
- )
- if self.is_modular:
- logger.info("Modular configuration detected")
- def list_modular_configs(self) -> list[dict[str, str]]:
- """List all modular configuration files in squid.d directory."""
- if not os.path.exists(self.config_dir):
- logger.warning(f"Config directory not found: {self.config_dir}")
- return []
- try:
- configs = []
- for filename in sorted(os.listdir(self.config_dir)):
- if filename.endswith(".conf"):
- filepath = os.path.join(self.config_dir, filename)
- if os.path.isfile(filepath):
- try:
- stat = os.stat(filepath)
- configs.append(
- {
- "filename": filename,
- "filepath": filepath,
- "size": stat.st_size,
- "modified": datetime.fromtimestamp(
- stat.st_mtime
- ).strftime("%Y-%m-%d %H:%M:%S"),
- "readable": os.access(filepath, os.R_OK),
- "writable": os.access(filepath, os.W_OK),
- }
- )
- except Exception as e:
- logger.warning(
- f"Error reading file info for {filename}: {e}"
- )
- return configs
- except Exception as e:
- logger.error(f"Error listing modular configs: {e}")
- return []
- def read_modular_config(self, filename: str) -> str | None:
- """Read a specific modular configuration file."""
- filepath = os.path.join(self.config_dir, filename)
- if not os.path.exists(filepath):
- logger.error(f"Config file not found: {filepath}")
- return None
- if not filepath.endswith(".conf"):
- logger.error(f"Invalid file extension: {filename}")
- return None
- try:
- with open(filepath, encoding="utf-8") as f:
- content = f.read()
- logger.debug(f"Read modular config: {filename}")
- return content
- except Exception as e:
- logger.error(f"Error reading modular config {filename}: {e}")
- return None
- def save_modular_config(self, filename: str, content: str) -> bool:
- """Save content to a specific modular configuration file."""
- filepath = os.path.join(self.config_dir, filename)
- if not filename.endswith(".conf"):
- logger.error(f"Invalid file extension: {filename}")
- return False
- # Validate filename to prevent directory traversal
- if "/" in filename or "\\" in filename or ".." in filename:
- logger.error(f"Invalid filename (potential path traversal): {filename}")
- return False
- try:
- # Skip write if content hasn't changed
- if os.path.exists(filepath):
- try:
- with open(filepath, encoding="utf-8") as f:
- existing = f.read()
- if existing == content:
- logger.debug(
- f"Modular config unchanged, skipping write: {filename}"
- )
- return True
- except Exception:
- pass # If we can't read, proceed with write
- # Create single backup before overwriting
- backup_path = f"{filepath}.bak"
- try:
- shutil.copy2(filepath, backup_path)
- logger.debug(f"Backup created: {backup_path}")
- except Exception as e:
- logger.warning(f"Could not create backup for {filename}: {e}")
- with open(filepath, "w", encoding="utf-8") as f:
- f.write(content)
- logger.info(f"Saved modular config: {filename}")
- return True
- except Exception as e:
- logger.error(f"Error saving modular config {filename}: {e}")
- return False
- def delete_modular_config(self, filename: str) -> bool:
- """Delete a specific modular configuration file."""
- filepath = os.path.join(self.config_dir, filename)
- if not os.path.exists(filepath):
- logger.error(f"Config file not found: {filepath}")
- return False
- if not filename.endswith(".conf"):
- logger.error(f"Invalid file extension: {filename}")
- return False
- # Validate filename to prevent directory traversal
- if "/" in filename or "\\" in filename or ".." in filename:
- logger.error(f"Invalid filename (potential path traversal): {filename}")
- return False
- try:
- # Keep a single .deleted backup, removing any previous one
- backup_path = f"{filepath}.deleted"
- if os.path.exists(backup_path):
- try:
- os.remove(backup_path)
- except Exception as e:
- logger.warning(f"Could not remove previous deleted backup: {e}")
- try:
- shutil.move(filepath, backup_path)
- logger.info(f"File moved to: {backup_path}")
- return True
- except Exception as e:
- logger.error(f"Error deleting file {filename}: {e}")
- return False
- except Exception as e:
- logger.error(f"Error handling file deletion {filename}: {e}")
- return False
- def get_modular_config_info(self) -> dict:
- """Get information about the modular configuration setup."""
- return {
- "is_modular": self.is_modular,
- "config_dir": self.config_dir,
- "config_dir_exists": os.path.exists(self.config_dir),
- "config_files_count": len(self.list_modular_configs()),
- "main_config_path": self.config_path,
- }
- def detect_ssl_bump(self) -> dict:
- """Detect whether SSL Bump is enabled in the Squid configuration.
- Inspects ``http_port`` directives (with backslash-continuation support),
- ``ssl_bump`` action rules, and ``sslcrtd_*`` directives.
- Returns a dict::
- {
- "enabled": bool,
- "mode": "peek-and-splice" | "bump-all" | "custom" | "basic" | None,
- "cert": str | None, # path in cert= option
- "generate_certs": bool,
- "sslcrtd_configured": bool,
- "sslcrtd_children": int | None,
- "http_port_entry": str | None,
- "ssl_bump_rules": list[str],
- "source": "main" | "modular",
- }
- """
- result: dict = {
- "enabled": False,
- "mode": None,
- "cert": None,
- "generate_certs": False,
- "sslcrtd_configured": False,
- "sslcrtd_children": None,
- "http_port_entry": None,
- "ssl_bump_rules": [],
- "source": "main",
- }
- if not self.is_valid:
- return result
- ports_content = self.config_content
- ssl_content = self.config_content
- if self.is_modular:
- # Use os.path.exists to avoid ERROR logs for optional modular files
- ports_path = os.path.join(self.config_dir, "00_ports.conf")
- ssl_path = os.path.join(self.config_dir, "55_ssl_bump.conf")
- if os.path.exists(ports_path):
- mc_ports = self.read_modular_config("00_ports.conf")
- if mc_ports:
- ports_content = mc_ports
- result["source"] = "modular"
- if os.path.exists(ssl_path):
- mc_ssl = self.read_modular_config("55_ssl_bump.conf")
- if mc_ssl:
- ssl_content = mc_ssl
- result["source"] = "modular"
- # --- http_port: join continuation lines then scan ---
- joined_ports = _join_continuation_lines(ports_content)
- for line in joined_ports.splitlines():
- stripped = line.strip()
- if not stripped or stripped.startswith("#"):
- continue
- if re.match(r"^http_port\b", stripped):
- tokens = stripped.split()
- if "ssl-bump" in tokens:
- result["enabled"] = True
- result["http_port_entry"] = stripped
- cert_m = re.search(r"\bcert=(\S+)", stripped)
- if cert_m:
- result["cert"] = cert_m.group(1)
- gen_m = re.search(
- r"\bgenerate-host-certificates=(on|off)\b", stripped
- )
- if gen_m:
- result["generate_certs"] = gen_m.group(1) == "on"
- break
- # --- ssl_bump action rules ---
- ssl_bump_rules = []
- for line in ssl_content.splitlines():
- stripped = line.strip()
- if not stripped or stripped.startswith("#"):
- continue
- if re.match(r"^ssl_bump\b", stripped):
- ssl_bump_rules.append(stripped)
- result["ssl_bump_rules"] = ssl_bump_rules
- # --- sslcrtd_* directives ---
- for line in ssl_content.splitlines():
- stripped = line.strip()
- if not stripped or stripped.startswith("#"):
- continue
- if re.match(r"^sslcrtd_program\b", stripped):
- result["sslcrtd_configured"] = True
- elif re.match(r"^sslcrtd_children\b", stripped):
- m = re.match(r"^sslcrtd_children\s+(\d+)", stripped)
- if m:
- result["sslcrtd_children"] = int(m.group(1))
- # --- determine mode ---
- if result["enabled"]:
- has_bump = any(re.match(r"^ssl_bump\s+bump\b", r) for r in ssl_bump_rules)
- has_peek = any(re.match(r"^ssl_bump\s+peek\b", r) for r in ssl_bump_rules)
- has_splice = any(
- re.match(r"^ssl_bump\s+splice\b", r) for r in ssl_bump_rules
- )
- if has_peek or has_splice:
- result["mode"] = "peek-and-splice"
- elif has_bump:
- result["mode"] = "bump-all"
- elif ssl_bump_rules:
- result["mode"] = "custom"
- else:
- result["mode"] = "basic"
- return result
- def get_status(self):
- return {
- "is_valid": self.is_valid,
- "errors": self.errors,
- "config_loaded": bool(self.config_content),
- "config_path": self.config_path,
- "config_dir": self.config_dir,
- "is_modular": self.is_modular,
- "acl_files_dir": ACL_FILES_DIR,
- }
|