Mark Gilbert's Blog

Science and technology, served light and fluffy.

A “Potentially Dangerous” Blog Post

Many months ago I started seeing exceptions being generated from a couple of the web sites that I manage to the effect of:

A potentially dangerous Request.QueryString value was detected from the client (Field12="<a>").


A potentially dangerous Request.Form value was detected from the client (Field12="<a>").

After some digging I determined that there was a link out in the wild that was trying to request a page in these sites, and that request included a parameter value of an HTML tag, which the ASP.NET engine was tossing out as being “potentially dangerous”.  Initially I concluded this was nothing I could do anything about, and ignored it.

A couple of months ago, when I had a short break in my usual workload, I decided to return to this issue with a new approach.  Instead of trying to fix the inbound link, perhaps I could detect when requests like this were coming through, and do something more useful than throwing an exception.  As it turns out, the solution was pretty straightforward.

ASP.NET Pages have an Error event that gets fired whenever an unhandled exception occurs on that page.  So, I handled that event, and started looking for the “potentially dangerous” exceptions:

Private Sub MyPage_Error(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Error
    Dim ex As Exception

    ex = Server.GetLastError

    If (ex.Message.Contains("A potentially dangerous Request.QueryString value was detected from the client")) Then
        Throw New Exception(ex.Message, ex.InnerException)
    End If
End Sub

I examine the contents of the Server.GetLastError property (which returns exactly what you’d think it would – the last exception thrown), and look for the offending text.  If I find that the “potentially dangerous” error was the last one, I clear it and redirect to some place safe (in this example, the site’s default page).

If the exception thrown wasn’t the “potentially dangerous” one, then I rethrow the exception, taking care to preserve the stack trace.

I placed this logic on every page that was being requested in this manner (three pages across two web sites).  Both sites have had this logic in production for well over a month now, and the exceptions have completely stopped.


June 30, 2010 - Posted by | Visual Studio/.NET

Sorry, the comment form is closed at this time.

%d bloggers like this: