Strange unhandled exception from asp.net application - Validation of viewstate MAC failed - asp.net

I don't know if anyone has seen this issue before but I'm just stumped. Here's the unhandled exception message that my error page is capturing.
Error Message: Validation of
viewstate MAC failed. If this
application is hosted by a Web Farm or
cluster, ensure that configuration
specifies the same validationKey and
validation algorithm. AutoGenerate
cannot be used in a cluster.
Stack Trace: at
System.Web.UI.ViewStateException.ThrowError(Exception
inner, String persistedState, String
errorPageMessage, Boolean
macValidationError) at
System.Web.UI.ObjectStateFormatter.Deserialize(String
inputString) at
System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String
serializedState) at
System.Web.UI.Util.DeserializeWithAssert(IStateFormatter
formatter, String serializedState) at
System.Web.UI.HiddenFieldPageStatePersister.Load()
at
System.Web.UI.Page.LoadPageStateFromPersistenceMedium()
at System.Web.UI.Page.LoadAllState()
at
System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean
includeStagesAfterAsyncPoint) at
System.Web.UI.Page.ProcessRequest(Boolean
includeStagesBeforeAsyncPoint, Boolean
includeStagesAfterAsyncPoint) at
System.Web.UI.Page.ProcessRequest()
at
System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext
context) at
System.Web.UI.Page.ProcessRequest(HttpContext
context) at
ASP.generic_aspx.ProcessRequest(HttpContext
context) at
System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at
System.Web.HttpApplication.ExecuteStep(IExecutionStep
step, Boolean& completedSynchronously)
Source: System.Web
Anybody have any ideas on how I could resolve this? Thanks.

I seem to recall that this error can occur if you click a button/link etc before the page has fully loaded.
If this is the case, the error is caused by an ASP.net 2.0 feature called Event Validation. This is a security feature that ensures that postback actions only come from events allowed and created by the server to help prevent spoofed postbacks. This feature is implemented by having controls register valid events when they render (as in, during their actual Render() methods). The end result is that at the bottom of your rendered
form tag, you'll see something like this:
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="AEBnx7v.........tS" />
When a postback occurs, ASP.net uses the values stored in this hidden field to ensure that the button you clicked invokes a valid event. If it's not valid, you get the exception that you've been seeing.
The problem you're seeing happens specifically when you postback before the EventValidation field has been rendered. If EventValidation is enabled (which it is, by default), but ASP.net doesn't see the hidden field when you postback, you also get the exception. If you submit a form before it has been entirely rendered, then chances are the EventValidation field has not yet been rendered, and thus ASP.net cannot validate your click.
One work around is of course to just disable event validation, but you have to be aware of the security implications. Alternatively, just never post back before the form has finished rendering. Of course, that's hard to tell your users, but perhaps you could disable the UI until the form has rendered?
from http://forums.asp.net/p/955145/1173230.aspx

#Chris
if the problem is clicking an item before the page has completely rendered, asp.net 3.5 SP1 added a web.config entry on the page element called renderAllHiddenFieldsAtTopOfForm.

do you have multiple servers running this application and/or have a web garden? If yes, you are going to have to set the machine key in the web.config

By default, ASP.NET includes a digital signature of the ViewState value in the page. It does so with an automatically-generated key that is held in memory. This is done to prevent a malicious user from altering the ViewState from the browser and, for example, grant him/herself access to stuff they wouldn't normally have access to.
ASP.NET can also, optionally, encrypt the ViewState, but it's turned off by default for performance reasons. In many web sites, it is a lot more important to make sure that the content of the ViewState is not 'mucked with', than it is to keep it confidential.
The error message says that the signature verification failed. The page was posted with a ViewState, but the ViewState signature didn't match the signature calculated with the keys held by the server.
The most common reason for this error is that you are using two or more web servers in a farm-like environment: one server sends the original page, signed with the key in memory on that server, but the page is posted back to the second (or third...) server. Because the two or more servers don't share the signature key, the signatures don't match.
...If this application is hosted by a Web Farm or cluster,
ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.
What the error message is telling you is to use the validationKey attribute (see details in MSDN) in your web.config to hardcode the signature key to a value shared by all your servers, instead of using a dynamically-generated one. That way, the signature validation can succeed independently of which server receives the postback.
You could turn off the verification, but it's very dangerous to do so. It means any hacker with a bit of free time can fake values in your application. For example, if you keep the price of the item in a ViewState value, the hacker could change the value from the browser to $0.01 right before putting the order.

