In a way to limit the risk of Cross-Site Scripting (XSS) attacks, ASP.NET 2.0 introduced a way to detect such attack and automatically reject the request. This functionality is exposed by the PageSections.ValidationRequest and is turned on by default. This should not be considered an s a full proof solution against XSS but a good first line of defense for common cases. For information about this feature can be found on:
- http://www.asp.net/(S(ywiyuluxr3qb2dfva1z5lgeg))/learn/whitepapers/request-validation/
- http://msdn.microsoft.com/en-us/library/ms972969.aspx#securitybarriers_topic6
Some of the questions I’ve been asked repeatedly are:
When ASP.NET detects that XSS is occurring it throws an HttpRequestValidationException which can be caught in the Application_Error handler.
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
Exception lastError;
lastError = Server.GetLastError();
// If the last exception is HttpRequestValidationException
// we log it and signout the user
if (lastError is HttpRequestValidationException)
// Log information about the attack
LogXssAttack();
Server.ClearError();
}
One of the option that can be quite annoying for attackers trying to scan the application for XSS is to log them off automatically when HttpRequestValidationException.
// Log the attack
// If the user is authenticated we:
// - log the user out
// - invalidate his session
// - redirect him to the login page
if (Request.IsAuthenticated)
FormsAuthentication.SignOut();
Session.Abandon();
FormsAuthentication.RedirectToLoginPage();