Monday, August 03, 2009

ASCII Encoded/Binary String Automated SQL Injection Attack

Useful code for preventing SQL injections in .NET Querystrings, lifted from the following page:
http://www.bloombit.com/Articles/2008/05/ASCII-Encoded-Binary-String-Automated-SQL-Injection.aspx

/// /// global.asax/// public class Global : System.Web.HttpApplication{
...
private static string[] SQLKeywords = new string[]
{
"EXEC", "SELECT", "INSERT", "UPDATE", "DELETE",
"CAST", "DECLARE", "NVARCHAR", "VARCHAR"
};
...
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
if (context != null)
{
string queryString =
context.Request.ServerVariables["QUERY_STRING"];
if (string.IsNullOrEmpty(queryString) == false)
{
if (queryString.Length > 500)
throw new SQLInjectionException(string.Format("Unexpected 'QUERY_STRING' length ({0}).", queryString));
queryString = Server.UrlDecode(queryString);
queryString =
queryString.Replace(" ", string.Empty).ToUpper();
foreach (string keyword in SQLKeywords)
{
if (queryString.IndexOf(keyword) != (-1))
throw new SQLInjectionException(string.Format("Unexpected T-SQL keyword ('{0}') has been detected ({1})", keyword, queryString));
}
}
}
}
...}
Post a Comment