import fcntl import glob import os import re import shutil import tempfile import threading from contextlib import contextmanager from datetime import datetime from dotenv import load_dotenv from loguru import logger from config import Config from utils.custom_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", "" ) FALLBACK_SQUID_CONFIG_PATH = "/etc/squid/squid.conf" FALLBACK_ACL_FILES_DIRS = ["/etc/squid/acls", "/etc/squid/squid.d"] # All Squid configuration writers use this lock file for the short interval # between comparing a loaded snapshot and atomically replacing a file. The # in-process RLock avoids self-deadlock when a multi-file transaction invokes # ``save_config``/``save_modular_config`` while it already owns the lock; the # advisory flock coordinates separate web/scheduler worker processes. _SQUID_WRITE_LOCKS_GUARD = threading.Lock() _SQUID_WRITE_LOCKS: dict[str, threading.RLock] = {} _SQUID_WRITE_LOCK_STATE = threading.local() @contextmanager def squid_config_write_lock(config_path: str = SQUID_CONFIG_PATH): """Serialize Squid configuration read-modify-write transactions. The lock is held on the real configuration directory, which keeps it shared by app/scheduler processes using the same Squid configuration volume without creating a file that could be picked up by a wildcard ``include``. A process that cannot read that directory cannot safely inspect and replace the configuration, so failure is intentionally fail-closed. """ effective_config_path = config_path if config_path == SQUID_CONFIG_PATH: effective_config_path, _unused_config_dir = _normalize_squid_paths( SQUID_CONFIG_PATH, ACL_FILES_DIR ) lock_key = os.path.dirname(os.path.realpath(os.path.abspath(effective_config_path))) held = getattr(_SQUID_WRITE_LOCK_STATE, "held", None) if held is None: held = {} _SQUID_WRITE_LOCK_STATE.held = held existing = held.get(lock_key) if existing is not None: existing["depth"] += 1 try: yield finally: existing["depth"] -= 1 return with _SQUID_WRITE_LOCKS_GUARD: thread_lock = _SQUID_WRITE_LOCKS.setdefault(lock_key, threading.RLock()) thread_lock.acquire() file_descriptor: int | None = None try: flags = os.O_RDONLY if hasattr(os, "O_DIRECTORY"): flags |= os.O_DIRECTORY file_descriptor = os.open(lock_key, flags) fcntl.flock(file_descriptor, fcntl.LOCK_EX) held[lock_key] = {"descriptor": file_descriptor, "depth": 1} yield finally: current = held.get(lock_key) if current is not None: held.pop(lock_key, None) try: fcntl.flock(current["descriptor"], fcntl.LOCK_UN) finally: os.close(current["descriptor"]) elif file_descriptor is not None: os.close(file_descriptor) thread_lock.release() def _normalize_squid_paths(config_path: str, config_dir: str) -> tuple[str, str]: """Return effective Squid config and ACL directory paths. If configured paths do not exist, but the standard /etc/squid paths do, prefer a recognized fallback so the app can work in both container and older host environments. """ config_path = os.path.abspath(os.path.expanduser(config_path)) config_dir = os.path.abspath(os.path.expanduser(config_dir)) if not os.path.exists(config_path) and config_path != FALLBACK_SQUID_CONFIG_PATH: if os.path.exists(FALLBACK_SQUID_CONFIG_PATH): config_path = FALLBACK_SQUID_CONFIG_PATH if not os.path.exists(config_dir): for fallback_dir in FALLBACK_ACL_FILES_DIRS: if os.path.exists(fallback_dir): config_dir = fallback_dir break return config_path, config_dir def _replacement_ownership(previous_metadata, *, warn: bool = True) -> tuple[int, int]: """Return ownership that an atomic replacement can safely restore. An unprivileged service may replace a configuration file through a directory ACL even when that file is owned by root. It cannot restore root ownership afterwards. It can, however, retain a group to which it belongs, which preserves a common ``root:proxy 0640`` arrangement. Do not replace a non-world-readable file if neither guarantee is available: Squid could lose access to its configuration after an otherwise valid write. """ effective_uid = os.geteuid() effective_gid = os.getegid() if effective_uid == 0: return previous_metadata.st_uid, previous_metadata.st_gid effective_groups = {effective_gid, *os.getgroups()} target_group = previous_metadata.st_gid if target_group not in effective_groups: if not (previous_metadata.st_mode & 0o004): raise PermissionError( "No se puede conservar el grupo de un squid.conf no legible " "globalmente; usa un grupo accesible para SquidStats o un " "mecanismo de administración privilegiado." ) if warn: logger.warning( "Replacing Squid configuration without its original group because " "it is world-readable" ) return -1, -1 if warn and previous_metadata.st_uid != effective_uid: logger.warning( "Replacing root-owned Squid configuration as an unprivileged user; " "the replacement will be owned by the service account", ) return -1, target_group if target_group != effective_gid else -1 def can_atomically_replace_file(path: str) -> bool: """Whether this process can safely use :meth:`_atomic_write` for *path*. Replacing a file atomically needs write *and* search permission on the resolved parent directory. Testing only ``os.access(file, W_OK)`` is both misleading (a directory ACL can be sufficient) and misses a later ``NamedTemporaryFile``/``os.replace`` failure. Metadata preservation is checked here as well so the preflight does not promise a write that would make a protected Squid config unreadable. """ try: target = os.path.realpath(os.path.abspath(path)) directory = os.path.dirname(target) if not os.path.isfile(target) or not os.access(target, os.R_OK): return False if not os.access(directory, os.W_OK | os.X_OK): return False _replacement_ownership(os.stat(target), warn=False) except (OSError, PermissionError): return False return True 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( config_path: str = SQUID_CONFIG_PATH, config_dir: str = ACL_FILES_DIR ): """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(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 can_atomically_replace_file(squid_conf): errors.append( "No safe atomic write permissions for Squid configuration: " f"{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 can_atomically_replace_file(squid_conf): errors.append( "No safe atomic write permissions for Squid configuration: " f"{squid_conf}" ) # ACL / modular-config directory — warnings only, never a hard error _, acl_dir = _normalize_squid_paths(config_path, config_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 | os.X_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, self.config_dir = _normalize_squid_paths( config_path, config_dir ) self.config_content = "" self._modular_content_snapshots: dict[str, str | None] = {} 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(self.config_path, self.config_dir) 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. """ # Replace the resolved target rather than a symlink itself. Squid # packages sometimes expose squid.conf through a symlink; replacing # that link would leave the daemon reading a different file after the # next restart. abs_path = os.path.realpath(os.path.abspath(path)) dir_name = os.path.dirname(abs_path) tmp_path = None try: previous_metadata = os.stat(abs_path) except FileNotFoundError: previous_metadata = 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 if previous_metadata is not None: # ``NamedTemporaryFile`` starts at 0600 and belongs to # SquidStats. Replacing a config file with it without # restoring metadata can make Squid unable to read its # own configuration after a successful-looking update. restore_uid, restore_gid = _replacement_ownership(previous_metadata) if restore_uid != -1 or restore_gid != -1: os.fchown( tmp.fileno(), restore_uid, restore_gid, ) # Copy mode and supported ACL/xattr metadata after the # ownership change. This is important for installations # that grant the Squid account access with a POSIX ACL. shutil.copystat(abs_path, tmp_path, follow_symlinks=False) else: # Generated .conf modules contain no keytab material; # make them readable by Squid even when the web process # and Squid do not share a primary group. Existing files # keep their stricter administrator-selected mode above. os.fchmod(tmp.fileno(), 0o644) 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: with squid_config_write_lock(self.config_path): # Skip write if content hasn't changed. This deliberately # does not overwrite a newer on-disk version merely to make a # stale manager's snapshot current again. if self.config_content == content: logger.debug("Main config unchanged, skipping write") return True with open(self.config_path, encoding="utf-8") as current_file: current_content = current_file.read() if current_content != self.config_content: logger.warning( "Refusing stale write to squid.conf; reload the configuration and retry" ) return False 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 whether active includes point at the configured module directory.""" if not self.config_content: return config_dir = os.path.abspath(self.config_dir) include_dirs: list[str] = [] for raw_line in _join_continuation_lines(self.config_content).splitlines(): line = raw_line.split("#", 1)[0].strip() match = re.match(r"^include\s+(.+)$", line, re.IGNORECASE) if not match: continue raw_include_path = os.path.expanduser(match.group(1).strip().strip('"')) include_path = os.path.abspath( raw_include_path if os.path.isabs(raw_include_path) else os.path.join(os.path.dirname(self.config_path), raw_include_path) ) filename = os.path.basename(include_path) # A standalone text include may be an ACL value list. A .conf # include (including a glob) is a real configuration module. if ".conf" in filename: include_dirs.append(os.path.dirname(include_path)) self.is_modular = bool(include_dirs) if self.is_modular: # Old installers sometimes leave ACL_FILES_DIR pointing at an ACL # value-list directory while squid.conf includes squid.d/conf.d. # Prefer the directory actually referenced by Squid so writes go # to active files rather than an unrelated folder. if config_dir in include_dirs: selected_dir = config_dir else: selected_dir = next( ( directory for directory in include_dirs if "squid.d" in directory.casefold() ), include_dirs[0], ) if selected_dir != config_dir: logger.info( "Using modular configuration directory referenced by Squid: {}", selected_dir, ) self.config_dir = selected_dir 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 hasattr(self, "_modular_content_snapshots"): self._modular_content_snapshots = {} if not os.path.exists(filepath): logger.error(f"Config file not found: {filepath}") self._modular_content_snapshots[filename] = None 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() self._modular_content_snapshots[filename] = content # 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 has_proxy_authentication(self) -> bool: """Return whether Squid has a usable ``proxy_auth`` identity ACL. Authentication directives may be placed in ``50_auth.conf`` after a split, in the main file, or in another active include. Consumers such as quota accounting must inspect only files Squid actually loads: a stale, unreferenced ``50_auth.conf`` must not switch quota accounting to usernames when the proxy has no active authentication helper. """ if not self.is_valid: return False content = "\n".join( _join_continuation_lines(item) for item in self._active_configuration_contents() ) has_helper = bool( re.search( r"^\s*auth_param\s+\S+\s+program\b", content, re.IGNORECASE | re.MULTILINE, ) ) has_identity_acl = bool( re.search( r"^\s*acl\s+\S+(?:\s+-\S+)*\s+proxy_auth\b", content, re.IGNORECASE | re.MULTILINE, ) ) return has_helper and has_identity_acl def _active_configuration_contents(self) -> list[str]: """Read active Squid include files, bounded against value-list files. This deliberately follows only actual ``include`` directives (and their globs), not every file in ``config_dir``. It is small and private because it supports configuration status checks rather than attempting to be a full Squid parser. """ main_content = self.config_content or "" contents = [main_content] main_path = os.path.realpath(self.config_path) seen = {main_path} def visit(content: str, directory: str, depth: int = 0) -> None: if depth >= 8: logger.warning("Maximum Squid include depth reached") return for raw_line in _join_continuation_lines(content).splitlines(): line = raw_line.split("#", 1)[0].strip() match = re.match(r"^include\s+(.+)$", line, re.IGNORECASE) if not match: continue include_path = os.path.expanduser(match.group(1).strip().strip('"')) pattern = os.path.abspath( include_path if os.path.isabs(include_path) else os.path.join(directory, include_path) ) try: candidates = sorted(glob.glob(pattern)) except OSError: continue for candidate in candidates: real_candidate = os.path.realpath(candidate) if real_candidate in seen or not os.path.isfile(real_candidate): continue try: if os.path.getsize(real_candidate) > 1024 * 1024: continue with open(real_candidate, encoding="utf-8") as included: included_content = included.read() except (OSError, UnicodeDecodeError): continue seen.add(real_candidate) contents.append(included_content) visit(included_content, os.path.dirname(real_candidate), depth + 1) visit(main_content, os.path.dirname(main_path)) return contents 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 hasattr(self, "_modular_content_snapshots"): self._modular_content_snapshots = {} 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: with squid_config_write_lock(self.config_path): try: with open(filepath, encoding="utf-8") as current_file: current_content: str | None = current_file.read() except FileNotFoundError: current_content = None snapshot_known = filename in self._modular_content_snapshots expected_content = self._modular_content_snapshots.get(filename) if snapshot_known and current_content != expected_content: logger.warning( "Refusing stale write to modular config %s; reload it and retry", filename, ) return False if ( not snapshot_known and current_content is not None and current_content != content ): logger.warning( "Refusing to overwrite modular config %s without a loaded snapshot", filename, ) return False if current_content == content: self._modular_content_snapshots[filename] = content return True if current_content is not None: # 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) self._modular_content_snapshots[filename] = 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, }