"""Unified API endpoint for analyzing all IOC types with source selection.""" import logging from concurrent.futures import ThreadPoolExecutor, as_completed from fastapi import APIRouter, File, Form, HTTPException, UploadFile from src.exceptions import APIKeyMissingError, ExternalAPIError from src.models.threat_context import MSSPSummaryRow from src.models.unified import ( SourceResult, UnifiedAnalysisResponse, UnifiedIOCResult, ) from src.services import ( AbuseIPDBService, MalwareBazaarService, OTXService, ThreatFoxService, URLhausService, URLScanService, VirusTotalService, context_aggregator, threat_analyzer, ) from src.services.cache import cache from src.services.stats import stats_service from src.utils.helpers import get_country_name from src.utils.ioc_detector import IOCType, detect_ioc_type from src.utils.validators import ( is_private_ip, parse_iocs_from_file, parse_iocs_from_text, ) logger = logging.getLogger(__name__) router = APIRouter() # Thread pool for parallel API calls MAX_PARALLEL_SOURCES = 8 MAX_PARALLEL_IOCS = 10 # Process up to 10 IOCs in parallel # Available sources for each IOC type IOC_SOURCE_MAP = { IOCType.IP: ["virustotal", "abuseipdb", "urlscan", "threatfox", "urlhaus", "otx"], IOCType.DOMAIN: ["virustotal", "urlscan", "threatfox", "urlhaus", "otx"], IOCType.URL: ["virustotal", "urlscan", "threatfox", "urlhaus", "otx"], IOCType.HASH: ["virustotal", "threatfox", "malwarebazaar", "otx"], } def _get_services( sources: list[str], ) -> dict[str, VirusTotalService | AbuseIPDBService | URLScanService | ThreatFoxService | URLhausService | MalwareBazaarService | None]: """Initialize requested services.""" services = {} if "virustotal" in sources: try: services["virustotal"] = VirusTotalService() except APIKeyMissingError: services["virustotal"] = None if "abuseipdb" in sources: try: services["abuseipdb"] = AbuseIPDBService() except APIKeyMissingError: services["abuseipdb"] = None if "urlscan" in sources: try: services["urlscan"] = URLScanService() except APIKeyMissingError: services["urlscan"] = None # abuse.ch services - no API key required (optional key improves rate limits) if "threatfox" in sources: services["threatfox"] = ThreatFoxService() if "urlhaus" in sources: services["urlhaus"] = URLhausService() if "malwarebazaar" in sources: services["malwarebazaar"] = MalwareBazaarService() if "otx" in sources: try: services["otx"] = OTXService() except APIKeyMissingError: services["otx"] = None return services def _close_services(services: dict) -> None: """Close all service connections.""" for service in services.values(): if service is not None: service.close() # === Parallel Source Fetch Helpers === def _fetch_virustotal_ip(vt_service, ip: str) -> SourceResult: """Fetch VirusTotal data for IP.""" if vt_service is None: return SourceResult(source="virustotal", available=False, error="API key not configured") try: cached = cache.get("virustotal", "ip", ip) if cached: return SourceResult(source="virustotal", data=cached) data = vt_service.analyze_ip(ip) cache.set("virustotal", "ip", ip, data) return SourceResult(source="virustotal", data=data) except ExternalAPIError as e: return SourceResult(source="virustotal", error=str(e)) def _fetch_abuseipdb_ip(abuseipdb_service, ip: str) -> SourceResult: """Fetch AbuseIPDB data for IP.""" if abuseipdb_service is None: return SourceResult(source="abuseipdb", available=False, error="API key not configured") try: cached = cache.get("abuseipdb", "ip", ip) if cached: return SourceResult(source="abuseipdb", data=cached) data = abuseipdb_service.check_ip(ip) if data.get("country_code"): data["country_name"] = get_country_name(data["country_code"]) cache.set("abuseipdb", "ip", ip, data) return SourceResult(source="abuseipdb", data=data) except ExternalAPIError as e: return SourceResult(source="abuseipdb", error=str(e)) def _fetch_urlscan_ip(urlscan_service, ip: str) -> SourceResult: """Fetch URLScan data for IP.""" if urlscan_service is None: return SourceResult(source="urlscan", available=False, error="API key not configured") try: data = urlscan_service.search_ip(ip) return SourceResult(source="urlscan", data=data) except ExternalAPIError as e: return SourceResult(source="urlscan", error=str(e)) def _fetch_threatfox(threatfox_service, ioc: str) -> SourceResult: """Fetch ThreatFox data for any IOC.""" if threatfox_service is None: return SourceResult(source="threatfox", available=False, error="Service not available") try: data = threatfox_service.search_ioc(ioc) return SourceResult(source="threatfox", data=data) except ExternalAPIError as e: return SourceResult(source="threatfox", error=str(e)) def _fetch_urlhaus_host(urlhaus_service, host: str) -> SourceResult: """Fetch URLhaus data for host (IP/Domain).""" if urlhaus_service is None: return SourceResult(source="urlhaus", available=False, error="Service not available") try: data = urlhaus_service.lookup_host(host) return SourceResult(source="urlhaus", data=data) except ExternalAPIError as e: return SourceResult(source="urlhaus", error=str(e)) def _fetch_otx_ip(otx_service, ip: str) -> SourceResult: """Fetch OTX data for IP.""" if otx_service is None: return SourceResult(source="otx", available=False, error="API key not configured") try: cached = cache.get("otx", "ip", ip) if cached: return SourceResult(source="otx", data=cached) data = otx_service.analyze_ip(ip) cache.set("otx", "ip", ip, data) return SourceResult(source="otx", data=data) except ExternalAPIError as e: return SourceResult(source="otx", error=str(e)) # === Domain Parallel Helpers === def _fetch_virustotal_domain(vt_service, domain: str) -> SourceResult: """Fetch VirusTotal data for domain.""" if vt_service is None: return SourceResult(source="virustotal", available=False, error="API key not configured") try: cached = cache.get("virustotal", "domain", domain) if cached: return SourceResult(source="virustotal", data=cached) data = vt_service.analyze_domain(domain) cache.set("virustotal", "domain", domain, data) return SourceResult(source="virustotal", data=data) except ExternalAPIError as e: return SourceResult(source="virustotal", error=str(e)) def _fetch_urlscan_domain(urlscan_service, domain: str) -> SourceResult: """Fetch URLScan data for domain.""" if urlscan_service is None: return SourceResult(source="urlscan", available=False, error="API key not configured") try: data = urlscan_service.search_domain(domain) return SourceResult(source="urlscan", data=data) except ExternalAPIError as e: return SourceResult(source="urlscan", error=str(e)) def _fetch_otx_domain(otx_service, domain: str) -> SourceResult: """Fetch OTX data for domain.""" if otx_service is None: return SourceResult(source="otx", available=False, error="API key not configured") try: cached = cache.get("otx", "domain", domain) if cached: return SourceResult(source="otx", data=cached) data = otx_service.analyze_domain(domain) cache.set("otx", "domain", domain, data) return SourceResult(source="otx", data=data) except ExternalAPIError as e: return SourceResult(source="otx", error=str(e)) # === URL Parallel Helpers === def _fetch_virustotal_url(vt_service, url: str) -> SourceResult: """Fetch VirusTotal data for URL.""" if vt_service is None: return SourceResult(source="virustotal", available=False, error="API key not configured") try: cached = cache.get("virustotal", "url", url) if cached: return SourceResult(source="virustotal", data=cached) data = vt_service.analyze_url(url) cache.set("virustotal", "url", url, data) return SourceResult(source="virustotal", data=data) except ExternalAPIError as e: return SourceResult(source="virustotal", error=str(e)) def _fetch_urlscan_url(urlscan_service, url: str) -> SourceResult: """Fetch URLScan data for URL.""" if urlscan_service is None: return SourceResult(source="urlscan", available=False, error="API key not configured") try: data = urlscan_service.search_url(url) return SourceResult(source="urlscan", data=data) except ExternalAPIError as e: return SourceResult(source="urlscan", error=str(e)) def _fetch_urlhaus_url(urlhaus_service, url: str) -> SourceResult: """Fetch URLhaus data for URL.""" if urlhaus_service is None: return SourceResult(source="urlhaus", available=False, error="Service not available") try: data = urlhaus_service.lookup_url(url) return SourceResult(source="urlhaus", data=data) except ExternalAPIError as e: return SourceResult(source="urlhaus", error=str(e)) def _fetch_otx_url(otx_service, url: str) -> SourceResult: """Fetch OTX data for URL.""" if otx_service is None: return SourceResult(source="otx", available=False, error="API key not configured") try: cached = cache.get("otx", "url", url) if cached: return SourceResult(source="otx", data=cached) data = otx_service.analyze_url(url) cache.set("otx", "url", url, data) return SourceResult(source="otx", data=data) except ExternalAPIError as e: return SourceResult(source="otx", error=str(e)) # === Hash Parallel Helpers === def _fetch_virustotal_hash(vt_service, hash_val: str) -> SourceResult: """Fetch VirusTotal data for hash.""" if vt_service is None: return SourceResult(source="virustotal", available=False, error="API key not configured") try: cached = cache.get("virustotal", "hash", hash_val) if cached: return SourceResult(source="virustotal", data=cached) data = vt_service.analyze_file_hash(hash_val) cache.set("virustotal", "hash", hash_val, data) return SourceResult(source="virustotal", data=data) except ExternalAPIError as e: return SourceResult(source="virustotal", error=str(e)) def _fetch_malwarebazaar(malwarebazaar_service, hash_val: str) -> SourceResult: """Fetch MalwareBazaar data for hash.""" if malwarebazaar_service is None: return SourceResult(source="malwarebazaar", available=False, error="Service not available") try: data = malwarebazaar_service.lookup_hash(hash_val) return SourceResult(source="malwarebazaar", data=data) except ExternalAPIError as e: return SourceResult(source="malwarebazaar", error=str(e)) def _fetch_otx_hash(otx_service, hash_val: str) -> SourceResult: """Fetch OTX data for hash.""" if otx_service is None: return SourceResult(source="otx", available=False, error="API key not configured") try: cached = cache.get("otx", "hash", hash_val) if cached: return SourceResult(source="otx", data=cached) data = otx_service.analyze_hash(hash_val) cache.set("otx", "hash", hash_val, data) return SourceResult(source="otx", data=data) except ExternalAPIError as e: return SourceResult(source="otx", error=str(e)) def _analyze_ip( ip: str, services: dict, requested_sources: list[str], ) -> dict[str, SourceResult]: """Analyze an IP address with requested sources IN PARALLEL.""" results = {} # Check if private IP - skip all lookups if is_private_ip(ip): for source in requested_sources: if source in IOC_SOURCE_MAP[IOCType.IP]: results[source] = SourceResult( source=source, available=False, error="Private/Reserved IP - API lookup skipped", ) return results # Build list of tasks for parallel execution tasks = [] if "virustotal" in requested_sources: tasks.append(("virustotal", _fetch_virustotal_ip, services.get("virustotal"), ip)) if "abuseipdb" in requested_sources: tasks.append(("abuseipdb", _fetch_abuseipdb_ip, services.get("abuseipdb"), ip)) if "urlscan" in requested_sources: tasks.append(("urlscan", _fetch_urlscan_ip, services.get("urlscan"), ip)) if "threatfox" in requested_sources: tasks.append(("threatfox", _fetch_threatfox, services.get("threatfox"), ip)) if "urlhaus" in requested_sources: tasks.append(("urlhaus", _fetch_urlhaus_host, services.get("urlhaus"), ip)) if "otx" in requested_sources: tasks.append(("otx", _fetch_otx_ip, services.get("otx"), ip)) # Execute all tasks in parallel with ThreadPoolExecutor(max_workers=MAX_PARALLEL_SOURCES) as executor: futures = { executor.submit(func, service, ioc): source_name for source_name, func, service, ioc in tasks } for future in as_completed(futures): source_name = futures[future] try: result = future.result() results[source_name] = result except Exception as e: logger.error(f"Parallel fetch error for {source_name}: {e}") results[source_name] = SourceResult(source=source_name, error=str(e)) return results def _analyze_domain( domain: str, services: dict, requested_sources: list[str], ) -> dict[str, SourceResult]: """Analyze a domain with requested sources IN PARALLEL.""" results = {} tasks = [] if "virustotal" in requested_sources: tasks.append(("virustotal", _fetch_virustotal_domain, services.get("virustotal"), domain)) if "urlscan" in requested_sources: tasks.append(("urlscan", _fetch_urlscan_domain, services.get("urlscan"), domain)) if "threatfox" in requested_sources: tasks.append(("threatfox", _fetch_threatfox, services.get("threatfox"), domain)) if "urlhaus" in requested_sources: tasks.append(("urlhaus", _fetch_urlhaus_host, services.get("urlhaus"), domain)) if "otx" in requested_sources: tasks.append(("otx", _fetch_otx_domain, services.get("otx"), domain)) # Execute all tasks in parallel with ThreadPoolExecutor(max_workers=MAX_PARALLEL_SOURCES) as executor: futures = { executor.submit(func, service, ioc): source_name for source_name, func, service, ioc in tasks } for future in as_completed(futures): source_name = futures[future] try: result = future.result() results[source_name] = result except Exception as e: logger.error(f"Parallel fetch error for {source_name}: {e}") results[source_name] = SourceResult(source=source_name, error=str(e)) return results def _analyze_url( url: str, services: dict, requested_sources: list[str], ) -> dict[str, SourceResult]: """Analyze a URL with requested sources IN PARALLEL.""" results = {} tasks = [] if "virustotal" in requested_sources: tasks.append(("virustotal", _fetch_virustotal_url, services.get("virustotal"), url)) if "urlscan" in requested_sources: tasks.append(("urlscan", _fetch_urlscan_url, services.get("urlscan"), url)) if "threatfox" in requested_sources: tasks.append(("threatfox", _fetch_threatfox, services.get("threatfox"), url)) if "urlhaus" in requested_sources: tasks.append(("urlhaus", _fetch_urlhaus_url, services.get("urlhaus"), url)) if "otx" in requested_sources: tasks.append(("otx", _fetch_otx_url, services.get("otx"), url)) # Execute all tasks in parallel with ThreadPoolExecutor(max_workers=MAX_PARALLEL_SOURCES) as executor: futures = { executor.submit(func, service, ioc): source_name for source_name, func, service, ioc in tasks } for future in as_completed(futures): source_name = futures[future] try: result = future.result() results[source_name] = result except Exception as e: logger.error(f"Parallel fetch error for {source_name}: {e}") results[source_name] = SourceResult(source=source_name, error=str(e)) return results def _analyze_hash( hash_value: str, services: dict, requested_sources: list[str], ) -> dict[str, SourceResult]: """Analyze a file hash with requested sources IN PARALLEL.""" results = {} tasks = [] if "virustotal" in requested_sources: tasks.append(("virustotal", _fetch_virustotal_hash, services.get("virustotal"), hash_value)) if "threatfox" in requested_sources: tasks.append(("threatfox", _fetch_threatfox, services.get("threatfox"), hash_value)) if "malwarebazaar" in requested_sources: tasks.append(("malwarebazaar", _fetch_malwarebazaar, services.get("malwarebazaar"), hash_value)) if "otx" in requested_sources: tasks.append(("otx", _fetch_otx_hash, services.get("otx"), hash_value)) # Execute all tasks in parallel with ThreadPoolExecutor(max_workers=MAX_PARALLEL_SOURCES) as executor: futures = { executor.submit(func, service, ioc): source_name for source_name, func, service, ioc in tasks } for future in as_completed(futures): source_name = futures[future] try: result = future.result() results[source_name] = result except Exception as e: logger.error(f"Parallel fetch error for {source_name}: {e}") results[source_name] = SourceResult(source=source_name, error=str(e)) return results def _analyze_single_ioc( value: str, ioc_type: IOCType, services: dict, requested_sources: list[str], ) -> UnifiedIOCResult: """Analyze a single IOC based on its detected type.""" # Filter sources to only those available for this IOC type available_sources = IOC_SOURCE_MAP.get(ioc_type, []) sources_to_use = [s for s in requested_sources if s in available_sources] # Handle unknown IOC type if ioc_type == IOCType.UNKNOWN: return UnifiedIOCResult( value=value, detected_type=ioc_type, sources={ "error": SourceResult( source="detection", available=False, error="Could not determine IOC type", ) }, ) # Route to appropriate analyzer if ioc_type == IOCType.IP: source_results = _analyze_ip(value, services, sources_to_use) elif ioc_type == IOCType.DOMAIN: source_results = _analyze_domain(value, services, sources_to_use) elif ioc_type == IOCType.URL: source_results = _analyze_url(value, services, sources_to_use) elif ioc_type == IOCType.HASH: source_results = _analyze_hash(value, services, sources_to_use) else: source_results = {} # Aggregate threat context from all sources threat_context = context_aggregator.aggregate(source_results) # Build result object result = UnifiedIOCResult( value=value, detected_type=ioc_type, sources=source_results, threat_context=threat_context, ) # Determine verdict for stats logging verdict = "unknown" if ioc_type == IOCType.IP and is_private_ip(value): verdict = "private ip" elif threat_context: # Use the aggregated threat context to determine verdict # Check for malicious indicators: malware families indicate known malware if threat_context.malware_families: verdict = "malicious" elif threat_context.threat_actors: verdict = "suspicious" elif any(sr.data and sr.data.get("status") == "clean" for sr in source_results.values()): verdict = "clean" # Extract country_code from source results for geo stats country_code = None if ioc_type == IOCType.IP: # Priority: AbuseIPDB > OTX > VirusTotal > URLScan for src_key, field in [ ("abuseipdb", "country_code"), ("otx", "country_code"), ("virustotal", "country"), ]: sr = source_results.get(src_key) if sr and sr.data: country_code = sr.data.get(field) if country_code: break if not country_code: sr = source_results.get("urlscan") if sr and sr.data: results_list = sr.data.get("results", []) if results_list: country_code = results_list[0].get("country") elif ioc_type in (IOCType.DOMAIN, IOCType.URL): # URLScan provides hosting server country for domains/URLs sr = source_results.get("urlscan") if sr and sr.data: results_list = sr.data.get("results", []) if results_list: country_code = results_list[0].get("country") elif ioc_type == IOCType.HASH: # MalwareBazaar provides origin_country for hashes sr = source_results.get("malwarebazaar") if sr and sr.data: country_code = sr.data.get("origin_country") # Log to stats (synchronous, non-blocking in separate thread context) try: stats_service.log_lookup( ioc_value=value, ioc_type=ioc_type.value, verdict=verdict, country_code=country_code, ) except Exception: pass # Don't let stats logging break the main flow return result @router.post("/analyze", response_model=UnifiedAnalysisResponse) async def analyze_unified( text_input: str | None = Form( None, description="IOCs (comma or newline separated) - auto-detected" ), file: UploadFile | None = File( None, description="TXT file containing IOCs, one per line" ), sources: str = Form( "virustotal,abuseipdb,urlscan", description="Comma-separated list of sources to query", ), ): """ Analyze IOCs with automatic type detection and source selection. Supports IP addresses, domains, URLs, and file hashes. The backend automatically detects the IOC type and routes to appropriate APIs. Args: text_input: IOCs (comma or newline separated) file: TXT file containing IOCs (one per line) sources: Comma-separated list of sources (virustotal, abuseipdb, urlscan) Returns: UnifiedAnalysisResponse with results from all requested sources """ # Validate input if not text_input and not file: raise HTTPException( status_code=400, detail="Please provide either text_input or file. Both cannot be empty.", ) # Parse IOCs from input iocs: list[str] = [] if text_input: iocs.extend(parse_iocs_from_text(text_input)) if file: if not file.filename or not file.filename.lower().endswith(".txt"): raise HTTPException( status_code=400, detail="File must be a .txt file", ) content = await file.read() file_content = content.decode("utf-8-sig") iocs.extend(parse_iocs_from_file(file_content)) if not iocs: raise HTTPException( status_code=400, detail="No IOCs found in input", ) # Remove duplicates while preserving order seen: set[str] = set() unique_iocs: list[str] = [] for ioc in iocs: if ioc.lower() not in seen: seen.add(ioc.lower()) unique_iocs.append(ioc) # Enforce maximum IOC limit MAX_IOCS = 100 if len(unique_iocs) > MAX_IOCS: raise HTTPException( status_code=400, detail=f"Maximum {MAX_IOCS} IOCs per request. You submitted {len(unique_iocs)} unique IOCs. Please reduce the number of IOCs and try again.", ) # Parse requested sources requested_sources = [s.strip().lower() for s in sources.split(",") if s.strip()] valid_sources = ["virustotal", "abuseipdb", "urlscan", "threatfox", "urlhaus", "malwarebazaar", "otx"] requested_sources = [s for s in requested_sources if s in valid_sources] if not requested_sources: requested_sources = valid_sources # Initialize services services = _get_services(requested_sources) try: results: list[UnifiedIOCResult] = [] type_counts: dict[str, int] = {} # Pre-detect IOC types and count them (fast operation) ioc_type_map = {} for ioc in unique_iocs: ioc_type = detect_ioc_type(ioc) ioc_type_map[ioc] = ioc_type type_name = ioc_type.value type_counts[type_name] = type_counts.get(type_name, 0) + 1 # === PARALLEL IOC PROCESSING === # Process ALL IOCs in parallel (up to MAX_PARALLEL_IOCS) # This is the critical optimization - instead of waiting for each IOC sequentially, # we process them all at once. Each IOC still fetches its sources in parallel internally. with ThreadPoolExecutor(max_workers=MAX_PARALLEL_IOCS) as executor: futures = { executor.submit( _analyze_single_ioc, ioc, ioc_type_map[ioc], services, requested_sources ): ioc for ioc in unique_iocs } for future in as_completed(futures): ioc = futures[future] try: result = future.result() results.append(result) except Exception as e: logger.error(f"Error analyzing IOC {ioc}: {e}") # Create error result for failed IOC results.append(UnifiedIOCResult( value=ioc, detected_type=ioc_type_map[ioc], sources={"error": SourceResult( source="error", available=False, error=str(e), )}, )) # Generate MSSP summary table mssp_summary = _generate_mssp_summary(results) return UnifiedAnalysisResponse( results=results, summary=type_counts, mssp_summary=mssp_summary, ) except Exception as e: logger.error(f"Error processing IOCs: {str(e)}") raise HTTPException( status_code=500, detail=f"Error processing IOCs: {str(e)}", ) from e finally: _close_services(services) def _generate_mssp_summary(results: list[UnifiedIOCResult]) -> list[MSSPSummaryRow]: """ Generate MSSP executive summary table from analysis results. This creates a structured, exportable table suitable for customer reports. """ mssp_rows = [] for result in results: # Get threat context ctx = result.threat_context # Build source data dict for threat analyzer source_data = {} for source_name, source_result in result.sources.items(): if source_result.data: source_data[source_name] = {"data": source_result.data} # Run deterministic threat analysis threat_result = threat_analyzer.analyze( result.value, result.detected_type.value, source_data, ) # Determine which sources had positive detections sources_detected = [] for source_name, source_result in result.sources.items(): if source_result.data and source_result.data.get("found"): # Check if it's a positive detection status = source_result.data.get("status", "") if status in ["malicious", "suspicious"]: sources_detected.append(source_name) # Build MSSP row row = MSSPSummaryRow( ioc=result.value, ioc_type=result.detected_type.value, verdict=threat_result.verdict, risk_level=threat_result.risk_level, risk_score=threat_result.risk_score, threat_actor=ctx.threat_actors[0] if ctx and ctx.threat_actors else None, malware_family=ctx.malware_families[0] if ctx and ctx.malware_families else None, mitre_techniques=ctx.mitre_techniques[:5] if ctx else [], first_seen=ctx.first_seen if ctx else None, last_seen=ctx.last_seen if ctx else None, sources_detected=sources_detected, detection_count=len(sources_detected), recommended_action=threat_result.recommendations[0] if threat_result.recommendations else "Monitor", confidence=ctx.confidence if ctx else "unknown", ) mssp_rows.append(row) return mssp_rows