Spaces:
Running

File size: 14,364 Bytes
90531db
 
 
 
 
7fddf3d
90531db
 
 
 
 
dd1eee1
90531db
7fddf3d
 
 
 
 
 
 
90531db
 
 
 
 
7fddf3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb36037
7fddf3d
 
 
 
 
 
 
 
 
 
 
 
eb36037
 
 
 
 
 
 
 
 
 
 
 
 
7fddf3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd1eee1
7fddf3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd1eee1
7fddf3d
 
 
 
 
dd1eee1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7fddf3d
 
90531db
7fddf3d
 
 
 
 
 
 
 
90531db
7fddf3d
 
 
 
 
90531db
7fddf3d
90531db
 
7fddf3d
 
90531db
 
 
 
 
7fddf3d
90531db
7fddf3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90531db
 
 
 
 
 
 
 
 
 
 
 
 
7fddf3d
 
 
 
90531db
 
 
 
7fddf3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90531db
7fddf3d
 
 
 
 
 
eb36037
 
 
 
 
 
 
 
 
 
 
7fddf3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90531db
7fddf3d
 
 
 
90531db
 
 
 
 
 
 
 
7fddf3d
90531db
 
 
 
 
7fddf3d
90531db
7fddf3d
90531db
7fddf3d
 
 
 
 
 
 
90531db
 
 
7fddf3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90531db
 
 
 
7fddf3d
 
90531db
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
"""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"},
    )