Spaces:
Running
Running
Download src/api/url.py from reputeradar/ioc-core: direct link, hf CLI and curl.
- Browser
- Download file 9.48 kB
-
https://huggingface.co/spaces/reputeradar/ioc-core/resolve/main/src/api/url.py
- Command line
-
hf download hf://spaces/reputeradar/ioc-core/src/api/url.py
-
curl -L -o url.py https://huggingface.co/spaces/reputeradar/ioc-core/resolve/main/src/api/url.py
9.48 kB
| """API endpoints for URL 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.url import UrlResult | |
| 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_txt_file, | |
| validate_url, | |
| ) | |
| logger = logging.getLogger(__name__) | |
| router = APIRouter() | |
| def _analyze_single_url(url: str, vt_service: VirusTotalService) -> UrlResult: | |
| """ | |
| Analyze a single URL using VirusTotal. | |
| Args: | |
| url: URL to analyze | |
| vt_service: VirusTotal service instance | |
| Returns: | |
| UrlResult with all available analysis data | |
| """ | |
| url = url.strip() | |
| logger.info(f"Analyzing URL: {url}") | |
| # Validate URL format | |
| if not validate_url(url): | |
| return UrlResult( | |
| url=url, | |
| error="Invalid URL format - must start with http:// or https://", | |
| ) | |
| try: | |
| analysis = vt_service.analyze_url(url) | |
| if not analysis.get("found"): | |
| result = UrlResult( | |
| url=url, | |
| error="URL 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 | |
| result = UrlResult( | |
| url=url, | |
| # Resolved info | |
| final_url=analysis.get("final_url"), | |
| title=analysis.get("title"), | |
| # 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, | |
| timeout_count=analysis.get("timeout_count", 0), | |
| malicious_percentage=round(malicious_percentage, 2), | |
| is_malicious=malicious > 0, | |
| # Reputation | |
| reputation_score=analysis.get("reputation_score"), | |
| categories=analysis.get("categories") or None, | |
| tags=analysis.get("tags") or None, | |
| # Metadata | |
| 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"), | |
| # HTTP response | |
| last_http_response_code=analysis.get("last_http_response_code"), | |
| last_http_response_content_length=analysis.get( | |
| "last_http_response_content_length" | |
| ), | |
| last_http_response_content_sha256=analysis.get( | |
| "last_http_response_content_sha256" | |
| ), | |
| # Page info | |
| trackers=analysis.get("trackers") or None, | |
| outgoing_links=analysis.get("outgoing_links") or None, | |
| ) | |
| except ExternalAPIError as e: | |
| logger.error(f"VirusTotal error for URL {url}: {str(e)}") | |
| result = UrlResult(url=url, error=str(e)) | |
| except (ValueError, KeyError) as e: | |
| logger.error(f"Unexpected error analyzing URL {url}: {str(e)}") | |
| result = UrlResult(url=url, 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=url, ioc_type="url", verdict=verdict) | |
| except Exception: | |
| pass # Never let stats logging break the main flow | |
| return result | |
| async def analyze_urls( | |
| text_input: str | None = Form( | |
| None, description="URLs (comma or newline separated)" | |
| ), | |
| file: UploadFile | None = File( | |
| None, description="TXT file containing URLs, one per line" | |
| ), | |
| ): | |
| """ | |
| Analyze URLs using VirusTotal API. | |
| Accepts either: | |
| - text_input: URLs (comma or newline separated) | |
| - file: A .txt file containing URLs (one per line) | |
| Args: | |
| text_input: Text containing URLs | |
| file: TXT file containing URLs | |
| Returns: | |
| List of UrlResult 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 URLs from input | |
| urls: list[str] = [] | |
| if text_input: | |
| urls.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") | |
| urls.extend(parse_iocs_from_file(file_content)) | |
| if not urls: | |
| raise HTTPException( | |
| status_code=400, | |
| detail="No URLs found in input", | |
| ) | |
| # Remove duplicates while preserving order | |
| seen: set[str] = set() | |
| unique_urls: list[str] = [] | |
| for u in urls: | |
| if u.lower() not in seen: | |
| seen.add(u.lower()) | |
| unique_urls.append(u) | |
| 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[UrlResult] = [] | |
| for url in unique_urls: | |
| result = _analyze_single_url(url, vt_service) | |
| results.append(result) | |
| return results | |
| except Exception as e: | |
| logger.error(f"Error processing URLs: {str(e)}") | |
| raise HTTPException( | |
| status_code=500, detail=f"Error processing URLs: {str(e)}" | |
| ) from e | |
| finally: | |
| vt_service.close() | |
| async def analyze_single_url_endpoint( | |
| url: str = Form(..., description="Single URL to analyze"), | |
| ): | |
| """ | |
| Analyze a single URL using VirusTotal API. | |
| Args: | |
| url: Single URL to analyze | |
| Returns: | |
| UrlResult with analysis results | |
| Raises: | |
| HTTPException: If API key missing or analysis fails | |
| """ | |
| url = url.strip() | |
| if not url: | |
| raise HTTPException( | |
| status_code=400, | |
| detail="URL 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_url(url, vt_service) | |
| return result | |
| finally: | |
| vt_service.close() | |
| async def export_url_results(results: list[UrlResult]): | |
| """ | |
| Export URL analysis results to TXT format. | |
| Args: | |
| results: List of UrlResult objects to export | |
| Returns: | |
| Plain text file with formatted results | |
| """ | |
| logger.info(f"Exporting {len(results)} URL results") | |
| lines: list[str] = [] | |
| lines.append("=" * 80) | |
| lines.append("IOC CORE - URL REPUTATION RESULTS") | |
| lines.append("=" * 80) | |
| lines.append("") | |
| for i, result in enumerate(results, 1): | |
| lines.append(f"[{i}] URL: {result.url}") | |
| lines.append("-" * 40) | |
| if result.error: | |
| lines.append(f" ERROR: {result.error}") | |
| else: | |
| lines.append(f" Final URL: {result.final_url or result.url}") | |
| lines.append(f" Title: {result.title or 'N/A'}") | |
| lines.append("") | |
| malicious = result.malicious_count or 0 | |
| total = result.total_engines or 0 | |
| lines.append(f" Malicious: {malicious}/{total} 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 Score: {result.reputation_score or 0}") | |
| if result.tags: | |
| lines.append(f" Tags: {', '.join(result.tags)}") | |
| lines.append(f" HTTP Status: {result.last_http_response_code or 'N/A'}") | |
| lines.append( | |
| f" Verdict: {'MALICIOUS' if result.is_malicious 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=url_reputation.txt"}, | |
| ) | |