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:

1.      How to detect when this is occurring and?

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();

    }

}

 

2.      What could potentially be done about it?

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.

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 the attack

        LogXssAttack();

 

        // 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();

        }

 

        Server.ClearError();

    }

}