Message: CSRF attack detected - asp.net

I am trying to solve this issue.
I have two cdn url abc.com pointing to elb1 and def.com pointing to elb2.
Both elb (elb1 and elb2) pointing to same ec2 instances which is load balanced(ec2-A and ec2-B)
I can login to the server which is navigated from abc.com
but i am unable to login to the server which is navigated from def.com
def.com login gives following error.
Since both dns points to same EC2. Web.config files are same.
Message: CSRF attack detected.
Exception type: CMS.Protection.Web.UI.CsrfException
Stack trace:
at CMS.Protection.Web.UI.CsrfProtection.ThrowCsrfException(Exception innerException)
at CMS.Protection.Web.UI.CsrfProtection.OnPostMapRequestHandlerExecute(Object sender, EventArgs eventArgs)
at CMS.Base.AbstractHandler.CallEventHandler[TArgs](EventHandler`1 h, TArgs e)
at CMS.Base.AbstractHandler.Raise[TArgs](String partName, List`1 list, TArgs e, Boolean important)
at CMS.Base.SimpleHandler`2.RaiseExecute(TArgs e)
at CMS.Base.SimpleHandler`2.RaiseExecute(TArgs e)
at CMS.Base.SimpleHandler`2.StartEvent(TArgs e)
at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Message: Error occurred during a cryptographic operation.
Exception type: System.Security.Cryptography.CryptographicException
Stack trace:
at System.Web.Security.Cryptography.HomogenizingCryptoServiceWrapper.HomogenizeErrors(Func`2 func, Byte[] input)
at CMS.Protection.Web.UI.CsrfProtection.OnPostMapRequestHandlerExecute(Object sender, EventArgs eventArgs)

CSRF protection in Kentico validates the tokens using the MachineKey.Unprotect() method, therefore it is necessary that all servers use the same encryption keys.
See the documentation for more details about how to achieve this behavior.

This worked for me:
Add the following key in the appSettings of your web.config
<add key="CMSEnableCsrfProtection" value="false" />

its fixed, i generated machine key, and put the same machine key in both ec2 instances. hence the issues are fixed

Neshi is correct and you need to ensure, that the post request on the page comes from the same source otherwise you pretty much fulfill definition of cross site scripting.
Overall setup is quite complex, however you still need to ensure that security token in CSRF cookie is the same as token generated by CMSPage on load and I am not sure if these redirects and load transfers are able to do so as well as to keep session sticky enough.
General description is at:
https://docs.kentico.com/k10/securing-websites/developing-secure-websites/cross-site-request-forgery-csrf-xsrf

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

ASP.NET - Accessing Active Directory from code behind page

I have made a web application, which reads/writes from/to Active Directory. In my web.config file there is
<identity impersonate="true"/>
and
<authentication mode="Windows"/>
When I display
System.Web.HttpContext.Current.User.Identity.Name
in some label, it shows mydomain\myusername, so I think impersonation works.
Now to the question. When I access the application on the server, where the IIS web server is running, everything works great. But when I access the web application from a remote PC, I get an exception (the label still shows "mydomain\myusername").
I have traced the problem down. In the code behind when I call
Forest currentForest = Forest.GetCurrentForest();
the variable currentForest knows its currentForest.Name, currentForest.RootDomain or currentForest.ForestMode, but any call to currentForest.Domains, currentForest.Sites or currentForest.GlobalCatalogs results in
System.DirectoryServices.ActiveDirectory.ActiveDirectoryOperationException.
Now I'm lost and don't know what to debug further. The account I'm using is member of Enterprise Admins (multi-domain forest). I have tried it on two different servers with different IIS versions (IIS 7.5 and IIS 6.0) with no luck.
And the thrown exception isn't of much help:
Exception Details: System.DirectoryServices.DirectoryServicesCOMException: An operations error occurred.
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:
DirectoryServicesCOMException (0x80072020): An operations error occurred.
System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail) +557
System.DirectoryServices.DirectoryEntry.Bind() +44
System.DirectoryServices.DirectoryEntry.get_AdsObject() +42
System.DirectoryServices.DirectorySearcher.FindAll(Boolean findMoreThanOne) +98
System.DirectoryServices.ActiveDirectory.ADSearcher.FindAll() +46
System.DirectoryServices.ActiveDirectory.Forest.GetDomains() +543
[ActiveDirectoryOperationException: An operations error occurred.]
System.DirectoryServices.ActiveDirectory.Forest.GetDomains() +512484
System.DirectoryServices.ActiveDirectory.Forest.get_Domains() +44
myWebApp.ASPpage.Button_Click(Object sender, EventArgs e) in C:\Documents and Settings\myUser\documents\visual studio\Projects\MyWebApp\MyWebApp\ASPPage.aspx.cs:158
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +115
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +140
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +29
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2981
EDIT: If it is not obvious, I want to use currentForest.Domains to search the whole forest (all domains) for a user given by UPN name.
I found the answer to my question in one of "Related questions" on this page. The answer was in this topic: Why does DirectoryServicesCOMException occur querying Active Directory from a machine other than the web server?
I found, that it was exactly my case. After reading the suggested Microsoft article, I learned, that impersonating works only for local resources on the IIS server. To access network resources (SQL, Active Directory), I have to set "Trust this computer for delegation" in the computer object in Active Directory.
It was because the IIS always authenticate therefore System.Web.HttpContext.Current.User.Identity.Name showsmydomain\myusername; to verify that the impersonation works you could use:
System.Security.Principal.WindowsIdentity.GetCurrent().Name, also the System.Security.Principal.WindowsIdentity.GetCurrent(true) returns null when it is not impersonating.

