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

转载 2012年03月22日 11:53:32

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

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,具体代码类似如下:

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注入式攻击

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

六个建议防止SQL注入式攻击

  • 2011年06月30日 11:27
  • 34KB
  • 下载

六招防止SQL注入式攻击

SQL注入是目前比较常见的针对数据库的一种攻击方式。在这种攻击方式中,攻击者会将一些恶意代码插入到字符串中。然后会通过各种手段将该字符串传递到SQLServer数据库的实例中进行分析和执行。只要这个恶...

六个建议防止SQL注入式攻击

SQL注入攻击的危害性很大。在讲解其防止办法之前,数据库管理员有必要先了解一下其攻击的原理。这有利于管理员采取有针对性的防治措施。   一、 SQL注入攻击的简单示例。   stateme...

防止SQL注入式攻击

原文地址:  http://www.cnblogs.com/lrary/archive/2006/01/09/313906.html 所谓SQL注入式攻击,就是攻击者把SQL命令插入到W...

防止SQL注入式攻击的一些方法分享

SQL 注入是恶意用户输入 Transact-SQL 语句取代有效输入的过程。如果输入的语句没有经过验证直接传递到服务器,并且应用程序不慎执行了注入的代码,这种攻击有可能损坏或毁坏数据。 任何构造 ...

六个建议防止SQL注入式攻击(转载)

SQL注入攻击的危害性很大。在讲解其防止办法之前,数据库管理员有必要先了解一下其攻击的原理。这有利于管理员采取有针对性的防治措施。 一、 SQL注入攻击的简单示例。  statement := "SE...
  • yym154
  • yym154
  • 2011年02月09日 15:36
  • 205

SQL防注入式攻击源代码

  • 2014年06月12日 11:00
  • 504B
  • 下载

ASP.NET中如何防范SQL注入式攻击

  • 2008年09月30日 11:57
  • 439B
  • 下载

sql注入式攻击

SQL注入原理及防止注入
  • wjq008
  • wjq008
  • 2015年01月20日 10:01
  • 353
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:通过HttpModule、httpHandlers防止SQL注入式攻击
举报原因:
原因补充:

(最多只允许输入30个字)