Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /risk_engine /example_usage.py
| """ | |
| Risk Engine Usage Examples | |
| Demonstrates how to use the complete Risk Scoring system with: | |
| - CVSS 3.1 Calculator | |
| - EPSS Integration | |
| - Business Impact Scoring | |
| - Combined Risk Formula | |
| """ | |
| import asyncio | |
| def example_1_basic_risk_calculation(): | |
| """Example 1: Basic risk calculation for a finding.""" | |
| print("=" * 60) | |
| print("Example 1: Basic Risk Calculation") | |
| print("=" * 60) | |
| from risk_engine.scorer import RiskScorer | |
| # Create risk scorer | |
| scorer = RiskScorer() | |
| # Define a finding | |
| finding = { | |
| "title": "SQL Injection in Login Form", | |
| "description": "Blind SQL injection vulnerability in the login form allows authentication bypass", | |
| "severity": "critical", | |
| "cve_id": "CVE-2023-12345", | |
| "cvss_score": 9.8, | |
| "cvss_vector": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", | |
| "tool": "SQLMap", | |
| "target": "https://example.com/login", | |
| "exploit_available": True, | |
| } | |
| # Define target context | |
| context = { | |
| "internet_facing": True, | |
| "network_exposure": "internet", | |
| "data_sensitivity": "pii", | |
| "compliance": ["GDPR", "PCI-DSS"], | |
| "asset_criticality": "critical", | |
| } | |
| # Calculate risk | |
| result = scorer.calculate(finding, context) | |
| # Display results | |
| print(f"\nFinding: {finding['title']}") | |
| print(f"Risk Score: {result.value:.2f}/10") | |
| print(f"Severity: {result.severity.name} ({result.severity.label})") | |
| print(f"SLA Target: {result.sla_target}") | |
| print("\nComponents:") | |
| print(f" CVSS Base: {result.components.cvss_base:.2f}") | |
| print(f" EPSS Score: {result.components.epss_score:.4f} ({result.components.epss_score * 100:.2f}%)") | |
| print(f" Business Impact: {result.components.business_impact:.3f}") | |
| print(f" Exploit Availability: {result.components.exploit_availability:.3f}") | |
| print("\nPrioritized Actions:") | |
| for action in result.prioritized_actions: | |
| print(f" - {action}") | |
| return result | |
| def example_2_cve_lookup(): | |
| """Example 2: Look up CVE information with CVSS + EPSS.""" | |
| print("\n" + "=" * 60) | |
| print("Example 2: CVE Information Lookup") | |
| print("=" * 60) | |
| from risk_engine.scorer import RiskScorer | |
| scorer = RiskScorer() | |
| # Look up famous CVEs | |
| cves = [ | |
| "CVE-2021-44228", # Log4j | |
| "CVE-2017-0144", # EternalBlue | |
| "CVE-2014-0160", # Heartbleed | |
| ] | |
| for cve_id in cves: | |
| print(f"\n{cve_id}:") | |
| cve_info = scorer.get_cve_info(cve_id) | |
| if cve_info: | |
| print(f" CVSS Score: {cve_info.cvss_score}") | |
| print(f" CVSS Vector: {cve_info.cvss_vector}") | |
| print(f" EPSS Score: {cve_info.epss_score:.4f}") | |
| if cve_info.epss_percentile: | |
| print(f" EPSS Percentile: {cve_info.epss_percentile:.4f}") | |
| print(f" Description: {cve_info.description[:100]}...") | |
| else: | |
| print(" Not found") | |
| def example_3_batch_prioritization(): | |
| """Example 3: Batch prioritize findings.""" | |
| print("\n" + "=" * 60) | |
| print("Example 3: Batch Finding Prioritization") | |
| print("=" * 60) | |
| from risk_engine.scorer import RiskScorer | |
| scorer = RiskScorer() | |
| # Multiple findings | |
| findings = [ | |
| { | |
| "title": "XSS in Comment Field", | |
| "description": "Stored XSS in user comments", | |
| "severity": "high", | |
| "cvss_score": 6.1, | |
| "cve_id": None, | |
| }, | |
| { | |
| "title": "Log4j RCE", | |
| "description": "Remote code execution via Log4j", | |
| "severity": "critical", | |
| "cvss_score": 10.0, | |
| "cve_id": "CVE-2021-44228", | |
| "exploit_available": True, | |
| }, | |
| { | |
| "title": "Information Disclosure", | |
| "description": "Server version exposed in headers", | |
| "severity": "low", | |
| "cvss_score": 5.3, | |
| "cve_id": None, | |
| }, | |
| { | |
| "title": "SQL Injection", | |
| "description": "SQLi in search function", | |
| "severity": "critical", | |
| "cvss_score": 9.1, | |
| "cve_id": "CVE-2023-11111", | |
| }, | |
| ] | |
| context = { | |
| "internet_facing": True, | |
| "data_sensitivity": "confidential", | |
| "compliance": ["GDPR"], | |
| "asset_criticality": "high", | |
| } | |
| # Prioritize | |
| prioritized = scorer.prioritize_findings(findings, context) | |
| print("\nPrioritized Findings (Highest Risk First):") | |
| print("-" * 60) | |
| for i, finding in enumerate(prioritized, 1): | |
| risk = finding.get("risk_score", {}) | |
| print(f"{i}. {finding['title']}") | |
| print(f" Risk Score: {risk.get('risk_score', 'N/A')}") | |
| print(f" Severity: {risk.get('severity', {}).get('level', 'N/A')}") | |
| print(f" SLA: {risk.get('severity', {}).get('sla', 'N/A')}") | |
| print() | |
| def example_4_cvss_calculation(): | |
| """Example 4: Calculate CVSS from metrics.""" | |
| print("\n" + "=" * 60) | |
| print("Example 4: CVSS Calculation from Metrics") | |
| print("=" * 60) | |
| from risk_engine.cvss_calculator import ExtendedCVSSCalculator | |
| calc = ExtendedCVSSCalculator() | |
| # Metrics for a vulnerability | |
| metrics = { | |
| "AV": "N", # Network | |
| "AC": "L", # Low complexity | |
| "PR": "N", # No privileges required | |
| "UI": "N", # No user interaction | |
| "S": "U", # Unchanged scope | |
| "C": "H", # High confidentiality impact | |
| "I": "H", # High integrity impact | |
| "A": "H", # High availability impact | |
| } | |
| # Calculate base score | |
| base_score = calc.calculate(metrics) | |
| vector = calc.get_vector_from_metrics(metrics) | |
| print(f"\nCVSS Base Score: {base_score}") | |
| print(f"Vector: {vector}") | |
| # Calculate with temporal | |
| temporal = { | |
| "E": "F", # Functional exploit | |
| "RL": "O", # Official fix | |
| "RC": "C", # Confirmed | |
| } | |
| extended = calc.calculate_extended( | |
| metrics=metrics, | |
| temporal=temporal, | |
| ) | |
| print("\nExtended Scores:") | |
| print(f" Base: {extended['base_score']}") | |
| print(f" Temporal: {extended['temporal_score']}") | |
| print(f" Environmental: {extended['environmental_score']}") | |
| def example_5_business_impact(): | |
| """Example 5: Calculate business impact.""" | |
| print("\n" + "=" * 60) | |
| print("Example 5: Business Impact Calculation") | |
| print("=" * 60) | |
| from risk_engine.business_impact import BusinessImpactCalculator | |
| calc = BusinessImpactCalculator() | |
| finding = { | |
| "title": "Data Breach Vulnerability", | |
| "description": "SQL injection allowing database access", | |
| "severity": "critical", | |
| } | |
| # High impact context | |
| high_context = { | |
| "internet_facing": True, | |
| "network_exposure": "internet", | |
| "data_sensitivity": "pii", | |
| "compliance": ["GDPR", "PCI-DSS"], | |
| "asset_criticality": "critical", | |
| } | |
| # Low impact context | |
| low_context = { | |
| "internet_facing": False, | |
| "network_exposure": "internal", | |
| "data_sensitivity": "public", | |
| "compliance": [], | |
| "asset_criticality": "low", | |
| } | |
| high_impact = calc.calculate(finding, high_context) | |
| low_impact = calc.calculate(finding, low_context) | |
| print("\nSame finding, different contexts:") | |
| print(f" Internet-facing + PII: {high_impact:.3f} (High Impact)") | |
| print(f" Internal + Public data: {low_impact:.3f} (Low Impact)") | |
| # Questions for context collection | |
| print("\nContext Collection Questions:") | |
| for q in calc.generate_context_questions(): | |
| print(f" - {q['question']}") | |
| def example_6_dashboard_stats(): | |
| """Example 6: Generate dashboard statistics.""" | |
| print("\n" + "=" * 60) | |
| print("Example 6: Dashboard Statistics") | |
| print("=" * 60) | |
| from risk_engine.scorer import RiskScorer | |
| scorer = RiskScorer() | |
| # Sample findings | |
| findings = [ | |
| {"title": "Critical RCE", "cvss_score": 9.8, "cve_id": "CVE-2021-44228"}, | |
| {"title": "High SQLi", "cvss_score": 8.5, "cve_id": None}, | |
| {"title": "Medium XSS", "cvss_score": 6.1, "cve_id": None}, | |
| {"title": "Low Info", "cvss_score": 3.2, "cve_id": None}, | |
| {"title": "Critical Auth Bypass", "cvss_score": 9.1, "cve_id": "CVE-2023-12345"}, | |
| ] | |
| stats = scorer.get_dashboard_stats(findings) | |
| print("\nDashboard Statistics:") | |
| print(f" Total Findings: {stats['total_findings']}") | |
| print(f" Average Risk Score: {stats['avg_risk_score']}") | |
| print(f" High Risk Count: {stats['high_risk_count']}") | |
| print(f" Critical Count: {stats['critical_count']}") | |
| print(f" Requires Immediate Action: {stats['requires_immediate_action']}") | |
| print("\nBy Severity:") | |
| for sev, count in stats["by_severity"].items(): | |
| print(f" {sev}: {count}") | |
| async def example_7_false_positive_detection(): | |
| """Example 7: False positive detection.""" | |
| print("\n" + "=" * 60) | |
| print("Example 7: False Positive Detection") | |
| print("=" * 60) | |
| from risk_engine.false_positive_engine import ( | |
| FalsePositiveEngine, | |
| Finding, | |
| VulnerabilityType, | |
| ) | |
| engine = FalsePositiveEngine(enable_llm_voting=False) | |
| # Suspected finding | |
| finding = Finding( | |
| id="finding-001", | |
| title="Potential SQL Injection", | |
| description="Possible SQL injection in search parameter", | |
| severity="high", | |
| vulnerability_type=VulnerabilityType.SQL_INJECTION, | |
| cve_ids=[], | |
| raw_evidence={"parameter": "search", "payload": "' OR '1'='1"}, | |
| ) | |
| result = await engine.validate_finding(finding) | |
| print(f"\nFinding: {finding.title}") | |
| print(f"Status: {finding.status.value}") | |
| print(f"False Positive: {result.is_false_positive}") | |
| print(f"Confidence: {result.confidence:.2f}") | |
| print(f"Risk Score: {result.risk_score:.3f}") | |
| print(f"Priority: {result.priority}") | |
| print(f"Reasoning: {result.reasoning}") | |
| print(f"\nValidation Methods: {', '.join(result.validation_methods)}") | |
| def example_8_api_usage(): | |
| """Example 8: API usage examples (documentation).""" | |
| print("\n" + "=" * 60) | |
| print("Example 8: API Endpoints") | |
| print("=" * 60) | |
| print(""" | |
| API Endpoints: | |
| 1. Calculate Risk Score: | |
| POST /api/v1/risk/calculate | |
| { | |
| "finding": { | |
| "title": "SQL Injection", | |
| "description": "Blind SQLi in login", | |
| "cvss_score": 9.1, | |
| "cve_id": "CVE-2023-12345" | |
| }, | |
| "target_context": { | |
| "internet_facing": true, | |
| "data_sensitivity": "pii", | |
| "compliance": ["GDPR"] | |
| } | |
| } | |
| 2. Get CVE Info: | |
| GET /api/v1/risk/cve/CVE-2021-44228 | |
| 3. Calculate CVSS: | |
| POST /api/v1/risk/cvss/calculate | |
| { | |
| "metrics": { | |
| "attack_vector": "N", | |
| "attack_complexity": "L", | |
| "privileges_required": "N", | |
| "user_interaction": "N", | |
| "scope": "U", | |
| "confidentiality": "H", | |
| "integrity": "H", | |
| "availability": "H" | |
| } | |
| } | |
| 4. Get EPSS Score: | |
| GET /api/v1/risk/epss/CVE-2021-44228 | |
| 5. Prioritize Findings: | |
| POST /api/v1/risk/prioritize | |
| { | |
| "findings": [...], | |
| "target_context": {...} | |
| } | |
| 6. Get Dashboard Stats: | |
| POST /api/v1/risk/dashboard/analyze | |
| { | |
| "findings": [...] | |
| } | |
| 7. Get Severity Levels: | |
| GET /api/v1/risk/severity/levels | |
| """) | |
| def run_all_examples(): | |
| """Run all examples.""" | |
| print("\n") | |
| print("╔" + "=" * 78 + "╗") | |
| print("║" + " " * 20 + "ZEN-AI-PENTEST RISK ENGINE" + " " * 28 + "║") | |
| print("║" + " " * 18 + "Complete Risk Scoring Examples" + " " * 26 + "║") | |
| print("╚" + "=" * 78 + "╝") | |
| try: | |
| example_1_basic_risk_calculation() | |
| except Exception as e: | |
| print(f"Example 1 failed: {e}") | |
| try: | |
| example_2_cve_lookup() | |
| except Exception as e: | |
| print(f"Example 2 failed: {e}") | |
| try: | |
| example_3_batch_prioritization() | |
| except Exception as e: | |
| print(f"Example 3 failed: {e}") | |
| try: | |
| example_4_cvss_calculation() | |
| except Exception as e: | |
| print(f"Example 4 failed: {e}") | |
| try: | |
| example_5_business_impact() | |
| except Exception as e: | |
| print(f"Example 5 failed: {e}") | |
| try: | |
| example_6_dashboard_stats() | |
| except Exception as e: | |
| print(f"Example 6 failed: {e}") | |
| try: | |
| asyncio.run(example_7_false_positive_detection()) | |
| except Exception as e: | |
| print(f"Example 7 failed: {e}") | |
| try: | |
| example_8_api_usage() | |
| except Exception as e: | |
| print(f"Example 8 failed: {e}") | |
| print("\n" + "=" * 80) | |
| print("Examples completed!") | |
| print("=" * 80) | |
| if __name__ == "__main__": | |
| run_all_examples() | |
Xet Storage Details
- Size:
- 12.7 kB
- Xet hash:
- b9fe8460e0f3b335845ec30eb0f77c0a655b722c2926b16a5b89562b9912b89a
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.