sql注入是被谈的很多的一个话题,有很多的方法能够实现sql的防注入,在这里就简单说一下如果使用HttpModule来实现sql的防注入。
在项目中添加一个类让其实现IHttpModule接口。IHttpModule接口有两个方法 Init 和 Dispose。然后在Init方法中来订阅
AcquireRequestState事件。
为什么是AcquireRequestState 事件而不是Begin_Request呢 ,因为在Begin_Request执行的时候还没有加载session状态,而在处理的时侯
可能会用到session。
在AcquireRequestState 事件中我们就要进行相应的处理了,思路如下,一般网站提交数据只有两个地方,表单和url,所有就在该事件中将从这两处
提交的数据截取,判断是否有一些危险字符,然后做相应处理。代码如下
- 1. private void context_AcquireRequestState(object sender, EventArgs e)
- 2. {
- 3. HttpContext context = ((HttpApplication)sender).Context;
- 4.
- 5. try
- 6. {
- 7. string getkeys = string.Empty;
- 8. string sqlErrorPage = "~/Error.aspx";//转向的错误提示页面
- 9. string keyvalue = string.Empty;
- 10.
- 11. string requestUrl = context.Request.Path.ToString();
- 12. //url提交数据
- 13. if (context.Request.QueryString != null)
- 14. {
- 15. for (int i = 0; i < context.Request.QueryString.Count; i++)
- 16. {
- 17. getkeys = context.Request.QueryString.Keys[i];
- 18. keyvalue = context.Server.UrlDecode(context.Request.QueryString[getkeys]);
- 19.
- 20. if (!ProcessSqlStr(keyvalue))
- 21. {
- 22. context.Response.Redirect(sqlErrorPage);
- 23. context.Response.End();
- 24. break;
- 25. }
- 26. }
- 27. }
- 28. //表单提交数据
- 29. if (context.Request.Form != null)
- 30. {
- 31. for (int i = 0; i < context.Request.Form.Count; i++)
- 32. {
- 33. getkeys = context.Request.Form.Keys[i];
- 34. keyvalue = context.Server.HtmlDecode(context.Request.Form[i]);//[getkeys];
- 35. if (getkeys == "__VIEWSTATE") continue;
- 36. if (!ProcessSqlStr(keyvalue))
- 37. {
- 38. context.Response.Redirect(sqlErrorPage);
- 39. context.Response.End();
- 40. break;
- 41. }
- 42. }
- 43. }
- 44. }
- 45. catch (Exception ex)
- 46. {
- 47. }
- 48. }
而且还用到了一个叫ProcessSqlStr的方法,这个方法就是用来处理字符串的,判断是否合法,如下
- 1. private bool ProcessSqlStr(string str)
- 2. {
- 3. bool returnValue = true;
- 4. try
- 5. {
- 6. if (str.Trim() != "")
- 7. {
- 8. //string sqlStr = ConfigurationManager.AppSettings["FilterSql"].Trim();
- 9. string sqlStr = "declare |exec|varchar|cursor|begin|open |drop |creat |select |truncate";
- 10.
- 11. string[] sqlStrs = sqlStr.Split('|');
- 12. foreach (string ss in sqlStrs)
- 13. {
- 14. if (str.ToLower().IndexOf(ss) >= 0)
- 15. {
- 16. m_sqlstr = ss;
- 17. returnValue = false;
- 18. break;
- 19. }
- 20. }
- 21. }
- 22. }
- 23. catch
- 24. {
- 25. returnValue = false;
- 26. }
- 27. return returnValue;
- 28. }
- 到这儿类就写好了,再在web.config中做相应的配置就大功告成
-
- # <httpModules>
- # <add type="HttpModule" name="HttpModule"/>
- # </httpModules>