For anyone else ending up struggling with this issue here is a helpful link to some work arounds:
http://blogs.msdn.com/tom/archive/2008/03/14/validation-of-viewstate-mac-failed-error.aspx

I know you can disable the Validation of viewstate MAC, but I think if the page is not loaded you can get into more trouble. When I ran into this problem I had to disable all buttons until the page was fully loaded.

Related

Viewstate exception Validation of viewstate MAC failed

In our log files I find the following exception. (ASP.NET, Sitecore 6.6). Any ideas why this happens?
I referred to this post. My app is not in a server farm. Also this does not happen with every postback.
7776 02:11:53 ERROR Application error.
Exception: System.Web.HttpException
Message: Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.
Source: System.Web
at System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError)
at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString, Purpose purpose)
at System.Web.UI.Util.DeserializeWithAssert(IStateFormatter2 formatter, String serializedState, Purpose purpose)
at System.Web.UI.HiddenFieldPageStatePersister.Load()
at System.Web.UI.Page.LoadPageStateFromPersistenceMedium()
at System.Web.UI.Page.LoadAllState()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Nested Exception
Exception: System.Web.UI.ViewStateException
Message: Invalid viewstate.
Client IP: xxx.xxx.xxx.201
Port: <PORT>
Referer: <URL>
Path: /<PAGE>
User-Agent: Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11
ViewState: /wEPDwUJMzY0OTY5Mjg5D2QWAgIFEGRkFgQCAw9kFgJmD2QWAmYPZBYCAg4PZBYCZg9kFgQCAw8PFgQeFUN1cnJlbnRTZWxlY3Rpb25WYWx1ZQUkMDAwMDAwMDAtMDAwMC0wMDAwLTAwMDAtMDAwMDAwMDAwMDAwHhRDdXJyZW50U2VsZWN0aW9uVGV4dAUVQWxsIENhdGVnb3JpZXMgKDY5NTEpZBYCAgEPZBYCZg9kFgICAQ8UKwACDxYGHgRUZXh0BRVBbGwgQ2F0ZWdvcmllcyAoNjk1MSkeBF8hU0ICAh4IQ3NzQ2xhc3MFB1Rvb2xCYXJkEBYBZhYBFCsAAmRkDxYBZhYBBXdUZWxlcmlrLldlYi5VSS5SYWRDb21ib0JveEl0ZW0sIFRlbGVyaWsuV2ViLlVJLCBWZXJzaW9uPTIwMTIuMi42MDcuMzUsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49MTIxZmFlNzgxNjViYTNkNBYCAgIPFCsAAWQWAgIBDxQrAAIUKwACFCsAAg8WBB8EBQdUb29sQmFyHwMCAmQPFCsAARQrAAIPFgYfAgUVQWxsIENhdGVnb3JpZXMgKDY5NTEpHgVWYWx1ZQUkMDAwMDAwMDAtMDAwMC0wMDAwLTAwMDAtMDAwMDAwMDAwMDAwHghTZWxlY3RlZGdkZA8UKwEBZhYBBXNUZWxlcmlrLldlYi5VSS5S...
please check this link
Root Cause
This exception appears because Controls using DataKeyNames require Viewstate to be encrypted. When Viewstate is encrypted (Default mode, Auto, is to encrypt if controls require that, otherwise not), Page adds field just before closing of the tag. But this hidden field might not have been rendered to the browser with long-running pages, and if you make a postback before it does, the browser initiates postback without this field (in form post collection). End result is that if this field is omitted on postback, the page doesn't know that Viewstate is encrypted and causes the aforementioned Exception. I.E. page expects to be fully-loaded before you make a postback.
And by the way similar problem is with event validation since __EVENTVALIDATION field is also rendered on the end of the form. This is a security feature that ensures that postback actions only come from events allowed and created by the server to help prevent spoofed postbacks. This feature is implemented by having controls register valid events when they render (as in, during their actual Render() methods). The end result is that at the bottom of your rendered tag, you'll see something like this: . When a postback occurs, ASP.NET uses the values stored in this hidden field to ensure that the button you clicked invokes a valid event. If it's not valid, you get the exception above.
The problem happens specifically when you postback before the EventValidation field has been rendered. If EventValidation is enabled (which it is, by default), but ASP.net doesn't see the hidden field when you postback, you also get the exception. If you submit a form before it has been entirely rendered, then chances are the EventValidation field has not yet been rendered, and thus ASP.NET cannot validate your click.
Workarounds
1. Set enableEventValidation to false and viewStateEncryptionMode to Never as follows:
This has the unwanted side-effect of disabling validation and encryption. On some sites, this may be ok to do, but it isn't a best practice, especially in publicly facing sites.
I have similar issue in my recent project.When I tried to find some help from google, the things that most people discussed are the following
Add machine key in web.config
<system.web>
<machineKey validationKey="..." decryptionKey="..." validation="SHA1" />
</system.web>
Set EnableViewStateMAC=False in web.config
<system.web>
<pages enableViewStateMac="False"/>
</system.web>
But all above solution did not work for me. Whenever I try to open application with IP address it works fine but if I tried open application with domain name it showed me "Viewstate MAC failed" error. I dig down to find out what an issue and finally I found solution, this error occurs when browser does not accept cookie from server.
Godaddy provides feature for domain forwarding with masking. One of my colleague set that feature on our application domain, IE and Safari have security Level that they does not accept cookies from third parties and Advertiser, therefore both these browser generated "Viewstate MAC failed" error.
You can set Security Level to Accept all cookie in IE
Tools > Internet Options > Privacy
and Move Setting slider bottom for the Value "Accept all Cookie".
Hope this solution will help other to get out of asp.net legacy error "Viewstate MAC failed".