connection that was expected to be kept alive was closed by the server in asp.net

When i try to redirect to next page, I get the following error
Note: Even the connection is open and it is fine.
The underlying connection was closed: A connection that was expected to be kept alive was closed by the server.
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.Net.WebException: The underlying connection was closed: A connection that was expected to be kept alive was closed by the server.
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:
[WebException: The underlying connection was closed: A connection that was expected to be kept alive was closed by the server.]
Effrtpartsigndone.Page_Load(Object sender, EventArgs e) +8196
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
System.Web.UI.Control.OnLoad(EventArgs e) +91
System.Web.UI.Control.LoadRecursive() +74
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2207
Version Information: Microsoft .NET Framework Version:4.0.30319;
ASP.NET Version:4.0.30319.272
This MSDN post seems to describe a similar situation. Let us know if it matches your issue:
http://social.msdn.microsoft.com/forums/en-US/netfxnetcom/thread/246ffc07-1cab-44b5-b529-f1135866ebca/
Quote:
[...].Net is sending first Expect 100 in one senddata of socket then send the actual request. Server Responds back with Continue 100. And exactly here .Net is showing message "Underlying connection was close. Connection was closed unexpectedly".
.Net is under impression that it has anyway already sent the data but server sent Connection : Close so it shows error without resending(sic) the request.
So the solution for the above that worked for me was
System.Net.ServicePointManager.Expect100Continue = False
If you want to see the traffic between the interlopers, snoop the HTTP exchange with Wireshark or a similar tool.
This is probably because the Client's time out is greater than the server's time out. Server closes the connection and the client is still waiting for a response or sending the request.
You must set the KeepAlive Property to False so the connection will be closed by itself and re opened for every request. This will avoid the issue of attempting to use a closed connection.
I had this configured:
ServicePointManager.DefaultConnectionLimit = 100;
Once I removed that, the errors went away.
I had the same issue when using RestSharp library. I solved by adding these two lines before creating RestClient object:
ServicePointManager.DefaultConnectionLimit = 100;
ServicePointManager.MaxServicePointIdleTime = 5000;
I had the same problem and setting in the server's config in the serviceBehaviors element
<serviceBehaviors>
<behavior name="ServiceBehaviour">
...
<dataContractSerializer maxItemsInObjectGraph="6553500"/>
...
</behavior>
</serviceBehaviors>
solved the issue.
Tracing helps a lot in finding the root of these problems: https://msdn.microsoft.com/en-us/library/ms733025(v=vs.110).aspx
In my case, the issue is in the file length. Please do check the allowed file size on your server. In your script just do check this part :
dataStream.Write(filesBytesArray, 0, filesBytesArray.Length);
dataStream.Close();
And if you dont know, just limit the file uploaded size in your frontend section ie. HTML <input type="file"> upload element, this is good reference for limiting file size and other filter.
We had a loop in our object graph that we were returning. I know this probably isn't your problem but I'm adding it here in case anyone else has the same problem. We had IncludeExceptionDetailInFaults enabled but weren't getting the error in any client (our application or the WCF Test Client). Luckily it showed up in server logs so we were able to find it that way.
We had parent -> child and child -> parent for two-way navigation, we had to break that link and instead have parent -> child, and the child had an id to lookup the parent, then the error went away.
Hope this helps someone!

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.

Resources