通过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>

 

 

你可能感兴趣的:(通过HttpModule、httpHandlers防止SQL注入式攻击)