When users log out using CAS SSO, ASP.NET MVC triggers a HttpRequestValidationException

We're using the Jasig .NET CAS Client to interface with our organization's CAS SSO server.
However, we've noticed that in ASP.NET MVC 3 (and I would assume this affects ASP.NET WebForms as well) applications, when users log out, we see the following error in our error log:
System.Web.HttpRequestValidationException (0x80004005):
A potentially dangerous Request.Form value was detected from the client
(logoutRequest="<samlp:LogoutRequest...").
at System.Web.HttpRequest.ValidateString(String value, String collectionKey, RequestValidationSource requestCollection)
at System.Web.HttpRequest.ValidateNameValueCollection(NameValueCollection nvc, RequestValidationSource requestCollection)
at System.Web.HttpRequest.get_Form()
at System.Web.HttpRequest.FillInParamsCollection()
at System.Web.HttpRequest.GetParams()
at DotNetCasClient.Utils.RequestEvaluator.GetRequestIsCasSingleSignOut() in C:\Projects\Jasig\CAS\dotnet-client\trunk\DotNetCasClient\Utils\RequestEvaluator.cs:line 292
at DotNetCasClient.CasAuthenticationModule.OnBeginRequest(Object sender, EventArgs e) in C:\Projects\Jasig\CAS\dotnet-client\trunk\DotNetCasClient\CasAuthenticationModule.cs:line 93
at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
I don't believe this is an error message users are receiving -- it seems to only be seen by the server. As far as the users are concerned, log out is successful.
Is there any way I can get ASP.NET MVC to stop trying to validate these types of requests? I know I can disable request validation completely, but that's out of the question. The site with a hyphen has a good question on this, but not really an acceptable answer:
add the following setting to the web.config:
<httpRuntime requestValidationMode="2.0" />
After setting this value, U can disable request validation by setting validateRequest="false"
So, is there any way to disable ASP.NET validation for this request without turning it off completely?
Edit: This is also tricky to debug because this request is coming from the CAS server, NOT from the user's browser. I think this is the CAS server attempting to notify all running applications that the user has signed out (single sign out). So we're only receiving this error in production, not when testing locally.
The dotnetcas client gets access to the request before it gets to an MVC controller action, so it is not possible to simply set the validation attribute on an MVC controller or action.
The target of this request seems to be the last URL that was validated, so it is not possible to disable validation for a specific path in your application by using this method either: http://erikbra.wordpress.com/2012/04/17/wif-saml-token-post-and-requestvalidationmode2-0/
From what I see you have a couple of options:
Disable this validation:
<system.web>
<httpRuntime requestValidationMode="2.0" />
</system.web>
or
.Net 4.5 allows you to access a request before it goes through validation. If you have access to this you can re-compile the client from source, fixing the relevant issue.
I am not familar with Jasig .NET CAS but ASP.NET MVC allows you to disable request validation at the page level.
Add the following attribute to your controller action:
[ValidateInput(false)]

