- Do you work in a **cybersecurity company**? Do you want to see your **company advertised in HackTricks**? or do you want to have access to the **latest version of the PEASS or download HackTricks in PDF**? Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
- **Join the** [**💬**](https://emojipedia.org/speech-balloon/) [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** [**🐦**](https://github.com/carlospolop/hacktricks/tree/7af18b62b3bdc423e11444677a6a73d4043511e9/\[https:/emojipedia.org/bird/README.md)[**@carlospolopm**](https://twitter.com/carlospolopm)**.**
**The content of this post was extracted from** [**https://soroush.secproject.com/blog/2019/04/exploiting-deserialisation-in-asp-net-via-viewstate/**](https://soroush.secproject.com/blog/2019/04/exploiting-deserialisation-in-asp-net-via-viewstate/)
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:
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 [\[13\]](https://docs.microsoft.com/en-us/dotnet/api/system.web.configuration.machinekeysection) for more details.
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 [\[3\]](https://devblogs.microsoft.com/aspnet/farewell-enableviewstatemac/) 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_” [\[4\]](https://www.owasp.org/index.php/Anti\_CSRF\_Tokens\_ASP.NET), it is s**till possible to disable the MAC validation feature by setting** the `AspNetEnforceViewStateMac` registry key to zero in:
When ViewState MAC validation has been **disabled**, the [YSoSerial.Net](https://github.com/pwntester/ysoserial.net) project can be used to generate `LosFormatter` payloads as the ViewState in order to run arbitrary code on the server.
**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:
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:
In older versions (**prior to 4.5**), .NET Framework uses the **`TemplateSourceDirectory`** property [\[15\]](https://docs.microsoft.com/en-us/dotnet/api/system.web.ui.control.templatesourcedirectory) 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**.
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.
The ASP.NET ViewState contains a property called `ViewStateUserKey` [\[16\]](https://docs.microsoft.com/en-us/previous-versions/dotnet/articles/ms972969\(v=msdn.10\)) that can be used to mitigate risks of cross-site request forgery (CSRF) attacks [\[4\]](https://www.owasp.org/index.php/Anti\_CSRF\_Tokens\_ASP.NET). 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 ([\[17\]](https://software-security.sans.org/developer-how-to/developer-guide-csrf) shows an implemented example).
In YSoSerial.Net master and YSoSerial.Netv2 you can find a plugin ([**this**](https://github.com/pwntester/ysoserial.net/blob/master/ysoserial/Plugins/ViewStatePlugin.cs) and [**this**](https://github.com/pwntester/ysoserial.net/blob/v2/ysoserial/Plugins/ViewStatePlugin.cs)) to exploit this technique when all the information is known.
_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**:_
**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.
You can check [\[20\]](https://docs.microsoft.com/en-us/iis/get-started/planning-your-iis-architecture/understanding-sites-applications-and-virtual-directories-on-iis) if you are not familiar with virtual directory and application terms in IIS.
In order to generate a ViewState for the above URL, the `--path` and `--apppath` arguments should be as follows:
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).
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.
In order to exploit applications that use .NET Framework v4.0 or below, the YSoSerial.Net v2.0 branch [\[21\]](https://github.com/nccgroup/VulnerableDotNetHTTPRemoting/tree/master/ysoserial.net-v2) can be used (this was originally developed as part of another research [\[22\]](https://www.nccgroup.trust/uk/about-us/newsroom-and-events/blogs/2019/march/finding-and-exploiting-.net-remoting-over-http-using-deserialisation/)). 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 [\[29\]](https://vimeopro.com/user18478112/canvas/video/260982761). The following tools were also released coincidentally at the same time as I was about to publish my work which was quite surprising:
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.
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.
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.
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.
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.
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**.
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:
```markup
<asp:TextBoxrunat="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:
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.
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:
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:
- Do you work in a **cybersecurity company**? Do you want to see your **company advertised in HackTricks**? or do you want to have access to the **latest version of the PEASS or download HackTricks in PDF**? Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
- **Join the** [**💬**](https://emojipedia.org/speech-balloon/) [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** [**🐦**](https://github.com/carlospolop/hacktricks/tree/7af18b62b3bdc423e11444677a6a73d4043511e9/\[https:/emojipedia.org/bird/README.md)[**@carlospolopm**](https://twitter.com/carlospolopm)**.**