When users log out using CAS SSO, ASP.NET MVC triggers a HttpRequestValidationException - asp.net

We're using the Jasig .NET CAS Client to interface with our organization's CAS SSO server.
However, we've noticed that in ASP.NET MVC 3 (and I would assume this affects ASP.NET WebForms as well) applications, when users log out, we see the following error in our error log:
System.Web.HttpRequestValidationException (0x80004005):
A potentially dangerous Request.Form value was detected from the client
(logoutRequest="<samlp:LogoutRequest...").
at System.Web.HttpRequest.ValidateString(String value, String collectionKey, RequestValidationSource requestCollection)
at System.Web.HttpRequest.ValidateNameValueCollection(NameValueCollection nvc, RequestValidationSource requestCollection)
at System.Web.HttpRequest.get_Form()
at System.Web.HttpRequest.FillInParamsCollection()
at System.Web.HttpRequest.GetParams()
at DotNetCasClient.Utils.RequestEvaluator.GetRequestIsCasSingleSignOut() in C:\Projects\Jasig\CAS\dotnet-client\trunk\DotNetCasClient\Utils\RequestEvaluator.cs:line 292
at DotNetCasClient.CasAuthenticationModule.OnBeginRequest(Object sender, EventArgs e) in C:\Projects\Jasig\CAS\dotnet-client\trunk\DotNetCasClient\CasAuthenticationModule.cs:line 93
at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
I don't believe this is an error message users are receiving -- it seems to only be seen by the server. As far as the users are concerned, log out is successful.
Is there any way I can get ASP.NET MVC to stop trying to validate these types of requests? I know I can disable request validation completely, but that's out of the question. The site with a hyphen has a good question on this, but not really an acceptable answer:
add the following setting to the web.config:
<httpRuntime requestValidationMode="2.0" />
After setting this value, U can disable request validation by setting validateRequest="false"
So, is there any way to disable ASP.NET validation for this request without turning it off completely?
Edit: This is also tricky to debug because this request is coming from the CAS server, NOT from the user's browser. I think this is the CAS server attempting to notify all running applications that the user has signed out (single sign out). So we're only receiving this error in production, not when testing locally.

The dotnetcas client gets access to the request before it gets to an MVC controller action, so it is not possible to simply set the validation attribute on an MVC controller or action.
The target of this request seems to be the last URL that was validated, so it is not possible to disable validation for a specific path in your application by using this method either: http://erikbra.wordpress.com/2012/04/17/wif-saml-token-post-and-requestvalidationmode2-0/
From what I see you have a couple of options:
Disable this validation:
<system.web>
<httpRuntime requestValidationMode="2.0" />
</system.web>
or
.Net 4.5 allows you to access a request before it goes through validation. If you have access to this you can re-compile the client from source, fixing the relevant issue.

I am not familar with Jasig .NET CAS but ASP.NET MVC allows you to disable request validation at the page level.
Add the following attribute to your controller action:
[ValidateInput(false)]

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

Forms Authentication Cookie and WCF

