Key not valid for use in specified state after IISRESET - encryption

I have created a Custom STS Login Application and logging in/out functionalities were working fine. But if i login as some user and do IISRESET and then reloaded the page the below error is spitted. (But as expected it works fine after I cleared the cookies and logged in again :) )
Apppool user for STS Application is "A" and he has never windows logged into the server machine, where STS Application is deployed(he is in administrators group and has access to encryption certificates).
I tried to login once as "A" in to the server(Windows Login) and after that all of a sudden this issue is solved.
Can anyone tell why was it not working after IISRESET and working after windows logging in once?
Server Error in '/’ Application.
Key not valid for use in specified state.
[CryptographicException: Key not valid for use in specified state.]
System.Security.Cryptography.ProtectedData.Unprotect(Byte[] encryptedData, Byte[] optionalEntropy, DataProtectionScope scope)
Microsoft.IdentityModel.Web.ProtectedDataCookieTransform.Decode(Byte[] encoded)
[InvalidOperationException: 1D1073: A CryptographicException occurred when attempting to decrypt the cookie using the ProtectedData API (see inner exception for details).
Microsoft.IdentityModel.Web.ProtectedDataCookieTransform.Decode(Byte[] encoded) +433
Microsoft.IdentityModel .Tokens.SessionSecurityTokenHandler.ApplyTransforms(Byte] cookie, Boolean outbound) +189
Microsoft. IdentityModel .Tokens. SessionSecurityTokenHandler. ReadToken(XmlReader reader, SecurityTokenResolver tokenResolver) +894
Microsoft. IdentityModel .Tokens. SessionSecurityTokenHandler. ReadToken(Byte]] token, SecurityTokenResolver tokenResolver) +118
Microsoft.IdentityModel.Web.SessionAuthenticationModule.ReadSessionTokenrrocCookie(Byte] sessionCookie) +363
Microsoft.IdentityModel.Web. SessionAuthenticationModule.TryReadSessionTokenFroaCookie(SessionSecurityToken& sessionToken) +124
Microsoft. IdentityModel .Web. SessionAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs eventArgs) +61
System.Web.SyncEventExecutionstep.System.Web.HttpApplication.IExecutionStep.Execute() +80
System. Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +270
Version Information: Microsoft .NET Framework Version:4.D.30319; ASP NET Version:4.O.30319.272

If you're running with the default WIF config, the keys used to secure the session tokens are handled through DPAPI and are stored in the user profile. These keys change on iisreset unless you configure IIS with "Load User Profile" as true.
If you're running on .NET 4.5 the easiest approach would be to configure machineKeys for your application and use the new MachineKeySessionSecurityTokenHandler, as documented in Wif and Web Farms.

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

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

Federated Authentication on Azure

