"""API endpoints for domain reputation analysis.""" import io import logging from fastapi import APIRouter, File, Form, HTTPException, UploadFile from fastapi.responses import StreamingResponse from src.exceptions import APIKeyMissingError, ExternalAPIError from src.models.domain import DomainResult from src.services import VirusTotalService from src.services.stats import stats_service from src.utils.validators import ( parse_iocs_from_file, parse_iocs_from_text, validate_domain, validate_txt_file, ) logger = logging.getLogger(__name__) router = APIRouter() def _analyze_single_domain(domain: str, vt_service: VirusTotalService) -> DomainResult: """ Analyze a single domain using VirusTotal. Args: domain: Domain name to analyze vt_service: VirusTotal service instance Returns: DomainResult with all available analysis data """ domain = domain.strip().lower() logger.info(f"Analyzing domain: {domain}") # Validate domain format if not validate_domain(domain): return DomainResult( domain=domain, error="Invalid domain format", ) try: analysis = vt_service.analyze_domain(domain) if not analysis.get("found"): result = DomainResult( domain=domain, error="Domain not found in VirusTotal database", ) else: categories = analysis.get("categories", []) categories_str = ", ".join(categories) if categories else None result = DomainResult( domain=domain, # Detection stats malicious_count=analysis.get("malicious_count"), suspicious_count=analysis.get("suspicious_count"), harmless_count=analysis.get("harmless_count"), undetected_count=analysis.get("undetected_count"), total_engines=analysis.get("total_engines"), timeout_count=analysis.get("timeout_count"), # Reputation reputation_score=analysis.get("reputation_score"), categories=categories_str, tags=analysis.get("tags") or None, # Registration info registrar=analysis.get("registrar"), creation_date=analysis.get("creation_date"), last_update_date=analysis.get("last_update_date"), expiration_date=analysis.get("expiration_date"), last_analysis_date=analysis.get("last_analysis_date"), last_modification_date=analysis.get("last_modification_date"), # DNS and WHOIS last_dns_records=analysis.get("last_dns_records") or None, whois=analysis.get("whois"), popularity_ranks=analysis.get("popularity_ranks") or None, ) except ExternalAPIError as e: logger.error(f"VirusTotal error for domain {domain}: {str(e)}") result = DomainResult(domain=domain, error=str(e)) except (ValueError, KeyError) as e: logger.error(f"Unexpected error analyzing domain {domain}: {str(e)}") result = DomainResult(domain=domain, error=f"Analysis error: {str(e)}") # Log to dashboard analytics try: verdict = "unknown" if result.error: verdict = "unknown" elif result.malicious_count and result.malicious_count > 0: verdict = "malicious" elif result.suspicious_count and result.suspicious_count > 0: verdict = "suspicious" else: verdict = "clean" stats_service.log_lookup(ioc_value=domain, ioc_type="domain", verdict=verdict) except Exception: pass # Never let stats logging break the main flow return result @router.post("/analyze", response_model=list[DomainResult]) async def analyze_domains( text_input: str | None = Form( None, description="Domain names (comma or newline separated)" ), file: UploadFile | None = File( None, description="TXT file containing domains, one per line" ), ): """ Analyze domains using VirusTotal API. Accepts either: - text_input: Domain names (comma or newline separated) - file: A .txt file containing domain names (one per line) Args: text_input: Text containing domains file: TXT file containing domains Returns: List of DomainResult objects with analysis results Raises: HTTPException: If no input provided, API key missing, or invalid format """ # 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 domains from input domains: list[str] = [] if text_input: domains.extend(parse_iocs_from_text(text_input)) if file: if not validate_txt_file(file.filename): raise HTTPException( status_code=400, detail="File must be a .txt file", ) content = await file.read() file_content = content.decode("utf-8-sig") domains.extend(parse_iocs_from_file(file_content)) if not domains: raise HTTPException( status_code=400, detail="No domains found in input", ) # Remove duplicates while preserving order seen: set[str] = set() unique_domains: list[str] = [] for d in domains: if d.lower() not in seen: seen.add(d.lower()) unique_domains.append(d) try: vt_service = VirusTotalService() except APIKeyMissingError as e: logger.error(f"API key missing: {str(e)}") raise HTTPException(status_code=500, detail=str(e)) from e try: results: list[DomainResult] = [] for domain in unique_domains: result = _analyze_single_domain(domain, vt_service) results.append(result) return results except Exception as e: logger.error(f"Error processing domains: {str(e)}") raise HTTPException( status_code=500, detail=f"Error processing domains: {str(e)}" ) from e finally: vt_service.close() @router.post("/analyze/single", response_model=DomainResult) async def analyze_single_domain_endpoint( domain: str = Form(..., description="Single domain name to analyze"), ): """ Analyze a single domain using VirusTotal API. Args: domain: Single domain name to analyze Returns: DomainResult with analysis results Raises: HTTPException: If API key missing or analysis fails """ domain = domain.strip() if not domain: raise HTTPException( status_code=400, detail="Domain cannot be empty", ) try: vt_service = VirusTotalService() except APIKeyMissingError as e: logger.error(f"API key missing: {str(e)}") raise HTTPException(status_code=500, detail=str(e)) from e try: result = _analyze_single_domain(domain, vt_service) return result finally: vt_service.close() @router.post("/export") async def export_domain_results(results: list[DomainResult]): """ Export domain reputation results to TXT format. Args: results: List of DomainResult objects to export Returns: Plain text file with formatted results """ logger.info(f"Exporting {len(results)} domain results") lines: list[str] = [] lines.append("=" * 80) lines.append("IOC CORE - DOMAIN REPUTATION RESULTS") lines.append("=" * 80) lines.append("") for i, result in enumerate(results, 1): lines.append(f"[{i}] Domain: {result.domain}") lines.append("-" * 40) if result.error: lines.append(f" ERROR: {result.error}") else: malicious = result.malicious_count or 0 total = result.total_engines or 0 percentage = (malicious / total * 100) if total > 0 else 0 lines.append( f" Malicious: {malicious}/{total} engines ({percentage:.1f}%)" ) lines.append(f" Suspicious: {result.suspicious_count or 0}") lines.append(f" Harmless: {result.harmless_count or 0}") lines.append(f" Undetected: {result.undetected_count or 0}") lines.append(f" Reputation Score: {result.reputation_score or 0}") lines.append(f" Categories: {result.categories or 'N/A'}") if result.tags: lines.append(f" Tags: {', '.join(result.tags)}") lines.append(f" Registrar: {result.registrar or 'N/A'}") lines.append(f" Created: {result.creation_date or 'N/A'}") lines.append(f" Verdict: {'MALICIOUS' if malicious > 0 else 'CLEAN'}") lines.append("") lines.append("=" * 80) lines.append("") output = io.BytesIO("\n".join(lines).encode("utf-8")) output.seek(0) return StreamingResponse( output, media_type="text/plain", headers={"Content-Disposition": "attachment; filename=domain_reputation.txt"}, )