"Padding is Invalid and cannot be removed" exception on WebResource.axd - asp.net

I have an ASP.NET 2.0 application that is working fine in our local environment. When published to a test server, we're getting intermittent errors on the server.
Here's the most common:
Padding is invalid and cannot be removed.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details:
System.Security.Cryptography.CryptographicException:
Padding is invalid and cannot be
removed.
Source Error:
An unhandled exception was generated
during the execution of the current
web request. Information regarding the
origin and location of the exception
can be identified using the exception
stack trace below.
Stack Trace:
[CryptographicException: Padding is
invalid and cannot be removed.]
System.Security.Cryptography.RijndaelManagedTransform.DecryptData(Byte[]
inputBuffer, Int32 inputOffset, Int32
inputCount, Byte[]& outputBuffer,
Int32 outputOffset, PaddingMode
paddingMode, Boolean fLast) +1545747
System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[]
inputBuffer, Int32 inputOffset, Int32
inputCount) +257
System.Security.Cryptography.CryptoStream.FlushFinalBlock()
+30 System.Web.Configuration.MachineKeySection.EncryptOrDecryptData(Boolean
fEncrypt, Byte[] buf, Byte[] modifier,
Int32 start, Int32 length, Boolean
useValidationSymAlgo) +164
System.Web.UI.Page.DecryptString(String
s) +83
System.Web.Handlers.AssemblyResourceLoader.System.Web.IHttpHandler.ProcessRequest(HttpContext
context) +148
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+358 System.Web.HttpApplication.ExecuteStep(IExecutionStep
step, Boolean& completedSynchronously)
+64
This happens on a request to a specific WebResource.axd request.
The other error that we're seeing is this:
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. Description: An
unhandled exception occurred during
the execution of the current web
request. Please review the stack trace
for more information about the error
and where it originated in the code.
Exception Details:
System.Web.HttpException: 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.
This error happens occasionally while posting a form.
Now before you jump in and tell me the obvious (usual) answer to this error, consider this:
The application is deployed to Windows Server 2003 on IIS6
It is NOT on a web farm. Only one webserver is in use here.
The application pool identity is a custom service account, and I did run aspnet_regiss -ga <username> on the server. No effect.

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
I also had been wondering about it for quite a while. After I saw this question it got me on it again: Is this an attempt to break my ASP.Net site's security? ... which I just answered with very much the same. I had the feeling it was around some restart of something, because when we published something that recycled the application the error showed in the log, but I didn't have any other source stating its relation (today I found that case on invalidviewstate because of the machinekey change :))
Ps. above finally explains it on single server :)

This problem appears when a post is generated before the page is fully loaded in the browser. Have a look at this question.

Ben,
For your first problem, I found this that seems to be a bit more to the point of what you are seeing in that the problem is sporadically occurring.
You should be able to find a full explanation of this at http://www.codeproject.com/KB/security/Cryptor.aspx#aes.
What you really need to do is set RijndaelAlg.Padding to PaddingMode.ISO10126, PaddingMode.PKCS7, or PaddingMode.ANSIX923. Any one of these 3 values should work, provided that you use the same value when encrypting and decrypting. Other values will work with some data, but not with all data. The above URL explains why.
What I don't understand is the reason Microsoft provides options that sometimes don't work, or at least why they don't default to a reliable option.

Related

CryptographicException ID1073 error The is invalid on ASP.NET 4.0 site

Has anyone ever come across this error? I'm getting this when I post back to a forms authenticated site after redirecting to another site and then redirecting back. I've already checked that loadUserProfiles="true" but that did not help. This is a site hosted on IISExpress via other sites also hosted on IISExpress, using localhost gen'ed SSL certs and differentiating via host header. I'm pretty clueless at this point on where the error even comes from. Is it a cookie error? The FormsAuth cookie? It's ASP.NET 4.0 site where I'm authenticating against a Thinktecture Id server. Any feedback is appreciated to help me with my current block. Thanks
Server Error in '/' Application.
The data is invalid.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Security.Cryptography.CryptographicException: The data is invalid.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[CryptographicException: The data is invalid.
]
System.Security.Cryptography.ProtectedData.Unprotect(Byte[] encryptedData, Byte[] optionalEntropy, DataProtectionScope scope) +318
Microsoft.IdentityModel.Web.ProtectedDataCookieTransform.Decode(Byte[] encoded) +203
[InvalidOperationException: ID1073: A CryptographicException occurred when attempting to decrypt the cookie using the ProtectedData API (see inner exception for details). If you are using IIS 7.5, this could be due to the loadUserProfile setting on the Application Pool being set to false. ]
Microsoft.IdentityModel.Web.ProtectedDataCookieTransform.Decode(Byte[] encoded) +319
Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler.ApplyTransforms(Byte[] cookie, Boolean outbound) +217
Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(XmlReader reader, SecurityTokenResolver tokenResolver) +1951
Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(Byte[] token, SecurityTokenResolver tokenResolver) +149
Microsoft.IdentityModel.Web.SessionAuthenticationModule.ReadSessionTokenFromCookie(Byte[] sessionCookie) +595
Microsoft.IdentityModel.Web.SessionAuthenticationModule.TryReadSessionTokenFromCookie(SessionSecurityToken& sessionToken) +120
Microsoft.IdentityModel.Web.SessionAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs eventArgs) +113
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +136
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18044
Crypto errors like this are common if your application pool is not set to load its user profile. The crypto system needs to access user's cert store.
The exact moment the error occurs is when you authenticate and the sts sends back the signed SAML token.
This means that the error is subtle. You don't see it everytime, only in one exact moment. You can even be deceived that the error is gone because the site works correctly, however the error reappears as soon as someone tries to log in.
The problem was only happening in IE9 when running in Debug mode. After awhile it went away for whatever reason. :/