I'm using WIF (.net 4.5), and Azure Active directory for authentication. The website will sit on Azure.
Everything works as expected locally, however when I put it onto azure I get the error:
The data protection operation was unsuccessful. This may have been caused by not having the user profile loaded for the current thread's user context, which may be the case when the thread is impersonating.
I understand this is because the apps can't use DAPI, so I need to switch to protecting my app with the MAC.
Locally I added this to my webconfig:-
<securityTokenHandlers>
<remove type="System.IdentityModel.Tokens.SessionSecurityTokenHandler, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add type="System.IdentityModel.Services.Tokens.MachineKeySessionSecurityTokenHandler, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</securityTokenHandlers>
as recommended in the documentation, and I added a static machine key, but I can't find any advice around the key length - so I have assumed 256.
This configuration however just gives this error:
[CryptographicException: Error occurred during a cryptographic operation.]
System.Web.Security.Cryptography.HomogenizingCryptoServiceWrapper.HomogenizeErrors(Func`2 func, Byte[] input) +115
System.Web.Security.Cryptography.HomogenizingCryptoServiceWrapper.Unprotect(Byte[] protectedData) +59
System.Web.Security.MachineKey.Unprotect(ICryptoServiceProvider cryptoServiceProvider, Byte[] protectedData, String[] purposes) +62
System.Web.Security.MachineKey.Unprotect(Byte[] protectedData, String[] purposes) +122
System.IdentityModel.Services.MachineKeyTransform.Decode(Byte[] encoded) +161
System.IdentityModel.Tokens.SessionSecurityTokenHandler.ApplyTransforms(Byte[] cookie, Boolean outbound) +123
System.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(XmlReader reader, SecurityTokenResolver tokenResolver) +575
System.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(Byte[] token, SecurityTokenResolver tokenResolver) +76
System.IdentityModel.Services.SessionAuthenticationModule.ReadSessionTokenFromCookie(Byte[] sessionCookie) +833
System.IdentityModel.Services.SessionAuthenticationModule.TryReadSessionTokenFromCookie(SessionSecurityToken& sessionToken) +186
System.IdentityModel.Services.SessionAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs eventArgs) +210
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +136
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69
I removed the machinekey section incase I hadn't specified a correctly formatted key, but the error doesn't go away.
What a fight WIF has been!
If you don't specify machineKey in configuration, Azure adds one. But if you create new version of your application and deploy it to Azure using VIP switching, Azure generates a new machine Key for the deployment in Staging (assuming your first deployment was to Production). (VIP switching is nice mechanism for deploying new version and then switching virtual IP addresses between Production and Staging).
So basically one solution is letting Azure to generate the key but after VIP switch you have the problem back. To avoid it you can catch the CryptographicException in Global.asax in Application_Error handler, something like this:
// Be sure to reference System.IdentityModel.Services
// and include using System.IdentityModel.Services;
// at the start of your class
protected void Application_Error(object sender, EventArgs e)
{
var error = Server.GetLastError();
var cryptoEx = error as CryptographicException;
if (cryptoEx != null)
{
FederatedAuthentication.WSFederationAuthenticationModule.SignOut();
Server.ClearError();
}
}
The SignOut() method causes the cookie is removed.
Edit: updated info on generating machineKey as noted by #anjdreas.
Another solution is to generate the machineKey, you can use IIS Manager to do it, see Easiest way to generate MachineKey for details. If you put the same key into all your web appliactions within Azure Web Role, the Azure deployment process will not replace it.
The machine key shouldn't be there: Windows Azure generates one for you and makes sure it is identical on every instance in your role.
About the error you're seeing: can you try clearing cookies?
Simply clearing the cookies solved the whole problem for me in this case.
If you are using forms auth. you can signout when you catch the exception and allow your users to login and create a valid cookie
catch (CryptographicException cex)
{
FormsAuthentication.SignOut();
}
Asking all the users to clear all cookies wasn't really an option for me. On this site and also in the book "Programming Windows Identity Federation" I found a better solution (for me, anyways). If you're already uploading an SSL certificate to Azure, you can use that certificate to also encrypt your cookie on all Azure instances, and you won't need to worry about new machine keys, IIS user profiles, etc.

Hosting WCF Web Serveic on Windows Server 2003

Getting the following err...
Server Error in '/' Application. IIS
specified authentication schemes
'IntegratedWindowsAuthentication,
Anonymous', but the binding only
supports specification of exactly one
authentication scheme. Valid
authentication schemes are Digest,
Negotiate, NTLM, Basic, or Anonymous.
Change the IIS settings so that only a
single authentication scheme is used.
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.InvalidOperationException: IIS
specified authentication schemes
'IntegratedWindowsAuthentication,
Anonymous', but the binding only
supports specification of exactly one
authentication scheme. Valid
authentication schemes are Digest,
Negotiate, NTLM, Basic, or Anonymous.
Change the IIS settings so that only a
single authentication scheme is used.
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:
[InvalidOperationException: IIS
specified authentication schemes
'IntegratedWindowsAuthentication,
Anonymous', but the binding only
supports specification of exactly one
authentication scheme. Valid
authentication schemes are Digest,
Negotiate, NTLM, Basic, or Anonymous.
Change the IIS settings so that only a
single authentication scheme is used.]
System.ServiceModel.Web.WebServiceHost.SetBindingCredentialBasedOnHostedEnvironment(ServiceEndpoint
serviceEndpoint, AuthenticationSchemes
supportedSchemes) +446264
System.ServiceModel.Web.WebServiceHost.AddAutomaticWebHttpBindingEndpoints(ServiceHost
host, IDictionary`2
implementedContracts, String
multipleContractsErrorMessage) +709
System.ServiceModel.Web.WebServiceHost.OnOpening()
+203 Microsoft.ServiceModel.Web.WebServiceHost2.OnOpening()
in
e:\bt\3781\Microsoft.ServiceModel.Web\Microsoft.ServiceModel.Web\WebServiceHost2.cs:69
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
timeout) +229
System.ServiceModel.HostingManager.ActivateService(String
normalizedVirtualPath) +121
System.ServiceModel.HostingManager.EnsureServiceAvailable(String
normalizedVirtualPath) +479
[ServiceActivationException: The
service '/Service.svc' cannot be
activated due to an exception during
compilation. The exception message
is: IIS specified authentication
schemes
'IntegratedWindowsAuthentication,
Anonymous', but the binding only
supports specification of exactly one
authentication scheme. Valid
authentication schemes are Digest,
Negotiate, NTLM, Basic, or Anonymous.
Change the IIS settings so that only a
single authentication scheme is
used..]
System.ServiceModel.AsyncResult.End(IAsyncResult
result) +11599786
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult
result) +194
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.ExecuteSynchronous(HttpApplication
context, Boolean flowContext) +176
System.ServiceModel.Activation.HttpModule.ProcessRequest(Object
sender, EventArgs e) +278
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+68 System.Web.HttpApplication.ExecuteStep(IExecutionStep
step, Boolean& completedSynchronously)
+75
Version Information: Microsoft .NET
Framework Version:2.0.50727.3615;
ASP.NET Version:2.0.50727.3618
According to your error above, you have IIS authentication configured on your Windows 2003 machine to allow two different types of authentication (integrated & anonymous). Change it to one type of authentication - the one that matches your WCF configuration. I'm guessing you only want anonymous (and not integrated) enabled in the IIS configuration, but that's your design choice..

