Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /api /routes /risk.py
| """ | |
| Risk Scoring API Routes | |
| Provides endpoints for: | |
| - Risk score calculation | |
| - CVE lookup with CVSS + EPSS | |
| - Finding risk assessment | |
| - Risk dashboard | |
| """ | |
| import logging | |
| from typing import Any, Dict, List, Optional | |
| from fastapi import APIRouter, Depends, HTTPException, status | |
| from pydantic import BaseModel, Field | |
| # Risk Engine imports | |
| try: | |
| from risk_engine.cvss_calculator import ExtendedCVSSCalculator | |
| from risk_engine.epss import EPSSClient | |
| from risk_engine.scorer import RiskScorer | |
| RISK_ENGINE_AVAILABLE = True | |
| except ImportError as e: | |
| logging.warning(f"Risk engine not available: {e}") | |
| RISK_ENGINE_AVAILABLE = False | |
| # Auth imports (adapt based on your auth system) | |
| try: | |
| from api.main import verify_token | |
| AUTH_AVAILABLE = True | |
| except ImportError: | |
| try: | |
| from ..main import verify_token # noqa: F401 | |
| AUTH_AVAILABLE = True | |
| except ImportError: | |
| AUTH_AVAILABLE = False | |
| logging.warning("Auth verification not available") | |
| logger = logging.getLogger(__name__) | |
| router = APIRouter(prefix="/risk", tags=["Risk Scoring"]) | |
| # ============================================================================ | |
| # Pydantic Models | |
| # ============================================================================ | |
| class CVSSMetricsInput(BaseModel): | |
| """CVSS metrics input.""" | |
| attack_vector: str = Field("N", description="N/A/L/P") | |
| attack_complexity: str = Field("L", description="L/H") | |
| privileges_required: str = Field("N", description="N/L/H") | |
| user_interaction: str = Field("N", description="N/R") | |
| scope: str = Field("U", description="U/C") | |
| confidentiality: str = Field("N", description="N/L/H") | |
| integrity: str = Field("N", description="N/L/H") | |
| availability: str = Field("N", description="N/L/H") | |
| class BusinessContextInput(BaseModel): | |
| """Business context for risk scoring.""" | |
| internet_facing: bool = Field(False, description="Is the asset internet-facing?") | |
| network_exposure: str = Field("internal", description="internet/dmz/internal/airgapped") | |
| data_sensitivity: str = Field("internal", description="pii/phi/financial/confidential/internal/public") | |
| compliance: List[str] = Field(default_factory=list, description="PCI-DSS, HIPAA, GDPR, SOX, etc.") | |
| asset_criticality: str = Field("medium", description="critical/high/medium/low") | |
| class FindingInput(BaseModel): | |
| """Finding input for risk calculation.""" | |
| title: str = Field(..., description="Finding title") | |
| description: str = Field(..., description="Finding description") | |
| severity: str = Field("medium", description="Initial severity") | |
| cvss_score: Optional[float] = Field(None, ge=0, le=10, description="CVSS base score") | |
| cvss_vector: Optional[str] = Field(None, description="CVSS vector string") | |
| cve_id: Optional[str] = Field(None, description="CVE identifier") | |
| tool: Optional[str] = Field(None, description="Tool that found the vulnerability") | |
| target: Optional[str] = Field(None, description="Target system") | |
| evidence: Optional[Dict[str, Any]] = Field(None, description="Evidence data") | |
| exploit_validated: bool = Field(False, description="Exploit validated?") | |
| exploit_available: bool = Field(False, description="Exploit code available?") | |
| poc_available: bool = Field(False, description="POC available?") | |
| cisa_kev: bool = Field(False, description="In CISA KEV catalog?") | |
| class RiskCalculateRequest(BaseModel): | |
| """Request for risk calculation.""" | |
| finding: FindingInput | |
| target_context: Optional[BusinessContextInput] = None | |
| include_temporal: bool = Field(False, description="Include temporal CVSS") | |
| include_environmental: bool = Field(False, description="Include environmental CVSS") | |
| class RiskComponentBreakdown(BaseModel): | |
| """Risk component breakdown.""" | |
| raw: float | |
| weight: float | |
| weighted: float | |
| description: str | |
| class RiskBreakdown(BaseModel): | |
| """Complete risk breakdown.""" | |
| cvss_contribution: RiskComponentBreakdown | |
| epss_contribution: RiskComponentBreakdown | |
| business_contribution: RiskComponentBreakdown | |
| exploit_contribution: RiskComponentBreakdown | |
| formula: str | |
| class CVSSComponentDetails(BaseModel): | |
| """CVSS component details.""" | |
| base: float | |
| temporal: Optional[float] | |
| environmental: Optional[float] | |
| class EPSSDetails(BaseModel): | |
| """EPSS details.""" | |
| score: float | |
| percentile: Optional[float] | |
| percentage: str | |
| class RiskComponents(BaseModel): | |
| """Risk components.""" | |
| cvss: CVSSComponentDetails | |
| epss: EPSSDetails | |
| business_impact: float | |
| exploit_availability: float | |
| class SeverityInfo(BaseModel): | |
| """Severity information.""" | |
| level: str | |
| label: str | |
| range: str | |
| sla: str | |
| class RiskScoreResponse(BaseModel): | |
| """Risk score response.""" | |
| risk_score: float | |
| severity: SeverityInfo | |
| confidence: float | |
| false_positive_likelihood: float | |
| components: RiskComponents | |
| weights: Dict[str, float] | |
| breakdown: RiskBreakdown | |
| target_context: Dict[str, Any] | |
| finding_context: Dict[str, Any] | |
| prioritized_actions: List[str] | |
| sla_target: str | |
| timestamp: str | |
| class CVSSCalculationRequest(BaseModel): | |
| """Request for CVSS calculation.""" | |
| metrics: CVSSMetricsInput | |
| temporal: Optional[Dict[str, str]] = None | |
| environmental: Optional[Dict[str, str]] = None | |
| class CVSSCalculationResponse(BaseModel): | |
| """Response for CVSS calculation.""" | |
| base_score: float | |
| temporal_score: Optional[float] | |
| environmental_score: Optional[float] | |
| overall_score: float | |
| vector_string: str | |
| severity: str | |
| class CVEResponse(BaseModel): | |
| """CVE information response.""" | |
| cve_id: str | |
| cvss: Dict[str, Any] | |
| epss: Dict[str, Any] | |
| description: str | |
| dates: Dict[str, Optional[str]] | |
| references: List[str] | |
| class RiskDashboardStats(BaseModel): | |
| """Risk dashboard statistics.""" | |
| total_findings: int | |
| by_severity: Dict[str, int] | |
| avg_risk_score: float | |
| high_risk_count: int | |
| critical_count: int | |
| requires_immediate_action: bool | |
| class BatchRiskRequest(BaseModel): | |
| """Batch risk calculation request.""" | |
| findings: List[FindingInput] | |
| target_context: Optional[BusinessContextInput] = None | |
| class BatchRiskResponse(BaseModel): | |
| """Batch risk calculation response.""" | |
| results: List[RiskScoreResponse] | |
| total: int | |
| high_risk_count: int | |
| critical_count: int | |
| class EPSSScoreResponse(BaseModel): | |
| """EPSS score response.""" | |
| cve_id: str | |
| epss_score: float | |
| percentile: Optional[float] | |
| probability_percentage: str | |
| interpretation: str | |
| # ============================================================================ | |
| # Helper Functions | |
| # ============================================================================ | |
| def get_scorer() -> RiskScorer: | |
| """Get configured risk scorer instance.""" | |
| if not RISK_ENGINE_AVAILABLE: | |
| raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="Risk engine not available") | |
| return RiskScorer() | |
| def convert_context(input_ctx: Optional[BusinessContextInput]) -> Dict[str, Any]: | |
| """Convert business context input to dict.""" | |
| if not input_ctx: | |
| return {} | |
| return { | |
| "internet_facing": input_ctx.internet_facing, | |
| "network_exposure": input_ctx.network_exposure, | |
| "data_sensitivity": input_ctx.data_sensitivity, | |
| "compliance": input_ctx.compliance, | |
| "asset_criticality": input_ctx.asset_criticality, | |
| } | |
| def convert_finding(input_finding: FindingInput) -> Dict[str, Any]: | |
| """Convert finding input to dict.""" | |
| return { | |
| "title": input_finding.title, | |
| "description": input_finding.description, | |
| "severity": input_finding.severity, | |
| "cvss_score": input_finding.cvss_score, | |
| "cvss_vector": input_finding.cvss_vector, | |
| "cve_id": input_finding.cve_id, | |
| "tool": input_finding.tool, | |
| "target": input_finding.target, | |
| "evidence": input_finding.evidence or {}, | |
| "exploit_validated": input_finding.exploit_validated, | |
| "exploit_available": input_finding.exploit_available, | |
| "poc_available": input_finding.poc_available, | |
| "cisa_kev": input_finding.cisa_kev, | |
| } | |
| # ============================================================================ | |
| # API Endpoints | |
| # ============================================================================ | |
| async def calculate_risk( | |
| request: RiskCalculateRequest, | |
| scorer: RiskScorer = Depends(get_scorer), | |
| ): | |
| """ | |
| Calculate comprehensive risk score for a vulnerability finding. | |
| Combines: | |
| - CVSS Base Score (30% weight) | |
| - EPSS Exploit Probability (25% weight) | |
| - Business Impact (35% weight) | |
| - Exploit Availability (10% weight) | |
| Formula: (CVSS×0.30 + EPSS×0.25 + Business×0.35 + Exploit×0.10) × 10 | |
| """ | |
| try: | |
| finding_dict = convert_finding(request.finding) | |
| context_dict = convert_context(request.target_context) | |
| result = scorer.calculate( | |
| finding=finding_dict, | |
| target_context=context_dict, | |
| calculate_temporal=request.include_temporal, | |
| calculate_environmental=request.include_environmental, | |
| ) | |
| return result.to_dict() | |
| except HTTPException: | |
| raise | |
| except Exception as e: | |
| logger.error(f"Error calculating risk: {e}") | |
| raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"Risk calculation failed: {str(e)}") | |
| async def batch_calculate_risk( | |
| request: BatchRiskRequest, | |
| scorer: RiskScorer = Depends(get_scorer), | |
| ): | |
| """ | |
| Calculate risk scores for multiple findings in batch. | |
| More efficient than individual calls as it batches EPSS requests. | |
| """ | |
| try: | |
| findings_dicts = [convert_finding(f) for f in request.findings] | |
| context_dict = convert_context(request.target_context) | |
| results = scorer.batch_calculate(findings_dicts, context_dict) | |
| high_risk = sum(1 for r in results if r.value >= 7.0) | |
| critical = sum(1 for r in results if r.value >= 9.0) | |
| return { | |
| "results": [r.to_dict() for r in results], | |
| "total": len(results), | |
| "high_risk_count": high_risk, | |
| "critical_count": critical, | |
| } | |
| except Exception as e: | |
| logger.error(f"Error in batch calculation: {e}") | |
| raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"Batch calculation failed: {str(e)}") | |
| async def get_cve_info( | |
| cve_id: str, | |
| scorer: RiskScorer = Depends(get_scorer), | |
| ): | |
| """ | |
| Get comprehensive CVE information including: | |
| - CVSS score from NVD | |
| - EPSS probability score | |
| - Description and references | |
| """ | |
| try: | |
| # Validate CVE ID format | |
| if not cve_id.upper().startswith("CVE-"): | |
| raise HTTPException( | |
| status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid CVE ID format. Expected: CVE-YYYY-NNNNN" | |
| ) | |
| cve_info = scorer.get_cve_info(cve_id.upper()) | |
| if not cve_info: | |
| raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"CVE {cve_id} not found") | |
| return cve_info.to_dict() | |
| except HTTPException: | |
| raise | |
| except Exception as e: | |
| logger.error(f"Error fetching CVE info: {e}") | |
| raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"Failed to fetch CVE info: {str(e)}") | |
| async def get_finding_risk( | |
| finding_id: str, | |
| target_context: Optional[BusinessContextInput] = None, | |
| scorer: RiskScorer = Depends(get_scorer), | |
| ): | |
| """ | |
| Calculate risk score for a stored finding. | |
| In a real implementation, this would fetch the finding from the database. | |
| For now, it expects finding data in the request body. | |
| """ | |
| # This is a placeholder - in production, fetch from DB | |
| raise HTTPException( | |
| status_code=status.HTTP_501_NOT_IMPLEMENTED, | |
| detail="Finding lookup from database not yet implemented. Use /risk/calculate instead.", | |
| ) | |
| async def get_risk_dashboard( | |
| scorer: RiskScorer = Depends(get_scorer), | |
| ): | |
| """ | |
| Get risk dashboard statistics. | |
| Returns aggregated statistics about risk scores. | |
| In production, this would fetch findings from the database. | |
| """ | |
| # Placeholder - in production, fetch findings from DB | |
| # For now, return empty stats | |
| return { | |
| "total_findings": 0, | |
| "by_severity": { | |
| "Critical": 0, | |
| "High": 0, | |
| "Medium": 0, | |
| "Low": 0, | |
| }, | |
| "avg_risk_score": 0.0, | |
| "high_risk_count": 0, | |
| "critical_count": 0, | |
| "requires_immediate_action": False, | |
| } | |
| async def analyze_findings_dashboard( | |
| findings: List[FindingInput], | |
| target_context: Optional[BusinessContextInput] = None, | |
| scorer: RiskScorer = Depends(get_scorer), | |
| ): | |
| """ | |
| Analyze multiple findings and return dashboard statistics. | |
| """ | |
| try: | |
| findings_dicts = [convert_finding(f) for f in findings] | |
| convert_context(target_context) | |
| stats = scorer.get_dashboard_stats(findings_dicts) | |
| return stats | |
| except Exception as e: | |
| logger.error(f"Error analyzing findings: {e}") | |
| raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"Analysis failed: {str(e)}") | |
| async def calculate_cvss( | |
| request: CVSSCalculationRequest, | |
| ): | |
| """ | |
| Calculate CVSS v3.1 score from individual metrics. | |
| Also supports temporal and environmental score calculation. | |
| """ | |
| try: | |
| if not RISK_ENGINE_AVAILABLE: | |
| raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="Risk engine not available") | |
| calc = ExtendedCVSSCalculator() | |
| # Convert metrics to dict | |
| metrics = { | |
| "AV": request.metrics.attack_vector, | |
| "AC": request.metrics.attack_complexity, | |
| "PR": request.metrics.privileges_required, | |
| "UI": request.metrics.user_interaction, | |
| "S": request.metrics.scope, | |
| "C": request.metrics.confidentiality, | |
| "I": request.metrics.integrity, | |
| "A": request.metrics.availability, | |
| } | |
| # Calculate scores | |
| scores = calc.calculate_extended( | |
| metrics=metrics, | |
| temporal=request.temporal, | |
| environmental=request.environmental, | |
| ) | |
| # Build vector string | |
| vector = calc.parser.build(metrics) | |
| # Determine severity | |
| severity = "None" | |
| if scores["base_score"] >= 9.0: | |
| severity = "Critical" | |
| elif scores["base_score"] >= 7.0: | |
| severity = "High" | |
| elif scores["base_score"] >= 4.0: | |
| severity = "Medium" | |
| elif scores["base_score"] >= 0.1: | |
| severity = "Low" | |
| return { | |
| "base_score": scores["base_score"], | |
| "temporal_score": scores.get("temporal_score"), | |
| "environmental_score": scores.get("environmental_score"), | |
| "overall_score": scores["overall_score"], | |
| "vector_string": vector, | |
| "severity": severity, | |
| } | |
| except HTTPException: | |
| raise | |
| except Exception as e: | |
| logger.error(f"Error calculating CVSS: {e}") | |
| raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"CVSS calculation failed: {str(e)}") | |
| async def get_epss_score( | |
| cve_id: str, | |
| ): | |
| """ | |
| Get EPSS score for a CVE. | |
| EPSS provides the probability (0-1) that a vulnerability will be exploited | |
| in the wild within the next 30 days. | |
| """ | |
| try: | |
| if not RISK_ENGINE_AVAILABLE: | |
| raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="Risk engine not available") | |
| # Validate CVE ID format | |
| if not cve_id.upper().startswith("CVE-"): | |
| raise HTTPException( | |
| status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid CVE ID format. Expected: CVE-YYYY-NNNNN" | |
| ) | |
| client = EPSSClient() | |
| score = client.get_score(cve_id.upper()) | |
| percentile = client.get_percentile(cve_id.upper()) | |
| interpretation = client.interpret_score(score) | |
| return { | |
| "cve_id": cve_id.upper(), | |
| "epss_score": score, | |
| "percentile": percentile, | |
| "probability_percentage": f"{score * 100:.2f}%", | |
| "interpretation": interpretation, | |
| } | |
| except HTTPException: | |
| raise | |
| except Exception as e: | |
| logger.error(f"Error fetching EPSS: {e}") | |
| raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"EPSS fetch failed: {str(e)}") | |
| async def prioritize_findings( | |
| findings: List[FindingInput], | |
| target_context: Optional[BusinessContextInput] = None, | |
| scorer: RiskScorer = Depends(get_scorer), | |
| ): | |
| """ | |
| Prioritize a list of findings by their risk scores. | |
| Returns findings sorted by risk (highest first) with risk scores attached. | |
| """ | |
| try: | |
| findings_dicts = [convert_finding(f) for f in findings] | |
| context_dict = convert_context(target_context) | |
| prioritized = scorer.prioritize_findings(findings_dicts, context_dict) | |
| return [f.get("risk_score") for f in prioritized if f.get("risk_score")] | |
| except Exception as e: | |
| logger.error(f"Error prioritizing findings: {e}") | |
| raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"Prioritization failed: {str(e)}") | |
| async def get_severity_levels(): | |
| """ | |
| Get the defined severity levels with their ranges and SLA targets. | |
| """ | |
| return { | |
| "severity_levels": [ | |
| { | |
| "level": "Critical", | |
| "range": "9.0-10.0", | |
| "sla": "24h", | |
| "description": "Immediate action required", | |
| "color": "#DC2626", | |
| }, | |
| { | |
| "level": "High", | |
| "range": "7.0-8.9", | |
| "sla": "72h", | |
| "description": "Urgent action required", | |
| "color": "#EA580C", | |
| }, | |
| { | |
| "level": "Medium", | |
| "range": "4.0-6.9", | |
| "sla": "14d", | |
| "description": "Schedule remediation", | |
| "color": "#D97706", | |
| }, | |
| { | |
| "level": "Low", | |
| "range": "1.0-3.9", | |
| "sla": "30d", | |
| "description": "Address as time permits", | |
| "color": "#65A30D", | |
| }, | |
| { | |
| "level": "Info", | |
| "range": "0.0-0.9", | |
| "sla": "Best effort", | |
| "description": "Informational", | |
| "color": "#6B7280", | |
| }, | |
| ], | |
| "formula": "(CVSS×0.30 + EPSS×0.25 + Business×0.35 + Exploit×0.10) × 10", | |
| "weights": { | |
| "cvss": 0.30, | |
| "epss": 0.25, | |
| "business_impact": 0.35, | |
| "exploit_availability": 0.10, | |
| }, | |
| } | |
Xet Storage Details
- Size:
- 21 kB
- Xet hash:
- 968f414b538abd47bd34cfc501a002c769fb5c33f1599752d3178a80ac541463
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.