| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054 |
- 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 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:
- 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:
- # Create backup before saving
- if os.path.exists(filepath):
- backup_path = (
- f"{filepath}.bak{datetime.now().strftime('%Y%m%d_%H%M%S')}"
- )
- try:
- shutil.copy2(filepath, backup_path)
- logger.info(f"Backup created: {backup_path}")
- except Exception as e:
- logger.warning(f"Could not create backup: {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:
- # Create backup before deleting
- backup_path = (
- f"{filepath}.deleted{datetime.now().strftime('%Y%m%d_%H%M%S')}"
- )
- 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,
- }
|