Lately I have only published blog posts through the MDSec website. I thought it might be a good idea to link what I have published so far here as well:
COVID-19 has sadly affected many if not all of us. I hope everyone remains safe and we can all carry on the normal life we had before this crisis. Hopefully I can then publish more blog posts here as well.
This technique can come in handy when dealing with a file uploader that uses a blacklist approach to stop malicious extensions.
Interestingly, if you just search XAMLX in Google or Bing, this technique will be in the first page so it has taken over so many of its actual legitimate usage!
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("-"&"->")
' it is running the ASP code if you can see 3 by opening the web.config file!
Response.write(1+2)
Response.write("<!-"&"-")
%>
-->
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:
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:
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("-"&"->")
' it is running the ASP code if you can see 3 by opening the web.config file!
Response.write(1+2)
Response.write("<!-"&"-")
%>
-->
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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!):
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:
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.
When testing a website on IIS, it is sometimes important to know whether a path is an application or a folder (or a virtual folder). I am intruding a new sneaky method using some ASP.NET features that can be used to verify this in a blackbox assessment.
If we can upload a file in an IIS app rather than a folder,
we can do a lot more to gain RCE by uploading a web.config
or a resource
file for example as this is normally as effective as uploading a file on
the root of a website.
By sending one of the following GET requests to a path, if the application responds with the status code 200 Ok and some JavaScript code, it is an application. If it responds with the status code 500 Internal Error, it is a folder:
http(s)://target/path1/path2/profile_json_appservice.axd/jsdebug
or
http(s)://target/path1/path2/profile_json_appservice.axd/js
The Role_JSON_AppService.axd or Authentication_JSON_AppService.axd
can also be used instead of Profile_JSON_AppService.axd.
This would work even if these services
are disabled (default).
Here is an example that shows /start/ is an application:
When these services (Profile, Authentication, and Role) are enabled, it is also possible to send POST requests to their endpoints. Perhaps they should be reported as informational issues in an assessment in order to make sure they are really needed for the operation of the website. These web services might lead to information disclosure or password guessing attacks as well.
The following HTTP request shows a sample request to the login endpoint of the Authentication service:
POST /someapppath/authentication_json_appservice.axd/login HTTP/1.1
Host: target
Content-Length: 69
Content-Type: application/json
{"userName":"guest","password":"guest","createPersistentCookie":true}
In the Exploiting Deserialisation in ASP.NET via ViewState blog post, I explained how it is possible to run code on an ASP.NET web application using compromised Machine Key secrets. It covers cases in which the keys are hard coded and could be read using another vulnerability such as local file disclosure. However, most websites do not hard code these keys and use automatically generated values by ASP.NET. As a result, it is not simply possible to steal the keys by reading the configuration files.
Now I want to explain how hackers who have already exploited an ASP.NET application can read the auto generated parameters to maintain their access even after their original vulnerability has been patched.
This can also be abused very similar to a hidden key or a backdoor by malicious developers to execute code on a server when they do not have their access anymore.
What do
you do with a comprised box?
Assume this generic scenario: An outdated ASP.NET CMS on IIS
has been hacked using a vulnerability that has been patched in the latest
version of the software.
This is what we know:
The exploit and its patch
are public
A web shell was dropped
No other file changes have
been recorded
Database values have not
been modified by the attacker
No fixed machine key is in
the web.config file
This is what we have done after pulling the server offline:
The web server has been
restored to its pre-attack condition:
Web shell has been deleted
Database has been restored
to its pre-attack condition
Any potential data changes
have been reversed
The CMS application has
been updated
Vulnerability has been
patched
All the hardcoded secrets and
credentials within the application files or the database have been changed
Users’ passwords and other
sensitive tokens in the accessible databases have been reset
Can we go online now without risk of attackers coming
back?
Although some people may say “NO” for other reasons, I like
to say “NO” as the auto generated Machine Key might have been stolen! This can
be enough for hackers to run code on the server whenever they want.
Reading
the Generated Keys
Attackers should be able to calculate the validation and
decryption keys by reading the following registry keys (depends on the .NET
version):
These registry keys belong to the IIS user (Application Pool)
that runs the application.
However, when attackers can run ASP.NET code on the website,
it easier to extract the keys directly. It should be noted that used keys where
ASP.NET Framework 4.5 has been targeted are different than the previous versions.
Auto generated keys can have two modes:
IsolateApps
In this case, it uses the value of HttpRuntime.AppDomainAppVirtualPath (e.g. /dir/appname/) when transforming the auto-generated key to make the validation and decryption keys
IsolateByAppId
In this case, it uses the value of HttpRuntime.AppDomainAppId (e.g. /LM/W3SVC/1/ROOT/dir/appname/ where ‘1’ is the AppId) when transforming the auto-generated key to make the validation and decryption keys. This is useful when two different applications use the same virtual path so their keys will be different.
Different ASP.NET pages within the same application uses the
same set of transformed keys.
I have created a simple proof of concept code in the following GitHub gist in order to extract auto generated validation and decryption keys:
Create a new Application Pool for your ASP.NET application
when you need to reset all the credentials for any reasons. This will ensure
that a new ASP.NET key will be generated for the application.