Spaces:
Running

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