防SQL注入漏洞的HttpModule 主要功能預(yù)覽介紹:

1,檢測(cè)的最短長(zhǎng)長(zhǎng)度

2,SQL注入檢測(cè)的正則表達(dá)式,

3,檢測(cè)到SQL注入后跳轉(zhuǎn)到的頁(yè)面

4,截獲每個(gè)請(qǐng)求并分析其Request參數(shù)

對(duì)于線上項(xiàng)目的運(yùn)營(yíng),是不可缺少的好類庫(kù),可有效防止SQL注入漏洞



using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;
using System.IO;
using System.Configuration;
namespace jsons.Common
{
  
    /// <summary>
    /// 防SQL注入漏洞的HttpModule
    /// Powered By killkill
    /// </summary>
    public class SqlRegexFilter : IHttpModule
    {
        #region IHttpModule 成員
  
        public void Dispose()
        {
        }
  
        /// <summary>
        /// 檢測(cè)的最短長(zhǎng)長(zhǎng)度,在web.config中配置
        /// </summary>
        private int minQueryLength = 0;
  
        /// <summary>
        /// SQL注入檢測(cè)的正則表達(dá)式,在web.config中配置
        /// </summary>
        private Regex denyRegex = null;
  
        /// <summary>
        /// 檢測(cè)到SQL注入后跳轉(zhuǎn)到的頁(yè)面,在web.config中配置
        /// </summary>
        private string redirectPage = null;
  
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="context"></param>
        public void Init(HttpApplication context)
        {
            context.BeginRequest  = new EventHandler(context_BeginRequest);
            denyRegex =
                new Regex(
                    ConfigurationManager.AppSettings["killkill_DenyRegex"],
                    RegexOptions.IgnoreCase | RegexOptions.Compiled);
            this.minQueryLength =
                int.Parse(ConfigurationManager.AppSettings["killkill_QueryLength"]);
            this.redirectPage =
                ConfigurationManager.AppSettings["killkill_RedirectPage"];
        }
  
        /// <summary>
        /// 截獲每個(gè)請(qǐng)求并分析其Request參數(shù)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void context_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication Application = (HttpApplication)sender;
            HttpContext ctx = Application.Context;
            foreach (string key in ctx.Request.QueryString.Keys)
            {
                string value = ctx.Request[key];
                if (value.Length > 10)
                {
                    if (denyRegex.Match(value).Success)
                    {
                        Application.CompleteRequest();
                        ctx.Response.Redirect(redirectPage);
                    }
                }
            }
        }
  
        #endregion
    }
}


原文鏈接:.Net防止SQL注入漏洞的HttpModule