invalid viewstate error - OnPreRender

I'm getting 100+ errors per day on my website with System.Web.HttpException: Invalid viewstate.
The website is asp.net 3.5 running on iis6 , not running in a web-garden/web-farm , single server.
Here are a few sample errors.
Machine: ML Framework Version: 2.0.50727.3603 Assembly Version: 6.5.3664.33889
Source: http://www.domain.com/WebResource.axd?d=z5VmXXoSLLpQHoPictureAlert
Exception: System.Web.HttpException: Invalid viewstate. at System.Web.UI.Page.DecryptStringWithIV(String s, IVType ivType) at System.Web.Handlers.AssemblyResourceLoader.System.Web.IHttpHandler.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Machine: MLFramework Version: 2.0.50727.3603 Assembly Version: 6.5.3664.33889
Source: http://www.mydomain.com/ScriptResource.axd?d=SE0Ej7OlEAx91j2Cjv_6KkRPplqT-5wB4M7CZPdGdGn3LahLwqlRPApUcdxBsbFXYHZ91Q76FHAHWgHs8SmOC4zemr7
siym0QY0rF3XtJTu%3C/a%3E%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%3Ca%20id=
Exception: System.Web.HttpException: Invalid viewstate. at System.Web.UI.Page.DecryptStringWithIV(String s, IVType ivType) at
System.Web.UI.Page.DecryptString(String s) at System.Web.Handlers.ScriptResourceHandler.DecryptParameter(NameValueCollection queryString) at
System.Web.Handlers.ScriptResourceHandler.ProcessRequestInternal(HttpResponse response, NameValueCollection queryString,
VirtualFileReader fileReader) at System.Web.Handlers.ScriptResourceHandler.ProcessRequest(HttpContext context) at
System.Web.Handlers.ScriptResourceHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext context) at
System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
i already tried wraping all inline javascript with //<![CDATA[ //]]>
i already set enableViewStateMac to false.
From looking at all the errors guessing out of the "d" paramter it seems to focus on a single usercontrol on my website.
in this control i change the visiblity of div's + text in the usercontrol OnPreRender function.
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
PreparePage();
}
Can the errors be related to the usercontrol behavioral?
thanks!
If your site is running in a web farm this might be related to having different machine keys. For example if one server is used to encode the viewstate then another server won't be able to decode it if it does not have the same machine key. Checkout this article. Even if you don't have multiple servers try specifying fixed machine keys.
The invalid ViewState exception is generally from ASP.NET's built in event validation. Turning off EnableViewStateMac simply stops the MAC-based encryption, not the viewstate validation. To do that you need to set EnableEventValidation="false" in the Page directive.
As to why it's happening... three possible reasons:
1) You are modifying the contents of a control on the client side (such as DropDownList items).
2) The page is being posted back before the ViewState validation field is being rendered.
3) Your site is the target of a malicious script searching for vulnerabilities... in which case, EventValidation is doing its job.
I'd say #1 is most likely... bu #2 is also very common, especially when you're seeing this error inconsistently.

ViewState and Security Settings generating errors

I have an odd reoccurring error that I believe is related to View State and security settings. This error appears on one of my client’s site between 1 to 6 times a day:
Source: System.Web
Error in: /detail.aspx?CaseID=1852
Error Message: Unable to validate data.
Stack Trace: at System.Web.Configuration.MachineKeySection.**EncryptOrDecryptData(**Boolean fEncrypt, Byte[] buf, Byte[] modifier, Int32 start, Int32 length, IVType ivType, Boolean useValidationSymAlgo)
at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString)
Researching online has lead to a deadend. I believe it has do with security and ViewState. Because this is an ecommerce site, I took the extra steps of protecting against a number of treats, includign XSS and CSFR. Here are the steps I took:
Turned on HTTPOnly Cookies (Protects against XSS Style Attacks)
Turned on Secure Cookie Flag (Protects against XSS Style Attacks)
Created a BasePage which all the pages inherit instead of Page, in the Basepage I overrides OnInit and set ViewStateUserKey to SessionID (Protects against certain CSFR Style Attacks)
Explicitly enabled validateRequest (On by default, but can be overwritten)
ViewState Encryption Enabled
The website is hosted on a Win2003 Virtual Server, using ASP.NET 3.5 SP1 and AJAX. The page is not using caching, which some articles I found suggested was a problem when you set the ViewStateUserKey key to a unique value, such as SessionID. I can duplicate this exact error if I turn off cookies in my browser and try to view one of the pages that creates the error.
Notes, The error message does NOT mention MAC has failed
My theory is that those that experience this error are on networks that have a Proxy/Caching Server. My solution was to only set the ViewStateUserKey when it was a secure connection. Most Proxy/Caching Servers are only set to cache HTTP connections, not secure connections.

