I'm currently fixing some Security issues in our ASP.net website application.
One of the issue was that the ViewState was not encrypted.
So I did check on StackOverFlow and elsewhere on how to encrypt the viewState, and I did it using the <pages viewStateEncryptionMode="Always" /> and adding a 3DES machinekey like this <machineKey validation="3DES" /> in Web.config .
I would like to know if the "EnableViewStateMAC=true" is also compulsorily necessary? since this was mentioned in some of the suggested solutions I had found online.
But, on my checks I found the encryption is working even without this.
[NOTE: I had to do these changes at an application level (Web.config) since making individual page changes is not a practical solution for this application.]
Do not ever set EnableViewStateMac to false, even if encryption is enabled. The MAC guarantees that the client cannot maliciously tamper with the contents of ViewState. (Encryption by itself isn't sufficient to guarantee this; the MAC is necessary.)
The EnableViewStateMac property will be removed in a future version of the product since there is no valid reason to set it to 'false'.
Just in case:
Starting with ASP.NET 4.5.2, the runtime enforces EnableViewStateMac = true
more details here: ASP.NET 4.5.2 and EnableViewStateMac
You might want to note that as of September 2014
All versions of the ASP.NET runtime 1.1 - 4.5.2 now forbid setting
<%# Page EnableViewStateMac="false" %>
and
<pages enableViewStateMac="false" />
http://blogs.msdn.com/b/webdev/archive/2014/09/09/farewell-enableviewstatemac.aspx
It 'll be problem When You host multi server. Because Machine Keys are different.
IF your project runs on single machine. EnableViewStateMAC=true is safely.
Using enableViewStateMac requires that successive requests be forwarded to the same server (i.e. server affinity). This feature is used to help prevent tampering of a page's view state; however, it does so based on an auto-generated validation key on the current server. From this key, a message authentication code (MAC) is generated and sent in the ViewState back to the browser. The problem is that if a POST back is performed and goes to a different server, you will get a nice little error message saying “Corrupt View State“.
To fix this, you can either set enableViewStateMac to false in the element or specify a common value for the validationKey attribute in the element across all servers (in the farm).
By the way, documentation says that this is OFF by default. That is incorrect! Go check machine.config!
I'm seeing some very strange behaviour when debugging my web application in VS2010 locally. The same user journey/sequence of pages happens in Production.
Debugging, I'm seeing this:
1. request for MyPage.aspx - handled by thread_1
2. (there is something on that page that IIS/ASP.Net doesn't like it seems) I'm slowly removing sections to pin-point exactly but there's
no JS, or anything fancy there just html content, user controls etc.
3. Either way a separate thread_2 to begin processing the Page_Load of my defaultdocument i.e. home.aspx is executed. There is logic in
home.aspx.cs to clear some data.
4. So when thread_1 continues processing, checks against the data above fail, resulting with the user being redirected to an error page.
Can anyone shed any light on why the second thread is created and why it starts to process my default document?
Please note:
I've checked the global methods for errors e.g. session_end,
app_error etc but nothing.
I do intermittently see a 401 error with Failed Request Tracing Logging enabled but I don't understand how that would start the
processing of my default home page?
just to sanity check, I placed a new doc test.aspx at the beginning of my defaultdocument list in the web.config and it did get called.
It seems as though, something within IIS/ASP.Net is configured to begin processing the default page on an error but this is new behaviour to me?
I've tried researching this but the only thing that seems that it could be related is thread-agility but I'm not too sure..?
It seems like there are two HTTP requests running concurrently. As each request (generally) executes on its on thread this condition would make sense.
HTTP requests by default do not share state. They operate on different data. For that reason this is not a thread-safety issue.
An exception to this rule is if you explicitly share state e.g. using static variables. You shouldn't do this for various reasons.
To debug the problem launch Fiddler and examine the HTTP request being executed. Also example HttpContext.Current.Request.RawUrl on each of the two concurrent threads.
After removing a lot of content within the faulty MyPage.aspx, I came across the guilty line of code: btnShowPost.ImageUrl = SitePath + "post.png"; (it was never accessed behind an if statement) and therefore the image <asp:Image ID="btnShowPost" runat="server" /> never set the necessary ImageUrl.
Without it, apparently this is standard browser behavior: any img, script, css, etc, with a
src= missing, will use the default path as the url. iis will usually redirect to default.aspx (or whatever is the default).
See full explanation on this link
I am getting this error, and I know what causes it. There are many causes, but in my case, the issue is that the machinekey differs from server to server (in the web farm) and therefore when it jumpes from machine to machine, it can't decrypt viewstate and/or cookies . I've since fixed this issue, however, there are some users still left with a cookie on their machine, written with the old machinekey, and they are getting this error. I need a good way to handle this error, log them out and then redirect back to the login page. I've tried putting an exception handler in global.asax in Application_error, but this doesn't seem to fire for this error. There are other errors that happen, and I've filtered to catch only this error (by looking at the exception). I have customErrors 'on' in the web.config. How do I do this?
There are a few ways to resolve this issue. The best overall solution is to set the encryption and decryption keys explicitly in the machine.config of each server:
<machineKey validationKey="JFDSGOIEURTJKTREKOIRUWTKLRJTKUROIUFLKSIOSUGOIFDS..." decriptionKey="KAJDFOIAUOILKER534095U43098435H43OI5098479854" validation="SHA1" />
Another option is to disable encryption of the ViewState altogether, but you will lose some security benefits by doing this:
<pages viewStateEncryptionMode="Never" />
Lastly, you can disable the validation:
<pages enableViewStateMac="false" ... />
On one of my servers which has quite a big trasffic Im receiving error: Validation of viewstate mac failed.
Is it possible that it happens because user submits form (for example by clicking asp:Button) before all viewstate is loaded ?
Thank You for any suggestions
If you are hosting this app in a Web Farm or cluster make sure that configuration specifies the same validationKey and validation algorithm. Remember that AutoGenerate cannot be used in a cluster.
See this article for complete root conditions of this type of error and suggested work arounds.
I seem to be getting a "invalid viewstate" every now and then in the event viewer for my ASP.NET application.
Most of them (95%) seem to be referencing ScriptResource.axd (the application
uses the ASP.NET AJAX library). There is no way I can remove the Ajax library either as Ajax is used everywhere..
How can I reduce these errors? I'm getting ~ 100-200 errors a day and I have no idea how to fix them! They come from different browsers, different IPs and geographical locations.
It's difficult for me to reproduce the problem because it barely even happened to me, it has only happened to me 3-4 times out of the blue.
Error:
Process information:
Process ID: 4004
Process name: w3wp.exe
Account name: NT AUTHORITY\NETWORK SERVICE
Exception information:
Exception type: HttpException
Exception message: Invalid viewstate.
Request information:
Request URL: http://domainnamehere/ScriptResource.axd?d=W1R6x9VzZ2C9SKnIkOmX9VRLhSjJ3nOF1GSQvPwKS3html
Request path: /ScriptResource.axd
User host address: 124.177.170.75
User:
Is authenticated: False
Authentication Type:
Thread account name: NT AUTHORITY\NETWORK SERVICE
Thread information:
Thread ID: 1
Thread account name: NT AUTHORITY\NETWORK SERVICE
Is impersonating: False
Stack trace: 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)
Custom event details:
For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.
I also get this error every now and then in my .NET code which happens at the same time which might be related:
Exception raised in GLOBAL.ASAX.Application_Error(): 'Padding is invalid and cannot be removed.' 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.ObjectStateFormatter.Deserialize(String inputString)
This appears to be the same IE8 issue that many people have been experiencing. What appears to happen is that somehow IE8 (in both IE8 rendering mode and IE7 compatibility mode) will lose 4096 bytes out of the middle of the HTML document and this missing data causes this exception (you usually see this in a ScriptResource or WebResource call).
Here is a Microsoft bug report on the issue:
https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=434997
Also there are plenty of forum, blog etc posts on this issue:
Invalid Webresource.axd parameters being generated
IE 8 dropping memory pages?
http://forums.asp.net/t/1373410.aspx?PageIndex=1
http://forums.asp.net/p/1409964/3085329.aspx
Microsoft has responded to this issue:
Note is a bug in Internet Explorer 8. The Internet Explorer team has been investigating this issue.
Impact: Thus far, we believe the problem has no impact on the end-user's experience with the web application; the only negative effect is the spurious/malformed requests sent by the JavaScript speculative-download engine. When the script is actually needed by the parser, it will properly be downloaded and used at that time.
Circumstances: The spurious-request appears to occur only in certain timing situations, only when a META HTTP-EQUIV tag containing a Content-Type with a CHARSET directive appears in the document, and only when a JavaScript SRC URL spans the 4096th byte of the HTTP response body.
Workaround: Hence, we currently believe this issue can be mitigated by declaring the CHARSET of the page using the HTTP Content-Type header rather than specifying it within the page.
So, rather than putting
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8">
In your head tag, instead, send the following HTTP response header:
Content-Type: text/html; charset=utf-8
Note that specification of the charset in the HTTP header results in improved performance in all browsers, because the browser's parsers need not restart parsing from the beginning upon encountering the character set declaration. Furthermore, using the HTTP header helps mitigate certain XSS attack vectors.
NOTE: There have been reports that this problem still happens when the META HTTP-EQUIV is not on the page. We will update this comment when we have more investigation.
Posted by Microsoft on 6/30/2009 at 12:25 PM.
Edit:
I still see this exception occasionally, but this bug is reported as being fixed:
Link
I guess you are using ASP.NET AJAX. I am having the same problem. Sporadically I would find this exception in my Event Log, and the requested path is ALWAYS ScriptResource.axd.
Using fixed validationKey and decryptionKey in machineKey did not fix the problem for me.
Based on what I was able to gather, I tend to believe that this error has nothing to do with the ViewState whatsoever; my theory is that for some reason, certain UAs somehow mess up the "d" parameter of the ScriptResource.axd. The problem is easily replicable by requesting the offending path manually. This gives an "Invalid ViewState" exception, even though ViewState doesn't even apply here.
Digging through my logs, I found for example:
This request is served OK (200):
/ScriptResource.axd?d=oFCAB7_vUyp7Hhe9lxZBz37lpoAxhfbWwwdfFy3Zd3z41W_33Y_9Dq6i10g9Q1NRCY1n0_DNg1nE6-DDbsD6r4EiuwoeDzp9mjDDfBNLb1k1&t=41df03cc
This slightly different request is also served OK (200):
/ScriptResource.axd?d=oFCAB7_vUyp7Hhe9lxZBz37lpoAxhfbWwwdfFy3Zd3z41W_33Y_9Dq6i10g9Q1NR5ijsxQts4AfbJdACRwmQ8sHt6UAzui3spEnooPneTz01&t=41df03cc
This request fails with a 500 response and the Invalid ViewState exception:
/ScriptResource.axd?d=oFCAB7_vUyp7Hhe9lxZBz37lpoAxhfbWwwdfFy3Zd3z41W_3products$ctl00$AddToCart1$id
If you look closely, the first few characters on all three request are the same, but the last few characters of the last request (in bold) clearly is Control ID "products$ctl00$AddToCart1$id" (I have a controls named products and AddToCart). I don't know how this ID got there, but in my case this is what is causing all these Invalid ViewState exceptions.
I'm not sure whether this is the same case as the OP or not, but I notice Martin's Request URL ends in "html", which is a bit of a coincidence for a parameter that is supposed to be a key...
I already have a headache thanks to this problem. And so far, the most insightful post I came across is this one http://bytes.com/topic/asp-net/answers/861764-invalid-viewstate-system-string-decryptstringwithiv
Any insights?
Viewstate issues are annoying and frustrating - I've noticed a few people have talked about having Viewstate issues in this thread. So, here are some suggestions you can look at in order.
I'd echo what Freddy Rios has said
in the thread already. Make sure
that you've hardcoded the machine
key. This will solve the vast
majority of these issues. The
important thing about the
ScriptResource link is that it
should have a d parameter and a t
parameter in the querystring. If it
doesn't something else is wrong!
Don't let the user postback until
your done. You could probably do
this with javascript and a bit of
css. From memory, I think there is a
way to do this with a meta tag but
it might be IE only.
I would look at is flushing the
response early. I would think after
the script manager would be best.
But you might need to experiment a
bit.
If your viewstate looks bloated,
turn on GZip compression on in IIS.
If your viewstate has became really
bloated and you can't get GZip
compression turned on/or it has an
undesired side affect. Then you can
compress and uncompress the
viewstate.
http://www.codeproject.com/KB/viewstate/ViewStateCompression.aspx
If that still leaves you with a
bloated viewstate, you could look at
storing the viewstate locally.
http://blog.arctus.co.uk/articles/2007/04/23/advanced-asp-net-storing-viewstate-in-a-database/
is a good starting point.
Use a fixed machine key (even when doing single server).
The issue occurs when using the auto configuration for the machine key, you get a new one each time the app domain is recycled. This affects viewstate validation, dynamic resources query string decryption and authentication tickets [insert other uses of the machine key].
I've seen problems like this when the Viewstate is too large. I've seen it happen becaue of the problem Freddy describes.
I generally dislike the idea of using Viewstate. Can you turn Viewstate off altogether?
I am also having this issue, and I've tried everything mentioned in all the blogs I've found (fixed machine key, viewstate size, etc). 99% of the time the error is logged on requests to ScriptResource.axd. I am using .net 3.5 SP1, on Win 2003 server. The app is hosted on two parallel identical servers, balanced 50/50. Each server has the same machine key.
Normally this error does not concern me much, however, over a 3 month period, the trend on occurance has been going way up.
Does anyone think this error is related to the Viewstate not being UrlEncoded/HtmlEncoded or UrlDecoded correctly. Perhaps there is character subset within the viewstate that some browsers are replacing with some encoded value. I'm not sure if that even makes sense..
I think, you must use in aspx page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
This solve my problem
Are you running a non-english Operation System?
For some reasons, the account name of "NT Authority\Network Service" has been localized in other languages.
Sadly, a lot of programs have the account name hard coded to the english name, and won't find the Network Service when running on foreign versions of Windows, leading to all kind of funky errors in the event log.
I have just narrowed this issue down for me to a user with Trend Micro antivirus and the errors just started to occur after he updated his trend micro software on 5/21/2009. No errors before this date.
The problem seems to be the lookahead downloader in IE8.
It seems to only affect IE8 in a fairly obscure set of circumstances. One of the reasons it can go unnoticed is that a 4k chunk of data appended to a URL is often discarded by the server. One of the things that seems to make it more likely is a slow network connection. Someone in one of the below resources noted that he only had the issue with his clients in New Zealand.
Lots of people explaining two separate problems, one of which is described in the question above (malformed URLs sent to server):
http://connect.microsoft.com/VisualStudio/feedback/details/434997/invalid-webresource-axd-parameters-being-generated
Article explaining that the lookahead downloader is fixed:
http://blogs.msdn.com/b/ieinternals/archive/2010/04/01/ie8-lookahead-downloader-fixed.aspx
KB980182 – Cumulative update in which issue is fixed:
http://support.microsoft.com/kb/980182
NOTE: Because the script is automatically re-downloaded if it couldn’t be retrieved by the lookahead downloader, it should be possible to change back to the old validation mode in which .axd files were not checked for validity and remove the symptoms of the issue:
<httpRuntime requestValidationMode="2.0" />