Windows Authentication in IIS 7.5 Fails with Trust Relationship Exception

I have an ASP.Net 2.0 application that uses integrated Windows Authentication to authenticate/authorize users. The application works fine on Windows XP/IIS 5.1, Windows Server 2008/IIS 7, and Windows Vista/IIS 7. When I try to run this application on Windows 7/IIS 7.5, I get the following exception: The trust relationship between this workstation and the primary domain failed.
The stack trace is as follows:
[SystemException: The trust relationship between this workstation and the primary domain failed.
]
System.Security.Principal.NTAccount.TranslateToSids(IdentityReferenceCollection sourceAccounts, Boolean& someFailed) +1085
System.Security.Principal.NTAccount.Translate(IdentityReferenceCollection sourceAccounts, Type targetType, Boolean forceSuccess) +46
System.Security.Principal.WindowsPrincipal.IsInRole(String role) +128
System.Web.Configuration.AuthorizationRule.IsTheUserInAnyRole(StringCollection roles, IPrincipal principal) +229
System.Web.Configuration.AuthorizationRule.IsUserAllowed(IPrincipal user, String verb) +354
System.Web.Configuration.AuthorizationRuleCollection.IsUserAllowed(IPrincipal user, String verb) +245
System.Web.Security.UrlAuthorizationModule.OnEnter(Object source, EventArgs eventArgs) +11153304
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +171
The web.config file contains the following information related to authentication/authorization:
<authentication mode="Windows" />
<authorization&gt
<!--Deny anonymous users--&gt
<deny users="?"/&gt
<allow roles="domain\GroupWithAccess"/&gt
<deny users="*"/&gt
</authorization&gt
Most of the results I found when researching this error state that the problem is related to a broken computer account in the domain and list the solution as re-joining the domain. I've done this but the error still appears. "Normal" domain operations work fine (accessing UNC shares, logging in, etc.).
This application runs in the Classic .Net AppPool for compatibility reasons. I tried changing the identity of the AppPool to "NetworkService" but the error still persists.
Any help is greatly appreciated.
I finally found an answer to this after experiencing the same problem on Windows Server 2008 R2. From this article:
Disable the following policies on the Windows 2008 R2 server, run gpupdate /force and restart the server.
"Computer Configuration\Windows Setting\Security Settings\Local Policies\Security Option"
Domain Member: Digitally encrypt or sign secure channel data (always)
Domain Member: Digitally encrypt secure channel data (When possible)
Domain Member: Digitally sign secure channel data (When possible)
I can confirm that this fixed the problem on Windows 7 as well.
I'm adding this for future reference:
"Error 1789 when you use the LookupAccountName function on a computer that is running Windows 7 or Windows Server 2008 R2"
http://support.microsoft.com/kb/976494
That might be a solution to the problem as well.

Resources