Spaces:
Running

ioc-core / src /api /ip.py
hellium1999's picture
Update IP classification, unified API, and threat analyzer
eb36037
Raw History Blame
14.4 kB
"""API endpoints for IP 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.ip import AbuseIPDBResult, IPReputationResult, VirusTotalIPResult
from src.services import AbuseIPDBService, VirusTotalService
from src.services.stats import stats_service
from src.utils.helpers import get_country_name
from src.utils.validators import (
is_private_ip,
parse_iocs_from_file,
parse_iocs_from_text,
validate_ip,
validate_txt_file,
)
logger = logging.getLogger(__name__)
router = APIRouter()
def _analyze_single_ip(
ip: str,
vt_service: VirusTotalService | None,
abuseipdb_service: AbuseIPDBService | None,
) -> IPReputationResult:
"""
Analyze a single IP address using both services.
Args:
ip: IP address to analyze
vt_service: VirusTotal service instance (None for private IPs)
abuseipdb_service: AbuseIPDB service instance (None for private IPs)
Returns:
IPReputationResult with combined analysis results
"""
ip = ip.strip()
logger.info(f"Analyzing IP: {ip}")
# Validate IP format
if not validate_ip(ip):
error_msg = "Invalid IP address format"
return IPReputationResult(
abuseipdb=AbuseIPDBResult(ip_address=ip, error=error_msg),
virustotal=VirusTotalIPResult(vt_ip_address=ip, error=error_msg),
)
# Check if IP is private - skip API calls
if is_private_ip(ip):
logger.info(f"Private IP detected, skipping API calls: {ip}")
result = IPReputationResult(
abuseipdb=AbuseIPDBResult(
ip_address=ip,
is_private=True,
error="Private/Reserved IP - API lookup skipped",
),
virustotal=VirusTotalIPResult(
vt_ip_address=ip,
is_private=True,
error="Private/Reserved IP - API lookup skipped",
),
)
# Log to dashboard analytics
try:
stats_service.log_lookup(
ioc_value=ip,
ioc_type="ip",
verdict="private ip",
country_code=None,
)
except Exception:
pass
return result
# AbuseIPDB check
abuseipdb_result: AbuseIPDBResult
try:
abuseipdb_data = abuseipdb_service.check_ip(ip)
abuseipdb_result = AbuseIPDBResult(
ip_address=ip,
is_private=False,
is_public=abuseipdb_data.get("is_public"),
ip_version=abuseipdb_data.get("ip_version"),
is_whitelisted=abuseipdb_data.get("is_whitelisted"),
abuse_confidence_score=abuseipdb_data.get("abuse_confidence_score"),
country_code=abuseipdb_data.get("country_code"),
country_name=get_country_name(abuseipdb_data.get("country_code", "")),
usage_type=abuseipdb_data.get("usage_type"),
isp=abuseipdb_data.get("isp"),
domain=abuseipdb_data.get("domain"),
hostnames=", ".join(abuseipdb_data.get("hostnames", [])),
is_tor=abuseipdb_data.get("is_tor"),
total_reports=abuseipdb_data.get("total_reports"),
num_distinct_users=abuseipdb_data.get("num_distinct_users"),
last_reported_at=abuseipdb_data.get("last_reported_at"),
)
except ExternalAPIError as e:
logger.error(f"AbuseIPDB error for {ip}: {str(e)}")
abuseipdb_result = AbuseIPDBResult(ip_address=ip, error=str(e))
except (ValueError, KeyError) as e:
logger.error(f"Unexpected AbuseIPDB error for {ip}: {str(e)}")
abuseipdb_result = AbuseIPDBResult(
ip_address=ip, error=f"AbuseIPDB error: {str(e)}"
)
# VirusTotal check
vt_result: VirusTotalIPResult
try:
vt_data = vt_service.analyze_ip(ip)
if vt_data.get("found"):
vt_result = VirusTotalIPResult(
vt_ip_address=ip,
is_private=False,
vt_country=vt_data.get("country"),
vt_continent=vt_data.get("continent"),
vt_asn=vt_data.get("asn"),
vt_as_owner=vt_data.get("as_owner"),
vt_network=vt_data.get("network"),
vt_malicious_count=vt_data.get("malicious_count"),
vt_suspicious_count=vt_data.get("suspicious_count"),
vt_harmless_count=vt_data.get("harmless_count"),
vt_undetected_count=vt_data.get("undetected_count"),
vt_total_engines=vt_data.get("total_engines"),
vt_reputation_score=vt_data.get("reputation_score"),
vt_last_analysis_date=vt_data.get("last_analysis_date"),
vt_tags=vt_data.get("tags"),
vt_whois=vt_data.get("whois"),
)
else:
vt_result = VirusTotalIPResult(
vt_ip_address=ip, error="IP not found in VirusTotal database"
)
except ExternalAPIError as e:
logger.error(f"VirusTotal error for {ip}: {str(e)}")
vt_result = VirusTotalIPResult(vt_ip_address=ip, error=str(e))
except (ValueError, KeyError) as e:
logger.error(f"Unexpected VirusTotal error for {ip}: {str(e)}")
vt_result = VirusTotalIPResult(
vt_ip_address=ip, error=f"VirusTotal error: {str(e)}"
)
result = IPReputationResult(abuseipdb=abuseipdb_result, virustotal=vt_result)
# Log to dashboard analytics
try:
verdict = "unknown"
abuse_score = getattr(abuseipdb_result, "abuse_confidence_score", None)
vt_malicious = getattr(vt_result, "vt_malicious_count", None)
if (abuse_score and abuse_score > 50) or (vt_malicious and vt_malicious > 0):
verdict = "malicious"
elif (abuse_score and abuse_score > 20) or (vt_malicious == 0):
verdict = "suspicious" if abuse_score and abuse_score > 20 else "clean"
stats_service.log_lookup(
ioc_value=ip,
ioc_type="ip",
verdict=verdict,
country_code=getattr(abuseipdb_result, "country_code", None),
)
except Exception:
pass # Never let stats logging break the main flow
return result
@router.post("/analyze", response_model=list[IPReputationResult])
async def analyze_ips(
text_input: str | None = Form(
None, description="IP addresses (comma or newline separated)"
),
file: UploadFile | None = File(
None, description="TXT file containing IPs, one per line"
),
):
"""
Analyze IP addresses using AbuseIPDB and VirusTotal APIs.
Accepts either:
- text_input: IP addresses (comma or newline separated)
- file: A .txt file containing IP addresses (one per line)
Private IPs (192.168.x.x, 10.x.x.x, etc.) are detected and skipped.
Args:
text_input: Text containing IP addresses
file: TXT file containing IP addresses
Returns:
List of IPReputationResult objects with analysis from both providers
Raises:
HTTPException: If no input provided, API keys 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 IPs from input
ips: list[str] = []
if text_input:
ips.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")
ips.extend(parse_iocs_from_file(file_content))
if not ips:
raise HTTPException(
status_code=400,
detail="No IP addresses found in input",
)
# Remove duplicates while preserving order
seen: set[str] = set()
unique_ips: list[str] = []
for ip in ips:
if ip.lower() not in seen:
seen.add(ip.lower())
unique_ips.append(ip)
# Initialize services
try:
vt_service = VirusTotalService()
abuseipdb_service = AbuseIPDBService()
except APIKeyMissingError as e:
logger.error(f"API key missing: {str(e)}")
raise HTTPException(
status_code=500,
detail="Both AbuseIPDB and VirusTotal API keys are required",
) from e
try:
results: list[IPReputationResult] = []
for ip in unique_ips:
result = _analyze_single_ip(ip, vt_service, abuseipdb_service)
results.append(result)
return results
except Exception as e:
logger.error(f"Error processing IPs: {str(e)}")
raise HTTPException(
status_code=500, detail=f"Error processing IPs: {str(e)}"
) from e
finally:
vt_service.close()
abuseipdb_service.close()
@router.post("/analyze/single", response_model=IPReputationResult)
async def analyze_single_ip_endpoint(
ip_address: str = Form(..., description="Single IP address to analyze"),
):
"""
Analyze a single IP address using AbuseIPDB and VirusTotal APIs.
Private IPs are detected and skipped.
Args:
ip_address: Single IP address to analyze
Returns:
IPReputationResult with combined analysis from both providers
Raises:
HTTPException: If API keys missing or analysis fails
"""
ip_address = ip_address.strip()
if not ip_address:
raise HTTPException(
status_code=400,
detail="IP address cannot be empty",
)
# Check for private IP before initializing services
if is_private_ip(ip_address):
# Log to dashboard analytics
try:
stats_service.log_lookup(
ioc_value=ip_address,
ioc_type="ip",
verdict="private ip",
country_code=None,
)
except Exception:
pass
return IPReputationResult(
abuseipdb=AbuseIPDBResult(
ip_address=ip_address,
is_private=True,
error="Private/Reserved IP - API lookup skipped",
),
virustotal=VirusTotalIPResult(
vt_ip_address=ip_address,
is_private=True,
error="Private/Reserved IP - API lookup skipped",
),
)
# Initialize services
try:
vt_service = VirusTotalService()
abuseipdb_service = AbuseIPDBService()
except APIKeyMissingError as e:
logger.error(f"API key missing: {str(e)}")
raise HTTPException(
status_code=500,
detail="Both AbuseIPDB and VirusTotal API keys are required",
) from e
try:
result = _analyze_single_ip(ip_address, vt_service, abuseipdb_service)
return result
finally:
vt_service.close()
abuseipdb_service.close()
@router.post("/export")
async def export_ip_results(results: list[IPReputationResult]):
"""
Export IP reputation results to TXT format.
Args:
results: List of IPReputationResult objects to export
Returns:
Plain text file with formatted results
"""
logger.info(f"Exporting {len(results)} IP results")
lines: list[str] = []
lines.append("=" * 80)
lines.append("IOC CORE - IP REPUTATION RESULTS")
lines.append("=" * 80)
lines.append("")
for i, result in enumerate(results, 1):
abuseipdb = result.abuseipdb
vt = result.virustotal
lines.append(f"[{i}] IP Address: {abuseipdb.ip_address}")
if abuseipdb.is_private:
lines.append(" STATUS: PRIVATE/RESERVED IP - Skipped")
lines.append("")
lines.append("=" * 80)
lines.append("")
continue
lines.append("-" * 40)
# AbuseIPDB Results
lines.append(" ABUSEIPDB:")
if abuseipdb.error and not abuseipdb.is_private:
lines.append(f" ERROR: {abuseipdb.error}")
else:
lines.append(
f" Abuse Confidence Score: {abuseipdb.abuse_confidence_score or 0}%"
)
lines.append(f" Total Reports: {abuseipdb.total_reports or 0}")
lines.append(
f" Country: {abuseipdb.country_name or abuseipdb.country_code or 'N/A'}"
)
lines.append(f" ISP: {abuseipdb.isp or 'N/A'}")
lines.append(f" Usage Type: {abuseipdb.usage_type or 'N/A'}")
lines.append(f" Is Tor: {abuseipdb.is_tor or False}")
lines.append(f" Is Whitelisted: {abuseipdb.is_whitelisted or False}")
lines.append(f" Domain: {abuseipdb.domain or 'N/A'}")
lines.append(f" Hostnames: {abuseipdb.hostnames or 'N/A'}")
lines.append(f" Last Reported: {abuseipdb.last_reported_at or 'Never'}")
lines.append("")
# VirusTotal Results
lines.append(" VIRUSTOTAL:")
if vt.error and not vt.is_private:
lines.append(f" ERROR: {vt.error}")
else:
lines.append(
f" Malicious: {vt.vt_malicious_count or 0}/{vt.vt_total_engines or 0}"
)
lines.append(f" Suspicious: {vt.vt_suspicious_count or 0}")
lines.append(f" Reputation Score: {vt.vt_reputation_score or 0}")
lines.append(f" Country: {vt.vt_country or 'N/A'}")
lines.append(f" ASN: {vt.vt_asn or 'N/A'}")
lines.append(f" AS Owner: {vt.vt_as_owner or 'N/A'}")
lines.append(f" Network: {vt.vt_network or 'N/A'}")
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=ip_reputation.txt"},
)