Is this an attempt to break my ASP.Net site's security?

I am fairly new to ASP.NET. I recently set up automated email from my website to notify me of an unhandled exceptions. Just a few hours ago in 3 minutes there were 10 unhandled exceptions and all stack traces were similar. There is a lot in the error messages I do not understand, but I do not like the way this looks.
Here is one of the email messages:
An unhandled exception occurred:
Message: Padding is invalid and cannot be removed.
Stack Trace:
at System.Security.Cryptography.RijndaelManagedTransform.DecryptData(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount, Byte[]& outputBuffer, Int32 outputOffset, PaddingMode paddingMode, Boolean fLast)
at System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)
at System.Security.Cryptography.CryptoStream.FlushFinalBlock()
at System.Web.Configuration.MachineKeySection.EncryptOrDecryptData(Boolean fEncrypt, Byte[] buf, Byte[] modifier, Int32 start, Int32 length, IVType ivType, Boolean useValidationSymAlgo)
at System.Web.UI.Page.DecryptStringWithIV(String s, IVType ivType)
at System.Web.Handlers.AssemblyResourceLoader.System.Web.IHttpHandler.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Is this an attempt to hack into my site or something else?
Many thanks go to those who provided Answers and Comments provided which pointed me in the right direction to get an answer to this exception. It's cause can be difficult to determine, especially when not occuring in a web farm.
IE 5.5 was not causing the problem as I had earlier thought.
It was not easily found, but a post on my web host forum by one of the staff mentioned reports of Viewstate errors. The cause was attributed to the asp worker process or the server recycling.
The asp worker process settings refers to the processModel Element in the machine.config file. See http://msdn.microsoft.com/en-us/library/7w2sway1(VS.80).aspx for more information.
The recommended fix was to set an encrypted machineKey in the web.config file. The Machine Key node is in the system.web element.
This was easily done and solved the problem thanks to the handy ASP.NETResources site which has a MachineKey Generator. See http://www.aspnetresources.com/tools/keycreator.aspx.
This exception is thrown when the assembly resource handler gets an invalid request. It is unlikely this is related to any malicious activity; it's usually caused by an incorrectly configured machine config on the server.
Some background:
ASP.NET has built-in mechanisms for exposing resources from the assembly (dll) via an HttpHandler. Resources such as JavaScripts and images can be stored as text in the assembly and requested by the browser via .axd handlers. But for security reasons, the handlers don't accept a plain-text location of the resource, which might expose clues about how your code works. Instead, it uses information in the machine.config on the server to encrypt a unique identifier to the resource. This exception gets thrown when a resource is requested, but when the server tries to decrypt the identifier provided, it fails.
The error is because your appdomain was recycled/restarted. When that happens the application and the machine key is set to auto, it changes. That affects the decryption of the info in the url of the resources urls (.axd). Setting up a fixed machine key will prevent it from ever happening again.
Please check this for more info on a similar case (the explanation is with an issue with viewstate validation, but the cause is the same one):
http://www.developmentnow.com/blog/InvalidViewstate+Or+Unable+To+Validate+Data+Error.aspx
Ps. this explains it on single server deployments :) - although the solution is the same for both multi-single server, the fix was usually only explained to make all servers use the same machine key.
Update 1: The padding is invalid message doesn't have relation to the css padding. If it is only happening on ie 5.5, it is likely the parameters for the webresource.axd are being messed up, just like in this question: Invalid Webresource.axd parameters being generated.

Resources