Spaces:
No application file

abello commited on
Commit
0af0f16
·
verified ·
1 Parent(s): 45e1bf9

Upload 7 files

Browse files
.dockerignore ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ **/__pycache__
2
+ **/.venv
3
+ **/.classpath
4
+ **/.dockerignore
5
+ **/.env
6
+ **/.git
7
+ **/.gitignore
8
+ **/.project
9
+ **/.settings
10
+ **/.toolstarget
11
+ **/.vs
12
+ **/.vscode
13
+ **/*.*proj.user
14
+ **/*.dbmdl
15
+ **/*.jfm
16
+ **/bin
17
+ **/charts
18
+ **/docker-compose*
19
+ **/compose*
20
+ **/Dockerfile*
21
+ **/node_modules
22
+ **/npm-debug.log
23
+ **/obj
24
+ **/secrets.dev.yaml
25
+ **/values.dev.yaml
26
+ LICENSE
27
+ README.md
Dockerfile ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # For more information, please refer to https://aka.ms/vscode-docker-python
2
+ FROM python:3-slim
3
+
4
+ EXPOSE 8000
5
+
6
+ # Keeps Python from generating .pyc files in the container
7
+ ENV PYTHONDONTWRITEBYTECODE=1
8
+
9
+ # Turns off buffering for easier container logging
10
+ ENV PYTHONUNBUFFERED=1
11
+
12
+ # Install pip requirements
13
+ COPY requirements.txt .
14
+ RUN python -m pip install -r requirements.txt
15
+
16
+ WORKDIR /app
17
+ COPY . /app
18
+
19
+ # Creates a non-root user with an explicit UID and adds permission to access the /app folder
20
+ # For more info, please refer to https://aka.ms/vscode-docker-python-configure-containers
21
+ RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /app
22
+ USER appuser
23
+
24
+ # During debugging, this entry point will be overridden. For more information, please refer to https://aka.ms/vscode-docker-python-debug
25
+ CMD ["gunicorn", "--bind", "0.0.0.0:8000", "-k", "uvicorn.workers.UvicornWorker", "src._main_v2:app"]
README.md CHANGED
@@ -1,12 +1,3 @@
1
- ---
2
- title: OSINT
3
- emoji: 🌖
4
- colorFrom: green
5
- colorTo: red
6
- sdk: docker
7
- pinned: false
8
- license: unknown
9
- short_description: OSINT prototype for acquiring and correlating information
10
- ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
+ # OSINT Early Warning System
 
 
 
 
 
 
 
 
 
2
 
