"""API endpoints for hash 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.hash import HashResult from src.services import VirusTotalService from src.services.stats import stats_service from src.utils.validators import ( HashType, parse_iocs_from_file, parse_iocs_from_text, validate_hash, validate_txt_file, ) logger = logging.getLogger(__name__) router = APIRouter() def _analyze_single_hash(hash_value: str, vt_service: VirusTotalService) -> HashResult: """ Analyze a single hash value using VirusTotal. Args: hash_value: Hash string to analyze vt_service: VirusTotal service instance Returns: HashResult with all available analysis data """ hash_value = hash_value.strip() hash_type = validate_hash(hash_value) if hash_type == HashType.INVALID: logger.warning(f"Invalid hash format: {hash_value}") return HashResult( input_hash=hash_value, error="Invalid hash format - must be MD5 (32), SHA1 (40), or SHA256 (64) hex characters", ) try: analysis = vt_service.analyze_file_hash(hash_value) if not analysis.get("found"): result = HashResult( input_hash=hash_value, input_hash_type=hash_type.value, error="Hash not found in VirusTotal database", ) else: malicious = analysis.get("malicious_count", 0) total = analysis.get("total_engines", 0) malicious_percentage = (malicious / total * 100) if total > 0 else 0 # Get file name - prefer meaningful_name, fallback to first name in names array file_name = analysis.get("meaningful_name") names = analysis.get("names", []) if not file_name and names: file_name = names[0] result = HashResult( input_hash=hash_value, input_hash_type=hash_type.value, # All hashes md5=analysis.get("md5"), sha1=analysis.get("sha1"), sha256=analysis.get("sha256"), vhash=analysis.get("vhash"), ssdeep=analysis.get("ssdeep"), tlsh=analysis.get("tlsh"), # File info file_name=file_name, names=names if names else None, file_type=analysis.get("file_type"), file_size=analysis.get("size"), magic=analysis.get("magic"), type_tags=analysis.get("type_tags") or None, tags=analysis.get("tags") or None, # Detection stats malicious_count=malicious, suspicious_count=analysis.get("suspicious_count", 0), harmless_count=analysis.get("harmless_count", 0), undetected_count=analysis.get("undetected_count", 0), total_engines=total, malicious_percentage=round(malicious_percentage, 2), is_malicious=malicious > 0, # Metadata reputation=analysis.get("reputation"), times_submitted=analysis.get("times_submitted"), first_submission_date=analysis.get("first_submission_date"), last_submission_date=analysis.get("last_submission_date"), last_analysis_date=analysis.get("last_analysis_date"), last_modification_date=analysis.get("last_modification_date"), signature_info=analysis.get("signature_info"), ) except ExternalAPIError as e: logger.error(f"VirusTotal API error for hash {hash_value}: {str(e)}") result = HashResult( input_hash=hash_value, input_hash_type=hash_type.value, error=f"VirusTotal API error: {str(e)}", ) except (ValueError, KeyError) as e: logger.error(f"Unexpected error analyzing hash {hash_value}: {str(e)}") result = HashResult( input_hash=hash_value, input_hash_type=hash_type.value, error=f"Analysis error: {str(e)}", ) # Log to dashboard analytics try: verdict = "unknown" if result.error: verdict = "unknown" elif result.is_malicious: verdict = "malicious" elif result.suspicious_count and result.suspicious_count > 0: verdict = "suspicious" else: verdict = "clean" stats_service.log_lookup(ioc_value=hash_value, ioc_type="hash", verdict=verdict) except Exception: pass # Never let stats logging break the main flow return result @router.post("/analyze", response_model=list[HashResult]) async def analyze_hashes( text_input: str | None = Form( None, description="Hash values (comma or newline separated)" ), file: UploadFile | None = File( None, description="TXT file containing hashes, one per line" ), ): """ Analyze file hashes using VirusTotal API. Accepts either: - text_input: Hash values (comma or newline separated) - file: A .txt file containing hash values (one per line) Returns all corresponding hashes (MD5, SHA1, SHA256) regardless of input type. Args: text_input: Text containing hashes file: TXT file containing hashes Returns: List of HashResult objects with all corresponding hashes Raises: HTTPException: If no input provided, API key missing, or invalid format """ # Validate input - must provide either text or file 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 hashes from input hashes: list[str] = [] if text_input: hashes.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") hashes.extend(parse_iocs_from_file(file_content)) if not hashes: raise HTTPException( status_code=400, detail="No valid hashes found in input", ) # Remove duplicates while preserving order seen: set[str] = set() unique_hashes: list[str] = [] for h in hashes: if h.lower() not in seen: seen.add(h.lower()) unique_hashes.append(h) 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[HashResult] = [] for hash_value in unique_hashes: result = _analyze_single_hash(hash_value, vt_service) results.append(result) return results except Exception as e: logger.error(f"Error processing hashes: {str(e)}") raise HTTPException( status_code=500, detail=f"Error processing hashes: {str(e)}" ) from e finally: vt_service.close() @router.post("/analyze/single", response_model=HashResult) async def analyze_single_hash_endpoint( hash_value: str = Form(..., description="Single hash value to analyze"), ): """ Analyze a single file hash using VirusTotal API. Returns all corresponding hashes (MD5, SHA1, SHA256) regardless of input type. Args: hash_value: Single hash value to analyze Returns: HashResult with all corresponding hashes Raises: HTTPException: If API key missing or analysis fails """ hash_value = hash_value.strip() if not hash_value: raise HTTPException( status_code=400, detail="Hash value 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_hash(hash_value, vt_service) return result finally: vt_service.close() @router.post("/export") async def export_hash_results(results: list[HashResult]): """ Export hash analysis results to TXT format. Args: results: List of HashResult objects to export Returns: Plain text file with formatted results """ logger.info(f"Exporting {len(results)} hash results") lines: list[str] = [] lines.append("=" * 80) lines.append("IOC CORE - HASH ANALYSIS RESULTS") lines.append("=" * 80) lines.append("") for i, result in enumerate(results, 1): lines.append(f"[{i}] Input Hash: {result.input_hash}") lines.append(f" Hash Type: {result.input_hash_type or 'Unknown'}") lines.append("-" * 40) if result.error: lines.append(f" ERROR: {result.error}") else: lines.append(f" MD5: {result.md5 or 'N/A'}") lines.append(f" SHA1: {result.sha1 or 'N/A'}") lines.append(f" SHA256: {result.sha256 or 'N/A'}") if result.vhash: lines.append(f" VHash: {result.vhash}") if result.ssdeep: lines.append(f" SSDeep: {result.ssdeep}") lines.append("") lines.append(f" File Name: {result.file_name or 'N/A'}") lines.append(f" File Type: {result.file_type or 'N/A'}") lines.append(f" File Size: {result.file_size or 'N/A'} bytes") lines.append("") lines.append( f" Detection: {result.malicious_count or 0}/{result.total_engines or 0} engines" ) lines.append(f" Malicious: {result.malicious_percentage or 0}%") lines.append(f" Suspicious: {result.suspicious_count or 0}") lines.append(f" Harmless: {result.harmless_count or 0}") lines.append(f" Reputation: {result.reputation or 'N/A'}") lines.append( f" Verdict: {'MALICIOUS' if result.is_malicious else 'CLEAN'}" ) if result.tags: lines.append(f" Tags: {', '.join(result.tags)}") 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=hash_results.txt"}, )