通过HttpModule、httpHandlers防止SQL注入式攻击

 

1、通过HttpModule防止SQL注入式攻击,适用于.net1.1程序
(1)新建类文件SqlHttpModule.cs,具体代码类似如下:

 

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;

namespace HttpModule.Class
{
    /// <summary>
    /// SqlInPost 的摘要说明
    /// </summary>
    public class SqlHttpModule : System.Web.IHttpModule
    {
        public SqlHttpModule()
        {
        }

        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            context.AcquireRequestState += new EventHandler(context_AcquireRequestState);
        }

        private void context_AcquireRequestState(object sender, EventArgs e)
        {
            HttpContext context = ((HttpApplication)sender).Context;            
            try
            {
                string getkeys = string.Empty;  
                string keyvalue = string.Empty;
                string strErrorAlertScript = "<script type=\"text/javascript\">alert('字符串格式非法,请重新输入!');history.go(-1);</script>";
                string requestUrl = context.Request.Path.ToString();
                #region URL提交数据
                if (context.Request.QueryString != null)
                {
                    for (int i = 0; i < context.Request.QueryString.Count; i++)
                    {
                        getkeys = context.Request.QueryString.Keys[i];
                        keyvalue = context.Server.UrlDecode(context.Request.QueryString[getkeys]).Replace("'", "");

                        if (!IsSafeString(keyvalue))
                        {
                            context.Response.Write(strErrorAlertScript);
                            context.Response.End();
                            break;
                        }
                    }
                }
                #endregion

                #region 表单提交数据
                if (context.Request.Form != null)
                {
                    for (int i = 0; i < context.Request.Form.Count; i++)
                    {
                        getkeys = context.Request.Form.Keys[i].ToUpper();
                        if (getkeys == "__VIEWSTATE" || getkeys == "__EVENTARGUMENT" || getkeys == "__EVENTTARGET" || getkeys == "__CLIENTPOSTDATA__") continue;

                        keyvalue = context.Server.HtmlDecode(context.Request.Form[i]).Replace("'", "");
                        if (!IsSafeString(keyvalue))
                        {
                            context.Response.Write(strErrorAlertScript);
                            context.Response.End();
                            break;
                        }
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
            }
        }

        //判断是否为安全字符串
        public bool IsSafeString(string strText)
        {
            bool bResult = true;
            //strText = Regex.Replace(strText, "[\\s]{1,}", "");    //two or more spaces
            strText = Regex.Replace(strText, "(<[b|B][r|R]/*>)+|(<[p|P](.|\\n)*?>)", "\n");    //<br>


            string FilterSql = System.Configuration.ConfigurationSettings.AppSettings["SqlHttpModule_KeyWord"];//将关键词组配置在webconfig中
            if(FilterSql==null || FilterSql=="")
            {
                string[] UnSafeArray = new string[23];
                UnSafeArray[0] = "'";
                UnSafeArray[1] = "xp_cmdshell ";
                UnSafeArray[2] = "declare";
                UnSafeArray[3] = "netlocalgroupadministrators ";
                UnSafeArray[4] = "delete ";
                UnSafeArray[5] = "truncate ";
                UnSafeArray[6] = "netuser ";
                UnSafeArray[7] = "/add ";
                UnSafeArray[8] = "drop ";
                UnSafeArray[9] = "update ";
                UnSafeArray[10] = "select ";
                UnSafeArray[11] = "union ";  
                UnSafeArray[12] = "exec ";
                UnSafeArray[13] = "create ";
                UnSafeArray[14] = "insertinto ";
                UnSafeArray[15] = "sp_ ";
                UnSafeArray[16] = "exec ";
                UnSafeArray[17] = "create ";
                UnSafeArray[18] = "insert ";
                UnSafeArray[19] = "masterdbo ";
                UnSafeArray[20] = "sp_ ";
                UnSafeArray[21] = ";-- ";
                UnSafeArray[22] = "1= ";
                foreach (string strValue in UnSafeArray)
                {
                 
                    if (strText.ToLower().IndexOf(strValue) > -1)
                    {
                        bResult = false;
                        break;
                    }
                }
            }
            else
            {
                string sqlStr = FilterSql;
                string[] sqlStrs = sqlStr.Split('|');
                foreach (string ss in sqlStrs)
                {
                    if (strText.ToLower().IndexOf(ss) >= 0)
                    {                        
                        bResult = false;
                        break;
                    }
                }            
            }
            return bResult;
        }

    }
}



(2)在web.config文件中做以下配置
   </system.web>
     <httpModules>
           <add name="SqlHttpModule" type="HttpModule.Class.SqlHttpModule, HttpModule" />
     </httpModules>
   </system.web> 

 

2、通过httpHandlers防止SQL注入式攻击,适用于.net2.0及以上程序
(1)新建类文件SqlhttpHandlers.cs,具体代码类似如下:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
using System.Collections.Specialized;
namespace httpHandlers
{
    /// <summary>
    /// SqlInPost 的摘要说明
    /// </summary>
    public class SqlhttpHandlers : IHttpHandlerFactory
    {
        public SqlhttpHandlers()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }


