SQL防注入程序

1、在Global.asax.cs中写入:

protected void Application_BeginRequest(Object sender,EventArgs e)
{
      SqlInject myCheck = new SqlInject(this.Request);

      myCheck.CheckSqlInject();
}
 
2、新建一个SqlInject防注入类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SC_LuceneNet
{
    public class SqlInject : System.Web.UI.Page
    {
        //检测到注入后的处理方式:   0:仅警告;1:警告+记录;2:警告+自定义错误页面;3:警告+记录+自定义错误页面
        private const int _type = 3;
        private const string errRedirectPage = "/err.aspx";

        //过滤特征字符
        private const string StrKeyWord = @"select|insert|delete|from|count(|drop table|update|truncate|asc(|mid(|char(|xp_cmdshell|exec|master|net local group administrators|net user|or|and";
        private const string StrRegex = @"-|;|,|/|(|)|[|]|{|}|%|@|*|'|!";

        private HttpRequest request;

        public SqlInject(System.Web.HttpRequest _request)
        {
            this.request = _request;
        }

        public void CheckSqlInject()
        {
            bool isInject = false;
            if (CheckRequestQuery() || CheckRequestForm())
            {
                isInject = true;
            }
            else
            {
                return;
            }

            switch (_type)
            {
                case 0:
                    ShowErr();
                    break;
                case 1:
                    ShowErr();
                    break;
                case 2:
                    ShowErr();
                    string temp;
                    System.Web.HttpContext.Current.Response.Write("<script>setTimeout(\"" + "location.href='" + errRedirectPage + "'" + "\",5000)</script>");
                    break;
                case 3:
                    ShowErr();
                    System.Web.HttpContext.Current.Response.Write("<script>setTimeout(\"" + "location.href='" + errRedirectPage + "'" + "\",5000)</script>");
                    break;
                default:
                    break;
            }
            System.Web.HttpContext.Current.Response.End();

        }
        private string RelaceSingleQuotes(string _url)
        {
            string URL = _url.Replace("'", "单引号");
            return URL;
        }
        private void ShowErr()
        {
            string msg = @"<font color=red>请不要尝试未授权之入侵检测!</font>" + @"<br><br>";
            msg += @"操作IP:" + request.ServerVariables["REMOTE_ADDR"] + @"<br>";
            msg += @"操作时间:" + DateTime.Now + @"<br>";
            msg += @"页面:" + request.ServerVariables["URL"].ToLower() + request.QueryString.ToString() + @"<br>";
            msg += @"<a href='err.aspx' onclick='javascript:window.close()'>关闭</a>";
            System.Web.HttpContext.Current.Response.Clear();
            System.Web.HttpContext.Current.Response.Write(msg);
        }
        ///<summary>
        /// 特征字符
        ///</summary>
        public static string KeyWord
        {
            get
            {
                return StrKeyWord;
            }
        }
        ///<summary>
        /// 特征符号
        ///</summary>
        public static string RegexString
        {
            get
            {
                return StrRegex;
            }
        }

        ///<summary>
        ///检查字符串中是否包含Sql注入关键字
        /// <param name="_key">被检查的字符串</param>
        /// <returns>如果包含注入true;否则返回false</returns>
        ///</summary>
        private static bool CheckKeyWord(string _key)
        {
            string[] pattenString = StrKeyWord.Split('|');
            string[] pattenRegex = StrRegex.Split('|');
            foreach (string sqlParam in pattenString)
            {
                if (_key.Contains(sqlParam + " ") || _key.Contains(" " + sqlParam))
                {
                    return true;
                }
            }
            foreach (string sqlParam in pattenRegex)
            {
                if (_key.Contains(sqlParam))
                {
                    return true;
                }
            }
            return false;

        }
        ///<summary>
        ///检查URL中是否包含Sql注入
        /// <param name="_request">当前HttpRequest对象</param>
        /// <returns>如果包含注入true;否则返回false</returns>
        ///</summary>
        public bool CheckRequestQuery()
        {
            if (request.QueryString.Count > 0)
            {
                foreach (string sqlParam in this.request.QueryString)
                {
                    if (sqlParam == "__VIEWSTATE") continue;
                    if (sqlParam == "__EVENTVALIDATION") continue;
                    if (CheckKeyWord(request.QueryString[sqlParam].ToLower()))
                    {
                        return true;
                    }
                }
            }
            return false;
        }
        ///<summary>
        ///检查提交的表单中是否包含Sql注入
        /// <param name="_request">当前HttpRequest对象</param>
        /// <returns>如果包含注入true;否则返回false</returns>
        ///</summary>
        public bool CheckRequestForm()
        {
            if (request.Form.Count > 0)
            {
                foreach (string sqlParam in this.request.Form)
                {
                    if (sqlParam == "__VIEWSTATE") continue;
                    if (sqlParam == "__EVENTVALIDATION") continue;
                    if (CheckKeyWord(request.Form[sqlParam]))
                    {
                        return true;
                    }
                }
            }
            return false;
        }

    }
}
 
3、新建err.aspx错误文件:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="err.aspx.cs" Inherits="SC_LuceneNet.err" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <script type='text/javascript'>
         if (confirm('是否重新登陆~~~~~~')) {
             location = "login.aspx";
         }
    </script>
</body>
</html>

你可能感兴趣的:(sql)