Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /integrations /defect_dojo.py
| """ | |
| DefectDojo Integration - Phase 7.4 | |
| Integration mit DefectDojo für Vulnerability Management | |
| Dieses Modul implementiert die Integration mit DefectDojo zur | |
| Importierung von Scan-Ergebnissen und Verwaltung von Findings. | |
| """ | |
| import logging | |
| import mimetypes | |
| from dataclasses import dataclass, field | |
| from datetime import datetime | |
| from enum import Enum | |
| from pathlib import Path | |
| from typing import Any, Dict, List, Optional, Union | |
| import requests | |
| from requests.adapters import HTTPAdapter | |
| from urllib3.util.retry import Retry | |
| logger = logging.getLogger(__name__) | |
| class DefectDojoSeverity(str, Enum): | |
| """DefectDojo severity levels""" | |
| CRITICAL = "Critical" | |
| HIGH = "High" | |
| MEDIUM = "Medium" | |
| LOW = "Low" | |
| INFO = "Info" | |
| class ScanType(str, Enum): | |
| """Supported scan types for import""" | |
| NMAP = "Nmap Scan" | |
| NUCLEI = "Nuclei Scan" | |
| SQLMAP = "SQLMap Scan" | |
| BURP = "Burp Scan" | |
| OWASP_ZAP = "OWASP ZAP Scan" | |
| SONARQUBE = "SonarQube Scan" | |
| GENERIC = "Generic Findings Import" | |
| SARIF = "SARIF" | |
| class DefectDojoFinding: | |
| """DefectDojo finding data structure""" | |
| title: str | |
| description: str | |
| severity: DefectDojoSeverity | |
| cwe: Optional[int] = None | |
| cve: Optional[str] = None | |
| cvssv3_score: Optional[float] = None | |
| cvssv3: Optional[str] = None | |
| mitigation: Optional[str] = None | |
| impact: Optional[str] = None | |
| references: Optional[str] = None | |
| active: bool = True | |
| verified: bool = False | |
| false_p: bool = False | |
| duplicate: bool = False | |
| tags: List[str] = field(default_factory=list) | |
| file_path: Optional[str] = None | |
| line: Optional[int] = None | |
| component_name: Optional[str] = None | |
| component_version: Optional[str] = None | |
| class ImportResult: | |
| """Result of a scan import operation""" | |
| success: bool | |
| test_id: Optional[int] = None | |
| findings_count: int = 0 | |
| message: str = "" | |
| error: Optional[str] = None | |
| response_data: Dict[str, Any] = field(default_factory=dict) | |
| class DefectDojoClient: | |
| """ | |
| DefectDojo Integration Client für Vulnerability Management. | |
| Features: | |
| - Scan-Ergebnisse importieren (Nuclei, Nmap, SQLMap, etc.) | |
| - Findings erstellen und aktualisieren | |
| - Engagements und Tests verwalten | |
| - Produkt- und Tool-Konfiguration | |
| - Async/await Support | |
| API-Dokumentation: https://demo.defectdojo.org/api/v2/doc/ | |
| """ | |
| DEFAULT_TIMEOUT = 60 | |
| MAX_RETRIES = 3 | |
| # Severity mapping from internal to DefectDojo | |
| SEVERITY_MAP = { | |
| "critical": DefectDojoSeverity.CRITICAL, | |
| "high": DefectDojoSeverity.HIGH, | |
| "medium": DefectDojoSeverity.MEDIUM, | |
| "low": DefectDojoSeverity.LOW, | |
| "info": DefectDojoSeverity.INFO, | |
| } | |
| def __init__( | |
| self, | |
| url: str, | |
| api_key: str, | |
| username: Optional[str] = None, | |
| password: Optional[str] = None, | |
| timeout: int = DEFAULT_TIMEOUT, | |
| verify_ssl: bool = True, | |
| ): | |
| """ | |
| Initialize DefectDojo client. | |
| Args: | |
| url: DefectDojo base URL (e.g., "https://defectdojo.example.com") | |
| api_key: API v2 key for authentication | |
| username: Username for token-based auth (optional) | |
| password: Password for token-based auth (optional) | |
| timeout: Request timeout in seconds | |
| verify_ssl: Verify SSL certificates | |
| """ | |
| self.base_url = url.rstrip("/") | |
| self.api_key = api_key | |
| self.username = username | |
| self.password = password | |
| self.timeout = timeout | |
| self.verify_ssl = verify_ssl | |
| # Setup session with retries | |
| self.session = requests.Session() | |
| retry_strategy = Retry( | |
| total=self.MAX_RETRIES, | |
| backoff_factor=1, | |
| status_forcelist=[429, 500, 502, 503, 504], | |
| ) | |
| adapter = HTTPAdapter(max_retries=retry_strategy) | |
| self.session.mount("http://", adapter) | |
| self.session.mount("https://", adapter) | |
| # Set default headers | |
| self.session.headers.update( | |
| { | |
| "Authorization": f"Token {api_key}", | |
| "Accept": "application/json", | |
| "Content-Type": "application/json", | |
| } | |
| ) | |
| self._api_url = f"{self.base_url}/api/v2" | |
| logger.info(f"DefectDojoClient initialized for {self.base_url}") | |
| def _make_request(self, method: str, endpoint: str, **kwargs) -> requests.Response: | |
| """Make HTTP request with error handling""" | |
| url = f"{self._api_url}/{endpoint.lstrip('/')}" | |
| try: | |
| response = self.session.request( | |
| method=method, | |
| url=url, | |
| timeout=self.timeout, | |
| verify=self.verify_ssl, | |
| **kwargs, | |
| ) | |
| response.raise_for_status() | |
| return response | |
| except requests.exceptions.RequestException as e: | |
| logger.error(f"DefectDojo API request failed: {e}") | |
| raise | |
| def test_connection(self) -> bool: | |
| """Test connection to DefectDojo""" | |
| try: | |
| response = self._make_request("GET", "/users/") | |
| return response.status_code == 200 | |
| except Exception as e: | |
| logger.error(f"DefectDojo connection test failed: {e}") | |
| return False | |
| def get_user_info(self) -> Optional[Dict[str, Any]]: | |
| """Get current user information""" | |
| try: | |
| response = self._make_request("GET", "/users/?limit=1") | |
| data = response.json() | |
| if data.get("results"): | |
| return data["results"][0] | |
| return None | |
| except Exception as e: | |
| logger.error(f"Failed to get user info: {e}") | |
| return None | |
| # Product Operations | |
| def get_products(self, name: Optional[str] = None) -> List[Dict[str, Any]]: | |
| """Get list of products""" | |
| try: | |
| params = {"limit": 100} | |
| if name: | |
| params["name"] = name | |
| response = self._make_request("GET", "/products/", params=params) | |
| return response.json().get("results", []) | |
| except Exception as e: | |
| logger.error(f"Failed to get products: {e}") | |
| return [] | |
| def create_product( | |
| self, | |
| name: str, | |
| description: str, | |
| product_type: int = 1, | |
| tags: Optional[List[str]] = None, | |
| ) -> Optional[Dict[str, Any]]: | |
| """Create a new product""" | |
| try: | |
| data = { | |
| "name": name, | |
| "description": description, | |
| "prod_type": product_type, | |
| } | |
| if tags: | |
| data["tags"] = tags | |
| response = self._make_request("POST", "/products/", json=data) | |
| logger.info(f"Created product: {name}") | |
| return response.json() | |
| except Exception as e: | |
| logger.error(f"Failed to create product: {e}") | |
| return None | |
| def get_or_create_product(self, name: str, description: str = "") -> Optional[Dict[str, Any]]: | |
| """Get existing product or create new one""" | |
| products = self.get_products(name=name) | |
| if products: | |
| return products[0] | |
| return self.create_product(name, description) | |
| # Engagement Operations | |
| def get_engagements( | |
| self, | |
| product_id: Optional[int] = None, | |
| name: Optional[str] = None, | |
| status: Optional[str] = None, | |
| ) -> List[Dict[str, Any]]: | |
| """Get list of engagements""" | |
| try: | |
| params = {"limit": 100} | |
| if product_id: | |
| params["product"] = product_id | |
| if name: | |
| params["name"] = name | |
| if status: | |
| params["status"] = status | |
| response = self._make_request("GET", "/engagements/", params=params) | |
| return response.json().get("results", []) | |
| except Exception as e: | |
| logger.error(f"Failed to get engagements: {e}") | |
| return [] | |
| def create_engagement( | |
| self, | |
| product_id: int, | |
| name: str, | |
| description: str = "", | |
| status: str = "In Progress", | |
| engagement_type: str = "CI/CD", | |
| target_start: Optional[str] = None, | |
| target_end: Optional[str] = None, | |
| ) -> Optional[Dict[str, Any]]: | |
| """Create a new engagement""" | |
| try: | |
| today = datetime.now().strftime("%Y-%m-%d") | |
| data = { | |
| "product": product_id, | |
| "name": name, | |
| "description": description, | |
| "status": status, | |
| "engagement_type": engagement_type, | |
| "target_start": target_start or today, | |
| "target_end": target_end or today, | |
| } | |
| response = self._make_request("POST", "/engagements/", json=data) | |
| logger.info(f"Created engagement: {name}") | |
| return response.json() | |
| except Exception as e: | |
| logger.error(f"Failed to create engagement: {e}") | |
| return None | |
| def get_or_create_engagement( | |
| self, | |
| product_id: int, | |
| name: str, | |
| description: str = "", | |
| ) -> Optional[Dict[str, Any]]: | |
| """Get existing engagement or create new one""" | |
| engagements = self.get_engagements(product_id=product_id, name=name) | |
| if engagements: | |
| return engagements[0] | |
| return self.create_engagement(product_id, name, description) | |
| # Scan Import Operations | |
| def import_scan( | |
| self, | |
| engagement_id: int, | |
| scan_type: Union[ScanType, str], | |
| file_path: str, | |
| active: bool = True, | |
| verified: bool = False, | |
| close_old_findings: bool = False, | |
| push_to_jira: bool = False, | |
| tags: Optional[List[str]] = None, | |
| minimum_severity: Optional[str] = None, | |
| ) -> ImportResult: | |
| """ | |
| Import scan results to DefectDojo. | |
| Args: | |
| engagement_id: Engagement ID to import into | |
| scan_type: Type of scan (use ScanType enum or string) | |
| file_path: Path to scan result file | |
| active: Mark findings as active | |
| verified: Mark findings as verified | |
| close_old_findings: Close old findings not present in this scan | |
| push_to_jira: Push findings to JIRA | |
| tags: Tags to apply to imported findings | |
| minimum_severity: Minimum severity to import (Info, Low, Medium, High, Critical) | |
| Returns: | |
| ImportResult with import details | |
| """ | |
| file_path_obj = Path(file_path) | |
| if not file_path_obj.exists(): | |
| return ImportResult(success=False, error=f"File not found: {file_path}") | |
| try: | |
| # Prepare multipart form data | |
| files = { | |
| "file": ( | |
| file_path_obj.name, | |
| file_path_obj.open("rb"), | |
| mimetypes.guess_type(file_path)[0] or "application/octet-stream", | |
| ) | |
| } | |
| data = { | |
| "engagement": engagement_id, | |
| "scan_type": (scan_type.value if isinstance(scan_type, ScanType) else scan_type), | |
| "active": str(active).lower(), | |
| "verified": str(verified).lower(), | |
| "close_old_findings": str(close_old_findings).lower(), | |
| "push_to_jira": str(push_to_jira).lower(), | |
| } | |
| if tags: | |
| data["tags"] = ",".join(tags) | |
| if minimum_severity: | |
| data["minimum_severity"] = minimum_severity | |
| # Make request without Content-Type header (requests sets it for multipart) | |
| headers = self.session.headers.copy() | |
| headers.pop("Content-Type", None) | |
| response = self.session.post( | |
| f"{self._api_url}/import-scan/", | |
| data=data, | |
| files=files, | |
| headers=headers, | |
| timeout=self.timeout, | |
| verify=self.verify_ssl, | |
| ) | |
| response.raise_for_status() | |
| result = response.json() | |
| logger.info(f"Scan imported successfully: {result.get('test', 'N/A')}") | |
| return ImportResult( | |
| success=True, | |
| test_id=result.get("test"), | |
| findings_count=len(result.get("findings", [])), | |
| message="Scan imported successfully", | |
| response_data=result, | |
| ) | |
| except Exception as e: | |
| logger.error(f"Failed to import scan: {e}") | |
| return ImportResult( | |
| success=False, | |
| error=str(e), | |
| ) | |
| def reimport_scan( | |
| self, | |
| test_id: int, | |
| file_path: str, | |
| active: bool = True, | |
| verified: bool = False, | |
| close_old_findings: bool = True, | |
| ) -> ImportResult: | |
| """ | |
| Re-import scan results to update existing test. | |
| Args: | |
| test_id: Existing test ID to update | |
| file_path: Path to new scan result file | |
| active: Mark findings as active | |
| verified: Mark findings as verified | |
| close_old_findings: Close old findings not present in new scan | |
| Returns: | |
| ImportResult with import details | |
| """ | |
| file_path_obj = Path(file_path) | |
| if not file_path_obj.exists(): | |
| return ImportResult(success=False, error=f"File not found: {file_path}") | |
| try: | |
| files = { | |
| "file": ( | |
| file_path_obj.name, | |
| file_path_obj.open("rb"), | |
| mimetypes.guess_type(file_path)[0] or "application/octet-stream", | |
| ) | |
| } | |
| data = { | |
| "test": test_id, | |
| "active": str(active).lower(), | |
| "verified": str(verified).lower(), | |
| "close_old_findings": str(close_old_findings).lower(), | |
| } | |
| headers = self.session.headers.copy() | |
| headers.pop("Content-Type", None) | |
| response = self.session.post( | |
| f"{self._api_url}/reimport-scan/", | |
| data=data, | |
| files=files, | |
| headers=headers, | |
| timeout=self.timeout, | |
| verify=self.verify_ssl, | |
| ) | |
| response.raise_for_status() | |
| result = response.json() | |
| logger.info(f"Scan re-imported successfully: {test_id}") | |
| return ImportResult( | |
| success=True, | |
| test_id=test_id, | |
| findings_count=len(result.get("findings", [])), | |
| message="Scan re-imported successfully", | |
| response_data=result, | |
| ) | |
| except Exception as e: | |
| logger.error(f"Failed to reimport scan: {e}") | |
| return ImportResult( | |
| success=False, | |
| error=str(e), | |
| ) | |
| # Finding Operations | |
| def get_findings( | |
| self, | |
| product_id: Optional[int] = None, | |
| engagement_id: Optional[int] = None, | |
| test_id: Optional[int] = None, | |
| severity: Optional[str] = None, | |
| active: Optional[bool] = None, | |
| verified: Optional[bool] = None, | |
| limit: int = 100, | |
| ) -> List[Dict[str, Any]]: | |
| """Get list of findings with optional filtering""" | |
| try: | |
| params = {"limit": limit} | |
| if product_id: | |
| params["product"] = product_id | |
| if engagement_id: | |
| params["engagement"] = engagement_id | |
| if test_id: | |
| params["test"] = test_id | |
| if severity: | |
| params["severity"] = severity | |
| if active is not None: | |
| params["active"] = str(active).lower() | |
| if verified is not None: | |
| params["verified"] = str(verified).lower() | |
| response = self._make_request("GET", "/findings/", params=params) | |
| return response.json().get("results", []) | |
| except Exception as e: | |
| logger.error(f"Failed to get findings: {e}") | |
| return [] | |
| def create_finding( | |
| self, | |
| test_id: int, | |
| title: str, | |
| severity: Union[DefectDojoSeverity, str], | |
| description: str, | |
| mitigation: Optional[str] = None, | |
| impact: Optional[str] = None, | |
| cwe: Optional[int] = None, | |
| cve: Optional[str] = None, | |
| cvssv3_score: Optional[float] = None, | |
| active: bool = True, | |
| verified: bool = False, | |
| tags: Optional[List[str]] = None, | |
| ) -> Optional[Dict[str, Any]]: | |
| """ | |
| Create a manual finding. | |
| Args: | |
| test_id: Test ID to add finding to | |
| title: Finding title | |
| severity: Severity level (Critical, High, Medium, Low, Info) | |
| description: Finding description (supports markdown) | |
| mitigation: Remediation/mitigation steps | |
| impact: Impact description | |
| cwe: CWE identifier | |
| cve: CVE identifier | |
| cvssv3_score: CVSS v3 score (0-10) | |
| active: Is finding active | |
| verified: Is finding verified | |
| tags: List of tags | |
| Returns: | |
| Created finding or None if failed | |
| """ | |
| try: | |
| # Convert severity to proper format | |
| if isinstance(severity, str): | |
| severity = self.SEVERITY_MAP.get(severity.lower(), DefectDojoSeverity.MEDIUM) | |
| data = { | |
| "test": test_id, | |
| "title": title, | |
| "severity": severity.value, | |
| "description": description, | |
| "active": active, | |
| "verified": verified, | |
| } | |
| if mitigation: | |
| data["mitigation"] = mitigation | |
| if impact: | |
| data["impact"] = impact | |
| if cwe: | |
| data["cwe"] = cwe | |
| if cve: | |
| data["cve"] = cve | |
| if cvssv3_score is not None: | |
| data["cvssv3_score"] = cvssv3_score | |
| if tags: | |
| data["tags"] = tags | |
| response = self._make_request("POST", "/findings/", json=data) | |
| logger.info(f"Created finding: {title}") | |
| return response.json() | |
| except Exception as e: | |
| logger.error(f"Failed to create finding: {e}") | |
| return None | |
| def create_finding_from_dict( | |
| self, | |
| test_id: int, | |
| finding: DefectDojoFinding, | |
| ) -> Optional[Dict[str, Any]]: | |
| """Create finding from DefectDojoFinding dataclass""" | |
| return self.create_finding( | |
| test_id=test_id, | |
| title=finding.title, | |
| severity=finding.severity, | |
| description=finding.description, | |
| mitigation=finding.mitigation, | |
| impact=finding.impact, | |
| cwe=finding.cwe, | |
| cve=finding.cve, | |
| cvssv3_score=finding.cvssv3_score, | |
| active=finding.active, | |
| verified=finding.verified, | |
| tags=finding.tags, | |
| ) | |
| def update_finding(self, finding_id: int, **kwargs) -> Optional[Dict[str, Any]]: | |
| """Update an existing finding""" | |
| try: | |
| response = self._make_request("PATCH", f"/findings/{finding_id}/", json=kwargs) | |
| logger.info(f"Updated finding: {finding_id}") | |
| return response.json() | |
| except Exception as e: | |
| logger.error(f"Failed to update finding: {e}") | |
| return None | |
| def close_finding(self, finding_id: int, notes: Optional[str] = None) -> bool: | |
| """Close/mitigate a finding""" | |
| try: | |
| data = {"active": False, "is_mitigated": True} | |
| if notes: | |
| data["mitigation"] = notes | |
| self._make_request("PATCH", f"/findings/{finding_id}/", json=data) | |
| logger.info(f"Closed finding: {finding_id}") | |
| return True | |
| except Exception as e: | |
| logger.error(f"Failed to close finding: {e}") | |
| return False | |
| def accept_risk(self, finding_id: int, justification: str) -> bool: | |
| """Accept risk for a finding""" | |
| try: | |
| data = {"risk_accepted": True, "notes": justification} | |
| self._make_request("PATCH", f"/findings/{finding_id}/", json=data) | |
| logger.info(f"Risk accepted for finding: {finding_id}") | |
| return True | |
| except Exception as e: | |
| logger.error(f"Failed to accept risk: {e}") | |
| return False | |
| # Utility Methods | |
| def convert_finding( | |
| self, | |
| internal_finding: Dict[str, Any], | |
| ) -> DefectDojoFinding: | |
| """ | |
| Convert internal finding format to DefectDojoFinding. | |
| Args: | |
| internal_finding: Internal finding dictionary | |
| Returns: | |
| DefectDojoFinding dataclass | |
| """ | |
| severity = internal_finding.get("severity", "medium") | |
| dd_severity = self.SEVERITY_MAP.get(severity.lower(), DefectDojoSeverity.MEDIUM) | |
| # Build references | |
| references = [] | |
| if internal_finding.get("references"): | |
| references.extend(internal_finding.get("references", [])) | |
| if internal_finding.get("cve_ids"): | |
| references.extend(internal_finding.get("cve_ids", [])) | |
| return DefectDojoFinding( | |
| title=internal_finding.get("title", "Unknown Finding"), | |
| description=internal_finding.get("description", ""), | |
| severity=dd_severity, | |
| cwe=internal_finding.get("cwe"), | |
| cve=(internal_finding.get("cve_ids", [None])[0] if internal_finding.get("cve_ids") else None), | |
| cvssv3_score=internal_finding.get("cvss_score"), | |
| mitigation=internal_finding.get("remediation"), | |
| impact=internal_finding.get("impact"), | |
| references="\n".join(references) if references else None, | |
| tags=internal_finding.get("tags", []), | |
| file_path=internal_finding.get("file_path"), | |
| line=internal_finding.get("line"), | |
| ) | |
| def upload_pentest_report( | |
| self, | |
| product_name: str, | |
| engagement_name: str, | |
| scan_file: str, | |
| scan_type: Union[ScanType, str] = ScanType.GENERIC, | |
| tags: Optional[List[str]] = None, | |
| ) -> ImportResult: | |
| """ | |
| Convenience method to upload a pentest report. | |
| Creates product and engagement if they don't exist. | |
| Args: | |
| product_name: Product name | |
| engagement_name: Engagement name | |
| scan_file: Path to scan result file | |
| scan_type: Type of scan | |
| tags: Tags for findings | |
| Returns: | |
| ImportResult | |
| """ | |
| # Get or create product | |
| product = self.get_or_create_product(product_name, f"Product for {product_name}") | |
| if not product: | |
| return ImportResult(success=False, error="Failed to create/get product") | |
| # Get or create engagement | |
| engagement = self.get_or_create_engagement( | |
| product_id=product["id"], | |
| name=engagement_name, | |
| description=f"Pentest engagement for {engagement_name}", | |
| ) | |
| if not engagement: | |
| return ImportResult(success=False, error="Failed to create/get engagement") | |
| # Import scan | |
| return self.import_scan( | |
| engagement_id=engagement["id"], | |
| scan_type=scan_type, | |
| file_path=scan_file, | |
| tags=tags or ["pentest", "zen-ai"], | |
| ) | |
| def close(self): | |
| """Close HTTP session""" | |
| self.session.close() | |
| # Convenience functions | |
| def create_defect_dojo_client(url: str, api_key: str, **kwargs) -> DefectDojoClient: | |
| """ | |
| Create DefectDojo client with settings from environment or config. | |
| Args: | |
| url: DefectDojo base URL | |
| api_key: API v2 key | |
| **kwargs: Additional arguments for DefectDojoClient | |
| Returns: | |
| DefectDojoClient instance | |
| """ | |
| return DefectDojoClient(url=url, api_key=api_key, **kwargs) | |
| def import_nuclei_results( | |
| url: str, | |
| api_key: str, | |
| engagement_id: int, | |
| nuclei_json_file: str, | |
| ) -> ImportResult: | |
| """ | |
| Convenience function to import Nuclei results. | |
| Args: | |
| url: DefectDojo URL | |
| api_key: API key | |
| engagement_id: Engagement ID | |
| nuclei_json_file: Path to Nuclei JSON results | |
| Returns: | |
| ImportResult | |
| """ | |
| client = DefectDojoClient(url=url, api_key=api_key) | |
| try: | |
| return client.import_scan( | |
| engagement_id=engagement_id, | |
| scan_type=ScanType.NUCLEI, | |
| file_path=nuclei_json_file, | |
| ) | |
| finally: | |
| client.close() | |
| __all__ = [ | |
| "DefectDojoClient", | |
| "DefectDojoFinding", | |
| "DefectDojoSeverity", | |
| "ScanType", | |
| "ImportResult", | |
| "create_defect_dojo_client", | |
| "import_nuclei_results", | |
| ] | |
Xet Storage Details
- Size:
- 25 kB
- Xet hash:
- 5b35a3763048573eba2e358a33c42aba38d3e428d1b4e1a8f5eb6b16decf7a23
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.