Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /risk_engine /risk_report.py
| """ | |
| Risk Report Generation | |
| Erzeugt strukturierte Risk Reports mit: | |
| - Multi-Faktor Risk Scores | |
| - Priorisierten Findings | |
| - SLA-Tracking | |
| - Empfohlene Maßnahmen | |
| - Executive Summary | |
| Unterstützt Export nach: | |
| - JSON (für API/Integration) | |
| - Markdown (für Dokumentation) | |
| - HTML (für Dashboards) | |
| - PDF (für Berichte) | |
| """ | |
| import json | |
| import logging | |
| from dataclasses import dataclass, field | |
| from datetime import datetime, timedelta | |
| from enum import Enum | |
| from typing import Any, Dict, List, Optional | |
| from risk_engine.multi_factor_scorer import MultiFactorRiskScore, MultiFactorRiskScorer, RiskSeverity | |
| class ReportFormat(Enum): | |
| """Unterstützte Report-Formate""" | |
| JSON = "json" | |
| MARKDOWN = "markdown" | |
| HTML = "html" | |
| CSV = "csv" | |
| PDF = "pdf" | |
| class RiskFinding: | |
| """Einzelnes Finding im Risk Report""" | |
| finding_id: str | |
| cve_id: Optional[str] | |
| title: str | |
| description: str | |
| target: str | |
| # Scores | |
| cvss_score: float | |
| epss_score: float | |
| business_impact: float | |
| validation_confidence: float | |
| final_risk_score: float | |
| # Kategorisierung | |
| severity: str | |
| sla_target: str | |
| sla_deadline: Optional[datetime] = None | |
| # Maßnahmen | |
| recommendations: List[str] = field(default_factory=list) | |
| actions: List[str] = field(default_factory=list) | |
| # Status | |
| status: str = "open" # open, in_progress, resolved, accepted | |
| assigned_to: Optional[str] = None | |
| # Metadaten | |
| discovered_at: datetime = field(default_factory=datetime.now) | |
| raw_evidence: Dict[str, Any] = field(default_factory=dict) | |
| def to_dict(self) -> Dict[str, Any]: | |
| return { | |
| "finding_id": self.finding_id, | |
| "cve_id": self.cve_id, | |
| "title": self.title, | |
| "description": self.description, | |
| "target": self.target, | |
| "scores": { | |
| "cvss": self.cvss_score, | |
| "epss": self.epss_score, | |
| "business_impact": self.business_impact, | |
| "validation": self.validation_confidence, | |
| "final_risk": self.final_risk_score, | |
| }, | |
| "severity": self.severity, | |
| "sla": {"target": self.sla_target, "deadline": self.sla_deadline.isoformat() if self.sla_deadline else None}, | |
| "recommendations": self.recommendations, | |
| "actions": self.actions, | |
| "status": self.status, | |
| "assigned_to": self.assigned_to, | |
| "discovered_at": self.discovered_at.isoformat(), | |
| "raw_evidence": self.raw_evidence, | |
| } | |
| class RiskSummary: | |
| """Zusammenfassung eines Risk Reports""" | |
| total_findings: int | |
| critical_count: int | |
| high_count: int | |
| medium_count: int | |
| low_count: int | |
| info_count: int | |
| average_risk_score: float | |
| max_risk_score: float | |
| findings_due_24h: int | |
| findings_due_72h: int | |
| findings_due_14d: int | |
| total_estimated_cost: float | |
| def to_dict(self) -> Dict[str, Any]: | |
| return { | |
| "total_findings": self.total_findings, | |
| "severity_distribution": { | |
| "critical": self.critical_count, | |
| "high": self.high_count, | |
| "medium": self.medium_count, | |
| "low": self.low_count, | |
| "info": self.info_count, | |
| }, | |
| "risk_metrics": {"average_score": round(self.average_risk_score, 2), "max_score": round(self.max_risk_score, 2)}, | |
| "sla_summary": { | |
| "due_24h": self.findings_due_24h, | |
| "due_72h": self.findings_due_72h, | |
| "due_14d": self.findings_due_14d, | |
| }, | |
| "estimated_remediation_cost": self.total_estimated_cost, | |
| } | |
| class RiskReport: | |
| """ | |
| Risk Report Generator | |
| Erzeugt strukturierte Risk Reports mit Multi-Faktor Scoring. | |
| Usage: | |
| report = RiskReport( | |
| report_title="Q1 Security Assessment", | |
| organization="ACME Corp" | |
| ) | |
| # Findings hinzufügen | |
| report.add_finding( | |
| cve_id="CVE-2024-1234", | |
| title="Critical SQL Injection", | |
| cvss=9.8, | |
| epss=0.85, | |
| business_impact="CRITICAL", | |
| final_risk=9.5, | |
| sla="24h", | |
| recommendations=["Immediate patching", "WAF rule"] | |
| ) | |
| # Export | |
| json_report = report.to_json() | |
| md_report = report.to_markdown() | |
| """ | |
| def __init__( | |
| self, | |
| report_title: str = "Security Risk Report", | |
| organization: str = "", | |
| report_date: Optional[datetime] = None, | |
| report_id: Optional[str] = None, | |
| ): | |
| self.report_id = report_id or f"RR-{datetime.now().strftime('%Y%m%d-%H%M%S')}" | |
| self.report_title = report_title | |
| self.organization = organization | |
| self.report_date = report_date or datetime.now() | |
| self.findings: List[RiskFinding] = [] | |
| self.scorer = MultiFactorRiskScorer() | |
| self.logger = logging.getLogger(__name__) | |
| # Metadaten | |
| self.metadata: Dict[str, Any] = {} | |
| self.scope: str = "" | |
| self.assessors: List[str] = [] | |
| def add_finding( | |
| self, | |
| finding_id: Optional[str] = None, | |
| cve_id: Optional[str] = None, | |
| title: str = "", | |
| description: str = "", | |
| target: str = "", | |
| cvss: float = 5.0, | |
| epss: float = 0.0, | |
| business_impact: float = 0.5, | |
| validation_confidence: float = 0.0, | |
| final_risk: Optional[float] = None, | |
| severity: Optional[str] = None, | |
| sla: Optional[str] = None, | |
| recommendations: Optional[List[str]] = None, | |
| actions: Optional[List[str]] = None, | |
| raw_evidence: Optional[Dict[str, Any]] = None, | |
| ) -> RiskFinding: | |
| """ | |
| Fügt ein Finding zum Report hinzu. | |
| Args: | |
| finding_id: Eindeutige ID (optional, wird generiert) | |
| cve_id: CVE ID (optional) | |
| title: Titel des Findings | |
| description: Beschreibung | |
| target: Betroffenes System | |
| cvss: CVSS Score (0-10) | |
| epss: EPSS Score (0-1) | |
| business_impact: Business Impact (0-1) | |
| validation_confidence: Validation Confidence (0-1) | |
| final_risk: Final Risk Score (optional, wird berechnet) | |
| severity: Severity Level (optional, wird bestimmt) | |
| sla: SLA Target (optional, wird bestimmt) | |
| recommendations: Liste von Empfehlungen | |
| actions: Liste von Maßnahmen | |
| raw_evidence: Rohdaten/Evidenz | |
| Returns: | |
| Das erstellte RiskFinding | |
| """ | |
| # Generiere ID falls nicht angegeben | |
| if finding_id is None: | |
| finding_id = f"FIND-{len(self.findings) + 1:04d}" | |
| # Berechne finalen Risk Score falls nicht angegeben | |
| if final_risk is None: | |
| final_risk = self._calculate_final_risk(cvss, epss, business_impact, validation_confidence) | |
| # Bestimme Severity falls nicht angegeben | |
| if severity is None: | |
| severity = RiskSeverity.from_score(final_risk).name | |
| # Bestimme SLA falls nicht angegeben | |
| if sla is None: | |
| sla = self._get_sla_from_severity(severity) | |
| # Berechne SLA Deadline | |
| sla_deadline = self._calculate_sla_deadline(sla) | |
| finding = RiskFinding( | |
| finding_id=finding_id, | |
| cve_id=cve_id, | |
| title=title, | |
| description=description, | |
| target=target, | |
| cvss_score=cvss, | |
| epss_score=epss, | |
| business_impact=business_impact, | |
| validation_confidence=validation_confidence, | |
| final_risk_score=final_risk, | |
| severity=severity, | |
| sla_target=sla, | |
| sla_deadline=sla_deadline, | |
| recommendations=recommendations or [], | |
| actions=actions or [], | |
| raw_evidence=raw_evidence or {}, | |
| ) | |
| self.findings.append(finding) | |
| self.logger.debug(f"Finding hinzugefügt: {finding_id}") | |
| return finding | |
| def add_finding_from_calculation( | |
| self, | |
| risk_score: MultiFactorRiskScore, | |
| finding_id: Optional[str] = None, | |
| description: str = "", | |
| raw_evidence: Optional[Dict[str, Any]] = None, | |
| ) -> RiskFinding: | |
| """ | |
| Fügt ein Finding basierend auf einer MultiFactorRiskScore Berechnung hinzu. | |
| """ | |
| return self.add_finding( | |
| finding_id=finding_id, | |
| cve_id=risk_score.cve_id, | |
| title=risk_score.finding_title, | |
| description=description, | |
| target=risk_score.target, | |
| cvss=risk_score.cvss_component.score * 10, | |
| epss=risk_score.epss_component.score, | |
| business_impact=risk_score.business_component.score, | |
| validation_confidence=risk_score.validation_component.score, | |
| final_risk=risk_score.final_risk_score, | |
| severity=risk_score.severity.name, | |
| sla=risk_score.sla_target, | |
| recommendations=risk_score.recommendations, | |
| actions=risk_score.prioritized_actions, | |
| raw_evidence=raw_evidence, | |
| ) | |
| def _calculate_final_risk(self, cvss: float, epss: float, business: float, validation: float) -> float: | |
| """Berechnet den finalen Risk Score.""" | |
| return ((cvss / 10.0) * 0.30 + epss * 0.20 + business * 0.35 + validation * 0.15) * 10 | |
| def _get_sla_from_severity(self, severity: str) -> str: | |
| """Bestimmt SLA basierend auf Severity.""" | |
| sla_map = {"CRITICAL": "24h", "HIGH": "72h", "MEDIUM": "14d", "LOW": "30d", "INFO": "Best effort"} | |
| return sla_map.get(severity.upper(), "30d") | |
| def _calculate_sla_deadline(self, sla: str) -> Optional[datetime]: | |
| """Berechnet das SLA Deadline Datum.""" | |
| now = datetime.now() | |
| if sla == "24h": | |
| return now + timedelta(hours=24) | |
| elif sla == "72h": | |
| return now + timedelta(hours=72) | |
| elif sla == "14d": | |
| return now + timedelta(days=14) | |
| elif sla == "30d": | |
| return now + timedelta(days=30) | |
| return None | |
| def get_summary(self) -> RiskSummary: | |
| """Generiert eine Zusammenfassung des Reports.""" | |
| if not self.findings: | |
| return RiskSummary( | |
| total_findings=0, | |
| critical_count=0, | |
| high_count=0, | |
| medium_count=0, | |
| low_count=0, | |
| info_count=0, | |
| average_risk_score=0.0, | |
| max_risk_score=0.0, | |
| findings_due_24h=0, | |
| findings_due_72h=0, | |
| findings_due_14d=0, | |
| total_estimated_cost=0.0, | |
| ) | |
| # Zähle Severity Levels | |
| critical = sum(1 for f in self.findings if f.severity.upper() == "CRITICAL") | |
| high = sum(1 for f in self.findings if f.severity.upper() == "HIGH") | |
| medium = sum(1 for f in self.findings if f.severity.upper() == "MEDIUM") | |
| low = sum(1 for f in self.findings if f.severity.upper() == "LOW") | |
| info = sum(1 for f in self.findings if f.severity.upper() == "INFO") | |
| # Risk Scores | |
| scores = [f.final_risk_score for f in self.findings] | |
| avg_score = sum(scores) / len(scores) | |
| max_score = max(scores) | |
| # SLA Tracking | |
| now = datetime.now() | |
| due_24h = sum(1 for f in self.findings if f.sla_deadline and f.sla_deadline <= now + timedelta(hours=24)) | |
| due_72h = sum(1 for f in self.findings if f.sla_deadline and f.sla_deadline <= now + timedelta(hours=72)) | |
| due_14d = sum(1 for f in self.findings if f.sla_deadline and f.sla_deadline <= now + timedelta(days=14)) | |
| # Geschätzte Kosten (sehr vereinfacht) | |
| cost_per_critical = 50000 | |
| cost_per_high = 20000 | |
| cost_per_medium = 5000 | |
| cost_per_low = 1000 | |
| total_cost = critical * cost_per_critical + high * cost_per_high + medium * cost_per_medium + low * cost_per_low | |
| return RiskSummary( | |
| total_findings=len(self.findings), | |
| critical_count=critical, | |
| high_count=high, | |
| medium_count=medium, | |
| low_count=low, | |
| info_count=info, | |
| average_risk_score=avg_score, | |
| max_risk_score=max_score, | |
| findings_due_24h=due_24h, | |
| findings_due_72h=due_72h, | |
| findings_due_14d=due_14d, | |
| total_estimated_cost=total_cost, | |
| ) | |
| def get_prioritized_findings(self) -> List[RiskFinding]: | |
| """Gibt Findings nach Risk Score sortiert zurück.""" | |
| return sorted(self.findings, key=lambda f: f.final_risk_score, reverse=True) | |
| def to_dict(self) -> Dict[str, Any]: | |
| """Konvertiert den Report zu einem Dictionary.""" | |
| return { | |
| "report_metadata": { | |
| "report_id": self.report_id, | |
| "title": self.report_title, | |
| "organization": self.organization, | |
| "date": self.report_date.isoformat(), | |
| "scope": self.scope, | |
| "assessors": self.assessors, | |
| "custom_metadata": self.metadata, | |
| }, | |
| "summary": self.get_summary().to_dict(), | |
| "findings": [f.to_dict() for f in self.get_prioritized_findings()], | |
| } | |
| def to_json(self, indent: int = 2) -> str: | |
| """Exportiert den Report als JSON.""" | |
| return json.dumps(self.to_dict(), indent=indent, ensure_ascii=False) | |
| def to_markdown(self) -> str: | |
| """Exportiert den Report als Markdown.""" | |
| summary = self.get_summary() | |
| lines = [ | |
| f"# {self.report_title}", | |
| "", | |
| f"**Organization:** {self.organization}", | |
| f"**Report ID:** {self.report_id}", | |
| f"**Date:** {self.report_date.strftime('%Y-%m-%d %H:%M')}", | |
| f"**Scope:** {self.scope}", | |
| "", | |
| "## Executive Summary", | |
| "", | |
| f"This risk assessment identified **{summary.total_findings}** security findings:", | |
| "", | |
| "| Severity | Count |", | |
| "|----------|-------|", | |
| f"| Critical | {summary.critical_count} |", | |
| f"| High | {summary.high_count} |", | |
| f"| Medium | {summary.medium_count} |", | |
| f"| Low | {summary.low_count} |", | |
| f"| Info | {summary.info_count} |", | |
| "", | |
| f"- **Average Risk Score:** {summary.average_risk_score:.1f}/10", | |
| f"- **Maximum Risk Score:** {summary.max_risk_score:.1f}/10", | |
| f"- **Findings due within 24h:** {summary.findings_due_24h}", | |
| f"- **Estimated Remediation Cost:** €{summary.total_estimated_cost:,.0f}", | |
| "", | |
| "## Prioritized Findings", | |
| "", | |
| ] | |
| for finding in self.get_prioritized_findings()[:20]: # Top 20 | |
| lines.extend( | |
| [ | |
| f"### {finding.finding_id}: {finding.title}", | |
| "", | |
| f"**Target:** `{finding.target}`", | |
| f"**CVE:** {finding.cve_id or 'N/A'}", | |
| f"**Severity:** {finding.severity}", | |
| f"**Risk Score:** {finding.final_risk_score:.1f}/10", | |
| f"**SLA:** {finding.sla_target}", | |
| "", | |
| "**Scores:**", | |
| f"- CVSS: {finding.cvss_score:.1f}", | |
| f"- EPSS: {finding.epss_score * 100:.1f}%", | |
| f"- Business Impact: {finding.business_impact:.2f}", | |
| f"- Validation: {finding.validation_confidence:.2f}", | |
| "", | |
| "**Recommendations:**", | |
| ] | |
| ) | |
| for rec in finding.recommendations[:3]: | |
| lines.append(f"- {rec}") | |
| lines.append("") | |
| return "\n".join(lines) | |
| def to_html(self) -> str: | |
| """Exportiert den Report als HTML.""" | |
| summary = self.get_summary() | |
| findings_html = [] | |
| for finding in self.get_prioritized_findings()[:20]: | |
| severity_class = finding.severity.lower() | |
| findings_html.append(f""" | |
| <div class="finding {severity_class}"> | |
| <h3>{finding.finding_id}: {finding.title}</h3> | |
| <p><strong>Target:</strong> {finding.target}</p> | |
| <p><strong>CVE:</strong> {finding.cve_id or "N/A"}</p> | |
| <p><strong>Risk Score:</strong> <span class="score">{finding.final_risk_score:.1f}/10</span></p> | |
| <p><strong>SLA:</strong> {finding.sla_target}</p> | |
| <div class="scores"> | |
| <span>CVSS: {finding.cvss_score:.1f}</span> | |
| <span>EPSS: {finding.epss_score * 100:.1f}%</span> | |
| <span>Business: {finding.business_impact:.2f}</span> | |
| </div> | |
| </div> | |
| """) | |
| return f""" | |
| <!DOCTYPE html> | |
| <html> | |
| <head> | |
| <title>{self.report_title}</title> | |
| <style> | |
| body {{ font-family: Arial, sans-serif; margin: 40px; }} | |
| .summary {{ background: #f5f5f5; padding: 20px; border-radius: 8px; margin: 20px 0; }} | |
| .finding {{ border: 1px solid #ddd; padding: 15px; margin: 10px 0; border-radius: 5px; }} | |
| .critical {{ border-left: 5px solid #dc3545; }} | |
| .high {{ border-left: 5px solid #fd7e14; }} | |
| .medium {{ border-left: 5px solid #ffc107; }} | |
| .low {{ border-left: 5px solid #28a745; }} | |
| .score {{ font-size: 1.2em; font-weight: bold; color: #dc3545; }} | |
| .scores span {{ margin-right: 15px; background: #e9ecef; padding: 3px 8px; border-radius: 3px; }} | |
| table {{ border-collapse: collapse; width: 300px; }} | |
| th, td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }} | |
| th {{ background: #f5f5f5; }} | |
| </style> | |
| </head> | |
| <body> | |
| <h1>{self.report_title}</h1> | |
| <p><strong>Organization:</strong> {self.organization}</p> | |
| <p><strong>Date:</strong> {self.report_date.strftime("%Y-%m-%d %H:%M")}</p> | |
| <div class="summary"> | |
| <h2>Executive Summary</h2> | |
| <table> | |
| <tr><th>Severity</th><th>Count</th></tr> | |
| <tr><td>Critical</td><td>{summary.critical_count}</td></tr> | |
| <tr><td>High</td><td>{summary.high_count}</td></tr> | |
| <tr><td>Medium</td><td>{summary.medium_count}</td></tr> | |
| <tr><td>Low</td><td>{summary.low_count}</td></tr> | |
| </table> | |
| <p><strong>Average Risk Score:</strong> {summary.average_risk_score:.1f}/10</p> | |
| <p><strong>Due within 24h:</strong> {summary.findings_due_24h}</p> | |
| </div> | |
| <h2>Prioritized Findings</h2> | |
| {"".join(findings_html)} | |
| </body> | |
| </html> | |
| """.strip() | |
| def to_csv(self) -> str: | |
| """Exportiert Findings als CSV.""" | |
| lines = ["Finding ID,CVE,Title,Target,Severity,Risk Score,CVSS,EPSS %,Business Impact,SLA,Status"] | |
| for f in self.findings: | |
| lines.append( | |
| f'"{f.finding_id}","{f.cve_id or ""}","{f.title}","{f.target}",' | |
| f'"{f.severity}",{f.final_risk_score:.2f},{f.cvss_score:.1f},' | |
| f'{f.epss_score * 100:.1f},{f.business_impact:.2f},"{f.sla_target}","{f.status}"' | |
| ) | |
| return "\n".join(lines) | |
| def generate_quick_report(findings: List[Dict[str, Any]], title: str = "Risk Report", organization: str = "") -> RiskReport: | |
| """ | |
| Generiert schnell einen Risk Report aus einer Liste von Findings. | |
| Args: | |
| findings: Liste von Finding-Dictionaries | |
| title: Report-Titel | |
| organization: Organisationsname | |
| Returns: | |
| RiskReport | |
| """ | |
| report = RiskReport(report_title=title, organization=organization) | |
| scorer = MultiFactorRiskScorer() | |
| for finding_data in findings: | |
| # Berechne Multi-Faktor Score | |
| risk_score = scorer.calculate( | |
| finding_title=finding_data.get("title", "Unknown"), | |
| target=finding_data.get("target", "Unknown"), | |
| cve_id=finding_data.get("cve_id"), | |
| cvss_score=finding_data.get("cvss"), | |
| epss_score=finding_data.get("epss"), | |
| business_factors=finding_data.get("business_factors"), | |
| validation_status=finding_data.get("validation_status", "unknown"), | |
| ) | |
| # Füge zum Report hinzu | |
| report.add_finding_from_calculation( | |
| risk_score=risk_score, description=finding_data.get("description", ""), raw_evidence=finding_data.get("evidence") | |
| ) | |
| return report | |
Xet Storage Details
- Size:
- 20.6 kB
- Xet hash:
- 4db7dd5b5a9e2fa29bb926928c2ea8e29cc460e5723d908b3a0311d1d506b7a5
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.