使用HttpModule实现sql防注入
asp.net处理Http请求时,程序得到一个请求的时候,第一个会经过Http运行时,即编译过程,在这里我们的请求会被转化为机器懂的语言。下一个,我们的请求经过不同的HttpModule,即Http模块。事实上,我们的请求到达模块时系统没有对这个请求做任何的处理,也就是说此时对于请求来讲,模块是一个请求的“必经之路”。
模块可以在这个Http请求到达真正的处理中心(HttpHandler)之前,针对这个Http请求做一些额外的工作,或者在某些情况下干脆终止满足一些条件的Http请求,从而起到一个过滤器的作用。在经过我们的模块之后,我们的Http请求才到达真正的处理中心(HttpHandler)。Http请求在经过处理之后,原路返回,经过模块,进过运行时,返回到客户端。
那么既然我们的请求无论如何都会经过HttpModule,那么我们就可以在此进行一些判断(如是否有SQL关键字等)。
使用HttpModule完整代码:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Text; namespace DotNet.Common.WebForm { /**//// <summary> /// 简单防止sql注入 /// </summary> public class SqlHttpModule : IHttpModule { public void Dispose() { } public void Init(HttpApplication context) { context.AcquireRequestState += new EventHandler(context_AcquireRequestState); } /**//// <summary> /// 处理sql注入 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void context_AcquireRequestState(object sender, EventArgs e) { HttpContext context = ((HttpApplication)sender).Context; try { string key = string.Empty; string value = string.Empty; //url提交数据 get方式 if (context.Request.QueryString != null) { for (int i = 0; i < context.Request.QueryString.Count; i++) { key = context.Request.QueryString.Keys[i]; value = context.Server.UrlDecode(context.Request.QueryString[key]); if (!FilterSql(value)) { throw new Exception("QueryString(GET) including dangerous sql key word!"); } } } //表单提交数据 post方式 if (context.Request.Form != null) { for (int i = 0; i < context.Request.Form.Count; i++) { key = context.Request.Form.Keys[i]; if (key == "__VIEWSTATE") continue; value = context.Server.HtmlDecode(context.Request.Form[i]); if (!FilterSql(value)) { throw new Exception("Request.Form(POST) including dangerous sql key word!"); } } } } catch (Exception ex) { throw ex; } } /**//// <summary> /// 过滤非法关键字,这个可以按照项目灵活配置 /// </summary> /// <param name="key"></param> /// <returns></returns> private bool FilterSql(string key) { bool flag = true; try { if (!string.IsNullOrEmpty(key)) { //一般配置在公共的文件中,如xml文件,txt文本等等 string sqlStr = "insert |delete |select |update |exec |varchar |drop |creat |declare |truncate |cursor |begin |open|<-- |--> "; string[] sqlStrArr = sqlStr.Split('|'); foreach (string strChild in sqlStrArr) { if (key.ToUpper().IndexOf(strChild.ToUpper()) != -1) { flag = false; break; } } } } catch { flag = false; } return flag; } } }
参考资料: 如何使用HttpModule实现sql防注入 http://www.studyofnet.com/news/290.html