        public virtual IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
        {
            //得到编译实例(通过反射)
            PageHandlerFactory factory = (PageHandlerFactory)Activator.CreateInstance(typeof(PageHandlerFactory), true);
            IHttpHandler handler = factory.GetHandler(context, requestType, url, pathTranslated);
            //过滤字符串
            if (requestType == "POST")
            {
                Page page = handler as Page;
                if (page != null)
                    page.PreLoad += new EventHandler(FormFilterStrFactoryHandler_PreLoad);
            }
            if (requestType == "GET")
            {
                Page page = handler as Page;
                if (page != null)
                    page.PreLoad += new EventHandler(RequestFilterStrFactoryRHandler_PreLoad);
            }
            //返回
            return handler;
        }



       public virtual void ReleaseHandler(IHttpHandler handler)
        {

        }
        /// <summary>
        /// 过滤TextBox、Input和Textarea中非法字符
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
       void FormFilterStrFactoryHandler_PreLoad(object sender, EventArgs e)
        {
            try
            {
                  bool isSafe = true;
                Page page = sender as Page;
                NameValueCollection postData = page.Request.Form;
                foreach (string postKey in postData)
                {
                    Control ctl = page.FindControl(postKey);
                    if (ctl as TextBox != null)
                    {
                       ((TextBox)ctl).Text = ((TextBox)ctl).Text.Replace("'", "'");
                       string strValue = ((TextBox)ctl).Text.Trim();
                       if (!IsSafeString(strValue))
                       {
                          isSafe = false;
                          break;
                       }
                      
                        continue;
                    }
                    if (ctl as HtmlInputControl != null)
                    {
       
                        ((HtmlInputControl)ctl).Value = ((HtmlInputControl)ctl).Value.Replace("'", "'");
                         string strValue = ((HtmlInputControl)ctl).Value.Trim();
                        if (!IsSafeString(strValue))
                        {
                            isSafe = false;
                            break;
                        }
                        continue;
                    }
                    if (ctl as HtmlTextArea != null)
                    {
                        ((HtmlTextArea)ctl).Value = ((HtmlTextArea)ctl).Value.Replace("'", "'");
                        string strValue = ((HtmlTextArea)ctl).Value.Trim();
                        if (!IsSafeString(strValue))
                        {
                            isSafe = false;
                            break;
                        }        
                        continue;
                   }                
                }
                if (!isSafe)
                {
                    page.Response.Write("<b><font color='red' font-size=12pt>字符串格式非法!</font></b>");
                    page.Response.End();
                }
            }
            catch(Exception ex)
            {
                string a = ex.Message;
            }
        }


         


        /// <summary>
        /// 过滤QueryString 中的非法字符串
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void RequestFilterStrFactoryRHandler_PreLoad(object sender, EventArgs e)
        {
            try
            {
                Page page = sender as Page;
                NameValueCollection QueryNV = page.Request.QueryString;
                bool isSafe = true;
                for (int i = 0; i < QueryNV.Count; i++)
                {
                    if (!IsSafeString(QueryNV.Get(i)))
                    {
                        isSafe = false;
                        break;
                    }
                }
                if (!isSafe)
                {
                    page.Response.Write("<b><font color='red' font-size=12pt>字符串格式非法!</font></b>");
                    page.Response.End();
                }
            }
            catch { }
        }





        //判断是否为安全字符串
        public bool IsSafeString(string strText)
        {
            bool bResult = true;
            strText = Regex.Replace(strText, "[\\s]{1,}", "");    //two or more spaces
            strText = Regex.Replace(strText, "(<[b|B][r|R]/*>)+|(<[p|P](.|\\n)*?>)", "\n");    //<br>

            string[] UnSafeArray = new string[23];
            UnSafeArray[0] = "'";
            UnSafeArray[1] = "xp_cmdshell";
            UnSafeArray[2] = "declare";
            UnSafeArray[3] = "netlocalgroupadministrators";
            UnSafeArray[4] = "delete";
            UnSafeArray[5] = "truncate";
            UnSafeArray[6] = "netuser";
            UnSafeArray[7] = "/add";
            UnSafeArray[8] = "drop";
            UnSafeArray[9] = "update";
            UnSafeArray[10] = "select";
            UnSafeArray[11] = "union";
            UnSafeArray[12] = "exec";
            UnSafeArray[13] = "create";
            UnSafeArray[14] = "insertinto";
            UnSafeArray[15] = "sp_";
            UnSafeArray[16] = "exec";
            UnSafeArray[17] = "create";
            UnSafeArray[18] = "insertinto";
            UnSafeArray[19] = "masterdbo";
            UnSafeArray[20] = "sp_";
            UnSafeArray[21] = ";--";
            UnSafeArray[22] = "1=";
            foreach (string strValue in UnSafeArray)
            {
                 
                if (strText.ToLower().IndexOf(strValue) > -1)
                {
                    bResult = false;
                    break;
                }
            }
            return bResult;
        }

    }
}


(2)在web.config文件中做以下配置
   </system.web>
     <httpHandlers>
        <add verb="*" path="*.aspx" type="httpHandlers.SqlhttpHandlers, httpHandlers"/>
     </httpHandlers>
   </system.web>

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

灵雨飘零

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值