3
+ Multi-source OSINT platform integrating IntelligenceX, Maltego, ENISA CVE DB, Shodan, VirusTotal, and others, for entity-based threat correlation and early warning risk assessment.
docker-compose.debug.yml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ services:
2
+ osintbsc:
3
+ image: osintbsc
4
+ build:
5
+ context: .
6
+ dockerfile: ./Dockerfile
7
+ command: ["sh", "-c", "pip install debugpy -t /tmp && python /tmp/debugpy --wait-for-client --listen 0.0.0.0:5678 -m uvicorn src._main_v2:app --host 0.0.0.0 --port 8000"]
8
+ ports:
9
+ - 8000:8000
10
+ - 5678:5678
docker-compose.yml ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ services:
2
+ osintbsc:
3
+ image: osintbsc
4
+ build:
5
+ context: .
6
+ dockerfile: ./Dockerfile
7
+ ports:
8
+ - 8000:8000
osint_simplified v16.py ADDED
@@ -0,0 +1,787 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ==============================================================================
2
+ # OSINT Risk Analyzer - Versión Optimizada y Corregida
3
+ # Análisis de correlación de riesgos y amenazas sin persistencia
4
+ # ==============================================================================
5
+
6
+ import asyncio
7
+ import aiohttp
8
+ import structlog
9
+ import hashlib
10
+ import re
11
+ import ipaddress
12
+ import json
13
+ from typing import Dict, List, Optional, Any, Union, Tuple
14
+ from datetime import datetime
15
+ from dataclasses import dataclass, asdict
16
+ from enum import Enum
17
+ import base64
18
+
19
+ from fastapi import FastAPI, HTTPException
20
+ from fastapi.middleware.cors import CORSMiddleware
21
+ from pydantic import BaseModel, Field, validator
22
+
23
+ # ==============================================================================
24
+ # CONFIGURATION
25
+ # ==============================================================================
26
+
27
+ @dataclass
28
+ class Config:
29
+ """Configuración centralizada del sistema"""
30
+ # API Keys
31
+ intelx_api_key: Optional[str] = None
32
+ shodan_api_key: Optional[str] = None
33
+ vt_api_key: Optional[str] = None
34
+
35
+ # Risk thresholds
36
+ risk_threshold_low: float = 0.3
37
+ risk_threshold_medium: float = 0.5
38
+ risk_threshold_high: float = 0.7
39
+ risk_threshold_critical: float = 0.9
40
+
41
+ # API timeouts
42
+ api_timeout: int = 30
43
+ max_concurrent_requests: int = 5
44
+
45
+ # Logging
46
+ log_level: str = "INFO"
47
+
48
+ # Instancia global de configuración
49
+ config = Config()
50
+
51
+ # ==============================================================================
52
+ # DATA MODELS
53
+ # ==============================================================================
54
+
55
+ class RiskLevel(str, Enum):
56
+ NONE = "none"
57
+ LOW = "low"
58
+ MEDIUM = "medium"
59
+ HIGH = "high"
60
+ CRITICAL = "critical"
61
+
62
+ class IOCType(str, Enum):
63
+ IP = "ip"
64
+ DOMAIN = "domain"
65
+ URL = "url"
66
+ HASH = "hash"
67
+ EMAIL = "email"
68
+ CVE = "cve"
69
+
70
+ @dataclass
71
+ class ThreatIntelligence:
72
+ """Modelo de inteligencia de amenazas"""
73
+ ioc_value: str
74
+ ioc_type: IOCType
75
+ source: str
76
+ confidence: float
77
+ risk_score: float
78
+ threat_level: RiskLevel
79
+ metadata: Dict[str, Any]
80
+ tags: List[str]
81
+ timestamp: datetime
82
+
83
+ @dataclass
84
+ class RiskAssessment:
85
+ """Evaluación de riesgo consolidada"""
86
+ target: str
87
+ overall_risk: RiskLevel
88
+ risk_score: float
89
+ confidence: float
90
+ threat_count: int
91
+ sources: List[str]
92
+ threats: List[ThreatIntelligence]
93
+ recommendations: List[str]
94
+ analysis_timestamp: datetime
95
+
96
+ # ==============================================================================
97
+ # PYDANTIC MODELS (para API)
98
+ # ==============================================================================
99
+
100
+ class AnalysisRequest(BaseModel):
101
+ targets: List[str] = Field(..., description="Lista de IOCs a analizar", min_items=1, max_items=50)
102
+ include_metadata: bool = Field(default=True, description="Incluir metadatos detallados")
103
+
104
+ @validator('targets')
105
+ def validate_targets(cls, v):
106
+ if not v:
107
+ raise ValueError('La lista de targets no puede estar vacía')
108
+ # Limpiar y validar básicamente
109
+ cleaned_targets = []
110
+ for target in v:
111
+ cleaned = target.strip()
112
+ if cleaned:
113
+ cleaned_targets.append(cleaned)
114
+ if not cleaned_targets:
115
+ raise ValueError('No hay targets válidos después de la limpieza')
116
+ return cleaned_targets
117
+
118
+ class AnalysisResponse(BaseModel):
119
+ request_id: str
120
+ timestamp: datetime
121
+ results: List[Dict[str, Any]]
122
+ summary: Dict[str, Any]
123
+ processing_time_seconds: float
124
+
125
+ # ==============================================================================
126
+ # UTILITIES
127
+ # ==============================================================================
128
+
129
+ class IOCValidator:
130
+ """Validador de IOCs optimizado"""
131
+
132
+ @staticmethod
133
+ def validate_ip(ip: str) -> bool:
134
+ """Validar dirección IP"""
135
+ try:
136
+ ipaddress.ip_address(ip)
137
+ return True
138
+ except ValueError:
139
+ return False
140
+
141
+ @staticmethod
142
+ def validate_domain(domain: str) -> bool:
143
+ """Validar nombre de dominio"""
144
+ if len(domain) > 253:
145
+ return False
146
+ pattern = r'^[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?)*$'
147
+ return bool(re.match(pattern, domain))
148
+
149
+ @staticmethod
150
+ def validate_url(url: str) -> bool:
151
+ """Validar URL"""
152
+ pattern = r'^https?://[^\s<>"{}|\\^`\[\]]+$'
153
+ return bool(re.match(pattern, url))
154
+
155
+ @staticmethod
156
+ def validate_hash(hash_value: str) -> bool:
157
+ """Validar hash (MD5, SHA1, SHA256)"""
158
+ if len(hash_value) not in [32, 40, 64]:
159
+ return False
160
+ return all(c in '0123456789abcdefABCDEF' for c in hash_value)
161
+
162
+ @staticmethod
163
+ def validate_email(email: str) -> bool:
164
+ """Validar dirección de email"""
165
+ pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
166
+ return bool(re.match(pattern, email))
167
+
168
+ @staticmethod
169
+ def validate_cve(cve: str) -> bool:
170
+ """Validar formato CVE"""
171
+ pattern = r'^CVE-\d{4}-\d{4,}$'
172
+ return bool(re.match(pattern, cve.upper()))
173
+
174
+ def detect_ioc_type(ioc: str) -> IOCType:
175
+ """Detectar tipo de IOC de forma optimizada"""
176
+ ioc_clean = ioc.strip()
177
+ validator = IOCValidator()
178
+
179
+ if validator.validate_cve(ioc_clean):
180
+ return IOCType.CVE
181
+ elif validator.validate_ip(ioc_clean):
182
+ return IOCType.IP
183
+ elif ioc_clean.startswith(('http://', 'https://')):
184
+ return IOCType.URL
185
+ elif '@' in ioc_clean and validator.validate_email(ioc_clean):
186
+ return IOCType.EMAIL
187
+ elif validator.validate_hash(ioc_clean):
188
+ return IOCType.HASH
189
+ elif '.' in ioc_clean and validator.validate_domain(ioc_clean):
190
+ return IOCType.DOMAIN
191
+ else:
192
+ return IOCType.DOMAIN # Default fallback
193
+
194
+ # ==============================================================================
195
+ # THREAT INTELLIGENCE CONNECTORS
196
+ # ==============================================================================
197
+
198
+ class BaseConnector:
199
+ """Clase base para conectores"""
200
+
201
+ def __init__(self, name: str):
202
+ self.name = name
203
+ self.timeout = config.api_timeout
204
+
205
+ async def search(self, ioc: str, session: aiohttp.ClientSession) -> Dict[str, Any]:
206
+ """Método base para búsqueda"""
207
+ raise NotImplementedError
208
+
209
+ def _create_base_result(self, found: bool = False, error: str = None) -> Dict[str, Any]:
210
+ """Crear resultado base"""
211
+ return {
212
+ "found": found,
213
+ "confidence": 0.0,
214
+ "risk_score": 0.0,
215
+ "metadata": {"source": self.name},
216
+ "error": error
217
+ }
218
+
219
+ class IntelligenceXConnector(BaseConnector):
220
+ """Conector para Intelligence X optimizado"""
221
+
222
+ def __init__(self, api_key: Optional[str] = None):
223
+ super().__init__("IntelligenceX")
224
+ self.api_key = api_key or config.intelx_api_key
225
+ self.base_url = "https://2.intelx.io"
226
+
227
+ async def search(self, ioc: str, session: aiohttp.ClientSession) -> Dict[str, Any]:
228
+ if not self.api_key:
229
+ return self._create_base_result(error="No API key configured")
230
+
231
+ try:
232
+ headers = {"x-key": self.api_key, "Content-Type": "application/json"}
233
+ data = {"term": ioc, "maxresults": 10, "media": 0}
234
+
235
+ async with session.post(
236
+ f"{self.base_url}/phonebook/search",
237
+ headers=headers,
238
+ json=data,
239
+ timeout=aiohttp.ClientTimeout(total=self.timeout)
240
+ ) as resp:
241
+ if resp.status == 200:
242
+ result = await resp.json()
243
+ return self._process_result(result)
244
+ else:
245
+ return self._create_base_result(error=f"HTTP {resp.status}")
246
+
247
+ except asyncio.TimeoutError:
248
+ return self._create_base_result(error="Timeout")
249
+ except Exception as e:
250
+ return self._create_base_result(error=str(e))
251
+
252
+ def _process_result(self, result: Dict) -> Dict[str, Any]:
253
+ selectors = result.get("selectors", [])
254
+ count = len(selectors)
255
+
256
+ if count == 0:
257
+ return self._create_base_result()
258
+
259
+ confidence = min(0.8, count * 0.1)
260
+ risk_score = min(0.7, count * 0.05)
261
+
262
+ return {
263
+ "found": True,
264
+ "confidence": confidence,
265
+ "risk_score": risk_score,
266
+ "count": count,
267
+ "data": selectors[:5],
268
+ "metadata": {
269
+ "source": self.name,
270
+ "total_results": count
271
+ }
272
+ }
273
+
274
+ class ShodanConnector(BaseConnector):
275
+ """Conector para Shodan optimizado"""
276
+
277
+ def __init__(self, api_key: Optional[str] = None):
278
+ super().__init__("Shodan")
279
+ self.api_key = api_key or config.shodan_api_key
280
+ self.base_url = "https://api.shodan.io"
281
+
282
+ async def search(self, ip: str, session: aiohttp.ClientSession) -> Dict[str, Any]:
283
+ if not self.api_key:
284
+ return self._create_base_result(error="No API key configured")
285
+
286
+ if not IOCValidator.validate_ip(ip):
287
+ return self._create_base_result(error="Not a valid IP address")
288
+
289
+ try:
290
+ params = {"key": self.api_key}
291
+
292
+ async with session.get(
293
+ f"{self.base_url}/shodan/host/{ip}",
294
+ params=params,
295
+ timeout=aiohttp.ClientTimeout(total=self.timeout)
296
+ ) as resp:
297
+ if resp.status == 200:
298
+ result = await resp.json()
299
+ return self._process_result(result)
300
+ elif resp.status == 404:
301
+ return self._create_base_result(error="IP not found")
302
+ else:
303
+ return self._create_base_result(error=f"HTTP {resp.status}")
304
+
305
+ except asyncio.TimeoutError:
306
+ return self._create_base_result(error="Timeout")
307
+ except Exception as e:
308
+ return self._create_base_result(error=str(e))
309
+
310
+ def _process_result(self, result: Dict) -> Dict[str, Any]:
311
+ vulns = result.get("vulns", [])
312
+ ports = result.get("ports", [])
313
+
314
+ # Calcular riesgo basado en vulnerabilidades y exposición
315
+ base_risk = 0.3 # Base score para IP expuesta
316
+ if vulns:
317
+ risk_score = 0.8 + min(0.2, len(vulns) * 0.02)
318
+ elif len(ports) > 10:
319
+ risk_score = 0.6
320
+ else:
321
+ risk_score = base_risk
322
+
323
+ return {
324
+ "found": True,
325
+ "confidence": 0.9,
326
+ "risk_score": risk_score,
327
+ "vulnerabilities": len(vulns),
328
+ "open_ports": len(ports),
329
+ "data": {
330
+ "vulns": vulns[:3], # Limitar vulnerabilidades mostradas
331
+ "ports": ports,
332
+ "org": result.get("org"),
333
+ "country": result.get("country_name"),
334
+ "city": result.get("city")
335
+ },
336
+ "metadata": {
337
+ "source": self.name,
338
+ "last_update": result.get("last_update")
339
+ }
340
+ }
341
+
342
+ class VirusTotalConnector(BaseConnector):
343
+ """Conector para VirusTotal optimizado"""
344
+
345
+ def __init__(self, api_key: Optional[str] = None):
346
+ super().__init__("VirusTotal")
347
+ self.api_key = api_key or config.vt_api_key
348
+ self.base_url = "https://www.virustotal.com/api/v3"
349
+
350
+ async def search(self, ioc: str, session: aiohttp.ClientSession) -> Dict[str, Any]:
351
+ if not self.api_key:
352
+ return self._create_base_result(error="No API key configured")
353
+
354
+ try:
355
+ headers = {"x-apikey": self.api_key}
356
+ endpoint = self._get_endpoint(ioc)
357
+
358
+ if not endpoint:
359
+ return self._create_base_result(error="Unsupported IOC type")
360
+
361
+ async with session.get(
362
+ f"{self.base_url}/{endpoint}",
363
+ headers=headers,
364
+ timeout=aiohttp.ClientTimeout(total=self.timeout)
365
+ ) as resp:
366
+ if resp.status == 200:
367
+ result = await resp.json()
368
+ return self._process_result(result)
369
+ elif resp.status == 404:
370
+ return self._create_base_result(error="IOC not found")
371
+ else:
372
+ return self._create_base_result(error=f"HTTP {resp.status}")
373
+
374
+ except asyncio.TimeoutError:
375
+ return self._create_base_result(error="Timeout")
376
+ except Exception as e:
377
+ return self._create_base_result(error=str(e))
378
+
379
+ def _get_endpoint(self, ioc: str) -> Optional[str]:
380
+ """Obtener endpoint correcto según tipo de IOC"""
381
+ ioc_type = detect_ioc_type(ioc)
382
+
383
+ if ioc_type == IOCType.IP:
384
+ return f"ip_addresses/{ioc}"
385
+ elif ioc_type == IOCType.DOMAIN:
386
+ return f"domains/{ioc}"
387
+ elif ioc_type == IOCType.URL:
388
+ # URLs necesitan encoding especial
389
+ url_id = base64.urlsafe_b64encode(ioc.encode()).decode().strip("=")
390
+ return f"urls/{url_id}"
391
+ elif ioc_type == IOCType.HASH:
392
+ return f"files/{ioc}"
393
+ else:
394
+ return None
395
+
396
+ def _process_result(self, result: Dict) -> Dict[str, Any]:
397
+ attributes = result.get("data", {}).get("attributes", {})
398
+ stats = attributes.get("last_analysis_stats", {})
399
+
400
+ malicious = stats.get("malicious", 0)
401
+ suspicious = stats.get("suspicious", 0)
402
+ harmless = stats.get("harmless", 0)
403
+ undetected = stats.get("undetected", 0)
404
+ total = malicious + suspicious + harmless + undetected
405
+
406
+ if total == 0:
407
+ return self._create_base_result()
408
+
409
+ # Calcular métricas
410
+ confidence = min(0.95, total / 50.0)
411
+ risk_score = (malicious * 0.9 + suspicious * 0.4) / total
412
+
413
+ return {
414
+ "found": True,
415
+ "confidence": confidence,
416
+ "risk_score": risk_score,
417
+ "malicious_count": malicious,
418
+ "suspicious_count": suspicious,
419
+ "total_scans": total,
420
+ "data": {
421
+ "stats": stats,
422
+ "reputation": attributes.get("reputation"),
423
+ "categories": attributes.get("categories", {}),
424
+ "last_analysis_date": attributes.get("last_analysis_date")
425
+ },
426
+ "metadata": {
427
+ "source": self.name,
428
+ "detection_ratio": f"{malicious}/{total}"
429
+ }
430
+ }
431
+
432
+ class ENISACVEConnector(BaseConnector):
433
+ """Conector para ENISA CVE optimizado"""
434
+
435
+ def __init__(self):
436
+ super().__init__("ENISA_CVE")
437
+ self.base_url = "https://cve.circl.lu/api"
438
+
439
+ async def search(self, cve_id: str, session: aiohttp.ClientSession) -> Dict[str, Any]:
440
+ if not IOCValidator.validate_cve(cve_id):
441
+ return self._create_base_result(error="Not a valid CVE format")
442
+
443
+ try:
444
+ async with session.get(
445
+ f"{self.base_url}/cve/{cve_id.upper()}",
446
+ timeout=aiohttp.ClientTimeout(total=self.timeout)
447
+ ) as resp:
448
+ if resp.status == 200:
449
+ result = await resp.json()
450
+ return self._process_result(result)
451
+ elif resp.status == 404:
452
+ return self._create_base_result(error="CVE not found")
453
+ else:
454
+ return self._create_base_result(error=f"HTTP {resp.status}")
455
+
456
+ except asyncio.TimeoutError:
457
+ return self._create_base_result(error="Timeout")
458
+ except Exception as e:
459
+ return self._create_base_result(error=str(e))
460
+
461
+ def _process_result(self, result: Dict) -> Dict[str, Any]:
462
+ if not result:
463
+ return self._create_base_result()
464
+
465
+ # Extraer CVSS score
466
+ cvss_score = self._extract_cvss_score(result)
467
+ severity = self._extract_severity(result)
468
+
469
+ # Calcular riesgo basado en CVSS
470
+ risk_score = min(1.0, cvss_score / 10.0) if cvss_score > 0 else 0.3
471
+ confidence = 0.95 # ENISA es fuente oficial
472
+
473
+ # Extraer descripción
474
+ description = ""
475
+ desc_data = result.get("description", {}).get("description_data", [])
476
+ if desc_data:
477
+ description = desc_data[0].get("value", "")
478
+
479
+ return {
480
+ "found": True,
481
+ "confidence": confidence,
482
+ "risk_score": risk_score,
483
+ "cvss_score": cvss_score,
484
+ "severity": severity,
485
+ "data": {
486
+ "id": result.get("id"),
487
+ "description": description[:200] + "..." if len(description) > 200 else description,
488
+ "published_date": result.get("publishedDate"),
489
+ "last_modified": result.get("lastModifiedDate")
490
+ },
491
+ "metadata": {
492
+ "source": self.name,
493
+ "cvss_score": cvss_score,
494
+ "severity": severity
495
+ }
496
+ }
497
+
498
+ def _extract_cvss_score(self, result: Dict) -> float:
499
+ """Extraer CVSS score (v3 preferido, v2 como fallback)"""
500
+ impact = result.get("impact", {})
501
+
502
+ # Intentar CVSS v3 primero
503
+ cvss_v3 = impact.get("baseMetricV3", {}).get("cvssV3", {})
504
+ if cvss_v3.get("baseScore"):
505
+ return float(cvss_v3["baseScore"])
506
+
507
+ # Fallback a CVSS v2
508
+ cvss_v2 = impact.get("baseMetricV2", {}).get("cvssV2", {})
509
+ if cvss_v2.get("baseScore"):
510
+ return float(cvss_v2["baseScore"])
511
+
512
+ return 0.0
513
+
514
+ def _extract_severity(self, result: Dict) -> str:
515
+ """Extraer severidad"""
516
+ impact = result.get("impact", {})
517
+
518
+ # CVSS v3
519
+ cvss_v3 = impact.get("baseMetricV3", {}).get("cvssV3", {})
520
+ if cvss_v3.get("baseSeverity"):
521
+ return cvss_v3["baseSeverity"].lower()
522
+
523
+ # Fallback basado en score
524
+ score = self._extract_cvss_score(result)
525
+ if score >= 9.0:
526
+ return "critical"
527
+ elif score >= 7.0:
528
+ return "high"
529
+ elif score >= 4.0:
530
+ return "medium"
531
+ elif score > 0:
532
+ return "low"
533
+ else:
534
+ return "unknown"
535
+
536
+ # ==============================================================================
537
+ # RISK ENGINE
538
+ # ==============================================================================
539
+
540
+ class RiskEngine:
541
+ """Motor de evaluación de riesgos optimizado"""
542
+
543
+ def __init__(self):
544
+ self.connectors = {
545
+ "intelx": IntelligenceXConnector(),
546
+ "shodan": ShodanConnector(),
547
+ "virustotal": VirusTotalConnector(),
548
+ "enisa_cve": ENISACVEConnector()
549
+ }
550
+
551
+ async def analyze_ioc(self, ioc: str) -> ThreatIntelligence:
552
+ """Analizar un único IOC"""
553
+ ioc_type = detect_ioc_type(ioc)
554
+
555
+ # Determinar qué conectores usar
556
+ applicable_connectors = self._get_applicable_connectors(ioc_type)
557
+
558
+ # Ejecutar búsquedas en paralelo
559
+ async with aiohttp.ClientSession(
560
+ timeout=aiohttp.ClientTimeout(total=config.api_timeout),
561
+ connector=aiohttp.TCPConnector(limit=10)
562
+ ) as session:
563
+
564
+ tasks = []
565
+ for connector_name in applicable_connectors:
566
+ connector = self.connectors[connector_name]
567
+ task = self._safe_search(connector, ioc, session)
568
+ tasks.append((connector_name, task))
569
+
570
+ # Ejecutar con límite de concurrencia
571
+ semaphore = asyncio.Semaphore(config.max_concurrent_requests)
572
+ results = await asyncio.gather(
573
+ *[self._limited_task(semaphore, name, task) for name, task in tasks],
574
+ return_exceptions=True
575
+ )
576
+
577
+ # Procesar resultados
578
+ return self._consolidate_results(ioc, ioc_type, results)
579
+
580
+ def _get_applicable_connectors(self, ioc_type: IOCType) -> List[str]:
581
+ """Determinar qué conectores usar según el tipo de IOC"""
582
+ connectors = ["intelx", "virustotal"] # Estos van para todos
583
+
584
+ if ioc_type == IOCType.IP:
585
+ connectors.append("shodan")
586
+ elif ioc_type == IOCType.CVE:
587
+ connectors.append("enisa_cve")
588
+ connectors.remove("virustotal") # VT no es útil para CVEs
589
+
590
+ return connectors
591
+
592
+ async def _safe_search(self, connector, ioc: str, session: aiohttp.ClientSession) -> Dict[str, Any]:
593
+ """Búsqueda segura con manejo de errores"""
594
+ try:
595
+ return await connector.search(ioc, session)
596
+ except Exception as e:
597
+ return {
598
+ "found": False,
599
+ "error": str(e),
600
+ "metadata": {"source": connector.name}
601
+ }
602
+
603
+ async def _limited_task(self, semaphore: asyncio.Semaphore, name: str, task) -> Tuple[str, Dict]:
604
+ """Ejecutar tarea con límite de concurrencia"""
605
+ async with semaphore:
606
+ result = await task
607
+ await asyncio.sleep(0.2) # Rate limiting
608
+ return (name, result)
609
+
610
+ def _consolidate_results(self, ioc: str, ioc_type: IOCType, results: List[Any]) -> ThreatIntelligence:
611
+ """Consolidar resultados de múltiples fuentes"""
612
+
613
+ # Filtrar y procesar resultados
614
+ valid_results = []
615
+ sources_used = []
616
+
617
+ for item in results:
618
+ if isinstance(item, Exception):
619
+ continue
620
+
621
+ if isinstance(item, tuple) and len(item) == 2:
622
+ source_name, result = item
623
+ if isinstance(result, dict):
624
+ result["_source_name"] = source_name
625
+ valid_results.append(result)
626
+ sources_used.append(source_name)
627
+
628
+ # Filtrar solo resultados exitosos
629
+ found_results = [r for r in valid_results if r.get("found", False)]
630
+
631
+ if not found_results:
632
+ return self._create_empty_threat(ioc, ioc_type, sources_used)
633
+
634
+ # Calcular métricas consolidadas
635
+ confidence = self._calculate_confidence(found_results)
636
+ risk_score = self._calculate_risk_score(found_results)
637
+ threat_level = self._calculate_threat_level(risk_score)
638
+
639
+ # Extraer información adicional
640
+ tags = self._extract_tags(found_results)
641
+ metadata = self._build_metadata(found_results, sources_used)
642
+ sources_with_data = [r["_source_name"] for r in found_results]
643
+
644
+ return ThreatIntelligence(
645
+ ioc_value=ioc,
646
+ ioc_type=ioc_type,
647
+ source=",".join(sources_with_data),
648
+ confidence=round(confidence, 3),
649
+ risk_score=round(risk_score, 3),
650
+ threat_level=threat_level,
651
+ metadata=metadata,
652
+ tags=tags,
653
+ timestamp=datetime.utcnow()
654
+ )
655
+
656
+ def _create_empty_threat(self, ioc: str, ioc_type: IOCType, sources: List[str]) -> ThreatIntelligence:
657
+ """Crear objeto de amenaza vacío"""
658
+ return ThreatIntelligence(
659
+ ioc_value=ioc,
660
+ ioc_type=ioc_type,
661
+ source="none",
662
+ confidence=0.0,
663
+ risk_score=0.0,
664
+ threat_level=RiskLevel.NONE,
665
+ metadata={"sources_checked": sources, "total_detections": 0},
666
+ tags=[],
667
+ timestamp=datetime.utcnow()
668
+ )
669
+
670
+ def _calculate_confidence(self, results: List[Dict]) -> float:
671
+ """Calcular confianza consolidada"""
672
+ if not results:
673
+ return 0.0
674
+
675
+ # Promedio ponderado por fuente
676
+ weights = {
677
+ "VirusTotal": 0.3,
678
+ "ENISA_CVE": 0.4,
679
+ "Shodan": 0.2,
680
+ "IntelligenceX": 0.1
681
+ }
682
+
683
+ weighted_sum = 0.0
684
+ total_weight = 0.0
685
+
686
+ for result in results:
687
+ source = result.get("_source_name", "")
688
+ confidence = result.get("confidence", 0.0)
689
+ weight = weights.get(source, 0.1)
690
+
691
+ weighted_sum += confidence * weight
692
+ total_weight += weight
693
+
694
+ base_confidence = weighted_sum / total_weight if total_weight > 0 else 0.0
695
+
696
+ # Boost por múltiples fuentes
697
+ if len(results) > 1:
698
+ boost = min(0.2, (len(results) - 1) * 0.05)
699
+ base_confidence = min(1.0, base_confidence + boost)
700
+
701
+ return base_confidence
702
+
703
+ def _calculate_risk_score(self, results: List[Dict]) -> float:
704
+ """Calcular score de riesgo consolidado"""
705
+ if not results:
706
+ return 0.0
707
+
708
+ # Usar el score más alto como base
709
+ max_risk = max(r.get("risk_score", 0.0) for r in results)
710
+
711
+ # Aplicar factores específicos
712
+ for result in results:
713
+ source = result.get("_source_name", "")
714
+
715
+ # Boost por vulnerabilidades críticas
716
+ if source == "ENISA_CVE":
717
+ cvss = result.get("cvss_score", 0.0)
718
+ if cvss >= 9.0:
719
+ max_risk = min(1.0, max_risk + 0.1)
720
+
721
+ # Boost por detecciones múltiples en VT
722
+ elif source == "VirusTotal":
723
+ malicious = result.get("malicious_count", 0)
724
+ if malicious > 5:
725
+ max_risk = min(1.0, max_risk + 0.1)
726
+
727
+ return max_risk
728
+
729
+ def _calculate_threat_level(self, risk_score: float) -> RiskLevel:
730
+ """Calcular nivel de amenaza"""
731
+ if risk_score >= config.risk_threshold_critical:
732
+ return RiskLevel.CRITICAL
733
+ elif risk_score >= config.risk_threshold_high:
734
+ return RiskLevel.HIGH
735
+ elif risk_score >= config.risk_threshold_medium:
736
+ return RiskLevel.MEDIUM
737
+ elif risk_score >= config.risk_threshold_low:
738
+ return RiskLevel.LOW
739
+ else:
740
+ return RiskLevel.NONE
741
+
742
+ def _extract_tags(self, results: List[Dict]) -> List[str]:
743
+ """Extract relevant tags from analysis results."""
744
+ tags = set()
745
+ for result in results:
746
+ source = result.get("_source_name", "")
747
+ if source == "Shodan":
748
+ tags.add("infrastructure")
749
+ if result.get("vulnerabilities", 0) > 0:
750
+ tags.add("vulnerable")
751
+ if result.get("open_ports", 0) > 20:
752
+ tags.add("highly-exposed")
753
+ elif source == "VirusTotal":
754
+ if result.get("malicious_count", 0) > 0:
755
+ tags.add("malicious")
756
+ if result.get("suspicious_count", 0) > 0:
757
+ tags.add("suspicious")
758
+ if result.get("malicious_count", 0) > 5:
759
+ tags.add("confirmed-malicious")
760
+ elif source == "ENISA_CVE":
761
+ tags.add("vulnerability")
762
+ severity = result.get("severity", "")
763
+ if severity in ("critical", "high"):
764
+ tags.add("high-severity")
765
+ if result.get("cvss_score", 0) >= 7.0:
766
+ tags.add("exploitable")
767
+ elif source == "IntelligenceX":
768
+ if result.get("count", 0) > 10:
769
+ tags.add("well-documented")
770
+ # Sort for deterministic output and limit to 8 tags
771
+ return sorted(tags)[:8]
772
+
773
+ def _build_metadata(self, results: List[Dict], all_sources: List[str]) -> Dict[str, Any]:
774
+ """Build consolidated metadata from results."""
775
+ metadata = {
776
+ "sources_checked": all_sources,
777
+ "sources_with_data": [r.get("_source_name", "") for r in results],
778
+ "total_detections": len(results),
779
+ "analysis_details": {}
780
+ }
781
+ for result in results:
782
+ source = result.get("_source_name", "")
783
+ metadata["analysis_details"][source] = {
784
+ "confidence": result.get("confidence", 0.0),
785
+ "risk_score": result.get("risk_score", 0.0),
786
+ }
787
+ return metadata
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # To ensure app dependencies are ported from your virtual environment/host machine into your container, run 'pip freeze > requirements.txt' in the terminal to overwrite this file
2
+ fastapi[all]==0.109.0
3
+ uvicorn[standard]==0.27.0
4
+ gunicorn==21.2.0