Open Redirect – Bad Implementation

January 14, 2016 by · 1 Comment
Filed under: Security 

I was recently looking through some code and happen to stumble across some logic that is attempting to prohibit the application from redirecting to an external site. While this sounds like a pretty simple task, it is common to see it incorrectly implemented. Lets look at the check that is being performed.


	string url = Request.QueryString["returnUrl"];

	if (string.IsNullOrWhiteSpace(url) || !url.StartsWith("/"))
	{
		Response.Redirect("~/default.aspx");
	}
	else
	{
		Response.Redirect(url);
	}

The first thing I noticed was the line that checks to see if the url starts with a “/” characters. This is a common mistake when developers try to stop open redirection. The assumption is that to redirect to an external site one would need the protocol. For example, http://www.developsec.com. By forcing the url to start with the “/” character it is impossible to get the “http:” in there. Unfortunately, it is also possible to use //www.developsec.com as the url and it will also be interpreted as an absolute url. In the example above, by passing in returnUrl=//www.developsec.com the code will see the starting “/” character and allow the redirect. The browser would interpret the “//” as absolute and navigate to www.developsec.com.

After putting a quick test case together, I quickly proved out the point and was successful in bypassing this logic to enable a redirect to external sites.

Checking for Absolute or Relative Paths

ASP.Net has build in procedures for determining if a path is relative or absolute. The following code shows one way of doing this.

	string url = Request.QueryString["returnUrl"];
	Uri result;
    bool isAbsolute = false;

    isAbsolute = Uri.TryCreate(returnUrl, UriKind.Absolute, out result);

    if (!isAbsolute)
    {
         Response.Redirect(url);
    }
    else
    {
         Response.Redirect("~/default.aspx");
    }

In the above example, if the URL is absolute (starts with a protocol, http/https, or starts with “//”) it will just redirect to the default page. If the url is not absolute, but relative, it will redirect to the url passed in.

While doing some research I came across a recommendation to use the following:

	if (Uri.IsWellFormedUriString(returnUrl,UriKind.Relative))

When using the above logic, it flagged //www.developsec.com as a relative path which would not be what we are looking for. The previous logic correctly identified this as an absolute url. There may be other methods of doing this and MVC provides some other functions as well that we will cover in a different post.

Conclusion

Make sure that you have a solid understanding of the problem and the different ways it works. It is easy to overlook some of these different techniques. There is a lot to learn, and we should be learning every day.

.Net EnableHeaderChecking

November 9, 2015 by · Comments Off on .Net EnableHeaderChecking
Filed under: Security 

How often do you take untrusted input and insert it into response headers? This could be in a custom header or in the value of a cookie. Untrusted user data is always a concern when it comes to the security side of application development and response headers are no exception. This is referred to as Response Splitting or HTTP Header Injection.

Like Cross Site Scripting (XSS), HTTP Header Injection is an attack that results from untrusted data being used in a response. In this case, it is in a response header which means that the context is what we need to focus on. Remember that in XSS, context is very important as it defines the characters that are potentially dangerous. In the HTML context, characters like < and > are very dangerous. In Header Injection the greatest concern is over the carriage return (%0D or \r) and new line (%0A or \n) characters, or CRLF. Response headers are separated by CRLF, indicating that if you can insert a CRLF then you can start creating your own headers or even page content.

Manipulating the headers may allow you to redirect the user to a different page, perform cross-site scripting attacks, or even rewrite the page. While commonly overlooked, this is a very dangerous flaw.

ASP.Net has a built in defense mechanism that is enabled by default called EnableHeaderChecking. When EnableHeaderChecking is enabled, CRLF characters are converted to %0D%0A and the browser does not recognize it as a new line. Instead, it is just displayed as characters, not actually creating a line break. The following code snippet was created to show how the response headers look when adding CRLF into a header.

    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.AppendHeader("test", "tes%0D%0At\r\ntest2");
            Response.Cookies.Add(new HttpCookie("Test-Cookie", "Another%0D%0ATest\r\nCookie"));
        }
    }

When the application runs, it will properly encode the CRLF as shown in the image below.

EnableHeader1

My next step was to disable EnableHeaderChecking in the web.config file.

	 <httpRuntime targetFramework="4.6" enableHeaderChecking="false"/>

My expectation was that I would get a response that allowed the CRLF and would show me a line break in the response headers. To my surprise, I got the error message below:

EnableHeader2

So why the error? After doing a little Googling I found an article about ASP.Net 2.0 Breaking Changes on IIS 7.0. The item of interest is “13. IIS always rejects new lines in response headers (even if ASP.NET enableHeaderChecking is set to false)”

