日期:2014-05-20 浏览次数:20893 次
using System; using System.Collections.Generic; using System.Text; using System.Web; namespace ProcessSqlInjection { public class SqlFilterHttpModule : IHttpModule { HttpApplication app = null; string[] blacklist = { "and", "exec", "insert", "select", "delete", "update", "chr", "mid", "master", "or", "truncate", "char", "declare", "join", "cmd" }; #region IHttpModule Members public void Dispose() { } public void Init(HttpApplication context) { context.BeginRequest += new EventHandler(context_BeginRequest); } #endregion void context_BeginRequest(object sender, EventArgs e) { app = sender as HttpApplication; ProcessSqlInjection(); } void ProcessSqlInjection() { HttpRequest request = app.Context.Request; foreach (string i in request.Form) { if (i == "__VIEWSTATE" || i=="__EVENTVALIDATION") continue; goErr(request.Form[i]); } foreach (string i in request.QueryString) { goErr(request.QueryString[i]); } foreach (string i in request.Cookies) { goErr(request.Cookies[i].Value); } } /// <summary> ///Sql Injection Filter /// </summary> /// <param name="InText">To filter the string</param> /// <returns>If the parameters of the existence of unsafe characters return true.</returns> public bool SqlFilter(string inText) { foreach (string i in blacklist) if (inText.IndexOf(i + " ", StringComparison.OrdinalIgnoreCase) > -1) return true; return false; } /// <summary> /// Check parameters of the existence of SQL characters /// </summary> /// <param name="tm"> </param> void goErr(string tm) { if (SqlFilter(tm)) { HttpResponse response = app.Context.Response; throw new ArgumentException("You enter the wrong data parameters!"); } } } }
------解决方案--------------------
void Application_BeginRequest(Object sender, EventArgs e)
{
StartProcessRequest();
}
#region
private void StartProcessRequest()
{
try
{
string getkeys = "";
string sqlErrorPage = "index.aspx";
if (System.Web.HttpContext.Current.Request.QueryString != null)
{
for (int i = 0; i < System.Web.HttpContext.Current.Request.QueryString.Count; i++)
{
getkeys = System.Web.HttpContext.Current.Request.QueryString.Keys[i];
if (!ProcessSqlStr(System.Web.HttpContext.Current.Request.QueryString[getkeys]))
{
System.Web.HttpContext.Current.Response.Redirect(sqlErrorPage);
System.Web.HttpContext.Current.Response.End();
}
}