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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
| #!/usr/bin/env python3
"""
CVE-2025-59718 Fortinet Authentication Bypass Checker
Detecta vulnerabilidad en FortiOS, FortiProxy, FortiSwitchManager y FortiWeb
Autor: m10sec
Versión: 1.2
"""
import argparse
import json
import re
import socket
import ssl
from dataclasses import dataclass, asdict
from typing import Optional, Tuple, List, Dict
from urllib.parse import urlparse
from http.client import HTTPSConnection
from datetime import datetime
import paramiko
from colorama import init, Fore, Style
init()
# ==================== BANNER Y UTILIDADES ====================
def banner():
print(Fore.GREEN + Style.BRIGHT + r"""
░▒▓████████▓▒░▒▓██████▓▒░░▒▓███████▓▒░▒▓████████▓▒░▒▓█▓▒░
░▒▓█▓▒░ ░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░ ░▒▓█▓▒░ ░▒▓█▓▒░
░▒▓█▓▒░ ░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░ ░▒▓█▓▒░ ░▒▓█▓▒░
░▒▓██████▓▒░░▒▓█▓▒░░▒▓█▓▒░▒▓███████▓▒░ ░▒▓█▓▒░ ░▒▓█▓▒░
░▒▓█▓▒░ ░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░ ░▒▓█▓▒░ ░▒▓█▓▒░
░▒▓█▓▒░ ░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░ ░▒▓█▓▒░ ░▒▓█▓▒░
░▒▓█▓▒░ ░▒▓██████▓▒░░▒▓█▓▒░░▒▓█▓▒░ ░▒▓█▓▒░ ░▒▓█▓▒░
""" + Style.RESET_ALL)
def print_banner():
print(" Fortinet Checker CVE-2025-59718 v1.3 ")
print(" by m10sec (2025) m10sec@proton.me ")
print(" CVEs: CVE-2025-59718 / CVE-2025-59719 ")
print("=" * 55)
print()
def c_ok(msg): return f"{Fore.GREEN}[+]{Style.RESET_ALL} {msg}"
def c_warn(msg): return f"{Fore.YELLOW}[!]{Style.RESET_ALL} {msg}"
def c_err(msg): return f"{Fore.RED}[X]{Style.RESET_ALL} {msg}"
def c_info(msg): return f"{Fore.CYAN}[*]{Style.RESET_ALL} {msg}"
def c_crit(msg): return f"{Fore.RED + Style.BRIGHT}[!!!]{Style.RESET_ALL} {msg}"
# ==================== VERSION HELPERS ====================
def parse_ver(v: str) -> Tuple[int, int, int]:
"""Parse version string to tuple (major, minor, patch)"""
m = re.match(r"^\s*(\d+)\.(\d+)\.(\d+)", v)
if not m:
raise ValueError(f"Version no parseable: {v!r}")
return tuple(map(int, m.groups()))
def in_range(v: Tuple[int, int, int], lo: Tuple[int, int, int], hi: Tuple[int, int, int]) -> bool:
"""Check if version is within range (inclusive)"""
return lo <= v <= hi
# ==================== FINDING MODEL ====================
@dataclass
class Finding:
target: str
mode: str # ssh|passive
host: str
port: int
product: Optional[str] = None
version: Optional[str] = None
vulnerable_version: Optional[bool] = None
forticloud_sso_enabled: Optional[bool] = None
# Final verdict: EXISTS / NOT_FOUND / POTENTIAL / UNKNOWN
verdict: str = "UNKNOWN"
# Additional metadata
confidence: str = "unknown" # high, medium, low
indicators: List[str] = None
notes: List[str] = None
def __post_init__(self):
if self.notes is None:
self.notes = []
if self.indicators is None:
self.indicators = []
# ==================== CVE DETECTION LOGIC ====================
def detect_product_and_version(status_output: str) -> Tuple[Optional[str], Optional[str]]:
"""Detect Fortinet product and version from system status output"""
# FortiOS/FortiProxy:
m = re.search(r"Version:\s*(FortiOS|FortiProxy)\s*v?(\d+\.\d+\.\d+)", status_output, re.IGNORECASE)
if m:
return m.group(1), m.group(2)
# FortiSwitchManager:
m2 = re.search(r"(FortiSwitchManager).*?v?(\d+\.\d+\.\d+)", status_output, re.IGNORECASE)
if m2:
return "FortiSwitchManager", m2.group(2)
# FortiWeb:
m3 = re.search(r"(FortiWeb).*?v?(\d+\.\d+\.\d+)", status_output, re.IGNORECASE)
if m3:
return "FortiWeb", m3.group(2)
return None, None
def is_vulnerable(product: Optional[str], version: Optional[str]) -> bool:
"""
Check if product version is vulnerable to CVE-2025-59718
Based on official Fortinet advisory FG-IR-25-647
"""
if not product or not version:
return False
try:
v = parse_ver(version)
except ValueError:
return False
p = product.lower()
# FortiOS vulnerable ranges
if p == "fortios":
return any([
in_range(v, parse_ver("7.6.0"), parse_ver("7.6.3")),
in_range(v, parse_ver("7.4.0"), parse_ver("7.4.8")),
in_range(v, parse_ver("7.2.0"), parse_ver("7.2.11")),
in_range(v, parse_ver("7.0.0"), parse_ver("7.0.17")),
])
# FortiProxy vulnerable ranges
if p == "fortiproxy":
return any([
in_range(v, parse_ver("7.6.0"), parse_ver("7.6.3")),
in_range(v, parse_ver("7.4.0"), parse_ver("7.4.10")),
in_range(v, parse_ver("7.2.0"), parse_ver("7.2.14")),
in_range(v, parse_ver("7.0.0"), parse_ver("7.0.21")),
])
# FortiSwitchManager vulnerable ranges
if p == "fortiswitchmanager":
return any([
in_range(v, parse_ver("7.2.0"), parse_ver("7.2.6")),
in_range(v, parse_ver("7.0.0"), parse_ver("7.0.5")),
])
# FortiWeb vulnerable ranges
if p == "fortiweb":
return any([
in_range(v, parse_ver("8.0.0"), parse_ver("8.0.0")),
in_range(v, parse_ver("7.6.0"), parse_ver("7.6.4")),
in_range(v, parse_ver("7.4.0"), parse_ver("7.4.9")),
# 7.2 and 7.0 NOT affected
])
return False
def get_patch_version(product: Optional[str], version: Optional[str]) -> Optional[str]:
"""Get recommended patch version for vulnerable products"""
if not product or not version:
return None
try:
v = parse_ver(version)
except ValueError:
return None
p = product.lower()
if p == "fortios":
if in_range(v, parse_ver("7.6.0"), parse_ver("7.6.3")):
return "7.6.4"
elif in_range(v, parse_ver("7.4.0"), parse_ver("7.4.8")):
return "7.4.9"
elif in_range(v, parse_ver("7.2.0"), parse_ver("7.2.11")):
return "7.2.12"
elif in_range(v, parse_ver("7.0.0"), parse_ver("7.0.17")):
return "7.0.18"
elif p == "fortiproxy":
if in_range(v, parse_ver("7.6.0"), parse_ver("7.6.3")):
return "7.6.4"
elif in_range(v, parse_ver("7.4.0"), parse_ver("7.4.10")):
return "7.4.11"
elif in_range(v, parse_ver("7.2.0"), parse_ver("7.2.14")):
return "7.2.15"
elif in_range(v, parse_ver("7.0.0"), parse_ver("7.0.21")):
return "7.0.22"
elif p == "fortiswitchmanager":
if in_range(v, parse_ver("7.2.0"), parse_ver("7.2.6")):
return "7.2.7"
elif in_range(v, parse_ver("7.0.0"), parse_ver("7.0.5")):
return "7.0.6"
elif p == "fortiweb":
if in_range(v, parse_ver("8.0.0"), parse_ver("8.0.0")):
return "8.0.1"
elif in_range(v, parse_ver("7.6.0"), parse_ver("7.6.4")):
return "7.6.5"
elif in_range(v, parse_ver("7.4.0"), parse_ver("7.4.9")):
return "7.4.10"
return None
def infer_forticloud_sso_enabled(global_output: str) -> Optional[bool]:
"""
Parse FortiCloud SSO login setting from system global output
Returns: True if enabled, False if disabled, None if unknown
"""
m = re.search(r"set\s+admin-forticloud-sso-login\s+(enable|disable)", global_output, re.IGNORECASE)
if not m:
return None
return m.group(1).lower() == "enable"
# ==================== TARGET PARSING ====================
def normalize_target_to_host_port(t: str, default_port: int) -> Tuple[str, int, str]:
"""
Parse target string to (host, port, original_string)
Accepts: IP, hostname, host:port, https://host[:port]/path, ssh://host[:port]
"""
t = t.strip()
if "://" in t:
u = urlparse(t)
host = u.hostname or t
port = u.port or (443 if u.scheme in ("https",) else default_port)
return host, port, t
# host:port format
if ":" in t and not re.match(r"^\[.*\]$", t):
host, p = t.rsplit(":", 1)
if p.isdigit():
return host.strip(), int(p), t
# host only
return t, default_port, t
def read_targets_file(path: str, default_port: int) -> List[Tuple[str, int, str]]:
"""Read targets from file (one per line, # for comments)"""
out = []
with open(path, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
host, port, raw = normalize_target_to_host_port(line, default_port)
out.append((host, port, raw))
return out
# ==================== SSH MODE ====================
def ssh_run(host: str, port: int, user: str, password: Optional[str],
keyfile: Optional[str], cmd: str, timeout=10) -> str:
"""Execute SSH command and return output"""
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
if keyfile:
pkey = paramiko.RSAKey.from_private_key_file(keyfile)
client.connect(host, port=port, username=user, pkey=pkey,
timeout=timeout, banner_timeout=timeout)
else:
client.connect(host, port=port, username=user, password=password,
timeout=timeout, banner_timeout=timeout)
_, stdout, stderr = client.exec_command(cmd, timeout=timeout)
out = stdout.read().decode(errors="ignore")
err = stderr.read().decode(errors="ignore")
return out + ("\n" + err if err.strip() else "")
finally:
client.close()
def check_ssh(host: str, port: int, raw: str, user: str,
password: Optional[str], keyfile: Optional[str],
timeout: int) -> Finding:
"""
SSH-based verification (most reliable)
Requires valid credentials
"""
notes: List[str] = []
indicators: List[str] = []
f = Finding(target=raw, mode="ssh", host=host, port=port,
notes=notes, indicators=indicators)
try:
print(c_info(f"Conectando vía SSH a {host}:{port}..."))
# Get system status
status = ssh_run(host, port, user, password, keyfile,
"get system status", timeout=timeout)
product, version = detect_product_and_version(status)
f.product, f.version = product, version
if not product or not version:
notes.append("No se pudo inferir producto/versión desde 'get system status'")
f.verdict = "UNKNOWN"
f.confidence = "low"
return f
indicators.append(f"Producto detectado: {product} v{version}")
# Check if version is vulnerable
f.vulnerable_version = is_vulnerable(product, version)
if f.vulnerable_version:
indicators.append(f"⚠️ Versión {version} está en rango VULNERABLE")
patch_version = get_patch_version(product, version)
if patch_version:
notes.append(f"Actualizar a versión {patch_version} o superior")
else:
indicators.append(f"✓ Versión {version} NO es vulnerable")
# Check FortiCloud SSO setting (only for FortiOS/FortiProxy)
if product and product.lower() in ("fortios", "fortiproxy"):
try:
glob = ssh_run(host, port, user, password, keyfile,
"show system global | grep -i admin-forticloud-sso-login",
timeout=timeout)
f.forticloud_sso_enabled = infer_forticloud_sso_enabled(glob) if glob else None
if f.forticloud_sso_enabled is True:
indicators.append("⚠️ FortiCloud SSO login está HABILITADO")
elif f.forticloud_sso_enabled is False:
indicators.append("✓ FortiCloud SSO login está DESHABILITADO")
else:
indicators.append("? No se pudo determinar estado de FortiCloud SSO")
except Exception as e:
notes.append(f"Error al verificar FortiCloud SSO: {e}")
# Final verdict logic
if f.vulnerable_version is True:
if f.forticloud_sso_enabled is True:
f.verdict = "EXISTS"
f.confidence = "high"
notes.append("🚨 CRÍTICO: Sistema VULNERABLE y FortiCloud SSO HABILITADO")
notes.append("🚨 Este sistema está siendo explotado activamente in-the-wild")
notes.append("🚨 ACCIÓN INMEDIATA REQUERIDA")
elif f.forticloud_sso_enabled is False:
f.verdict = "NOT_FOUND"
f.confidence = "high"
notes.append("Versión vulnerable pero FortiCloud SSO está deshabilitado")
notes.append("Sistema no explotable por esta vía (aún así, actualizar ASAP)")
else:
f.verdict = "POTENTIAL"
f.confidence = "medium"
notes.append("⚠️ Versión vulnerable, estado FortiCloud SSO desconocido")
notes.append("Verificar manualmente: System > Settings > FortiCloud SSO")
elif f.vulnerable_version is False:
f.verdict = "NOT_FOUND"
f.confidence = "high"
notes.append("Sistema no vulnerable (versión parcheada)")
else:
f.verdict = "UNKNOWN"
f.confidence = "low"
return f
except (paramiko.SSHException, socket.error, TimeoutError) as e:
f.verdict = "UNKNOWN"
f.confidence = "low"
notes.append(f"Error SSH: {type(e).__name__}: {e}")
return f
# ==================== ACTIVE VULNERABILITY TESTING ====================
def test_forticloud_sso_endpoint(host: str, port: int, timeout: int) -> Dict:
"""
Test if FortiCloud SSO authentication endpoint exists and is vulnerable
CVE-2025-59718: Improper Verification of Cryptographic Signature
Returns dict with:
- endpoint_exists: bool
- endpoint_accessible: bool
- response_code: int
- vulnerable_behavior: bool (indica comportamiento sospechoso)
"""
result = {
'endpoint_exists': False,
'endpoint_accessible': False,
'response_code': None,
'vulnerable_behavior': False,
'details': []
}
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
# Endpoints conocidos de FortiCloud SSO
test_endpoints = [
'/api/v2/authentication/forticloud',
'/api/v2/cmdb/system/admin',
'/remote/logincheck',
'/remote/fgt_lang',
]
for endpoint in test_endpoints:
try:
conn = HTTPSConnection(host, port=port, timeout=timeout, context=ctx)
# Test básico GET
conn.request("GET", endpoint)
resp = conn.getresponse()
body = resp.read().decode('utf-8', errors='ignore')
if resp.status != 404:
result['endpoint_exists'] = True
result['response_code'] = resp.status
result['details'].append(f"{endpoint}: HTTP {resp.status}")
# Comportamientos que indican FortiCloud SSO activo
if endpoint == '/api/v2/authentication/forticloud':
if resp.status in [200, 401, 403]:
result['endpoint_accessible'] = True
result['details'].append("FortiCloud auth endpoint responde")
# Si responde 200 sin autenticación válida = sospechoso
if resp.status == 200:
result['vulnerable_behavior'] = True
result['details'].append("⚠️ Endpoint responde 200 sin auth")
# Buscar indicadores en respuesta
if 'forticloud' in body.lower() or 'sso' in body.lower():
result['details'].append("Respuesta contiene referencias SSO")
# Otros endpoints que confirman FortiCloud habilitado
if 'forticloud' in body.lower():
result['details'].append(f"Referencias FortiCloud en {endpoint}")
conn.close()
except Exception as e:
result['details'].append(f"{endpoint}: {type(e).__name__}")
return result
def test_authentication_bypass(host: str, port: int, timeout: int) -> Dict:
"""
Prueba activa (no destructiva) de bypass de autenticación
CVE-2025-59718: Authentication bypass via cryptographic signature flaw
NOTA: Esta es una prueba SEGURA que solo verifica el comportamiento,
NO intenta explotar el sistema.
"""
result = {
'bypass_possible': False,
'evidence': [],
'test_performed': False
}
try:
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
conn = HTTPSConnection(host, port=port, timeout=timeout, context=ctx)
# Test 1: Intentar acceso a endpoint administrativo
conn.request("GET", "/api/v2/monitor/system/status")
resp = conn.getresponse()
body = resp.read().decode('utf-8', errors='ignore')
result['test_performed'] = True
# Si el endpoint responde con información sin credenciales = problema
if resp.status == 200:
if any(keyword in body.lower() for keyword in ['version', 'hostname', 'serial']):
result['bypass_possible'] = True
result['evidence'].append("API status endpoint accesible sin auth")
# Test 2: Verificar headers de respuesta
if 'x-frame-options' not in [h.lower() for h in resp.getheaders()]:
result['evidence'].append("Falta X-Frame-Options (configuración débil)")
conn.close()
except Exception as e:
result['evidence'].append(f"Test error: {type(e).__name__}")
return result
# ==================== PASSIVE MODE ====================
|