I didn’t realize this change had been implemented, but apparently, if using IIS 7.0 or above, ASP.Net won’t allow newline characters in a response header. This is actually good news as there is very little reason to allow new lines in a response header when if that was required, just create a new header. This is a great mitigation and with the default configuration helps protect ASP.Net applications from Response Splitting and HTTP Header Injection attacks.

Understanding the framework that you use and the server it runs on is critical in fully understanding your security risks. These built in features can really help protect an application from security risks. Happy and Secure coding!

I did a podcast on this topic which you can find on the DevelopSec podcast.

Potentially Dangerous Request.Path Value was Detected…

November 4, 2015 by · Comments Off on Potentially Dangerous Request.Path Value was Detected…
Filed under: Development, Security 

I have discussed request validation many times when we see the potentially dangerous input error message when viewing a web page. Another interesting protection in ASP.Net is the built-in, on by default, Request.Path validation that occurs. Have you ever seen the error below when using or testing your application?

Pdc1

The screen above occurred because I placed the (*) character in the URL. In ASP.Net, there is a default set of defined illegal characters in the URL. This list is defined by RequestPathInvalidCharacters and can be configured in the web.config file. By default, the following characters are blocked:

  • <
  • >
  • *
  • %
  • &
  • :
  • \\

It is important to note that these characters are blocked from being included in the URL, this does not include the protocol specification or the query string. That should be obvious since the query string uses the & character to separate parameters.

