So I’m building an ASP.NET application to host Podcasts and in the post submission logic I want folks to be able to submit markup, but not JavaScript.

image

ASP.NET automatically traps suspicious posts to the server, but the results have to unfortunate defines.

First is the ugly resulting page. We’ve all seen them.

image

And the second is that I may want to be able to add some SPECIFIC logic to handling that Security exception because it probably means someone is intentionally trying to hack my web site.

It turns out that this is another that ASP.NET makes easy to solve.

First, add a Global.asax file to your solution and code the global Application_Error event handler as follows.

   1:  protected void Application_Error(object sender, EventArgs e)
   2:  {
   3:      Exception objErr = Server.GetLastError().GetBaseException();
   4:      string err = objErr.Message.ToString();
   5:   
   6:      string secError = "A potentially dangerous Request.Form value was detected";
   7:      string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority +
                                          Request.ApplicationPath.TrimEnd('/') + '/';
   8:      Server.ClearError();
   9:   
  10:      if (err.IndexOf(secError) != -1)
  11:      {
  12:          Response.Redirect(baseUrl + "SecurityError.aspx");
  13:      }
  14:      else
  15:      {
  16:   
  17:          Response.Redirect(baseUrl + "Error.aspx");
  18:      }
  19:  }

When the specific form validation error is encountered we redirect to a specific web page. (SecurityError.aspx)

The user gets a much better experience.

image 

This solves the second problem with the default handling. Even without additional work on my part the IIS Server Logs will be able to tell me how many times this happens along with information about the requests that generate them.

If I want to get more specific I can forward the originals HTTP request and exception info to SecurityError.aspx and take some action.

If the form can only be submitted by a user who is logged in to my application, even better. I can count how many times then cause this eror to happen and then based on that data I can warn them, log them off or ban them from my site completely

Do you add security specific error handling to your site ? If so, let me know.

Technorati Tags: ASP.NET Security Tips & Tricks