Spaces:
Running

File size: 9,333 Bytes
90531db
 
 
 
 
7fddf3d
90531db
 
 
 
 
dd1eee1
7fddf3d
 
 
 
 
 
90531db
 
 
 
 
7fddf3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd1eee1
7fddf3d
 
 
dd1eee1
 
 
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
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
"""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"},
    )