I have an asp.net 4.0 application (client) that makes ajax/json calls to a http facade that then passes on the calls to our wcf service layer.
Users must authenticate on the client using forms authentication. The idea then being that the authentication cookie will be passed to and be accessible at the http facade. [Design based on Dino Esposito's book - Microsoft ASP.NET and AJAX: Architecting Web Applications]
The problem is, that at the facade, HttpContext.Current.User.Identity.Name is an empty string and IsAuthenticated is false.
I have enabled compatibility by adding the following to my system.ServiceModel section in my web.config (http facade level):
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
</system.serviceModel>
I have decorated my service with the following:
[AspNetCompatibilityRequirements(RequirementsMode =
AspNetCompatibilityRequirementsMode.Required)]
When I am debugging in the ajax/facade app I can see that cookies exist at HttpContext.Current.Request.Cookies. It appears that Anonymous is being used and not my authenticated user.
Both applications are running on the same IIS server.
Calls to the AJAX enabled wcf service are made via serviceProxy.js. Perhaps this method is not passing the necessary cookie?
WCF tracing is currently showing '..ASPXANONYMOUS=.....; ASP.NET_SessionId=....; .ASPXAUTH=.....' in the message log.
I get the feeling I am missing something simple but am too close to the problem.
Any suggestions welcomed.
I am not sure I completely understand the context of what you are trying to accomplish, but if these are two separate applications you are going to need to share machine keys in order to decrypt/encrypt the auth cookies in both.
in your web.config, make sure you have the following set:
<machineKey
validationKey="[generated key]"
validation="HMACSHA512"
decryptionKey="[generated key]"
decryption="AES"
/>
see how to generate these keys (and more info about them) on this codeproject article:
ASP.Net machineKey Generator - CodeProject
Let me know if this helps...

{ApplicationName}/ScriptResource.axd and invalid viewstate

I have an asp.net web form application running in a web farm?
All the machine keys are configured the same in web.config according to MSDN recommendation, still, it periodically throw out "System.Web.HttpException: Invalid viewstate.", and according to the stack.
It's in this line
Request : /{applicationname}/ScriptResource.axd +92
Note:{applicationname} is my application name.
see Erratic Invalid Viewstate issue in .net application

ASP.NET Impersonation and SQL Server Trusted Connection Calls

I am working on an ASP.NET page that we, in code impersonate the requesting user. We are using the following code to start impersonating.
Dim impersonationContext As System.Security.Principal.WindowsImpersonationContext
Dim currentWindowsIdentity As System.Security.Principal.WindowsIdentity
currentWindowsIdentity = CType(User.Identity, System.Security.Principal.WindowsIdentity)
impersonationContext = currentWindowsIdentity.Impersonate()
After this we have validated that the application is running under the proper context by calling:
System.Security.Principal.WindowsIdentity.GetCurrent().Name
This returns the proper identity of the user, and file access and other items appear to be using their account. However when using the Microsoft Application Data Application Block SqlHelper class to call out to a database using a trusted connection authentication fails for the "NT AUTHORITY\ANONYMOUS LOGON" user.
We can re-validate after the failure that the current identity is still our desired account and NOT the ANONYMOUS LOGIN account.
Does anyone have an idea why this is? Or more specifically how we can get around it?
Edit
Some additional information about how the calls from these pages work.
We do the impersonate call from the .aspx page.
After we impersonate we call out to a "business logic" assembly that is referecned.
We know that the context identity is still correct here.
After that, the "business logic" assembly calls another assembly that actually executes the trusted connection call. We cannot modify this "data access" assembly, the authentication exception is reported by this assembly as well.
I think #John Sonmez is right, you're hitting the Double Hop issue. Impersonation is only half of the story, you also need to look at Delegation (assuming your network is using Kerberos authentication). The articles below were the most useful in helping me through the same issue
Impersonation and Delegation
ASP.NET Delegation
I know that I've used impersonation in ASP.NET before (using C# and accessing the filesystem) and I was wondering if you had tried wrapping the logic that includes currentWindowsIdentity.Impersonate() with a 'Using / End Using' (to explicitly define the security context for a block of code).
So, it would look like this:
Using impersonationContext = currentWindowsIdentity.Impersonate()
' Logic here
End Using

Strange unhandled exception from asp.net application - Validation of viewstate MAC failed

I don't know if anyone has seen this issue before but I'm just stumped. Here's the unhandled exception message that my error page is capturing.
Error Message: 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.
Stack Trace: at
System.Web.UI.ViewStateException.ThrowError(Exception
inner, String persistedState, String
errorPageMessage, Boolean
macValidationError) at
System.Web.UI.ObjectStateFormatter.Deserialize(String
inputString) at
System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String
serializedState) at
System.Web.UI.Util.DeserializeWithAssert(IStateFormatter
formatter, String serializedState) at
System.Web.UI.HiddenFieldPageStatePersister.Load()
at
System.Web.UI.Page.LoadPageStateFromPersistenceMedium()
at System.Web.UI.Page.LoadAllState()
at
System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean
includeStagesAfterAsyncPoint) at
System.Web.UI.Page.ProcessRequest(Boolean
includeStagesBeforeAsyncPoint, Boolean
includeStagesAfterAsyncPoint) at
System.Web.UI.Page.ProcessRequest()
at
System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext
context) at
System.Web.UI.Page.ProcessRequest(HttpContext
context) at
ASP.generic_aspx.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
Anybody have any ideas on how I could resolve this? Thanks.
I seem to recall that this error can occur if you click a button/link etc before the page has fully loaded.
If this is the case, the error is caused by an ASP.net 2.0 feature called Event Validation. This is a security feature that ensures that postback actions only come from events allowed and created by the server to help prevent spoofed postbacks. This feature is implemented by having controls register valid events when they render (as in, during their actual Render() methods). The end result is that at the bottom of your rendered
form tag, you'll see something like this:
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="AEBnx7v.........tS" />
When a postback occurs, ASP.net uses the values stored in this hidden field to ensure that the button you clicked invokes a valid event. If it's not valid, you get the exception that you've been seeing.
The problem you're seeing happens specifically when you postback before the EventValidation field has been rendered. If EventValidation is enabled (which it is, by default), but ASP.net doesn't see the hidden field when you postback, you also get the exception. If you submit a form before it has been entirely rendered, then chances are the EventValidation field has not yet been rendered, and thus ASP.net cannot validate your click.
One work around is of course to just disable event validation, but you have to be aware of the security implications. Alternatively, just never post back before the form has finished rendering. Of course, that's hard to tell your users, but perhaps you could disable the UI until the form has rendered?
from http://forums.asp.net/p/955145/1173230.aspx
#Chris
if the problem is clicking an item before the page has completely rendered, asp.net 3.5 SP1 added a web.config entry on the page element called renderAllHiddenFieldsAtTopOfForm.
do you have multiple servers running this application and/or have a web garden? If yes, you are going to have to set the machine key in the web.config
By default, ASP.NET includes a digital signature of the ViewState value in the page. It does so with an automatically-generated key that is held in memory. This is done to prevent a malicious user from altering the ViewState from the browser and, for example, grant him/herself access to stuff they wouldn't normally have access to.
ASP.NET can also, optionally, encrypt the ViewState, but it's turned off by default for performance reasons. In many web sites, it is a lot more important to make sure that the content of the ViewState is not 'mucked with', than it is to keep it confidential.
The error message says that the signature verification failed. The page was posted with a ViewState, but the ViewState signature didn't match the signature calculated with the keys held by the server.
The most common reason for this error is that you are using two or more web servers in a farm-like environment: one server sends the original page, signed with the key in memory on that server, but the page is posted back to the second (or third...) server. Because the two or more servers don't share the signature key, the signatures don't match.
...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.
What the error message is telling you is to use the validationKey attribute (see details in MSDN) in your web.config to hardcode the signature key to a value shared by all your servers, instead of using a dynamically-generated one. That way, the signature validation can succeed independently of which server receives the postback.
You could turn off the verification, but it's very dangerous to do so. It means any hacker with a bit of free time can fake values in your application. For example, if you keep the price of the item in a ViewState value, the hacker could change the value from the browser to $0.01 right before putting the order.
For anyone else ending up struggling with this issue here is a helpful link to some work arounds:
http://blogs.msdn.com/tom/archive/2008/03/14/validation-of-viewstate-mac-failed-error.aspx
I know you can disable the Validation of viewstate MAC, but I think if the page is not loaded you can get into more trouble. When I ran into this problem I had to disable all buttons until the page was fully loaded.

Resources