MSMQ: Message Queue service is not available. Error message

have had MSMQ working for the past few months but I am suddenly getting this error message:
Message Queue service is not available.
This is when i test it locally when I test it in live i get the follwoing message:
Unable to validate data.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: Unable to validate data.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[HttpException (0x80004005): Unable to validate data.]
System.Web.Configuration.MachineKeySection.EncryptOrDecryptData(Boolean fEncrypt, Byte[] buf, Byte[] modifier, Int32 start, Int32 length, Boolean useValidationSymAlgo, Boolean useLegacyMode, IVType ivType, Boolean signData) +4961431
System.Web.Security.MachineKey.Decode(String encodedData, MachineKeyProtection protectionOption) +194
System.Web.Helpers.AntiForgeryDataSerializer.Deserialize(String serializedToken) +120
[HttpAntiForgeryException (0x80004005): A required anti-forgery token was not supplied or was invalid.]
System.Web.Helpers.AntiForgeryDataSerializer.Deserialize(String serializedToken) +754
System.Web.Helpers.AntiForgeryWorker.Validate(HttpContextBase context, String salt) +199
System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor) +156
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +825488
System.Web.Mvc.Controller.ExecuteCore() +159
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +335
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +62
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +20
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +54
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +469
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +375
Has anyone come across this problem where it has been working and then stops and any fixes for this?
Edit: I had a few issues setting up msmq see:
MSMQ creating errors: A workgroup installation computer does not support the operation / User's internal Message Queuing certificate does not exist
My set up we have 6 servers which are load balanced and all have msmq set up, the domain is set up as a Network service and there are two other server which are involved - the doamin controller which receives the messages and serach server which receives the message - i don t kow if there is a problem on all or just one particular server. I have tried to narrow it down by using the Host file (C:\Windows\System32\drivers\etc\Host )and pointing at each server at a time but they still seem to be sporadic in whther they work or not. We do use caching so I'm not sure if this may be affecting anything...
Thanks
I know this might sounds like a dummy solution, but it will worked with me for sure.
You need to remove MSMQ and install again, but in order for the other services to actually see it you need to restart in between every step ... so What you need to do as follow:
Remove MSMQ
Restart Server
Install MSMQ
Restart Server: Noting sometime this step is not needed it depends on whether the other services are able to see the MSMQ at this level or not.
Good luck
To resolve this problem, follow these steps:
Log on to your computer as an administrator.
Click Start, and then click
Run.
The Run dialog box appears.
In the Open box, type
Services.msc, and then click OK.
The Services window appears.
Locate Message Queuing. Right-click
Message Queuing, and then click
Properties.
The Message Queuing Properties (Local Computer) dialog box appears.
On the Log On tab, click Local System account.
Click Apply, and then click
OK.
Stop the Message Queuing service, and then start the Message Queuing service.

asp.net error: This is an invalid webresource request

