import os import re import shutil import tempfile from datetime import datetime from dotenv import load_dotenv from loguru import logger from config import Config from utils.types import ACL_TYPES_INFO, PREDEFINED_ACLS load_dotenv() SQUID_CONFIG_PATH = Config.SQUID_CONFIG_PATH or "/etc/squid/squid.conf" ACL_FILES_DIR = Config.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 @staticmethod def _atomic_write(path: str, content: str, encoding: str = "utf-8") -> None: """Write *content* to *path* atomically: write to a temp file then os.replace. Using open(path, 'w') truncates the file immediately; if the process is interrupted mid-write squid.conf ends up empty/corrupt. Writing to a temporary file in the same directory and calling os.replace() is atomic on POSIX — the destination is either the old file or the new file, never a partial write. """ abs_path = os.path.abspath(path) dir_name = os.path.dirname(abs_path) tmp_path = None try: with tempfile.NamedTemporaryFile( mode="w", encoding=encoding, dir=dir_name, delete=False, suffix=".squidstats.tmp", ) as tmp: tmp.write(content) tmp_path = tmp.name os.replace(tmp_path, abs_path) except Exception: if tmp_path and os.path.exists(tmp_path): try: os.unlink(tmp_path) except Exception as cleanup_err: logger.warning( "Could not remove temporary file %s: %s", tmp_path, cleanup_err ) raise def save_config(self, content): if not self.is_valid: logger.error("Cannot save configuration: invalid environment") return False # Guard: never blank squid.conf — an empty file would bring down Squid if not content or not content.strip(): logger.error( "Refusing to save empty/whitespace-only content to squid.conf: " "this would disable the Squid proxy" ) 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...") self._atomic_write(self.config_path, 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 try: backup_path = f"{self.config_path}.bak" shutil.copy2(self.config_path, backup_path) logger.info(f"Backup created: {backup_path}") return True except FileNotFoundError: logger.warning(f"Config file not found for backup: {self.config_path}") return False except PermissionError: logger.error(f"No permission to create backup for: {self.config_path}") return False except Exception as e: logger.error(f"Unexpected error creating backup: {e}") 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 = PREDEFINED_ACLS # ACL type metadata acl_types_info = ACL_TYPES_INFO 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 "): pass # 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 as e: logger.debug( "Could not read existing config for comparison, proceeding with write: %s", e, ) # 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}") self._atomic_write(filepath, 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, }