Browse Source

feat: add SSL Bump detection functionality and integrate into admin dashboard

Manuel 8 months ago
parent
commit
009fb3f9e0

+ 8 - 1
routes/admin/dashboard.py

@@ -3,6 +3,7 @@
 from flask import render_template
 
 from services.auth.auth_service import admin_required
+from services.squid.ssl_bump_service import get_ssl_bump_status
 
 from .helpers import get_config_manager
 
@@ -21,4 +22,10 @@ def register_routes(bp):
             "total_http_rules": len(http_access_rules),
         }
         status = cm.get_status()
-        return render_template("admin/dashboardAdmin.html", stats=stats, status=status)
+        ssl_bump = get_ssl_bump_status(cm)
+        return render_template(
+            "admin/dashboardAdmin.html",
+            stats=stats,
+            status=status,
+            ssl_bump=ssl_bump,
+        )

+ 14 - 1
routes/admin/system_api.py

@@ -18,8 +18,9 @@ from services.system.system_service import (
 from services.system.system_service import (
     restart_squid as service_restart_squid,
 )
+from services.squid.ssl_bump_service import get_ssl_bump_status
 
-from .helpers import json_error, json_success
+from .helpers import json_error, json_success, get_config_manager
 
 
 def register_routes(bp):
@@ -43,6 +44,18 @@ def register_routes(bp):
             return json_success(message)
         return json_error(message, 500, details=details)
 
+    # ------------------------------------------------------------------
+    # SSL Bump detection
+    # ------------------------------------------------------------------
+
+    @bp.route("/api/ssl-bump-status", methods=["GET"])
+    @api_auth_required
+    def ssl_bump_status():
+        cm = get_config_manager()
+        data = get_ssl_bump_status(cm)
+        print("SSL Bump status:", data)  # Debug log
+        return jsonify(data), 200
+
     # ------------------------------------------------------------------
     # Database management
     # ------------------------------------------------------------------

+ 27 - 0
services/squid/ssl_bump_service.py

@@ -0,0 +1,27 @@
+"""Service layer for SSL Bump detection."""
+
+from loguru import logger
+
+
+def get_ssl_bump_status(config_manager) -> dict:
+    """Return SSL Bump detection results from *config_manager*.
+
+    Wraps :meth:`SquidConfigManager.detect_ssl_bump` with error handling so
+    callers always receive a well-formed dict.
+    """
+    try:
+        return config_manager.detect_ssl_bump()
+    except Exception:
+        logger.exception("Error detecting SSL Bump status")
+        return {
+            "enabled": False,
+            "mode": None,
+            "cert": None,
+            "generate_certs": False,
+            "sslcrtd_configured": False,
+            "sslcrtd_children": None,
+            "http_port_entry": None,
+            "ssl_bump_rules": [],
+            "source": "main",
+            "error": "Error al detectar la configuración SSL Bump",
+        }

+ 43 - 1
templates/admin/dashboardAdmin.html

@@ -6,7 +6,7 @@
         <h2 class="text-xl sm:text-2xl font-bold text-gray-800 mb-4 sm:mb-6">Dashboard - Resumen del Sistema</h2>
         
         <!-- Stats Cards -->
-        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6 mb-6 sm:mb-8">
+        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 sm:gap-6 mb-6 sm:mb-8">
 
             <!-- ACLs Card -->
             <div class="bg-gradient-to-r from-blue-500 to-blue-600 text-white p-6 rounded-lg">
@@ -86,6 +86,28 @@
                 </div>
             </div>
 
+            <!-- SSL Bump Card -->
+            {% if ssl_bump.enabled %}
+            <div class="bg-gradient-to-r from-yellow-500 to-orange-500 text-white p-6 rounded-lg">
+            {% else %}
+            <div class="bg-gradient-to-r from-gray-400 to-gray-500 text-white p-6 rounded-lg">
+            {% endif %}
+                <div class="flex items-center justify-between">
+                    <div>
+                        <p class="{% if ssl_bump.enabled %}text-yellow-100{% else %}text-gray-200{% endif %}">SSL Bump</p>
+                        {% if ssl_bump.enabled %}
+                            <p class="text-2xl font-bold">Activo</p>
+                            {% if ssl_bump.mode %}
+                                <p class="text-xs mt-1 {% if ssl_bump.enabled %}text-yellow-200{% else %}text-gray-300{% endif %}">{{ ssl_bump.mode }}</p>
+                            {% endif %}
+                        {% else %}
+                            <p class="text-2xl font-bold">Inactivo</p>
+                        {% endif %}
+                    </div>
+                    <i class="fas fa-user-secret text-4xl {% if ssl_bump.enabled %}text-yellow-200{% else %}text-gray-300{% endif %}"></i>
+                </div>
+            </div>
+
         </div>
 
         <!-- Info cuando todo está en 0 -->
@@ -180,6 +202,26 @@
                         <span class="text-blue-600 font-semibold">Cargada</span>
                     {% endif %}
                 </div>
+
+                <div class="flex items-center justify-between p-3 {% if ssl_bump.enabled %}bg-yellow-50{% else %}bg-gray-50{% endif %} rounded-lg">
+                    <div class="flex items-center">
+                        <i class="fas fa-user-secret {% if ssl_bump.enabled %}text-yellow-500{% else %}text-gray-400{% endif %} mr-3"></i>
+                        <span class="font-medium">SSL Bump (MITM)</span>
+                    </div>
+                    <div class="text-right">
+                        {% if ssl_bump.enabled %}
+                            <span class="text-yellow-600 font-semibold">Activo</span>
+                            {% if ssl_bump.mode %}
+                                <span class="ml-2 text-xs bg-yellow-100 text-yellow-800 px-2 py-0.5 rounded-full">{{ ssl_bump.mode }}</span>
+                            {% endif %}
+                            {% if ssl_bump.cert %}
+                                <br><span class="text-xs text-gray-500">cert: {{ ssl_bump.cert }}</span>
+                            {% endif %}
+                        {% else %}
+                            <span class="text-gray-500 font-semibold">Inactivo</span>
+                        {% endif %}
+                    </div>
+                </div>
             </div>
         </div>
     </div>

+ 160 - 7
utils/admin.py

@@ -1,19 +1,47 @@
 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 = os.getenv("SQUID_CONFIG_PATH", "/etc/squid/squid.conf")
-# ACL_FILES_DIR = os.getenv("ACL_FILES_DIR", "/etc/squid/acls")
-SQUID_CONFIG_PATH = "/etc/squid/squid.conf"
-ACL_FILES_DIR = "/etc/squid/squid.d/"
+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))
@@ -47,13 +75,17 @@ def validate_paths():
                 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):
-        errors.append(f"ACL directory not found: {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):
-        errors.append(f"ACL path is not a directory: {acl_dir}")
+        logger.warning(f"ACL path is not a directory: {acl_dir}")
     elif not os.access(acl_dir, os.W_OK):
-        errors.append(f"No write permissions in ACL directory: {acl_dir}")
+        logger.warning(f"No write permissions in ACL directory: {acl_dir}")
 
     return errors
 
@@ -894,6 +926,127 @@ class SquidConfigManager:
             "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,