I am getting a ton of error alerts from one of my asp servers in a web farm, and all the servers have the same machine key in their web.config files.
I've looked around here but didn't find this exact case answered. Any suggestions would be welcome.
thanks for considering the question!
Here are some of the the error stacks (the query string is not from our app and could be part of something else):
Error message: This is an invalid
webresource request. Stack trace:
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)
Source: System.Web Method: Void
System.Web.IHttpHandler.ProcessRequest(System.Web.HttpContext)
Page: QueryString: d=hAGTq1Iohid
These may have started when the Win 2003 server was patched. Later dot.net frameworks were installed on three other servers but not on the one throwing the errors.
Most of the error seem related to decryption but all servers in the same web farm now same machine key in their web config. But that has not stopped the errors.
Seeing as well :
"Length of the data to decrypt is invalid"
Error message: Length of the data to decrypt is invalid. Stack trace: 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, Boolean useValidationSymAlgo) at System.Web.UI.Page.DecryptString(String s) at
System.Web.Handlers.AssemblyResourceLoader.System.Web.IHttpHandler.ProcessReques­t(HttpContext context) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.I­ExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
And Also
"Invalid length for a Base-64 char array"
Error message: Invalid length for a Base-64 char array.
Stack trace: at System.Convert.FromBase64CharArray(Char[] inArray, Int32 offset, Int32 length)
at System.Web.HttpServerUtility.UrlTokenDecode(String input)
at System.Web.UI.Page.DecryptString(String s)
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)
Source: mscorlib
Method: Byte[] FromBase64CharArray(Char[], Int32, Int32)
And
"Invalid view state"
Error message: Invalid viewstate.
Stack trace: at System.Web.UI.Page.DecryptString(String s)
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)
Source: System.Web
Method: System.String DecryptString(System.String)
Thanks again everyone.
I can't be sure, but it looks like a hack attempt trying to exploit the very serious .NET 'Padding Oracle' Crypto Attack, also discussed by Scott Guthrie. There is a patch available, so if you find that your server is indeed vulnerable, make sure you patch it immediately, and take damage-control steps if it has in fact been compromised.
This could also be caused by a problem with your application. However, if you're suddenly seeing large amounts of these errors, especially without any recent changes to your app, my first thought would be an intrusion attempt. The method used to exploit this vulnerability would generate errors related to decryption and bad data length.
If this server is the only one that is both unpatched AND showing the errors then the very first thing I would do is run all the windows updates on it.
Actually, let me make that statement less complicated: If this server is unpatched, start there and apply them.
UPDATE
You mentioned that the servers are throwing viewstate length errors. One thing we found was that several components, notably data grids, shove a tremendous amount of data into viewstate. Another thing was that several browsers would choke on this depending on length and not send all of it back.
After we made a particular web.config change this problem went completely away. Even Safari 3 started working right. Go to the <system.web> <pages /> node and make the following change:
<pages maxPageStateFieldLength="500" />
This will cause viewstate to be broken up across multiple hidden fields at 500 bytes each. It's an automatic split so none of your regular code has to change to support it.
You might play with the value, but essentialy some browsers can only send so much data back per input field. Depending on the version I've seen safari choke when those values were much more than around 700 bytes or so. Also firewalls and proxy servers might cause issues as well. See the following for a bit more information: http://weblogs.asp.net/lduveau/archive/2007/04/17/viewstate-chunking-in-asp-net-2-0-maxpagestatefieldlength.aspx
Another option to pursue is to have viewstate cached locally and not send it across the wire at all. Of course, that has implications in a web farm scenario so pick your poison.
Happened to me just now on a web site, for no apparent reason: The request for a web resource generated "invalid request" error and all the scripts were broken.
Could be an update to the server, maybe..
My solution was to go to the IIS control panel and to generate a new machine key for the site.
This seems to solve the problem, whatever that was.

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.

System.Web.AspNetHostingPermission SecurityException when trying to use ManagedFusion Rewriter on Goddaddy

I wonder if someone could help me out with an issue I'm experiencing trying to get my site up and running on Goddaddy.
I'm trying to get extension-less url rewriting working using the ManagedFusion Rewriter (http://www.codeplex.com/urlrewriter/) Unfortunately I'm getting the following error:
Server Error in '/' Application.
Security Exception
Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.
Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) +0
System.Security.CodeAccessPermission.Demand() +59
System.Web.Hosting.HostingEnvironment.get_ApplicationID() +61
IIS7Injector.TraceManager.TraceEvent(TraceEventType eventType, String message) +62
IIS7Injector.ConfigManager.IsSkippedUrl(HttpRequest request, String ContentType) +38
IIS7Injector.InjectedContentStream.Write(Byte[] buffer, Int32 offset, Int32 count) +153
ManagedFusion.Rewriter.FormActionFilter.Write(Byte[] buffer, Int32 offset, Int32 count) +485
System.Web.HttpWriter.FilterIntegrated(Boolean finalFiltering, IIS7WorkerRequest wr) +265
System.Web.HttpResponse.FilterOutput() +80
System.Web.CallFilterExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +54
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +64
Version Information: Microsoft .NET Framework Version:2.0.50727.1434; ASP.NET Version:2.0.50727.1434
I'm runnung using IIS 7 in integrated mode. I've modified my web.config file by following the instructions in the readme file here:
http://www.codeplex.com/urlrewriter/Release/ProjectReleases.aspx?ReleaseId=22618
Thank very much in advance.
I hit this same exception on a new install, changing the App pool identity to NetworkService / aspnet fixed it.
Additionally, enabling Load User Profile on the app pool also worked.
Try the following:
App Pool -> Advanced Settings -> Load Users Profile = True
for me it was:
1. unblock all files
http://nicholasrogoff.wordpress.com/2010/09/01/how-to-bulk-unblock-files-in-windows-7-or-server-2008/
2.restart application pool
One cause for this problem is when you have done the totally odd thing of publishing you application on the server by using the server to download the application from the Internet. The files will then be marked as originating from the Internet, and security settings then prevent them from running.
The "downloaded-from-Internet" mark is stored in the file system as an NTFS alternative data stream. Use the "Streams" tool to display and remove the flags:
http://technet.microsoft.com/en-us/sysinternals/bb897440.aspx
Then restart the application pool.
This is actually a known issue with GoDaddy's Medium Trust environment. However with the latest release of URL Rewriter 3.0 all these issues are now gone. Please get the latest release and let me know if you have any issues.
I had a similar issue with GoDaddy. Even though it didn't seem related at first since it's not in the stack trace (and may not apply to you since you're using third party code), removing Response.End() calls solved the issue in my case.
I had this issue because of a networked drive at work.When i moved my project to my desktop it started working again.

Resources