Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /modules /report_generator.py
| """ | |
| Report Generator mit Multi-Format Export Support | |
| Unterstützte Formate: | |
| - JSON: Vollständige Scan-Ergebnisse | |
| - PDF: Professioneller Report mit Logo, Executive Summary (reportlab) | |
| - HTML: Interaktiver Report für Browser (jinja2) | |
| - XML: Für Integration mit anderen Tools | |
| Usage: | |
| from modules.report_generator import ReportExportGenerator | |
| generator = ReportExportGenerator() | |
| # JSON Export | |
| json_data = generator.export_json(scan_id=123, findings=[...]) | |
| # PDF Export | |
| pdf_bytes = generator.export_pdf(scan_id=123, scan={...}, findings=[...]) | |
| # HTML Export | |
| html_content = generator.export_html(scan_id=123, scan={...}, findings=[...]) | |
| # XML Export | |
| xml_content = generator.export_xml(scan_id=123, scan={...}, findings=[...]) | |
| """ | |
| import io | |
| import json | |
| import os | |
| import xml.etree.ElementTree as ET | |
| from datetime import datetime | |
| from pathlib import Path | |
| from typing import Any, Dict, List, Optional, Tuple, Union | |
| from jinja2 import Environment, FileSystemLoader | |
| class ReportExportGenerator: | |
| """ | |
| Erweiterter Report Generator für Multi-Format Export. | |
| Generiert professionelle Pentest Reports in: | |
| - JSON: Maschinenlesbare Daten | |
| - PDF: Professionelle Dokumente mit Deckblatt | |
| - HTML: Interaktive Web-Reports | |
| - XML: Für Tool-Integrationen | |
| """ | |
| def __init__( | |
| self, | |
| template_dir: str = "templates/reports", | |
| logo_path: Optional[str] = None, | |
| company_name: str = "Zen-AI Pentest", | |
| ): | |
| """ | |
| Initialize Report Export Generator. | |
| Args: | |
| template_dir: Verzeichnis mit Jinja2 Templates | |
| logo_path: Pfad zum Logo für PDF Reports | |
| company_name: Firmenname für Reports | |
| """ | |
| self.template_dir = Path(template_dir) | |
| self.logo_path = logo_path or "assets/logo.png" | |
| self.company_name = company_name | |
| # Jinja2 Environment für HTML Templates | |
| self.env = Environment( | |
| loader=FileSystemLoader(self.template_dir), | |
| autoescape=True, | |
| ) | |
| # Sicherstellen dass Output-Verzeichnis existiert | |
| self.output_dir = Path("reports/exports") | |
| self.output_dir.mkdir(parents=True, exist_ok=True) | |
| def count_severities(self, findings: List[Dict]) -> Dict[str, int]: | |
| """Zählt Findings nach Severity.""" | |
| counts = {"critical": 0, "high": 0, "medium": 0, "low": 0, "info": 0} | |
| for finding in findings: | |
| sev = finding.get("severity", "info").lower() | |
| if sev in counts: | |
| counts[sev] += 1 | |
| return counts | |
| def calculate_risk_score(self, findings: List[Dict]) -> Tuple[float, str]: | |
| """ | |
| Berechnet Gesamt-Risiko-Score. | |
| Returns: | |
| Tuple of (score, risk_level) | |
| """ | |
| if not findings: | |
| return 0.0, "LOW" | |
| severity_weights = { | |
| "critical": 10, | |
| "high": 7, | |
| "medium": 4, | |
| "low": 1, | |
| "info": 0, | |
| } | |
| total_score = 0 | |
| for finding in findings: | |
| sev = finding.get("severity", "info").lower() | |
| total_score += severity_weights.get(sev, 0) | |
| # Normalize to 0-10 scale | |
| max_possible = len(findings) * 10 | |
| normalized_score = (total_score / max_possible * 10) if max_possible > 0 else 0 | |
| if normalized_score >= 7: | |
| return round(normalized_score, 1), "CRITICAL" | |
| elif normalized_score >= 5: | |
| return round(normalized_score, 1), "HIGH" | |
| elif normalized_score >= 2: | |
| return round(normalized_score, 1), "MEDIUM" | |
| else: | |
| return round(normalized_score, 1), "LOW" | |
| def get_cvss_stats(self, findings: List[Dict]) -> Dict[str, Any]: | |
| """Berechnet CVSS Statistiken.""" | |
| scores = [] | |
| for finding in findings: | |
| cvss = finding.get("cvss_score") | |
| if cvss is not None: | |
| try: | |
| scores.append(float(cvss)) | |
| except (ValueError, TypeError): | |
| pass | |
| if not scores: | |
| return {"avg": None, "max": None, "min": None} | |
| return { | |
| "avg": round(sum(scores) / len(scores), 1), | |
| "max": max(scores), | |
| "min": min(scores), | |
| } | |
| def generate_executive_summary( | |
| self, | |
| scan: Dict, | |
| findings: List[Dict], | |
| counts: Dict[str, int], | |
| ) -> str: | |
| """Generiert Executive Summary Text.""" | |
| risk_score, risk_level = self.calculate_risk_score(findings) | |
| summaries = { | |
| "CRITICAL": ( | |
| f"Der Penetrationstest hat KRITISCHE Sicherheitslücken aufgedeckt, " | |
| f"die sofortige Aufmerksamkeit erfordern. Insgesamt wurden {len(findings)} " | |
| f"Schwachstellen identifiziert, darunter {counts['critical']} kritische und " | |
| f"{counts['high']} Hochrisiko-Findings. " | |
| f"EMPFEHLUNG: Sofortige Remediation aller kritischen Findings." | |
| ), | |
| "HIGH": ( | |
| f"Der Penetrationstest hat HOCHRISIKO-Sicherheitslücken identifiziert. " | |
| f"Es wurden {len(findings)} Findings gefunden, darunter {counts['high']} " | |
| f"mit hohem Risiko. EMPFEHLUNG: Behebung innerhalb von 30 Tagen." | |
| ), | |
| "MEDIUM": ( | |
| f"Der Penetrationstest hat mäßige Sicherheitsrisiken aufgedeckt. " | |
| f"{len(findings)} Findings wurden identifiziert. " | |
| f"EMPFEHLUNG: Systematische Behebung innerhalb von 90 Tagen." | |
| ), | |
| "LOW": ( | |
| f"Der Penetrationstest zeigt ein insgesamt niedriges Risiko. " | |
| f"{len(findings)} kleinere Findings wurden identifiziert. " | |
| f"Die Sicherheitslage ist generell gut." | |
| ), | |
| } | |
| return summaries.get(risk_level, summaries["LOW"]) | |
| def export_json( | |
| self, | |
| scan_id: Union[int, str], | |
| scan: Dict[str, Any], | |
| findings: List[Dict[str, Any]], | |
| include_metadata: bool = True, | |
| ) -> Dict[str, Any]: | |
| """Generiert JSON Report mit vollständigen Scan-Ergebnissen.""" | |
| counts = self.count_severities(findings) | |
| cvss_stats = self.get_cvss_stats(findings) | |
| risk_score, risk_level = self.calculate_risk_score(findings) | |
| report = { | |
| "report_metadata": { | |
| "title": f"Penetration Test Report - {scan.get('name', 'Unknown')}", | |
| "generated_at": datetime.now().isoformat(), | |
| "generated_by": self.company_name, | |
| "version": "2.0.0", | |
| "format": "json", | |
| }, | |
| "scan": { | |
| "id": scan_id, | |
| "name": scan.get("name"), | |
| "target": scan.get("target"), | |
| "scan_type": scan.get("scan_type"), | |
| "status": scan.get("status"), | |
| "created_at": scan.get("created_at"), | |
| "started_at": scan.get("started_at"), | |
| "completed_at": scan.get("completed_at"), | |
| }, | |
| "executive_summary": { | |
| "total_findings": len(findings), | |
| "severity_counts": counts, | |
| "risk_score": risk_score, | |
| "risk_level": risk_level, | |
| "cvss_statistics": cvss_stats, | |
| "summary_text": self.generate_executive_summary(scan, findings, counts), | |
| }, | |
| "findings": findings, | |
| } | |
| if include_metadata: | |
| report["export_info"] = { | |
| "export_format": "JSON", | |
| "export_timestamp": datetime.now().isoformat(), | |
| "schema_version": "1.0", | |
| } | |
| return report | |
| def export_json_string( | |
| self, | |
| scan_id: Union[int, str], | |
| scan: Dict[str, Any], | |
| findings: List[Dict[str, Any]], | |
| indent: int = 2, | |
| ) -> str: | |
| """Generiert JSON Report als String.""" | |
| report = self.export_json(scan_id, scan, findings) | |
| return json.dumps(report, indent=indent, default=str, ensure_ascii=False) | |
| def export_xml( | |
| self, | |
| scan_id: Union[int, str], | |
| scan: Dict[str, Any], | |
| findings: List[Dict[str, Any]], | |
| ) -> str: | |
| """Generiert XML Report für Tool-Integrationen.""" | |
| counts = self.count_severities(findings) | |
| cvss_stats = self.get_cvss_stats(findings) | |
| risk_score, risk_level = self.calculate_risk_score(findings) | |
| # Root Element | |
| root = ET.Element("penetration_test_report") | |
| root.set("version", "2.0") | |
| root.set("generated", datetime.now().isoformat()) | |
| # Metadata | |
| metadata = ET.SubElement(root, "metadata") | |
| ET.SubElement(metadata, "title").text = f"Pentest Report - {scan.get('name', 'Unknown')}" | |
| ET.SubElement(metadata, "generated_at").text = datetime.now().isoformat() | |
| ET.SubElement(metadata, "generator").text = self.company_name | |
| # Scan Info | |
| scan_elem = ET.SubElement(root, "scan") | |
| ET.SubElement(scan_elem, "id").text = str(scan_id) | |
| ET.SubElement(scan_elem, "name").text = scan.get("name", "") | |
| ET.SubElement(scan_elem, "target").text = scan.get("target", "") | |
| ET.SubElement(scan_elem, "type").text = scan.get("scan_type", "") | |
| ET.SubElement(scan_elem, "status").text = scan.get("status", "") | |
| # Executive Summary | |
| summary = ET.SubElement(root, "executive_summary") | |
| ET.SubElement(summary, "total_findings").text = str(len(findings)) | |
| ET.SubElement(summary, "risk_score").text = str(risk_score) | |
| ET.SubElement(summary, "risk_level").text = risk_level | |
| # Severity Counts | |
| severities = ET.SubElement(summary, "severity_counts") | |
| for sev, count in counts.items(): | |
| ET.SubElement(severities, sev).text = str(count) | |
| # CVSS Stats | |
| if cvss_stats["avg"] is not None: | |
| cvss_elem = ET.SubElement(summary, "cvss_statistics") | |
| ET.SubElement(cvss_elem, "average").text = str(cvss_stats["avg"]) | |
| ET.SubElement(cvss_elem, "maximum").text = str(cvss_stats["max"]) | |
| ET.SubElement(cvss_elem, "minimum").text = str(cvss_stats["min"]) | |
| # Findings | |
| findings_elem = ET.SubElement(root, "findings") | |
| findings_elem.set("count", str(len(findings))) | |
| for i, finding in enumerate(findings, 1): | |
| finding_elem = ET.SubElement(findings_elem, "finding") | |
| finding_elem.set("id", str(i)) | |
| ET.SubElement(finding_elem, "title").text = finding.get("title", "") | |
| ET.SubElement(finding_elem, "severity").text = finding.get("severity", "") | |
| if finding.get("cve_id"): | |
| ET.SubElement(finding_elem, "cve_id").text = finding.get("cve_id") | |
| if finding.get("cvss_score"): | |
| ET.SubElement(finding_elem, "cvss_score").text = str(finding.get("cvss_score")) | |
| if finding.get("epss_score"): | |
| ET.SubElement(finding_elem, "epss_score").text = str(finding.get("epss_score")) | |
| ET.SubElement(finding_elem, "description").text = finding.get("description", "") | |
| if finding.get("remediation"): | |
| ET.SubElement(finding_elem, "remediation").text = finding.get("remediation") | |
| if finding.get("evidence"): | |
| evidence_elem = ET.SubElement(finding_elem, "evidence") | |
| evidence_elem.text = finding.get("evidence") | |
| if finding.get("target"): | |
| ET.SubElement(finding_elem, "target").text = finding.get("target") | |
| if finding.get("tool"): | |
| ET.SubElement(finding_elem, "tool").text = finding.get("tool") | |
| # Convert to string | |
| xml_str = ET.tostring(root, encoding="unicode") | |
| formatted_xml = f'<?xml version="1.0" encoding="UTF-8"?>\n{xml_str}' | |
| return formatted_xml | |
| def export_html( | |
| self, | |
| scan_id: Union[int, str], | |
| scan: Dict[str, Any], | |
| findings: List[Dict[str, Any]], | |
| template: str = "default", | |
| interactive: bool = True, | |
| ) -> str: | |
| """Generiert HTML Report.""" | |
| counts = self.count_severities(findings) | |
| cvss_stats = self.get_cvss_stats(findings) | |
| risk_score, risk_level = self.calculate_risk_score(findings) | |
| template_file = f"{template}.html" | |
| try: | |
| template_obj = self.env.get_template(template_file) | |
| html_content = template_obj.render( | |
| scan=scan, | |
| findings=findings, | |
| counts=counts, | |
| cvss_stats=cvss_stats, | |
| risk_score=risk_score, | |
| risk_level=risk_level, | |
| executive_summary=self.generate_executive_summary(scan, findings, counts), | |
| generated_at=datetime.now(), | |
| company_name=self.company_name, | |
| interactive=interactive, | |
| ) | |
| return html_content | |
| except Exception: | |
| return self._generate_html_builtin(scan_id, scan, findings, counts, cvss_stats, risk_score, risk_level) | |
| def _generate_html_builtin( | |
| self, | |
| scan_id: Union[int, str], | |
| scan: Dict[str, Any], | |
| findings: List[Dict[str, Any]], | |
| counts: Dict[str, int], | |
| cvss_stats: Dict[str, Any], | |
| risk_score: float, | |
| risk_level: str, | |
| ) -> str: | |
| """Generiert eingebautes HTML Template.""" | |
| severity_colors = { | |
| "critical": "#dc2626", | |
| "high": "#ea580c", | |
| "medium": "#ca8a04", | |
| "low": "#65a30d", | |
| "info": "#0891b2", | |
| } | |
| # Generate findings HTML | |
| findings_html = [] | |
| for finding in findings: | |
| sev = finding.get("severity", "info").lower() | |
| color = severity_colors.get(sev, "#6b7280") | |
| cve_html = f"<p><strong>CVE:</strong> {finding.get('cve_id')}</p>" if finding.get("cve_id") else "" | |
| cvss_html = f"<p><strong>CVSS:</strong> {finding.get('cvss_score')}</p>" if finding.get("cvss_score") else "" | |
| epss_html = f"<p><strong>EPSS:</strong> {finding.get('epss_score')}</p>" if finding.get("epss_score") else "" | |
| evidence_html = ( | |
| f"<div class='evidence'><h4>Evidence</h4><pre>{finding.get('evidence')}</pre></div>" | |
| if finding.get("evidence") | |
| else "" | |
| ) | |
| remediation_html = ( | |
| f"<div class='remediation'><h4>Remediation</h4><p>{finding.get('remediation')}</p></div>" | |
| if finding.get("remediation") | |
| else "" | |
| ) | |
| findings_html.append(f""" | |
| <div class="finding {sev}" id="finding-{finding.get("id", "0")}"> | |
| <div class="finding-header"> | |
| <h3>{finding.get("title", "Untitled")}</h3> | |
| <span class="severity-badge" style="background-color: {color}">{sev.upper()}</span> | |
| </div> | |
| <div class="finding-body"> | |
| <p>{finding.get("description", "")}</p> | |
| {cve_html} | |
| {cvss_html} | |
| {epss_html} | |
| {evidence_html} | |
| {remediation_html} | |
| </div> | |
| </div> | |
| """) | |
| findings_html_str = "\n".join(findings_html) | |
| return f"""<!DOCTYPE html> | |
| <html lang="de"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>Penetration Test Report - {scan.get("name", "Unknown")}</title> | |
| <style> | |
| * {{ box-sizing: border-box; margin: 0; padding: 0; }} | |
| body {{ | |
| font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; | |
| line-height: 1.6; | |
| color: #333; | |
| background: #f5f5f5; | |
| }} | |
| .container {{ max-width: 1200px; margin: 0 auto; padding: 20px; }} | |
| .header {{ | |
| background: linear-gradient(135deg, #1e3a5f 0%, #2d5a87 100%); | |
| color: white; | |
| padding: 40px; | |
| border-radius: 10px; | |
| margin-bottom: 30px; | |
| }} | |
| .header h1 {{ font-size: 2.5em; margin-bottom: 10px; }} | |
| .header h2 {{ font-weight: normal; opacity: 0.9; }} | |
| .meta-grid {{ | |
| display: grid; | |
| grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); | |
| gap: 20px; | |
| margin-bottom: 30px; | |
| }} | |
| .meta-card {{ | |
| background: white; | |
| padding: 20px; | |
| border-radius: 8px; | |
| box-shadow: 0 2px 4px rgba(0,0,0,0.1); | |
| }} | |
| .summary {{ | |
| background: white; | |
| padding: 30px; | |
| border-radius: 8px; | |
| box-shadow: 0 2px 4px rgba(0,0,0,0.1); | |
| margin-bottom: 30px; | |
| }} | |
| .severity-grid {{ | |
| display: grid; | |
| grid-template-columns: repeat(5, 1fr); | |
| gap: 15px; | |
| margin-top: 20px; | |
| }} | |
| .severity-box {{ | |
| text-align: center; | |
| padding: 20px; | |
| border-radius: 8px; | |
| color: white; | |
| }} | |
| .severity-box.critical {{ background: #dc2626; }} | |
| .severity-box.high {{ background: #ea580c; }} | |
| .severity-box.medium {{ background: #ca8a04; }} | |
| .severity-box.low {{ background: #65a30d; }} | |
| .severity-box.info {{ background: #0891b2; }} | |
| .severity-count {{ font-size: 2.5em; font-weight: bold; }} | |
| .findings {{ | |
| background: white; | |
| padding: 30px; | |
| border-radius: 8px; | |
| box-shadow: 0 2px 4px rgba(0,0,0,0.1); | |
| }} | |
| .finding {{ | |
| border-left: 5px solid #ddd; | |
| padding: 20px; | |
| margin-bottom: 20px; | |
| background: #f9fafb; | |
| border-radius: 0 8px 8px 0; | |
| }} | |
| .finding.critical {{ border-left-color: #dc2626; }} | |
| .finding.high {{ border-left-color: #ea580c; }} | |
| .finding.medium {{ border-left-color: #ca8a04; }} | |
| .finding.low {{ border-left-color: #65a30d; }} | |
| .finding-header {{ | |
| display: flex; | |
| justify-content: space-between; | |
| align-items: center; | |
| margin-bottom: 15px; | |
| }} | |
| .severity-badge {{ | |
| padding: 5px 15px; | |
| border-radius: 20px; | |
| color: white; | |
| font-size: 0.85em; | |
| font-weight: 600; | |
| text-transform: uppercase; | |
| }} | |
| .evidence pre {{ | |
| background: #1f2937; | |
| color: #10b981; | |
| padding: 15px; | |
| border-radius: 5px; | |
| overflow-x: auto; | |
| font-family: 'Courier New', monospace; | |
| }} | |
| .filter-bar {{ | |
| display: flex; | |
| gap: 10px; | |
| margin-bottom: 20px; | |
| flex-wrap: wrap; | |
| }} | |
| .filter-btn {{ | |
| padding: 8px 16px; | |
| border: 1px solid #ddd; | |
| background: white; | |
| border-radius: 5px; | |
| cursor: pointer; | |
| }} | |
| .filter-btn:hover, .filter-btn.active {{ | |
| background: #1e3a5f; | |
| color: white; | |
| }} | |
| </style> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| <div class="header"> | |
| <h1>Penetration Test Report</h1> | |
| <h2>{scan.get("name", "Unknown")}</h2> | |
| </div> | |
| <div class="meta-grid"> | |
| <div class="meta-card"> | |
| <h4>Target</h4> | |
| <p>{scan.get("target", "N/A")}</p> | |
| </div> | |
| <div class="meta-card"> | |
| <h4>Scan Type</h4> | |
| <p>{scan.get("scan_type", "N/A")}</p> | |
| </div> | |
| <div class="meta-card"> | |
| <h4>Risk Level</h4> | |
| <p style="color: {severity_colors.get(risk_level.lower(), "#333")}">{risk_level}</p> | |
| </div> | |
| <div class="meta-card"> | |
| <h4>Generated</h4> | |
| <p>{datetime.now().strftime("%Y-%m-%d %H:%M")}</p> | |
| </div> | |
| </div> | |
| <div class="summary"> | |
| <h3>Executive Summary</h3> | |
| <p>{self.generate_executive_summary(scan, findings, counts)}</p> | |
| <div class="severity-grid"> | |
| <div class="severity-box critical"> | |
| <div class="severity-count">{counts["critical"]}</div> | |
| <div class="severity-label">Critical</div> | |
| </div> | |
| <div class="severity-box high"> | |
| <div class="severity-count">{counts["high"]}</div> | |
| <div class="severity-label">High</div> | |
| </div> | |
| <div class="severity-box medium"> | |
| <div class="severity-count">{counts["medium"]}</div> | |
| <div class="severity-label">Medium</div> | |
| </div> | |
| <div class="severity-box low"> | |
| <div class="severity-count">{counts["low"]}</div> | |
| <div class="severity-label">Low</div> | |
| </div> | |
| <div class="severity-box info"> | |
| <div class="severity-count">{counts["info"]}</div> | |
| <div class="severity-label">Info</div> | |
| </div> | |
| </div> | |
| </div> | |
| <div class="findings"> | |
| <h3>Detailed Findings ({len(findings)})</h3> | |
| <div class="filter-bar"> | |
| <button class="filter-btn active" onclick="filterFindings('all')">All</button> | |
| <button class="filter-btn" onclick="filterFindings('critical')">Critical</button> | |
| <button class="filter-btn" onclick="filterFindings('high')">High</button> | |
| <button class="filter-btn" onclick="filterFindings('medium')">Medium</button> | |
| <button class="filter-btn" onclick="filterFindings('low')">Low</button> | |
| </div> | |
| {findings_html_str} | |
| </div> | |
| </div> | |
| <script> | |
| function filterFindings(severity) {{ | |
| const findings = document.querySelectorAll('.finding'); | |
| const buttons = document.querySelectorAll('.filter-btn'); | |
| buttons.forEach(btn => btn.classList.remove('active')); | |
| event.target.classList.add('active'); | |
| findings.forEach(f => {{ | |
| f.style.display = (severity === 'all' || f.classList.contains(severity)) ? 'block' : 'none'; | |
| }}); | |
| }} | |
| </script> | |
| </body> | |
| </html>""" | |
| def export_pdf( | |
| self, | |
| scan_id: Union[int, str], | |
| scan: Dict[str, Any], | |
| findings: List[Dict[str, Any]], | |
| include_logo: bool = True, | |
| ) -> bytes: | |
| """ | |
| Generiert professionellen PDF Report mit reportlab. | |
| Returns: | |
| PDF als Bytes | |
| """ | |
| try: | |
| from reportlab.lib import colors | |
| from reportlab.lib.enums import TA_CENTER, TA_JUSTIFY | |
| from reportlab.lib.pagesizes import A4 | |
| from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet | |
| from reportlab.lib.units import cm | |
| from reportlab.platypus import Image, PageBreak, Paragraph, SimpleDocTemplate, Spacer, Table, TableStyle | |
| except ImportError: | |
| raise ImportError("reportlab ist erforderlich für PDF Export. Installieren mit: pip install reportlab") | |
| counts = self.count_severities(findings) | |
| cvss_stats = self.get_cvss_stats(findings) | |
| risk_score, risk_level = self.calculate_risk_score(findings) | |
| # Create PDF in memory | |
| buffer = io.BytesIO() | |
| doc = SimpleDocTemplate( | |
| buffer, | |
| pagesize=A4, | |
| rightMargin=2 * cm, | |
| leftMargin=2 * cm, | |
| topMargin=2 * cm, | |
| bottomMargin=2 * cm, | |
| ) | |
| # Styles | |
| styles = getSampleStyleSheet() | |
| title_style = ParagraphStyle( | |
| "CustomTitle", | |
| parent=styles["Heading1"], | |
| fontSize=24, | |
| textColor=colors.HexColor("#1e3a5f"), | |
| spaceAfter=30, | |
| alignment=TA_CENTER, | |
| ) | |
| heading1_style = ParagraphStyle( | |
| "CustomH1", | |
| parent=styles["Heading1"], | |
| fontSize=18, | |
| textColor=colors.HexColor("#1e3a5f"), | |
| spaceAfter=12, | |
| spaceBefore=12, | |
| ) | |
| heading2_style = ParagraphStyle( | |
| "CustomH2", | |
| parent=styles["Heading2"], | |
| fontSize=14, | |
| textColor=colors.HexColor("#2d5a87"), | |
| spaceAfter=10, | |
| spaceBefore=10, | |
| ) | |
| normal_style = ParagraphStyle( | |
| "CustomNormal", | |
| parent=styles["Normal"], | |
| fontSize=10, | |
| leading=14, | |
| alignment=TA_JUSTIFY, | |
| ) | |
| story = [] | |
| # Cover Page | |
| story.append(Spacer(1, 3 * cm)) | |
| # Logo | |
| if include_logo and os.path.exists(self.logo_path): | |
| try: | |
| img = Image(self.logo_path, width=5 * cm, height=3 * cm) | |
| story.append(img) | |
| story.append(Spacer(1, 1 * cm)) | |
| except Exception: | |
| pass | |
| # Title | |
| story.append(Paragraph("Penetration Test Report", title_style)) | |
| story.append(Spacer(1, 0.5 * cm)) | |
| story.append(Paragraph(f"<b>{scan.get('name', 'Unknown Scan')}</b>", heading1_style)) | |
| story.append(Spacer(1, 2 * cm)) | |
| # Cover metadata | |
| cover_data = [ | |
| ["Target:", scan.get("target", "N/A")], | |
| ["Scan Type:", scan.get("scan_type", "N/A")], | |
| ["Report Date:", datetime.now().strftime("%Y-%m-%d")], | |
| ["Risk Level:", f"<font color='{self._get_risk_color(risk_level)}'>{risk_level}</font>"], | |
| ["Generated by:", self.company_name], | |
| ] | |
| cover_table = Table(cover_data, colWidths=[4 * cm, 10 * cm]) | |
| cover_table.setStyle( | |
| TableStyle( | |
| [ | |
| ("BACKGROUND", (0, 0), (0, -1), colors.HexColor("#f3f4f6")), | |
| ("FONTNAME", (0, 0), (0, -1), "Helvetica-Bold"), | |
| ("GRID", (0, 0), (-1, -1), 0.5, colors.grey), | |
| ("VALIGN", (0, 0), (-1, -1), "MIDDLE"), | |
| ("LEFTPADDING", (0, 0), (-1, -1), 10), | |
| ("TOPPADDING", (0, 0), (-1, -1), 8), | |
| ("BOTTOMPADDING", (0, 0), (-1, -1), 8), | |
| ] | |
| ) | |
| ) | |
| story.append(cover_table) | |
| story.append(PageBreak()) | |
| # Executive Summary | |
| story.append(Paragraph("Executive Summary", heading1_style)) | |
| story.append(Spacer(1, 0.3 * cm)) | |
| summary_text = self.generate_executive_summary(scan, findings, counts) | |
| story.append(Paragraph(summary_text.replace("\n", "<br/>"), normal_style)) | |
| story.append(Spacer(1, 0.5 * cm)) | |
| # Statistics Table | |
| story.append(Paragraph("Findings Summary", heading2_style)) | |
| stats_data = [ | |
| ["Severity", "Count", "Status"], | |
| ["Critical", str(counts["critical"]), self._get_severity_status(counts["critical"], "critical")], | |
| ["High", str(counts["high"]), self._get_severity_status(counts["high"], "high")], | |
| ["Medium", str(counts["medium"]), self._get_severity_status(counts["medium"], "medium")], | |
| ["Low", str(counts["low"]), self._get_severity_status(counts["low"], "low")], | |
| ["Info", str(counts["info"]), "Informational"], | |
| ["", "", ""], | |
| ["Total", str(len(findings)), ""], | |
| ] | |
| if cvss_stats["avg"] is not None: | |
| stats_data.append(["Avg CVSS", str(cvss_stats["avg"]), ""]) | |
| stats_data.append(["Max CVSS", str(cvss_stats["max"]), ""]) | |
| stats_table = Table(stats_data, colWidths=[4 * cm, 3 * cm, 7 * cm]) | |
| stats_table.setStyle( | |
| TableStyle( | |
| [ | |
| ("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#1e3a5f")), | |
| ("TEXTCOLOR", (0, 0), (-1, 0), colors.white), | |
| ("ALIGN", (0, 0), (-1, -1), "CENTER"), | |
| ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"), | |
| ("BOTTOMPADDING", (0, 0), (-1, 0), 12), | |
| ("BACKGROUND", (0, 1), (-1, -1), colors.HexColor("#f9fafb")), | |
| ("GRID", (0, 0), (-1, -1), 0.5, colors.grey), | |
| ("FONTNAME", (0, -1), (1, -1), "Helvetica-Bold"), | |
| ("BACKGROUND", (0, -1), (1, -1), colors.HexColor("#e5e7eb")), | |
| ] | |
| ) | |
| ) | |
| story.append(stats_table) | |
| story.append(Spacer(1, 0.5 * cm)) | |
| # Detailed Findings | |
| story.append(PageBreak()) | |
| story.append(Paragraph(f"Detailed Findings ({len(findings)})", heading1_style)) | |
| story.append(Spacer(1, 0.3 * cm)) | |
| severity_colors_pdf = { | |
| "critical": colors.HexColor("#fee2e2"), | |
| "high": colors.HexColor("#ffedd5"), | |
| "medium": colors.HexColor("#fef3c7"), | |
| "low": colors.HexColor("#ecfccb"), | |
| "info": colors.HexColor("#cffafe"), | |
| } | |
| for i, finding in enumerate(findings, 1): | |
| sev = finding.get("severity", "info").lower() | |
| bg_color = severity_colors_pdf.get(sev, colors.white) | |
| # Finding Header | |
| story.append(Paragraph(f"{i}. {finding.get('title', 'Untitled')}", heading2_style)) | |
| # Finding metadata | |
| finding_meta = [ | |
| ["Severity:", sev.upper()], | |
| ["Target:", finding.get("target", scan.get("target", "N/A"))], | |
| ] | |
| if finding.get("cve_id"): | |
| finding_meta.append(["CVE ID:", finding.get("cve_id")]) | |
| if finding.get("cvss_score"): | |
| finding_meta.append(["CVSS Score:", str(finding.get("cvss_score"))]) | |
| if finding.get("epss_score"): | |
| finding_meta.append(["EPSS Score:", str(finding.get("epss_score"))]) | |
| if finding.get("tool"): | |
| finding_meta.append(["Tool:", finding.get("tool")]) | |
| meta_table = Table(finding_meta, colWidths=[3 * cm, 11 * cm]) | |
| meta_table.setStyle( | |
| TableStyle( | |
| [ | |
| ("BACKGROUND", (0, 0), (0, -1), colors.HexColor("#f3f4f6")), | |
| ("BACKGROUND", (1, 0), (1, -1), bg_color), | |
| ("FONTNAME", (0, 0), (0, -1), "Helvetica-Bold"), | |
| ("GRID", (0, 0), (-1, -1), 0.5, colors.grey), | |
| ("LEFTPADDING", (0, 0), (-1, -1), 8), | |
| ("TOPPADDING", (0, 0), (-1, -1), 6), | |
| ("BOTTOMPADDING", (0, 0), (-1, -1), 6), | |
| ] | |
| ) | |
| ) | |
| story.append(meta_table) | |
| story.append(Spacer(1, 0.2 * cm)) | |
| # Description | |
| story.append(Paragraph("<b>Description:</b>", normal_style)) | |
| story.append(Paragraph(finding.get("description", "No description."), normal_style)) | |
| story.append(Spacer(1, 0.2 * cm)) | |
| # Evidence | |
| if finding.get("evidence"): | |
| story.append(Paragraph("<b>Evidence:</b>", normal_style)) | |
| evidence_text = finding.get("evidence", "")[:1000] # Limit length | |
| story.append(Paragraph(f"<font face='Courier' size='8'>{evidence_text}</font>", normal_style)) | |
| story.append(Spacer(1, 0.2 * cm)) | |
| # Remediation | |
| if finding.get("remediation"): | |
| story.append(Paragraph("<b>Remediation:</b>", normal_style)) | |
| story.append(Paragraph(finding.get("remediation"), normal_style)) | |
| story.append(Spacer(1, 0.4 * cm)) | |
| if i % 2 == 0 and i < len(findings): | |
| story.append(PageBreak()) | |
| # Footer | |
| story.append(Spacer(1, 1 * cm)) | |
| story.append( | |
| Paragraph( | |
| f"<font size='8' color='grey'>Generated by {self.company_name} v2.0.0 | © 2026</font>", | |
| ParagraphStyle("Footer", alignment=TA_CENTER), | |
| ) | |
| ) | |
| # Build PDF | |
| doc.build(story) | |
| pdf_bytes = buffer.getvalue() | |
| buffer.close() | |
| return pdf_bytes | |
| def _get_risk_color(self, risk_level: str) -> str: | |
| """Returns hex color for risk level.""" | |
| colors = { | |
| "CRITICAL": "#dc2626", | |
| "HIGH": "#ea580c", | |
| "MEDIUM": "#ca8a04", | |
| "LOW": "#65a30d", | |
| } | |
| return colors.get(risk_level.upper(), "#6b7280") | |
| def _get_severity_status(self, count: int, severity: str) -> str: | |
| """Returns status text for severity count.""" | |
| if count == 0: | |
| return "None" | |
| if severity == "critical": | |
| return "Action Required" | |
| elif severity == "high": | |
| return "Action Required" | |
| elif severity == "medium": | |
| return "Review Recommended" | |
| else: | |
| return "Informational" | |
| def export_to_file( | |
| self, | |
| scan_id: Union[int, str], | |
| scan: Dict[str, Any], | |
| findings: List[Dict[str, Any]], | |
| format: str, | |
| output_path: Optional[str] = None, | |
| ) -> str: | |
| """ | |
| Exportiert Report in Datei. | |
| Args: | |
| scan_id: Scan ID | |
| scan: Scan Metadaten | |
| findings: Liste der Findings | |
| format: Export-Format (json, pdf, html, xml) | |
| output_path: Ausgabepfad (optional) | |
| Returns: | |
| Pfad zur erstellten Datei | |
| """ | |
| format = format.lower() | |
| if output_path is None: | |
| timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") | |
| output_path = str(self.output_dir / f"report_scan_{scan_id}_{timestamp}.{format}") | |
| if format == "json": | |
| report = self.export_json(scan_id, scan, findings) | |
| with open(output_path, "w", encoding="utf-8") as f: | |
| json.dump(report, f, indent=2, default=str, ensure_ascii=False) | |
| elif format == "xml": | |
| xml_content = self.export_xml(scan_id, scan, findings) | |
| with open(output_path, "w", encoding="utf-8") as f: | |
| f.write(xml_content) | |
| elif format == "html": | |
| html_content = self.export_html(scan_id, scan, findings) | |
| with open(output_path, "w", encoding="utf-8") as f: | |
| f.write(html_content) | |
| elif format == "pdf": | |
| pdf_bytes = self.export_pdf(scan_id, scan, findings) | |
| with open(output_path, "wb") as f: | |
| f.write(pdf_bytes) | |
| else: | |
| raise ValueError(f"Unsupported format: {format}") | |
| return output_path | |
| class ReportGenerator(ReportExportGenerator): | |
| """Legacy ReportGenerator für Abwärtskompatibilität.""" | |
| pass | |
| __all__ = ["ReportExportGenerator", "ReportGenerator"] | |
Xet Storage Details
- Size:
- 35.2 kB
- Xet hash:
- 003318826fb5e914e35dbb400847cbf93b14084b868b7e3c5d20f2f796df1b5f
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.