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

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. :/

Related

Key not valid for use in specified state. After IIS Reset

I tried this:
runas /user: domain\user cmd with no luck
This seems to only occur now when IIS is reset and I try to resume my browsing session. So I am logged into the application, I reset IIS on the server, refresh the page and see the error.
I am building an application in .NET 4.0 MVC with a Secure Token Service that is using WIF 4.0. Everything works as expected, except this case. I even tried to use a custom error page, but the error is happening there as well. Because of that, I can't get the custom page to show either. Also, This is using a certificate that is located on both load balanced servers. This happens in my dev environment whihc consists of only one server (app, wfe, db operated there)
One thing I noticed is that if I switch my IIS APP Pool user back to Network Service account it doesn't throw the error any more. We have some restrictions (mostly network related) in the application that we need to use an account in our AD for the app pool sections
Anybody have any experience with this issue?
Key not valid for use in specified state.
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: Key not valid for
use in specified state.
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: Key not valid for use in specified state. ]
System.Security.Cryptography.ProtectedData.Unprotect(Byte[]
encryptedData, Byte[] optionalEntropy, DataProtectionScope scope) +428
Microsoft.IdentityModel.Web.ProtectedDataCookieTransform.Decode(Byte[]
encoded) +54
[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) +146
Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler.ApplyTransforms(Byte[]
cookie, Boolean outbound) +113
Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(XmlReader
reader, SecurityTokenResolver tokenResolver) +647
Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(Byte[]
token, SecurityTokenResolver tokenResolver) +105
Microsoft.IdentityModel.Web.SessionAuthenticationModule.ReadSessionTokenFromCookie(Byte[]
sessionCookie) +262
Microsoft.IdentityModel.Web.SessionAuthenticationModule.TryReadSessionTokenFromCookie(SessionSecurityToken&
sessionToken) +76
Microsoft.IdentityModel.Web.SessionAuthenticationModule.OnAuthenticateRequest(Object
sender, EventArgs eventArgs) +53
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+148 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
This issue is related to session cookies.
WIF protects session cookies using Data Protection API (DPAPI) by default, and the DPAPI is closely related to machine keys.
If the keys used to encrypt the session cookies change, it throws this exception.
It could be also related to your app hosting infrastructure.
if your app is running in an Network Load Balancer (NLB) environment
if you change the app pool settings (e.g., change the pool’s user)
More details about this scenario on the MSDN blog entry:
WIF 1.0 – ID1073 A CryptographicException occurred when attempting to decrypt the cookie using the ProtectedData API Archive.Today Shortlink
Todd Foust (October 29, 2012)
So, if your app runs in NLB environment, you could :
Configure your load balancer to use sticky sessions. This means that your user will be directed to the same server during the session duration. (I’m not very fond of that one)
Use a certificate to encrypt the session cookies
set all web.config files to use the same machine key in system.web
If you are not running the app in a NLB env, you could try:
set the machinekey in your web.config to use a pre-defined value instead of auto-generated values
Regarding auto-generated machinekey setting, please see:
How unique is your machine key?Archive.Today Shortlink

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.

exception Collection is read-only error with ASP4.5 on IIS7.5

I am running Dotnetnuke7 on a shared hosting environment using ASP.net 4.5 and IIS configured in integrated pipeline mode (as required by DNN7).
When I install it on a Win2008/IIS7 server (ASP4.0) at the hosting provider the application runs fine, but when I install it on a Win2008R2/IIS7.5 server at the hosting provider(ASP4.5) I get an exception Collection is read-only when trying to log-in or submitting anything to the site. (For example use DNN search function). See detailed stacktrace below.
The hosting provider checked the .net 4.5 permissions, and also applies apppool-specific permissions, but no luck yet.
Anybody a clue what IIS7.5 parameter or option can be the cause here?
Server Error in '/' Application.
Collection is read-only.
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.NotSupportedException: Collection is read-only.
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:
[NotSupportedException: Collection is read-only.] System.Collections.Specialized.NameObjectCollectionBase.BaseSet(String name, Object value) +6703734
System.Web.HttpServerVarsCollection.SetServerVariableManagedOnly(String name, String value) +116
System.Web.HttpServerVarsCollection.SynchronizeServerVariable(String name, String value) +28
System.Web.HttpRequest.SynchronizeServerVariable(String name, String value) +112 System.Web.Hosting.IIS7WorkerRequest.GetServerVarChanges(HttpContext ctx) +308 System.Web.Hosting.IIS7WorkerRequest.SynchronizeVariables(HttpContext context) +9676858 System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +151
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.17929
For anyone stumpling on this - I had this exact issue today.
Resolved by two actions for me:
Verify isapi filters in IIS for .net 4.0/4.5 etc are ALLOWED
I had installed rewriter-modules (Helicon). Once I removed these ISAPI-filters again - all worked fine.
So check isapi-filters is my advice and start without any additional filters except the needed .net filters.

Commerce Server and ASP.NET Integrated Pipeline error

I am using Microsoft Commerce Server 2007 and a custom ASP.NET 2.0 website. Everything works well in Classic Pipeline, but when I try to use the Integrated pipeline, it fails with the following error:
Server Error in '/' Application.
Request is not available in this context
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: Request is not available in this context
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): Request is not available in this context]
System.Web.HttpContext.get_Request()
+8794400 Microsoft.CommerceServer.Runtime.Orders.CommerceOrderModule.Init(HttpApplication
appInstance) +134
System.Web.HttpApplication.InitModulesCommon()
+65 System.Web.HttpApplication.InitIntegratedModules()
+49 System.Web.HttpApplication.InitInternal(HttpContext
context, HttpApplicationState state,
MethodInfo[] handlers) +729
System.Web.HttpApplicationFactory.GetNormalApplicationInstance(HttpContext
context) +298
System.Web.HttpApplicationFactory.GetApplicationInstance(HttpContext
context) +107
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest
wr, HttpContext context) +363
I've done my best to research this, and it's definitely caused by Commerce Server trying to access the HttpContext.Current when there is no current request. This all happens before anything in my code, and there's nothing to break into or any source code to look at. I've even tried attaching the debugger to the IIS process (w3wp.exe), but it doesn't catch anything.
I have followed the instructions Here to add the web.config section, but it hasn't made any difference.
I have a different website on a different server using Commerce Server in Integrated Pipeline mode with no problems, so I know it's possible. I can't find a significant difference between the two web.config files, so I'm assuming it's a config error somewhere else, but I don't have any idea where to look.
It is critical that I can get this working in Integrated Pipeline mode for performance reasons, plus I am creating a custom URL Rewriting HTTP Module which works with the integrated pipeline only.
Thank you in advance for any help!

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

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.

Resources