Buckets:

download
raw
62 kB
"""OWASP ZAP Integration - Web Application Security Scanner for Zen-AI-Pentest This module provides a comprehensive OWASP ZAP wrapper with: - REST API Wrapper für ZAP - Authentifizierte Scans (Form, JWT, OAuth2, API Key, Session Cookie) - Context Management - Session Handling - Spider/Crawling (Standard & AJAX) - Active Scan (Vulnerability Detection) - OpenAPI Scan (API Endpoints) - GraphQL Scan - Alert Management (High/Medium/Low/Informational) - CWE/WASC Mapping - Evidence Collection - Report Generation (HTML, JSON, SARIF) - Docker Support (Headless Mode) - Automation Framework Integration Author: Zen-AI-Pentest Team License: MIT """ import asyncio import json import logging import shutil import time from dataclasses import asdict, dataclass, field from datetime import datetime, timezone from enum import Enum from typing import Any, Callable, Dict, List, Optional from urllib.parse import urlparse import aiofiles import aiohttp logger = logging.getLogger(__name__) class ZAPScanPolicy(Enum): """ZAP scan policies for active scanning""" DEFAULT = "Default Policy" SQL_INJECTION = "SQL Injection" XSS = "Cross Site Scripting (Reflected)" DIRECTORY_BROWSING = "Directory Browsing" CSRF = "Cross Site Request Forgery" COMMAND_INJECTION = "Command Injection" LDAP_INJECTION = "LDAP Injection" XPATH_INJECTION = "XPath Injection" XML_EXTERNAL_ENTITY = "XML External Entity Attack" SERVER_SIDE_INCLUDE = "Server Side Include" PATH_TRAVERSAL = "Path Traversal" CUSTOM = "Custom Policy" class ZAPAlertRisk(Enum): """ZAP alert risk levels""" INFORMATIONAL = 0 LOW = 1 MEDIUM = 2 HIGH = 3 class ZAPAuthMethod(Enum): """ZAP authentication methods""" FORM_BASED = "formBasedAuthentication" JSON_BASED = "jsonBasedAuthentication" SCRIPT_BASED = "scriptBasedAuthentication" HTTP = "httpAuthentication" MANUAL = "manualAuthentication" class ZAPSessionAuth(Enum): """ZAP session authentication types""" COOKIE = "cookieBasedSessionManagement" HTTP = "httpAuthSessionManagement" SCRIPT = "scriptBasedSessionManagement" @dataclass class ZAPAlert: """Represents a ZAP security alert/finding""" alert_id: str name: str risk: str confidence: str description: str solution: str reference: str cwe_id: str = "" wasc_id: str = "" sourceid: str = "" url: str = "" method: str = "" attack: str = "" evidence: str = "" other_info: str = "" param: str = "" plugin_id: str = "" def to_dict(self) -> Dict[str, Any]: """Convert alert to dictionary""" return asdict(self) @dataclass class ZAPScanResult: """Complete ZAP scan result""" success: bool target: str scan_type: str alerts: List[ZAPAlert] = field(default_factory=list) scan_time: float = 0.0 error: Optional[str] = None scan_id: Optional[str] = None progress: int = 0 urls_crawled: int = 0 urls_audited: int = 0 start_time: Optional[datetime] = None end_time: Optional[datetime] = None auth_success: bool = False context_name: Optional[str] = None def get_alerts_by_risk(self, risk: str) -> List[ZAPAlert]: """Get alerts filtered by risk level""" return [a for a in self.alerts if a.risk.lower() == risk.lower()] def get_high_risk(self) -> List[ZAPAlert]: """Get high risk alerts""" return self.get_alerts_by_risk("High") def get_medium_risk(self) -> List[ZAPAlert]: """Get medium risk alerts""" return self.get_alerts_by_risk("Medium") def get_low_risk(self) -> List[ZAPAlert]: """Get low risk alerts""" return self.get_alerts_by_risk("Low") def get_info_risk(self) -> List[ZAPAlert]: """Get informational alerts""" return self.get_alerts_by_risk("Informational") @dataclass class ZAPAuthConfig: """ZAP authentication configuration""" method: ZAPAuthMethod login_url: str = "" username: str = "" password: str = "" username_field: str = "username" password_field: str = "password" # JWT Auth jwt_token: str = "" jwt_header_name: str = "Authorization" jwt_header_prefix: str = "Bearer" # OAuth 2.0 oauth_token_url: str = "" oauth_client_id: str = "" oauth_client_secret: str = "" oauth_scope: str = "" # API Key api_key_header: str = "X-API-Key" api_key_value: str = "" # Session Cookie session_cookie_name: str = "" session_cookie_value: str = "" # Form/JSON extra params extra_params: Dict[str, str] = field(default_factory=dict) # Logged in/out indicators logged_in_indicator: str = "" logged_out_indicator: str = "" def to_login_payload(self) -> str: """Convert to ZAP authentication payload""" if self.method == ZAPAuthMethod.FORM_BASED: params = { "loginUrl": self.login_url, "loginRequestData": f"{self.username_field}={{%username%}}&{self.password_field}={{%password%}}", } if self.extra_params: for key, value in self.extra_params.items(): params["loginRequestData"] += f"&{key}={value}" return json.dumps(params) elif self.method == ZAPAuthMethod.JSON_BASED: payload = { self.username_field: "{%username%}", self.password_field: "{%password%}", } payload.update(self.extra_params) return json.dumps( { "loginUrl": self.login_url, "loginRequestData": json.dumps(payload), } ) elif self.method == ZAPAuthMethod.HTTP: return json.dumps( { "hostname": urlparse(self.login_url).hostname, "realm": "", "port": urlparse(self.login_url).port or 80, } ) return "" @dataclass class ZAPContext: """ZAP Context configuration""" name: str include_regexes: List[str] = field(default_factory=list) exclude_regexes: List[str] = field(default_factory=list) auth_config: Optional[ZAPAuthConfig] = None session_management: ZAPSessionAuth = ZAPSessionAuth.COOKIE technologies: List[str] = field(default_factory=list) context_id: Optional[str] = None @dataclass class ZAPSpiderResult: """ZAP Spider scan result""" scan_id: str urls_found: List[str] = field(default_factory=list) urls_in_scope: int = 0 progress: int = 0 completed: bool = False @dataclass class ZAPActiveScanResult: """ZAP Active scan result""" scan_id: str progress: int = 0 completed: bool = False alerts_found: int = 0 scan_policy: str = "" class ZAPAPIClient: """REST API Client for OWASP ZAP""" def __init__( self, api_url: str = "http://localhost:8080", api_key: Optional[str] = None, timeout: int = 30, ): self.api_url = api_url.rstrip("/") self.api_key = api_key self.timeout = timeout self._session: Optional[aiohttp.ClientSession] = None async def _get_session(self) -> aiohttp.ClientSession: """Get or create aiohttp session""" if self._session is None or self._session.closed: self._session = aiohttp.ClientSession() return self._session async def close(self): """Close the client session""" if self._session and not self._session.closed: await self._session.close() async def request( self, endpoint: str, params: Optional[Dict[str, Any]] = None, method: str = "GET", ) -> Dict[str, Any]: """Make ZAP API request""" session = await self._get_session() url = f"{self.api_url}/JSON/{endpoint}" params = params or {} if self.api_key: params["apikey"] = self.api_key try: timeout = aiohttp.ClientTimeout(total=self.timeout) if method.upper() == "GET": async with session.get(url, params=params, timeout=timeout) as response: text = await response.text() if response.status == 200: try: return json.loads(text) except json.JSONDecodeError: return {"result": text} else: raise RuntimeError(f"ZAP API error {response.status}: {text}") elif method.upper() == "POST": async with session.post(url, data=params, timeout=timeout) as response: text = await response.text() if response.status == 200: try: return json.loads(text) except json.JSONDecodeError: return {"result": text} else: raise RuntimeError(f"ZAP API error {response.status}: {text}") except aiohttp.ClientError as e: raise RuntimeError(f"Failed to connect to ZAP API: {e}") async def core_version(self) -> str: """Get ZAP version""" result = await self.request("core/view/version/") return result.get("version", "unknown") async def core_status(self) -> Dict[str, Any]: """Get ZAP core status""" return await self.request("core/view/version/") async def is_running(self) -> bool: """Check if ZAP is running""" try: await self.core_version() return True except Exception: return False class ZAPContextManager: """ZAP Context Management""" def __init__(self, client: ZAPAPIClient): self.client = client async def create_context(self, context: ZAPContext) -> str: """Create a new context""" # Create context result = await self.client.request( "context/action/newContext/", {"contextName": context.name}, "POST", ) context_id = result.get("contextId", "") if not context_id: raise RuntimeError("Failed to create context") # Add include regexes for regex in context.include_regexes: await self.client.request( "context/action/includeInContext/", {"contextName": context.name, "regex": regex}, "POST", ) # Add exclude regexes for regex in context.exclude_regexes: await self.client.request( "context/action/excludeFromContext/", {"contextName": context.name, "regex": regex}, "POST", ) # Set session management if context.session_management: await self.client.request( "sessionManagement/action/setSessionManagementMethod/", { "contextId": context_id, "methodName": context.session_management.value, }, "POST", ) # Configure authentication if provided if context.auth_config: await self._configure_auth(context_id, context.auth_config) # Set technologies if context.technologies: for tech in context.technologies: await self.client.request( "context/action/includeContextTechnologies/", {"contextName": context.name, "technology": tech}, "POST", ) context.context_id = context_id return context_id async def _configure_auth(self, context_id: str, auth_config: ZAPAuthConfig) -> None: """Configure authentication for a context""" # Set authentication method await self.client.request( "authentication/action/setAuthenticationMethod/", { "contextId": context_id, "authMethodName": auth_config.method.value, "authMethodConfigParams": auth_config.to_login_payload(), }, "POST", ) # Set logged in/out indicators if provided if auth_config.logged_in_indicator: await self.client.request( "authentication/action/setLoggedInIndicator/", { "contextId": context_id, "loggedInIndicatorRegex": auth_config.logged_in_indicator, }, "POST", ) if auth_config.logged_out_indicator: await self.client.request( "authentication/action/setLoggedOutIndicator/", { "contextId": context_id, "loggedOutIndicatorRegex": auth_config.logged_out_indicator, }, "POST", ) # For session cookie auth, add the cookie if auth_config.method == ZAPAuthMethod.MANUAL and auth_config.session_cookie_name: await self.client.request( "httpSessions/action/addSessionToken/", { "site": urlparse(auth_config.login_url).netloc, "sessionToken": auth_config.session_cookie_name, }, "POST", ) await self.client.request( "httpSessions/action/setSessionTokenValue/", { "site": urlparse(auth_config.login_url).netloc, "session": "default", "sessionToken": auth_config.session_cookie_name, "tokenValue": auth_config.session_cookie_value, }, "POST", ) async def remove_context(self, context_name: str) -> None: """Remove a context""" await self.client.request( "context/action/removeContext/", {"contextName": context_name}, "POST", ) async def list_contexts(self) -> List[str]: """List all contexts""" result = await self.client.request("context/view/contextList/") return result.get("contextList", []) async def get_context(self, context_name: str) -> Dict[str, Any]: """Get context details""" return await self.client.request( "context/view/context/", {"contextName": context_name}, ) class ZAPSessionManager: """ZAP Session Management""" def __init__(self, client: ZAPAPIClient): self.client = client async def new_session(self, name: str = "", overwrite: bool = False) -> bool: """Create a new session""" result = await self.client.request( "core/action/newSession/", {"name": name, "overwrite": str(overwrite).lower()}, "POST", ) return "OK" in str(result) async def save_session(self, name: str, overwrite: bool = True) -> bool: """Save the current session""" result = await self.client.request( "core/action/saveSession/", {"name": name, "overwrite": str(overwrite).lower()}, "POST", ) return "OK" in str(result) async def load_session(self, name: str) -> bool: """Load a session""" result = await self.client.request( "core/action/loadSession/", {"name": name}, "POST", ) return "OK" in str(result) async def snapshot_session(self) -> bool: """Snapshot the current session""" result = await self.client.request( "core/action/snapshotSession/", method="POST", ) return "OK" in str(result) async def clear_session(self) -> bool: """Clear the current session""" result = await self.client.request( "core/action/deleteAllAlerts/", method="POST", ) return "OK" in str(result) class ZAPScanner: """ Advanced OWASP ZAP scanner with comprehensive features. """ DEFAULT_API_PORT = 8080 DEFAULT_DAEMON_PORT = 8080 def __init__( self, target: str, api_url: str = "http://localhost:8080", api_key: Optional[str] = None, zap_path: str = "zap", use_docker: bool = False, options: Optional[Dict[str, Any]] = None, ): self.target = target self.api_url = api_url.rstrip("/") self.api_key = api_key self.zap_path = zap_path self.use_docker = use_docker self.options = options or {} # Set defaults self.options.setdefault("spider", True) self.options.setdefault("ajax_spider", False) self.options.setdefault("active_scan", True) self.options.setdefault("recursion_depth", 5) self.options.setdefault("scan_timeout", 600) self.options.setdefault("scan_policy", ZAPScanPolicy.DEFAULT.value) self._session: Optional[aiohttp.ClientSession] = None self._docker_container: Optional[str] = None self._api_client: Optional[ZAPAPIClient] = None self._context_manager: Optional[ZAPContextManager] = None self._session_manager: Optional[ZAPSessionManager] = None @property def api_client(self) -> ZAPAPIClient: """Get or create API client""" if self._api_client is None: self._api_client = ZAPAPIClient(self.api_url, self.api_key) return self._api_client @property def context_manager(self) -> ZAPContextManager: """Get context manager""" if self._context_manager is None: self._context_manager = ZAPContextManager(self.api_client) return self._context_manager @property def session_manager(self) -> ZAPSessionManager: """Get session manager""" if self._session_manager is None: self._session_manager = ZAPSessionManager(self.api_client) return self._session_manager async def _get_session(self) -> aiohttp.ClientSession: """Get or create aiohttp session""" if self._session is None or self._session.closed: self._session = aiohttp.ClientSession() return self._session async def _api_request( self, endpoint: str, params: Optional[Dict[str, Any]] = None, method: str = "GET", ) -> Dict[str, Any]: """Make ZAP API request""" return await self.api_client.request(endpoint, params, method) def _check_zap_installed(self) -> bool: """Check if ZAP is installed""" if self.use_docker: return shutil.which("docker") is not None return shutil.which(self.zap_path) is not None async def start_daemon(self, port: int = 8080, headless: bool = True) -> bool: """Start ZAP daemon""" if not self._check_zap_installed(): raise RuntimeError("ZAP not found. Install ZAP from: https://www.zaproxy.org/download/") if self.use_docker: return await self._start_docker_daemon(port, headless) else: return await self._start_local_daemon(port, headless) async def _start_local_daemon(self, port: int, headless: bool = True) -> bool: """Start local ZAP daemon""" import subprocess cmd = [ self.zap_path, "-daemon" if headless else "", "-port", str(port), "-config", "api.disablekey=true" if not self.api_key else f"api.key={self.api_key}", "-config", "api.addrs.addr.regex=true", "-config", "api.addrs.addr.name=.*", ] cmd = [c for c in cmd if c] # Remove empty strings try: subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, start_new_session=True, ) # Wait for ZAP to start await asyncio.sleep(10) return True except Exception as e: logger.error(f"Failed to start ZAP daemon: {e}") return False async def _start_docker_daemon(self, port: int, headless: bool = True) -> bool: """Start ZAP in Docker""" import subprocess cmd = [ "docker", "run", "-d", "-p", f"{port}:{port}", "--name", f"zap_daemon_{port}", "ghcr.io/zaproxy/zaproxy:stable", "zap.sh", "-daemon" if headless else "", "-port", str(port), "-host", "0.0.0.0", # nosec B104 "-config", "api.disablekey=true" if not self.api_key else f"api.key={self.api_key}", "-config", "api.addrs.addr.regex=true", "-config", "api.addrs.addr.name=.*", ] cmd = [c for c in cmd if c] # Remove empty strings try: result = subprocess.run(cmd, capture_output=True, text=True) if result.returncode == 0: self._docker_container = result.stdout.strip() # Wait for ZAP to start await asyncio.sleep(15) return True else: logger.error(f"Docker error: {result.stderr}") return False except Exception as e: logger.error(f"Failed to start ZAP docker: {e}") return False async def stop_daemon(self) -> None: """Stop ZAP daemon""" if self._docker_container: import subprocess subprocess.run( ["docker", "stop", self._docker_container], capture_output=True, ) subprocess.run( ["docker", "rm", self._docker_container], capture_output=True, ) self._docker_container = None if self._session and not self._session.closed: await self._session.close() if self._api_client: await self._api_client.close() async def spider_scan( self, context_name: Optional[str] = None, progress_callback: Optional[Callable[[int], None]] = None, ) -> ZAPSpiderResult: """ Run spider scan. Returns: ZAPSpiderResult with scan details """ params = { "url": self.target, "maxChildren": self.options.get("max_children", 0), "recurse": str(self.options.get("recursion_depth", 5)), } if context_name: params["contextName"] = context_name elif self.options.get("context_name"): params["contextName"] = self.options["context_name"] if self.options.get("user_agent"): params["userAgent"] = self.options["user_agent"] if self.options.get("subtree_only", False): params["subtreeOnly"] = "true" # Start spider result = await self._api_request("spider/action/scan/", params, "POST") scan_id = result.get("scan") if not scan_id: raise RuntimeError("Failed to start spider scan") # Wait for completion timeout = self.options.get("scan_timeout", 600) start_time = time.time() urls_found = [] while time.time() - start_time < timeout: status = await self._api_request("spider/view/status/", {"scanId": scan_id}) progress = int(status.get("status", 0)) # Get URLs found urls_result = await self._api_request("spider/view/results/", {"scanId": scan_id}) urls_found = urls_result.get("results", []) if progress_callback: progress_callback(progress) if progress >= 100: return ZAPSpiderResult( scan_id=scan_id, urls_found=urls_found, urls_in_scope=len(urls_found), progress=100, completed=True, ) await asyncio.sleep(2) return ZAPSpiderResult( scan_id=scan_id, urls_found=urls_found, urls_in_scope=len(urls_found), progress=progress, completed=False, ) async def ajax_spider_scan( self, context_name: Optional[str] = None, progress_callback: Optional[Callable[[int], None]] = None, ) -> bool: """ Run AJAX spider scan for modern web applications. Returns: True if completed successfully """ params = { "url": self.target, } if context_name: params["contextName"] = context_name elif self.options.get("context_name"): params["contextName"] = self.options["context_name"] if self.options.get("user_agent"): params["userAgent"] = self.options["user_agent"] if self.options.get("subtree_only", False): params["subtreeOnly"] = "true" # Start AJAX spider await self._api_request("ajaxSpider/action/scan/", params, "POST") # Wait for completion timeout = self.options.get("ajax_timeout", 600) start_time = time.time() while time.time() - start_time < timeout: status = await self._api_request("ajaxSpider/view/status/") is_running = status.get("status") == "running" if not is_running: if progress_callback: progress_callback(100) return True if progress_callback: # Estimate progress based on time elapsed = time.time() - start_time estimated_progress = min(int((elapsed / timeout) * 100), 99) progress_callback(estimated_progress) await asyncio.sleep(2) return False async def active_scan( self, context_name: Optional[str] = None, user_id: Optional[str] = None, progress_callback: Optional[Callable[[int], None]] = None, ) -> ZAPActiveScanResult: """ Run active scan. Returns: ZAPActiveScanResult with scan details """ # Get context ID if provided context_id = "" if context_name: contexts = await self._api_request("context/view/contextList/") if context_name in contexts.get("contextList", []): context_id = context_name elif self.options.get("context_name"): contexts = await self._api_request("context/view/contextList/") if self.options["context_name"] in contexts.get("contextList", []): context_id = self.options["context_name"] params = { "url": self.target, "recurse": "true", "inScopeOnly": "false", "scanPolicyName": self.options.get("scan_policy", ""), "method": "", "postData": "", } if context_id: params["contextId"] = context_id if user_id: params["userId"] = user_id # Start active scan result = await self._api_request("ascan/action/scan/", params, "POST") scan_id = result.get("scan") if not scan_id: raise RuntimeError("Failed to start active scan") # Wait for completion timeout = self.options.get("active_scan_timeout", 1200) start_time = time.time() while time.time() - start_time < timeout: status = await self._api_request("ascan/view/status/", {"scanId": scan_id}) progress = int(status.get("status", 0)) if progress_callback: progress_callback(progress) if progress >= 100: # Get alerts count alerts = await self.get_alerts(self.target) return ZAPActiveScanResult( scan_id=scan_id, progress=100, completed=True, alerts_found=len(alerts), scan_policy=self.options.get("scan_policy", ""), ) await asyncio.sleep(2) return ZAPActiveScanResult( scan_id=scan_id, progress=progress, completed=False, alerts_found=0, scan_policy=self.options.get("scan_policy", ""), ) async def openapi_scan( self, openapi_url: str, target_url: Optional[str] = None, context_name: Optional[str] = None, progress_callback: Optional[Callable[[int], None]] = None, ) -> ZAPSpiderResult: """ Run OpenAPI scan for API endpoints. Args: openapi_url: URL to OpenAPI/Swagger specification target_url: Target URL to override in spec context_name: Optional context name progress_callback: Progress callback function Returns: ZAPSpiderResult with scan details """ params = { "url": openapi_url, } if target_url: params["targetUrl"] = target_url elif self.target: params["targetUrl"] = self.target if context_name: params["contextName"] = context_name elif self.options.get("context_name"): params["contextName"] = self.options["context_name"] # Import OpenAPI spec await self._api_request("openapi/action/importUrl/", params, "POST") # Run spider after import return await self.spider_scan(context_name, progress_callback) async def graphql_scan( self, endpoint: str, schema_url: Optional[str] = None, context_name: Optional[str] = None, progress_callback: Optional[Callable[[int], None]] = None, ) -> ZAPSpiderResult: """ Run GraphQL scan. Args: endpoint: GraphQL endpoint URL schema_url: URL to GraphQL schema (optional) context_name: Optional context name progress_callback: Progress callback function Returns: ZAPSpiderResult with scan details """ params = { "endpoint": endpoint, } if schema_url: params["schemaUrl"] = schema_url if context_name: params["contextName"] = context_name elif self.options.get("context_name"): params["contextName"] = self.options["context_name"] # Import GraphQL schema await self._api_request("graphql/action/importUrl/", params, "POST") # Run spider after import return await self.spider_scan(context_name, progress_callback) async def get_alerts(self, base_url: Optional[str] = None, risk: Optional[str] = None) -> List[ZAPAlert]: """ Get all alerts/findings from ZAP. Args: base_url: Filter alerts by base URL risk: Filter alerts by risk level Returns: List of ZAPAlert objects """ params = {} if base_url: params["baseurl"] = base_url if risk: params["riskId"] = str(ZAPAlertRisk[risk.upper()].value) result = await self._api_request("core/view/alerts/", params) alerts_data = result.get("alerts", []) alerts = [] for alert_data in alerts_data: alert = ZAPAlert( alert_id=str(alert_data.get("alertId", "")), name=alert_data.get("name", ""), risk=alert_data.get("risk", ""), confidence=alert_data.get("confidence", ""), description=alert_data.get("description", ""), solution=alert_data.get("solution", ""), reference=alert_data.get("reference", ""), cwe_id=str(alert_data.get("cweid", "")), wasc_id=str(alert_data.get("wascid", "")), sourceid=str(alert_data.get("sourceid", "")), url=alert_data.get("url", ""), method=alert_data.get("method", ""), attack=alert_data.get("attack", ""), evidence=alert_data.get("evidence", ""), other_info=alert_data.get("otherinfo", ""), param=alert_data.get("param", ""), plugin_id=str(alert_data.get("pluginId", "")), ) alerts.append(alert) return alerts async def get_alerts_by_id(self, alert_id: str) -> Optional[ZAPAlert]: """Get specific alert by ID""" alerts = await self.get_alerts() for alert in alerts: if alert.alert_id == alert_id: return alert return None async def delete_alert(self, alert_id: str) -> bool: """Delete an alert""" result = await self._api_request( "core/action/deleteAlert/", {"id": alert_id}, "POST", ) return "OK" in str(result) async def delete_all_alerts(self) -> bool: """Delete all alerts""" result = await self._api_request( "core/action/deleteAllAlerts/", method="POST", ) return "OK" in str(result) async def scan(self, auth_config: Optional[ZAPAuthConfig] = None) -> ZAPScanResult: """ Run complete ZAP scan based on options. Args: auth_config: Optional authentication configuration Returns: ZAPScanResult with scan results """ start_time = time.time() start_datetime = datetime.now(timezone.utc) progress_callback = self.options.get("progress_callback") context_name = self.options.get("context_name") auth_success = False try: # Setup authentication if provided if auth_config: logger.info(f"Setting up authentication for {self.target}") context = ZAPContext( name=context_name or f"auth_context_{int(time.time())}", include_regexes=[f"{self.target}.*"], auth_config=auth_config, ) await self.context_manager.create_context(context) context_name = context.name auth_success = True # Spider scan if self.options.get("spider", True): logger.info(f"Starting spider scan for {self.target}") await self.spider_scan( context_name=context_name, progress_callback=lambda p: progress_callback({"spider": p}) if progress_callback else None, ) # AJAX spider scan if self.options.get("ajax_spider", False): logger.info(f"Starting AJAX spider scan for {self.target}") await self.ajax_spider_scan( context_name=context_name, progress_callback=lambda p: progress_callback({"ajax_spider": p}) if progress_callback else None, ) # Active scan if self.options.get("active_scan", True): logger.info(f"Starting active scan for {self.target}") await self.active_scan( context_name=context_name, progress_callback=lambda p: progress_callback({"active_scan": p}) if progress_callback else None, ) # Get alerts alerts = await self.get_alerts(self.target) # Get scan statistics urls = await self._api_request("core/view/urls/") num_urls = len(urls.get("urls", [])) scan_time = time.time() - start_time return ZAPScanResult( success=True, target=self.target, scan_type="full", alerts=alerts, scan_time=scan_time, urls_crawled=num_urls, urls_audited=num_urls, start_time=start_datetime, end_time=datetime.now(timezone.utc), auth_success=auth_success, context_name=context_name, ) except Exception as e: logger.error(f"ZAP scan error: {e}") return ZAPScanResult( success=False, target=self.target, scan_type="full", error=str(e), scan_time=time.time() - start_time, start_time=start_datetime, end_time=datetime.now(timezone.utc), auth_success=auth_success, context_name=context_name, ) def parse_output(self, alerts: List[ZAPAlert]) -> List[Dict[str, Any]]: """ Parse ZAP alerts into standardized format. Args: alerts: List of ZAPAlert objects Returns: List of standardized finding dictionaries """ findings = [] for alert in alerts: finding = { "tool": "zap", "name": alert.name, "severity": self._risk_to_severity(alert.risk), "confidence": alert.confidence.lower(), "description": alert.description, "solution": alert.solution, "references": self._parse_references(alert.reference), "evidence": { "url": alert.url, "method": alert.method, "parameter": alert.param, "attack": alert.attack, "evidence": alert.evidence, }, "cwe_id": alert.cwe_id, "wasc_id": alert.wasc_id, "plugin_id": alert.plugin_id, } findings.append(finding) return findings def normalize_findings(self, findings: List[Dict[str, Any]]) -> List[Dict[str, Any]]: """ Normalize findings to standard format. Args: findings: List of finding dictionaries Returns: List of normalized findings """ normalized = [] severity_map = { "informational": "info", "low": "low", "medium": "medium", "high": "high", "critical": "critical", } for finding in findings: normalized_finding = { "tool": "owasp_zap", "target": self.target, "severity": severity_map.get(finding.get("severity", "").lower(), "info"), "title": finding.get("name", "Unknown"), "description": finding.get("description", ""), "evidence": finding.get("evidence", {}), "remediation": finding.get("solution", ""), "references": finding.get("references", []), "confidence": finding.get("confidence", "medium"), "cwe_id": finding.get("cwe_id", ""), "wasc_id": finding.get("wasc_id", ""), "plugin_id": finding.get("plugin_id", ""), } normalized.append(normalized_finding) return normalized def _risk_to_severity(self, risk: str) -> str: """Convert ZAP risk level to severity""" risk_map = { "Informational": "info", "Low": "low", "Medium": "medium", "High": "high", } return risk_map.get(risk, "info") def _parse_references(self, reference: str) -> List[str]: """Parse reference string into list of URLs""" if not reference: return [] # Split by common delimiters refs = [r.strip() for r in reference.replace("\n", " ").split() if r.strip().startswith("http")] return refs if refs else [reference] async def generate_report( self, report_format: str = "json", output_path: Optional[str] = None, theme: Optional[str] = None, ) -> str: """ Generate ZAP report. Args: report_format: Report format (html, xml, json, md, sarif) output_path: Path to save report theme: Optional theme for HTML reports Returns: Report content or path to saved report """ # Handle SARIF format separately if report_format.lower() == "sarif": return await self._generate_sarif_report(output_path) format_map = { "html": "traditional-html", "xml": "traditional-xml", "json": "traditional-json", "md": "traditional-md", } zap_format = format_map.get(report_format.lower(), "traditional-json") params = { "title": f"ZAP Scan Report - {self.target}", "template": zap_format, "sites": self.target, "reportFileName": output_path or "zap_report", } if theme: params["theme"] = theme result = await self._api_request( "reports/action/generate/", params, "POST", ) return result.get("generate", "") async def _generate_sarif_report(self, output_path: Optional[str] = None) -> str: """Generate SARIF format report""" alerts = await self.get_alerts() sarif = { "$schema": "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json", "version": "2.1.0", "runs": [ { "tool": { "driver": { "name": "OWASP ZAP", "informationUri": "https://www.zaproxy.org/", "rules": [], } }, "results": [], } ], } rules = {} for alert in alerts: rule_id = f"ZAP-{alert.plugin_id or alert.cwe_id or '0'}" if rule_id not in rules: rule = { "id": rule_id, "name": alert.name, "shortDescription": {"text": alert.name}, "fullDescription": {"text": alert.description}, "help": {"text": alert.solution}, "defaultConfiguration": {"level": self._zap_to_sarif_level(alert.risk)}, } if alert.cwe_id: rule["relationships"] = [ { "target": { "id": f"CWE-{alert.cwe_id}", "toolComponent": {"name": "CWE", "index": 0}, }, "kinds": ["relevant"], } ] rules[rule_id] = rule sarif["runs"][0]["tool"]["driver"]["rules"].append(rule) result = { "ruleId": rule_id, "level": self._zap_to_sarif_level(alert.risk), "message": {"text": alert.description}, "locations": [ { "physicalLocation": { "artifactLocation": {"uri": alert.url}, "region": { "startLine": 1, }, } } ], "properties": { "confidence": alert.confidence, "evidence": alert.evidence, "attack": alert.attack, "parameter": alert.param, }, } sarif["runs"][0]["results"].append(result) # Save to file if path provided if output_path: async with aiofiles.open(output_path, "w") as f: await f.write(json.dumps(sarif, indent=2)) return output_path return json.dumps(sarif, indent=2) def _zap_to_sarif_level(self, risk: str) -> str: """Convert ZAP risk to SARIF level""" mapping = { "High": "error", "Medium": "warning", "Low": "note", "Informational": "note", } return mapping.get(risk, "none") async def get_report(self, report_format: str = "json", theme: Optional[str] = None) -> Dict[str, Any]: """ Get scan report in various formats. Args: report_format: Format (json, html, xml, md, sarif) theme: Optional theme for HTML Returns: Report data """ alerts = await self.get_alerts() findings = self.parse_output(alerts) report = { "target": self.target, "scan_type": self.options.get("scan_type", "full"), "timestamp": datetime.now(timezone.utc).isoformat(), "alerts": findings, "summary": { "total": len(alerts), "high": len([a for a in alerts if a.risk == "High"]), "medium": len([a for a in alerts if a.risk == "Medium"]), "low": len([a for a in alerts if a.risk == "Low"]), "informational": len([a for a in alerts if a.risk == "Informational"]), }, } if report_format.lower() == "sarif": return json.loads(await self._generate_sarif_report()) return report def get_version(self) -> str: """Get ZAP version""" try: import asyncio result = asyncio.run(self._api_request("core/view/version/")) return result.get("version", "unknown") except Exception: return "unknown" class ZAPDockerManager: """Manage ZAP Docker containers""" DOCKER_IMAGE = "ghcr.io/zaproxy/zaproxy:stable" DOCKER_IMAGE_WEEKLY = "ghcr.io/zaproxy/zaproxy:weekly" DOCKER_IMAGE_NAKED = "ghcr.io/zaproxy/zaproxy:naked" def __init__(self): self.containers: Dict[str, str] = {} async def start_container( self, name: str, port: int = 8080, api_key: Optional[str] = None, headless: bool = True, network: Optional[str] = None, volumes: Optional[List[str]] = None, ) -> str: """Start a ZAP Docker container""" import subprocess cmd = [ "docker", "run", "-d", "--name", name, "-p", f"{port}:{port}", ] if network: cmd.extend(["--network", network]) if volumes: for vol in volumes: cmd.extend(["-v", vol]) cmd.append(self.DOCKER_IMAGE) cmd.extend( [ "zap.sh", "-daemon" if headless else "", "-port", str(port), "-host", "0.0.0.0", # nosec B104 "-config", f"api.key={api_key}" if api_key else "api.disablekey=true", "-config", "api.addrs.addr.regex=true", "-config", "api.addrs.addr.name=.*", ] ) cmd = [c for c in cmd if c] result = subprocess.run(cmd, capture_output=True, text=True) if result.returncode == 0: container_id = result.stdout.strip() self.containers[name] = container_id # Wait for ZAP to start await asyncio.sleep(15) return container_id else: raise RuntimeError(f"Failed to start container: {result.stderr}") async def stop_container(self, name: str) -> bool: """Stop a ZAP container""" import subprocess result = subprocess.run( ["docker", "stop", name], capture_output=True, ) if result.returncode == 0: subprocess.run(["docker", "rm", name], capture_output=True) if name in self.containers: del self.containers[name] return True return False async def stop_all(self) -> None: """Stop all managed containers""" for name in list(self.containers.keys()): await self.stop_container(name) def is_running(self, name: str) -> bool: """Check if container is running""" import subprocess result = subprocess.run( ["docker", "ps", "-q", "-f", f"name={name}"], capture_output=True, text=True, ) return bool(result.stdout.strip()) class ZAPAutomationFramework: """ZAP Automation Framework integration""" def __init__(self, api_client: ZAPAPIClient): self.api_client = api_client async def run_automation_plan( self, plan: Dict[str, Any], progress_callback: Optional[Callable[[Dict], None]] = None ) -> Dict[str, Any]: """ Run an automation framework plan. Args: plan: Automation plan dictionary progress_callback: Progress callback Returns: Plan execution results """ # Save plan to temp file and import import os import tempfile with tempfile.NamedTemporaryFile(mode="w", suffix=".yaml", delete=False) as f: import yaml yaml.dump(plan, f) plan_path = f.name try: # Import and run plan result = await self.api_client.request( "automation/action/runPlan/", {"filePath": plan_path}, "POST", ) # Monitor progress if progress_callback: while True: status = await self.api_client.request("automation/view/planProgress/") progress_callback(status) if status.get("finished", False): break await asyncio.sleep(2) return result finally: os.unlink(plan_path) def create_plan_template( self, target: str, spider: bool = True, active_scan: bool = True, report_formats: Optional[List[str]] = None, ) -> Dict[str, Any]: """Create a basic automation plan template""" plan = { "env": { "contexts": [ { "name": "Default Context", "urls": [target], "includePaths": [f"{target}.*"], } ], "parameters": {}, }, "jobs": [], } if spider: plan["jobs"].append( { "name": "spider", "type": "spider", "parameters": { "context": "Default Context", "url": target, "maxDuration": 10, }, } ) if active_scan: plan["jobs"].append( { "name": "activeScan", "type": "activeScan", "parameters": { "context": "Default Context", "url": target, "maxDuration": 30, }, } ) # Add reports report_formats = report_formats or ["json"] for fmt in report_formats: plan["jobs"].append( { "name": f"{fmt}Report", "type": "report", "parameters": { "template": f"traditional-{fmt}", "reportDir": "/zap/wrk/", "reportFile": f"zap_report.{fmt}", }, } ) return plan # LangChain Tool integration try: from langchain_core.tools import tool LANGCHAIN_AVAILABLE = True except ImportError: LANGCHAIN_AVAILABLE = False # Define a dummy decorator if langchain is not available def tool(func=None, **kwargs): if func: return func return lambda f: f @tool def zap_scan_url( target: str, spider: bool = True, active_scan: bool = True, ajax_spider: bool = False, api_url: str = "http://localhost:8080", api_key: str = "", ) -> str: """ Scan a web application using OWASP ZAP. Args: target: Target URL to scan (e.g., "http://example.com") spider: Enable spider/crawl functionality active_scan: Enable active scanning ajax_spider: Enable AJAX spider for modern web apps api_url: ZAP API URL (default: http://localhost:8080) api_key: ZAP API key Returns: Scan results with discovered vulnerabilities """ import asyncio options = { "spider": spider, "active_scan": active_scan, "ajax_spider": ajax_spider, } scanner = ZAPScanner( target=target, api_url=api_url, api_key=api_key if api_key else None, options=options, ) result = asyncio.run(scanner.scan()) if not result.success: return f"ZAP scan failed: {result.error}" # Format results lines = [ f"OWASP ZAP Scan completed in {result.scan_time:.2f}s", f"Target: {result.target}", f"URLs Crawled: {result.urls_crawled}", f"Alerts Found: {len(result.alerts)}", "", "Findings:", ] # Group alerts by risk risk_groups = {"High": [], "Medium": [], "Low": [], "Informational": []} for alert in result.alerts: risk = alert.risk if alert.risk in risk_groups else "Informational" risk_groups[risk].append(alert) for risk in ["High", "Medium", "Low"]: if risk_groups[risk]: lines.append(f"\n{risk} Risk Findings:") for alert in risk_groups[risk][:5]: # Limit to 5 per category lines.append(f" - {alert.name}") lines.append(f" URL: {alert.url}") lines.append(f" Description: {alert.description[:100]}...") return "\n".join(lines) @tool def zap_quick_scan(target: str, api_url: str = "http://localhost:8080") -> str: """ Quick ZAP scan with spider and basic active scanning. Args: target: Target URL to scan api_url: ZAP API URL Returns: Summary of findings """ import asyncio scanner = ZAPScanner( target=target, api_url=api_url, options={"spider": True, "active_scan": True, "scan_timeout": 300}, ) result = asyncio.run(scanner.scan()) if not result.success: return f"Quick scan failed: {result.error}" high_count = sum(1 for a in result.alerts if a.risk == "High") medium_count = sum(1 for a in result.alerts if a.risk == "Medium") low_count = sum(1 for a in result.alerts if a.risk == "Low") return ( f"ZAP Quick Scan Results for {target}:\n" f" High: {high_count}\n" f" Medium: {medium_count}\n" f" Low: {low_count}\n" f" Total Alerts: {len(result.alerts)}" ) @tool def zap_spider_only(target: str, api_url: str = "http://localhost:8080") -> str: """ Run only ZAP spider/crawler without active scanning. Args: target: Target URL to crawl api_url: ZAP API URL Returns: Discovered URLs """ import asyncio scanner = ZAPScanner( target=target, api_url=api_url, options={"spider": True, "active_scan": False, "ajax_spider": False}, ) result = asyncio.run(scanner.scan()) if not result.success: return f"Spider failed: {result.error}" return f"Spider completed. Crawled {result.urls_crawled} URLs from {target}" @tool def zap_scan_with_auth( target: str, login_url: str, username: str, password: str, auth_type: str = "form", api_url: str = "http://localhost:8080", ) -> str: """ Scan a web application with authentication using OWASP ZAP. Args: target: Target URL to scan login_url: URL for login page username: Username for authentication password: Password for authentication auth_type: Authentication type (form, json) api_url: ZAP API URL Returns: Scan results with authenticated access """ import asyncio auth_method = ZAPAuthMethod.FORM_BASED if auth_type == "form" else ZAPAuthMethod.JSON_BASED auth_config = ZAPAuthConfig( method=auth_method, login_url=login_url, username=username, password=password, ) scanner = ZAPScanner( target=target, api_url=api_url, options={ "spider": True, "active_scan": True, "scan_timeout": 600, "context_name": f"auth_scan_{int(time.time())}", }, ) result = asyncio.run(scanner.scan(auth_config=auth_config)) if not result.success: return f"Authenticated scan failed: {result.error}" return ( f"Authenticated ZAP Scan completed in {result.scan_time:.2f}s\n" f"Auth Success: {result.auth_success}\n" f"Alerts Found: {len(result.alerts)}\n" f"High: {len(result.get_high_risk())}\n" f"Medium: {len(result.get_medium_risk())}\n" f"Low: {len(result.get_low_risk())}" ) @tool def zap_api_scan( target: str, openapi_url: str, api_url: str = "http://localhost:8080", ) -> str: """ Scan an API using OpenAPI specification with OWASP ZAP. Args: target: Target URL to scan openapi_url: URL to OpenAPI/Swagger specification api_url: ZAP API URL Returns: API scan results """ import asyncio scanner = ZAPScanner( target=target, api_url=api_url, options={"active_scan": True, "scan_timeout": 600}, ) result_spider = asyncio.run(scanner.openapi_scan(openapi_url=openapi_url, target_url=target)) return f"API Scan completed\nURLs found: {len(result_spider.urls_found)}\nCompleted: {result_spider.completed}" # Tool Registry integration try: from .tool_registry import ToolCategory, ToolSafetyLevel, registry TOOL_REGISTRY_AVAILABLE = True except ImportError: TOOL_REGISTRY_AVAILABLE = False registry = None ToolCategory = None ToolSafetyLevel = None def register_zap_tools(): """Register ZAP tools with the tool registry""" if not TOOL_REGISTRY_AVAILABLE or not LANGCHAIN_AVAILABLE: return try: registry.register( tool=zap_scan_url, category=ToolCategory.SCANNING, safety_level=ToolSafetyLevel.DANGEROUS, requires_approval=True, tags=["web", "vulnerability", "scanner", "owasp", "zap"], author="Zen-AI-Pentest Team", version="2.0.0", ) registry.register( tool=zap_quick_scan, category=ToolCategory.SCANNING, safety_level=ToolSafetyLevel.DANGEROUS, requires_approval=True, tags=["web", "vulnerability", "quick", "owasp", "zap"], author="Zen-AI-Pentest Team", version="2.0.0", ) registry.register( tool=zap_spider_only, category=ToolCategory.RECONNAISSANCE, safety_level=ToolSafetyLevel.SAFE, tags=["web", "crawler", "spider", "owasp", "zap"], author="Zen-AI-Pentest Team", version="2.0.0", ) registry.register( tool=zap_scan_with_auth, category=ToolCategory.SCANNING, safety_level=ToolSafetyLevel.DANGEROUS, requires_approval=True, tags=["web", "vulnerability", "auth", "authenticated", "owasp", "zap"], author="Zen-AI-Pentest Team", version="2.0.0", ) registry.register( tool=zap_api_scan, category=ToolCategory.SCANNING, safety_level=ToolSafetyLevel.DANGEROUS, requires_approval=True, tags=["api", "openapi", "swagger", "rest", "owasp", "zap"], author="Zen-AI-Pentest Team", version="2.0.0", ) logger.info("ZAP tools registered successfully") except Exception as e: logger.warning(f"Could not register ZAP tools: {e}") # Auto-register on import try: register_zap_tools() except Exception: pass # Alias for tool registry compatibility zap_scan = zap_scan_url __all__ = [ # Main scanner "ZAPScanner", # Data classes "ZAPAlert", "ZAPScanResult", "ZAPSpiderResult", "ZAPActiveScanResult", "ZAPAuthConfig", "ZAPContext", # Enums "ZAPScanPolicy", "ZAPAlertRisk", "ZAPAuthMethod", "ZAPSessionAuth", # API Client & Managers "ZAPAPIClient", "ZAPContextManager", "ZAPSessionManager", "ZAPDockerManager", "ZAPAutomationFramework", # LangChain tools "zap_scan_url", "zap_scan", "zap_quick_scan", "zap_spider_only", "zap_scan_with_auth", "zap_api_scan", "register_zap_tools", ]
"""OWASP ZAP Integration - Web Application Security Scanner for Zen-AI-Pentest
This module provides a comprehensive OWASP ZAP wrapper with:
- REST API Wrapper für ZAP
- Authentifizierte Scans (Form, JWT, OAuth2, API Key, Session Cookie)
- Context Management
- Session Handling
- Spider/Crawling (Standard & AJAX)
- Active Scan (Vulnerability Detection)
- OpenAPI Scan (API Endpoints)
- GraphQL Scan
- Alert Management (High/Medium/Low/Informational)
- CWE/WASC Mapping
- Evidence Collection
- Report Generation (HTML, JSON, SARIF)
- Docker Support (Headless Mode)
- Automation Framework Integration
Author: Zen-AI-Pentest Team
License: MIT
"""
import asyncio
import json
import logging
import shutil
import time
from dataclasses import asdict, dataclass, field
from datetime import datetime, timezone
from enum import Enum
from typing import Any, Callable, Dict, List, Optional
from urllib.parse import urlparse
import aiofiles
import aiohttp
logger = logging.getLogger(__name__)
class ZAPScanPolicy(Enum):
"""ZAP scan policies for active scanning"""
DEFAULT = "Default Policy"
SQL_INJECTION = "SQL Injection"
XSS = "Cross Site Scripting (Reflected)"
DIRECTORY_BROWSING = "Directory Browsing"
CSRF = "Cross Site Request Forgery"
COMMAND_INJECTION = "Command Injection"
LDAP_INJECTION = "LDAP Injection"
XPATH_INJECTION = "XPath Injection"
XML_EXTERNAL_ENTITY = "XML External Entity Attack"
SERVER_SIDE_INCLUDE = "Server Side Include"
PATH_TRAVERSAL = "Path Traversal"
CUSTOM = "Custom Policy"
class ZAPAlertRisk(Enum):
"""ZAP alert risk levels"""
INFORMATIONAL = 0
LOW = 1
MEDIUM = 2
HIGH = 3
class ZAPAuthMethod(Enum):
"""ZAP authentication methods"""
FORM_BASED = "formBasedAuthentication"
JSON_BASED = "jsonBasedAuthentication"
SCRIPT_BASED = "scriptBasedAuthentication"
HTTP = "httpAuthentication"
MANUAL = "manualAuthentication"
class ZAPSessionAuth(Enum):
"""ZAP session authentication types"""
COOKIE = "cookieBasedSessionManagement"
HTTP = "httpAuthSessionManagement"
SCRIPT = "scriptBasedSessionManagement"
@dataclass
class ZAPAlert:
"""Represents a ZAP security alert/finding"""
alert_id: str
name: str
risk: str
confidence: str
description: str
solution: str
reference: str
cwe_id: str = ""
wasc_id: str = ""
sourceid: str = ""
url: str = ""
method: str = ""
attack: str = ""

Xet Storage Details

Size:
62 kB
·
Xet hash:
951777a1673acc8b0028c214b37ed98804da7470e5a7386ade36ad6a03ba06d2

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.