There are not many cases where your URL needs to use any of these default characters, but if there is a need to allow a specific character, you can override the default list. The override is done in the web.config file. The below snippet shows setting the new values (removing the < and > characters:

	<httpruntime requestPathInvalidCharacters="*,%,&,:,\\"/>

Be aware that due the the web.config file being an xml file, you need to escape the < and > characters and set them as &lt; and &gt; respectively.

Remember that modifying the default security settings can expose your application to a greater security risk. Make sure you understand the risk of making these modifications before you perform them. It should be a rare occurrence to require a change to this default list. Understanding the platform is critical to understanding what is and is not being protected by default.

Securing The .Net Cookies

October 13, 2015 by · Comments Off on Securing The .Net Cookies
Filed under: Development, Security 

I remember years ago when we talked about cookie poisoning, the act of modifying cookies to get the application to act differently.  An example was the classic cookie used to indicate a user’s role in the system.  Often times it would contain 1 for Admin or 2 for Manager, etc.  Change the cookie value and all of a sudden you were the new admin on the block.   You really don’t hear the phrase cookie poisoning anymore, I guess it was too dark. 

 

There are still security risks around the cookies that we use in our application.  I want to highlight 2 key attributes that help protect the cookies for your .Net application: Secure and httpOnly.

 

Secure Flag

The secure flag tells the browser that the cookie should only be sent to the server if the connection is using the HTTPS protocol.  Ultimately this is indicating that the cookie must be sent over an encrypted channel, rather than over HTTP which is plain text.

 

HttpOnly Flag

The httpOnly flag tells the browser that the cookie should only be accessed to be sent to the server with a request, not by client-side scripts like JavaScript.  This attribute helps protect the cookie from being stolen through cross-site scripting flaws.

 

Setting The Attributes

There are multiple ways to set these attributes of a cookie. Things get a little confusing when talking about session cookies or the forms authentication cookie, but I will cover that as I go.  The easiest way to set these flags for all developer created cookies is through the web.config file.  The following snippet shows the httpCookies element in the web.config.

  
<system.web>
    <authentication mode="None" />
    <compilation targetframework="4.6" debug="true" />
    <httpruntime targetframework="4.6" />
    <httpcookies httponlycookies="true" requiressl="true" />
 </system.web>

 

As you can see, you can set httponlycookies to true to se the httpOnly flag on all of the cookies.  In addition, the requiressl setting sets the secure flag on all of the cookies with a few exceptions.

 

Some Exceptions

I stated earlier there are a few exceptions to the cookie configuration.  The first I will discuss is the session cookie. The session cookie in ASP.Net is defaulted/hard-coded to set the httpOnly attribute.  This should override any value set in the httpCookies element in the web.config.  The session cookie does not default to requireSSL and setting that value in the httpCookies element as shown above should work just find for it.

 

The forms authentication cookie is another exception to the rules.  Like the session cookie, it is hard-coded to httpOnly.  The Forms element of the web.config has a requireSSL attribute that will override what is found in the httpCookies element.  Simply put, if you don’t set requiressl=”true” in the Forms element then the cookie will not have the secure flag even if requiressl=”true” in the httpCookies element.

 

This is actually a good thing, even though it might not seem so yet.  Here is the next thing about that Forms requireSSL setting.. When you set it, it will require that the web server is using a secure connection.  Seems like common sense, but…  imagine a web farm where the load balancers offload SSL.  In this case, while your web app uses HTTPS from client to server, in reality, the HTTPS stops at the load balancer and is then HTTP to the web server.   This will throw an exception in your application. 

 

I am not sure why Microsoft decided to make the decision to actually check this value, since the secure flag is a direction for the browser not the server.  If you are in this situation you can still set the secure flag, you just need to do it a little differently.  One option is to use your load balancer to set the flag when it sends any responses.  Not all devices may support this so check with your vendor.  The other option is to programmatically set the flag  right before the response is sent to the user.  The basic process is to find the cookie and just sent the .Secure property to “True”. 

 

Final Thoughts

While there are other security concerns around cookies, I see the secure and httpOnly flag commonly misconfigured.  While it does not seem like much, these flags go a long way to helping protect your application.  ASP.Net has done some tricky configuration of how this works depending on the cookie, so hopefully this helps sort some of it out.   If you have questions, please don’t hesitate to contact me.  I will be putting together something a little more formal to hopefully clear this up a bit more in the near future.

ASP.Net Insufficient Session Timeout

October 6, 2015 by · Comments Off on ASP.Net Insufficient Session Timeout
Filed under: Development, Security, Testing 

A common security concern found in ASP.Net applications is Insufficient Session Timeout. In this article, the focus is not on the ASP.Net session that is not effectively terminated, but rather the forms authentication cookie that is still valid after logout.

How to Test

  • User is currently logged into the application.
  • User captures the ASPAuth cookie (name may be different in different applications).
    • Cookie can be captured using a browser plugin or a proxy used for request interception.
  • User saves the captured cookie for later use.
  • User logs out of the application.
  • User requests a page on the application, passing the previously captured authentication cookie.
  • The page is processed and access is granted.

Typical Logout Options

  • The application calls FormsAuthentication.Signout()
  • The application sets the Cookie.Expires property to a previous DateTime.

Cookie Still Works!!

Following the user process above, the cookie still provides access to the application as if the logout never occurred. So what is the deal? The key is that unlike a true “session” which is maintained on the server, the forms authentication cookie is self contained. It does not have a server side component to stay in sync with. Among other things, the authentication cookie has your username or ID, possibly roles, and an expiration date. When the cookie is received by the server it will be decrypted (please tell me you are using protection = all) and the data extracted. If the cookie’s internal expiration date has not passed, the cookie is accepted and processed as a valid cookie.

So what did FormsAuthentation.Signout() do?

If you look under the hood of the .Net framework, it has been a few years but I doubt much has changed, you will see that FormsAuthentication.Signout() really just removes the cookie from the browser. There is no code to perform any server function, it merely asks the browser to remove it by clearing the value and back-dating the expires property. While this does work to remove the cookie from the browser, it doesn’t have any effect on a copy of the original cookie you may have captured. The only sure way to really make the cookie inactive (before the internal timeout occurs) would be to change your machine key in the web.config file. This is not a reasonable solution.

Possible Mitigations

You should be protecting your cookie by setting the httpOnly and Secure properties. HttpOnly tells the browser not to allow javascript to have access to the cookie value. This is an important step to protect the cookie from theft via cross-site scripting. The secure flag tells the browser to only send the authentication cookie over HTTPS, making it much more difficult for an attacker to intercept the cookie as it is sent to the server.

Set a short timeout (15 minutes) on the cookie to decrease the window an attacker has to obtain the cookie.

You could attempt to build a tracking system to manage the authentication cookie on the server to disable it before its time has expired. Maybe something for another post.

Understand how the application is used to determine how risky this issue may be. If the application is not used on shared/public systems and the cookie is protected as mentioned above, the attack surface is significantly decreased.

Final Thoughts

If you are facing this type of finding and it is a forms authentication cookie issue, not the Asp.Net session cookie, take the time to understand the risk. Make sure you understand the settings you have and the priority and sensitivity of the application to properly understand “your” risk level. Don’t rely on third party risk ratings to determine how serious the flaw is. In many situations, this may be a low priority, however in the right app, this could be a high priority.

Future of ViewStateMac: What We Know

December 12, 2013 by · Comments Off on Future of ViewStateMac: What We Know
Filed under: Development, Security, Testing 

The .Net Web Development and Tools Blog just recently posted some extra information about ASP.Net December 2013 Security Updates (http://blogs.msdn.com/b/webdev/archive/2013/12/10/asp-net-december-2013-security-updates.aspx).

The most interesting thing to me was a note near the bottom of the page that states that the next version of ASP.Net will FORBID setting ViewStateMac=false. That is right.. They will not allow it in the next version. So in short, if you have set it to false, start working out how to work it to true before you update.

So why forbid it? Apparently, there was a Remote Code Execution flaw identified that can be exploited when ViewStateMac is disabled. They don’t include a lot of details as to how to perform said exploit, but that is neither here nor there. It is about time that something was critical enough that they have decided to take this property out of the developer’s hands.

Over the years I have written many posts discussing attacking ASP.Net sites, many of which rely on ViewStateMac being disabled. I have written to Microsoft regarding how EventValidation can be manipulated if ViewStateMac is disabled. The response was that they think developers should be using the secure settings. I guess that is different now that there is remote code execution. We have reached a new level.

So what does ViewStateMac protect? There are three things that I am aware of that it protects (search this site for any of these and you will find articles with much more detail):

  • ViewState – protects this from parameter tampering
  • EventValidation – protects this from parameter tampering
  • ViewStateUserKey – Used to protect requests from CSRF

So why do developers disable ViewStateMac? Great question. I believe that in most cases, it is disabled because the application is deployed in a web farm and when the web.config is not configured properly, an error is thrown. When some developers search for the error, many forums recommend disabling the ViewStateMac to fix the problem. Unfortunately, that is WRONG!!. Here is a Microsoft KB article that explains in detail how to properly configure a system to allow ViewStateMac to be enabled (http://support.microsoft.com/kb/2915218).

Is this a good thing? For developers, yes!. This will definitely help increase the protection for ViewState, EventValidation and CSRF if ViewStateUserKey is set. For Penetration Testers, Yes/No. Yes, because we get to say you are doing a good job in this category. No, because some easy pickings are going to be wiped off the plate.

I think this is a pretty bold move by Microsoft to remove control over this, but I do think it is a good thing. This is an important control in the WebForm ecosystem and all too often mis-understood by developers. This should bring many sites one step closer to being a little more secure when this change rolls out.

ASP.Net: Tampering with Event Validation – Part 2

February 10, 2012 by · 1 Comment
Filed under: Development, Security, Testing 

In part 1 of this series I demonstrated how to modify the values of a list box and access data I was not given access to by manipulating the view state and event validation parameters.  Remember, the key to this is that ViewStateMac must be disabled.  In this post, I will be demonstrating triggering button events that are not available to me. 

Target Application

The target application has a simple screen that has a drop down list with some transactions and a button to view the selected transaction.

Image 1

When a user selects a transaction and clicks the “View Transaction” button, the transaction is loaded (see Image 2).

Image 2

As seen in Image 1 above, some users have access to delete the selected transaction.  Image 3 shows what happens when we delete the transaction. (For this demo, the transaction is actually not deleted, a message is just displayed to make things simple.

Image 3

Unfortunately, the account I am using doesn’t allow me to delete transactions.  Lets take a look at how we can potentially bypass this so we can delete a transaction we don’t want.

Tools

I will only be using Burp Suite Pro and my custom Event Validation tool for this.  Other proxies can be used as well.

The Process

Lets take a look at the page as I see it (See Image 4).  I will click the “View Transaction” button and view a transaction.  Notice that there is no “Delete” button available.

Image 4

When I view the source of the page (Tools…View Source) I can see that the id of the “Get Transaction” button is ctl00$MainContent$cmdGetTransaction.  In some cases, I may have access to the details of the delete button (that is currently invisible).  In most cases, I may be stuck just making educated guesses as to what it might be.  In this case I do know what it is called (ctl00$MainContent$cmdDelete), but one could easily make simple guesses like cmdDelete, cmdRemove, cmdDeleteTransaction, etc..

I like to avoid doing any url encoding myself, so my first step is to change my proxy into intercept mode and select a transaction to view.  I want to intercept the response so that I can modify my __EVENTVALIDATION field before it goes to my page.  I need to add in my button to the __EVENTVALIDATION so that ASP.Net will accept it as valid.  I will use the custom Event Validation tool to do this.  Image 5 shows the Event Validation application with the needed changes.

Image 5

After modifying the __EVENTVALIDATION field, I will update that in my intercepted response and then let the page continue.

Original __EVENTVALIDATION

/wEWBgKo4+wkAu7T+jAC79P6MALs0/owAu3T+jACo/P//wU=

 

Modified __EVENTVALIDATION

/wEWBwKo4+wkAu7T+jAC79P6MALs0/owAu3T+jACo/P//wUCzLeukgU=

 

Now that I have modified the data on my current page, the next step is to Click the “View Transaction” button again to trigger a request.  The triggered request is shown in Image 6. 

Image 6

This request is triggering a “View Transaction” request, which is what we do not want.  We need to change this request so that it is calling the “Delete” command instead.  You can see the change in Image 7 below.

Image 7

When I continue the request and turn my intercept off I can see that my delete button click did fire and I get the message alerting me that the item was deleted (Image 8).

Image 8

Additional Notes

Since this is using a drop down list to define the transaction we are dealing with, I could combine the concepts from Part 1 in this series to delete other transactions that may not even be mine.  There are a lot of possibilities with tampering with the Event Validation and View State that can cause big problems.

Conclusion

This is an overly simplified example of how events that are meant to be hidden from users can be triggered when ViewStateMac is disabled.  It is important that if you are changing the visibility of buttons or other controls that trigger events based on users roles, that the actual event checks to make sure that the current user is authorized to perform its function.  I personally like all of the built in security features that .Net has, but no one should rely solely on them.  Of course, there are multiple factors that go into this vulnerability, so if things are not just right, it may not work. 

This information is provided as-is and is for educational purposes only.  There is no claim to the accuracy of this data.  Use this information at your own risk.  Jardine Software is not responsible for how this data is used by other parties. 

ASP.Net Webforms CSRF Workflow

February 7, 2012 by · Comments Off on ASP.Net Webforms CSRF Workflow
Filed under: Security, Testing 

An important aspect of application security is the ability to verify whether or not vulnerabilities exist in the target application.  This task is usually outsourced to a company that specializes in penetration testing or vulnerability assessments.  Even if the task is performed internally, it is important that the testers have as much knowledge about vulnerabilities as possible.  It is often said that a pen test is just testing the tester’s capabilities.  In many ways that is true.  Every tester is different, each having different techniques, skills, and strengths. Companies rely on these tests to assess the risk the application poses to the company.

In an effort to help add knowledge to the testers, I have put together a workflow to aid in testing for Cross Site Request Forgery (CSRF) vulnerabilities.  This can also be used by developers to determine if, by their settings, their application may be vulnerable.  This does not cover every possible configuration, but focuses on the most common.  The workflow can be found here: CSRF Workflow.  I have also included the full link below.

Full Link: http://www.jardinesoftware.com/Documents/ASP_Net_Web_Forms_CSRF_Workflow.pdf

Happy Testing!!

 

The information is provided as-is and is for educational purposes only.  Jardine Software is not liable or responsible for inappropriate use of this information.

ASP.Net: Tampering with Event Validation – Part 1

February 6, 2012 by · Comments Off on ASP.Net: Tampering with Event Validation – Part 1
Filed under: Development, Security 

UPDATED 12/13/2012 – This post was updated to include a video demonstration of tampering with data with Event Validation enabled.   The video is embedded at the bottom of the post.

My last post brought up the topic of tampering with Event Validation (__EVENTVALIDATION) and how it is protected with the ViewStateMAC property.  This post, and the next few, will focus on how to actually tamper with the values in Event Validation to test for security vulnerabilities.  We will use a very basic demo application to demonstrate this.

Target Application

The target application has a simple screen with a drop down list, a button, and a data grid that displays the selected account information.  The drop down list is populated with accounts for the logged on user only.  I will show how the data can be modified to view another account that we were not granted access to.  It is important to note that there are many variables to requests and this assumes that authorization was only checked to fill the drop down list and not when an actual account is selected.  This is a pretty common practice because it is assumed that event validation will only allow the authorized drop down items (the accounts in this instance) to be selected by the user.  Not all applications are written in this way, and the goal is to test to see if there is authorization or parameter tampering issues.

Tools

I will use multiple tools to perform this test.  These tools are personal choice and other tools could be used.  The first, and my favorite, is Burp Suite Pro.   This will be my main proxy, but that is just because I like how it works better than some others.  Secondly, I will be using Fiddler and the ViewState Viewer plug-in to manipulate the View State field.  Finally, I have a custom application that I wrote to generate the Event Validation codes that I need to make this work.

The Process

First, I will just load the application and view the target page.  Image 1 shows the initial screen with the values from the drop down list.   Notice that only 3 accounts are available and they are all for James.  By looking at the source for the drop down list, I can see that the values for each of those items are numeric.  This is a good sign, for testing purposes.  Numeric values are usually easier at determining, especially if you can find a simple pattern.

Image 1

Next, it is time to de-serialize the view state so we can modify it for the value we want to add.  To do this, I will use Fiddler and the ViewState Viewer plug-in.  There are two changes I need to make.  First, I need to add an item to the ArrayList (seen in Image 2).

Image 2

Second, I need to add the drop down list item I want to try and access.   The text will not matter, but the value that I add is the key.  Although this may not always be the case, in this simple example, that is what the application uses to query the account data.  The value needed could be known, or you could just attempt to try different values until you find one that works.  The added item can be seen here in Image 3.

Image 3

Now that my view state has modified, I can press the “Encode” button and get the updated view state.  Here is the original and modified view state values:

Original __VIEWSTATE

/wEPDwUKMTE3ODU2MDQzNg9kFgJmD2QWAgIDD2QWAgIFD2QWBAIBDxBkDxYDZg

IBAgIWAxAFDkphbWVzIENoZWNraW5nBQUwMDEwMWcQBQ1KYW1lcyBTYXZpbmdz

BQUwMDEwMGcQBQlKYW1lcyBJUkEFBTAwMTAyZ2RkAgcPPCsACwBkZA==

 

Modified __VIEWSTATE

/wEPDwUKMTE3ODU2MDQzNg9kFgJmD2QWAgIDD2QWAgIFD2QWBAIBDxBkDxYEZg

IBAgICAxYEEAUOSmFtZXMgQ2hlY2tpbmcFBTAwMTAxZxAFDUphbWVzIFNhdmluZ3M

FBTAwMTAwZxAFCUphbWVzIElSQQUFMDAxMDJnEAUOSGFja2VkIEFjY291bnQFBTA
wMjAxZ2RkAgcPPCsACwBkZA==
 

The next step is to modify the Event Validation value.  There are two options to modify this value:

  1. Use Fiddler and the ViewState Viewer (just like how we just modified the view state)
  2. Use my custom application.  This is the method I will use for this example.  See Image 4 for a reference to the application.

I will retrieve the __EVENTVALIDATION value from the response and paste it into the Original Event Validation textbox and “De-Serialize” it.  This will populate the list box with all of the original hash values.  To add custom data, we must use the same technique that the ASP.Net uses to calculate the hash value for the items.  There are two values we need to modify in this example.

  1. First, I need to modify our allowed viewstate hash.  To do this, I will put my modified __VIEWSTATE value into the “Value” textbox and click the “Get Hash” button.  View State is a little different than other control data in that it does not require a Unique Id to be associated with it to generate the hash.  The hash value generated is 679154845.   This value must be placed in the first array item in event validation.
  2. Second, I need to add my own drop down item.  Previously, I added this to the view state and used a value of 00201.  Adding it to event validation is a little different.  I will enter in the value (00201) into the “Value” box, and then enter the drop down lists unique id (ctl00$MainContent$ddlAccounts) into the “Unique Id:” textbox.  Clicking the “Get hash” button produces the following hash: –439972587.  I then add this hash value to the array.

Now that my two hashes have been added, it is time to serialize the data back into the __EVENTVALIDATION value.  Here are the two different values we worked with:

Original __EVENTVALIDATION

/wEWBQKc7/W6AwK6gbzTBAK7gbzTBAK9gbzTBAKP5u6DCA==

 

Modified __EVENTVALIDATION

/wEWBwKdqezDAgK6gbzTBAK7gbzTBAK9gbzTBAKP5u6DCAKh96L5CQKVmpquDg==

Image 4

Due to the time it can take to perform the above steps, I like to do them without holding up my request.  Now that I have the values I need, I will refresh my page with my proxy set to intercept the response.  I will then modify the response and change the __VIEWSTATE and __EVENTVALIDATION values to my new modified ones.  I will let the response continue to allow my page to display.

At this point, nothing appears to have happened.   There is no additional drop down list item or anything else to indicate that this has worked.  The key is to now just select an existing account and hit the “Get Account” button.  If there is an error, something didn’t work right.  If you were successful, the page should re-load and you should see a new Drop down List item (See Image 5)

Image 5

I now need to determine if I was lucky enough to pick a valid account number.  I will select the “Hacked Account” list item (which is the one I added) and click the “Get Account” button.   If no data comes back then the account number did not exist.  It is back to the drawing board to try again with a different number.  If, however, account details did show up, then I have successfully accessed data I was not given access to.  Image 6 shows the results of a successful attempt.

Image 6

Conclusion

This showed the steps necessary to manipulate both view state and event validation to tamper with the allowed accounts were were authorized to see.  This requires that ViewStateMAC is disabled and that the view state has not been encrypted.  If either of those two factors were different, this would not be possible.  This demonstrates the importance of ensuring that you use ViewStateMAC to protect your view state AND event validation.  You should also be performing authorization checks on each request that requests sensitive information from your application.  This example application is completely fictional and there are no claims that this represents the way that any production application actually works.  It will be used to demonstrate the different techniques used to develop applications to understand how they can be fixed.

This information is provided as-is and is for educational purposes only.  There is no claim to the accuracy of this data.  Use this information at your own risk.  Jardine Software is not responsible for how this data is used by other parties. 

ViewStateMAC: Seriously, Enable It!

February 1, 2012 by · Comments Off on ViewStateMAC: Seriously, Enable It!
Filed under: Development, Security 

I have been doing a lot of research lately around event validation and view state.  I have always been interested in how Event Validation worked under the covers and if it could be tampered with.  I will attempt to explain that it is, in fact, possible to tamper with the Event Validation field in a similar manner that view state can be tampered.  I know, the title of the post reads “ViewStateMAC”, don’t worry I will get to that.  But first, it is important to discuss a little about how Event Validation works to understand why ViewStateMAC is important.

__EVENTVALIDATION – Basics

Event Validation is a feature that is built into ASP.Net web forms.  It is enabled by default and it serves the purpose to ensure that only valid data is received for  controls that register valid events or data.  As a quick example, think for a moment about a drop down list.  Each value that is programmatically added to the control will be registered with Event Validation.  Code Example 1 demonstrates loading values into a drop down list (data binding is also very common).  Each of these values will now exist in the Event Validation feature.  When a user attempts to submit a form, or post back, the application will verify the value submitted for that control is a valid value.  If it is not, a not so pretty exception is generated.

Example 1
private void FillDDL2()
{
  ddlList.Items.Add(new ListItem("1", "1"));
  ddlList.Items.Add(new ListItem("2", "2"));
  ddlList.Items.Add(new ListItem("3", "3"));
  ddlList.Items.Add(new ListItem("4", "4"));
  ddlList.Items.Add(new ListItem("5", "5"));
}

__EVENTVALIDATION – Hash

Event Validation is primarily based on storing a hash value for each of the values it needs to check for validity.  More specifically, there is a specific routine that is run to create an integer based hash from the control’s unique id and the specified value (the routine is beyond the scope of this post).  Every value that gets stored in Event Validation has a corresponding integer hash value.  These hash values are stored in an array list which gets serialized into the string that we see in the __EVENTVALIDATION hidden form field on the web page. 

__EVENTVALIDATION – Page Response

When a page is requested by the user it goes through an entire lifecycle of events.  To understand how Event Validation really works, lets first take a look at how the field is generated.  Before the page is rendered, each control or event that is registered for event validation will have its value hashed (see previous section) and added to the array list.  As mentioned before, this can be values for a list control, valid events for the page or controls (for example, button click events), and even View State.  This array is serialized and stored in the __EVENTVALIDATION hidden field.

__EVENTVALIDATION – Post Back Request

The request is where Event Validation takes action.  When a user submits a post back to the server, event validation will validate the values that have been registered.  So in the Drop Down List example in "Example 1” Event Validation is there to make sure that only the values 1-5 are submitted for ddlList.  It does this by taking the value that was sent (Request.Form[“ddlList”]) and re-generates the numeric hash.  The hash is then compared to the list and if it exists, the value is allowed.  If it doesn’t exist in the de-serialized Event Validation list, then an exception is thrown and the page cannot continue processing.

__EVENTVALIDATION – Manipulation

De-serializing the Event Validation value is pretty easy.  This is very similar to how it is done for View State.  After writing my own tool to tamper with the Event Validation, I found the ViewState Viewer (http://labs.neohapsis.com/2009/08/03/viewstateviewer-a-gui-tool-for-deserializingreserializing-viewstate/) plug-in for Fiddler.  The ViewState Viewer plugs right into Fiddler with no issues.  Don’t let the name mislead you, this tool works great with the Event Validation data as well.  When you paste in your Event Validation string and click the “Decode” button, it generates a nice XML snippet of the contents.  The screen shot below demonstrates the Event Validation value and its decoded value from a test page I created.

Once you have the information decoded, you can now add in your own integers to the System.Collections.ArrayList.  Look closely and you might see that the last integer –439972587 is not aligned with the rest of the items.  This is because that is a custom value that I added to the event validation.  These numbers don’t look like they really mean anything, but to Event Validation, they mean everything.  If we can determine how to create our own numbers, we can manipulate what the server will see as valid data.  Once you have made your modifications, click the “Encode” button and the value in the top box will refresh with the new __EVENTVALIDATION value.  It may be possible to attempt brute forcing the data you want (if you can’t create the exact hash code) by just padding a bunch of integers into the list and submitting your modified data.  This is definitely hit or miss, could be time consuming, and would probably generate a lot of errors for someone to notice.  We are monitoring our error logs right?

__EVENTVALIDATION – Thoughts

Maybe just me, but I always thought that if I had event validation enabled, as a developer, I didn’t have to validate the data from drop down lists that was submitted.  I thought that this type of data was protected because event validation enforced these constraints.  This is obviously not the case and honestly brings up a very important topic for another day; “We shouldn’t be relying solely on configuration for protection”.  Although this post uses the drop down lists as an example, this has a much greater effect.   What about buttons that are made visible based on your role.  If event validation can be tampered with, now those buttons that didn’t exist, can have their events added to the acceptable list.  If you are not checking that the user has the proper role within that event, you may be in big trouble. 

So what types of attacks are possible?

  • Parameter tampering
  • Authorization bypass
  • Cross Site Scripting
  • Maybe More…

ViewStateMAC – Finally!!

Ok, it is not all bad news and finally we come to our friend (or worst enemy if it is disabled) ViewStateMAC.  Keep in mind that ViewStateMAC is enabled by default, so if this is disabled, it was done explicitly.  ViewStateMAC adds a message authentication code to ViewState obviously, judging by its name.   Basically, it adds a hash to the view state so that an attacker cannot tamper with its data.  So if we go back to the drop down list, if a developer uses code like Example 2 to access the selected item, then you have to be able to tamper the view state, otherwise the first item in the original item will get selected.  But if you use code like Example 3 to access that data, you could add your value to the EventValidation and get it accepted by the application.   Or can you?

Example 2
protected void cmdSubmit_Click(object sender, EventArgs e)
{
  Response.Write(ddlList.SelectedItem.Value);
}

Example 3
protected void cmdSubmit_Click(object sender, EventArgs e)
{
  Response.Write(Request.Form["ddlList"].ToString());
}

Actually, ViewStateMAC does more than sign ViewState, it also signs the Event Validation value.  I was not able to identify any documentation on MSDN that indicates this feature, but apparently __PREVIOUSPAGE may get signed with this as well.  I have run extensive tests and can confirm that ViewStateMAC is critical to signing Event Validation.  So in general, If ViewStateMAC is enabled, it protects both ViewState and Event Validation from being tampered with.  That is pretty important and I am not sure why it is not listed on MSDN.  Unfortunately, disable it and it creates a much greater security risk than initially thought because it effects more than ViewState. 

ViewStateMAC – Not a Replacement for Input Validation

In no way should a developer rely solely on ViewStateMAC, Event Validation and ViewState as their means of input validation.  The application should be developed as if these features do not even exist.  Drop down lists should be validated that only valid values were submitted.  Control events should be verified that they are allowed.   Why not use these features?  I am not saying that you should not use these features, but they should be in addition to your own input validation.  What if ViewStateMAC were to get disabled during testing, or for some other unknown reason?  Even if Event Validation is still enabled, it is not looking good.  Unless you have ViewState being encrypted, which would help block tampering with the view state, an attacker could still manipulate the event validation code. 

Conclusion

The details provided here have been high level with not much actual detail in actually manipulating the Event Validation field.  The post would be too long to include all the details here.  Hopefully there is enough information to make developer’s aware of the severity of ViewStateMAC and how Event Validation actually works.  From a penetration tester’s view, if you visit a .net webform application with ViewStateMAC disabled, this should be researched more to help accurately identify risk for the application.  Devs, please, please, please do not disable this feature.  If you are on a web farm, make sure the same machine key is set for each machine and this should be supported. Remember, these features are helpers, but not complete solutions.   You are responsible for performing proper input validation to ensure that the data you expect is what you accept.

The information provided is for informational and educational purposes only.  The information is provided as-is with no claim to be error free.  Use this information at your own risk.

Next Page »