Tuesday, December 2, 2008

Avoiding Embedded T-SQL in Query String

I've seen folks trying to hack a web site by passing large amounts of hex-encoded T-SQL commands embedded withing a query string...and it's a bit disturbing. I like to be a bit proactive when it comes to this type of thing so I tend to use an a custom HTTP module that I register in my web.config. I write a class and place the file in my App_Code folder, then register it in my web.config like:

<httpModules>
<add name="RestrictionHttpModule" type="HttpModule.RestrictionHttpModule"/>
</httpModules>

The C# class looks something like this:

using System;
using System.Web;

namespace HttpModule
{
public class RestrictionHttpModule : IHttpModule
{
public RestrictionHttpModule()
{
}

#region IHttpModule Members

public void Dispose()
{
}

public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(Application_BeginRequest);
}

private void Application_BeginRequest(object source, EventArgs e)
{
HttpContext context = ((HttpApplication)source).Context;

// watch out for t-sql commands that may be embedded
string query = context.Request.Url.Query.ToLower();
if (!string.IsNullOrEmpty(query))
{
if (query.Contains(";declare") ||
query.Contains("exec(") ||
query.Contains("cast(") ||
query.Contains("convert("))
{
context.Response.StatusCode = 403; // forbidden
}
}
}

#endregion
}
}


This is just an example. My actual handler is a bit more robust. I include code that also allows me to reject remote host IPs, remote host names, and referrer names. Since my global exception handler email includes the full URL for any exceptions, it's easy for me to see which type of remote sites are attempting to hack, login without credentials, etc.

No comments:

Can't RDP? How to enable / disable virtual machine firewall for Azure VM

Oh no!  I accidentally blocked the RDP port on an Azure virtual machine which resulted in not being able to log into the VM anymore.  I did ...