随笔 - 750  文章 - 1  评论 - 107  阅读 - 34万

[转][C#]简单的防SQL注入方式

上代码:

在 Global.asax 文件中:

复制代码
//在接收到一个应用程序请求时触发。对于一个请求来说,它是第一个被触发的事件,请求一般是用户输入的一个页面请求(URL)。
void Application_BeginRequest(object sender, EventArgs e)
{
    //Response.Write("通用注入检查");
    bool result = false;

    if (Request.RequestType.ToUpper() == "POST")
    {
        result = SQLInjectionHelper.ValidUrlPostData();//Post数据检查
    }
    else
    {
        result = SQLInjectionHelper.ValidUrlGetData();//Get数据检查
    }

    if (result)
    {
        Response.Write("您提交的数据有恶意字符!");
        Response.Write("<script>alert('您提交的数据有恶意字符!');<//script>");
        Response.End();
    }
}
复制代码

校验片段:

复制代码
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using System.Text.RegularExpressions;

/// <summary>
///SQLInjectionHelper 的摘要说明
/// </summary>
public class SQLInjectionHelper
{
    private const string StrKeyWord = @".*(select|insert|delete|from|count(|drop table|update|truncate|asc(|mid(|char(|xp_cmdshell|exec master|netlocalgroup administrators|:|net user|""|or|and).*";
    private const string StrRegex = @"[-|;|,|/|(|)|[|]|}|{|%|@|*|!|']";

    /// <summary>
    /// 获取Post的数据
    /// </summary>
    public static bool ValidUrlPostData()
    {
        bool result = false;

        for (int i = 0; i < HttpContext.Current.Request.Form.Count; i++)
        {
            result = ValidData(HttpContext.Current.Request.Form[i].ToString());
            if (result)
            {
                break;
            }//如果检测存在漏洞
        }
        return result;
    }

    /// <summary>
    /// 获取QueryString中的数据
    /// </summary>
    public static bool ValidUrlGetData()
    {
        bool result = false;

        for (int i = 0; i < HttpContext.Current.Request.QueryString.Count; i++)
        {
            result = ValidData(HttpContext.Current.Request.QueryString[i].ToString());
            if (result)
            {
                break;
            }//如果检测存在漏洞
        }
        return result;
    }

    /// <summary>
    /// 验证是否存在注入代码
    /// </summary>
    /// <param name="inputData"></param>
    public static bool ValidData(string inputData)
    {
        //里面定义恶意字符集合
        //验证inputData是否包含恶意集合
        if (Regex.IsMatch(inputData, GetRegexString()))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    /// <summary>
    /// 获取正则表达式
    /// </summary>
    /// <param name="queryConditions"></param>
    /// <returns></returns>
    private static string GetRegexString()
    {
        //构造SQL的注入关键字符
    string[] strBadChar = {"and"
    ,"exec"
    ,"insert"
    ,"select"
    ,"delete"
    ,"update"
    ,"count"
    ,"from"
    ,"drop"
    ,"asc"
    ,"char"
    ,"or"
    //,"*"
    ,"%"
    ,";"
    ,":"
    ,"\'"
    ,"\""
    ,"-"
    ,"chr"
    ,"mid"
    ,"master"
    ,"truncate"
    ,"char"
    ,"declare"
    ,"SiteName"
    ,"net user"
    ,"xp_cmdshell"
    ,"/add"
    ,"exec master.dbo.xp_cmdshell"
    ,"net localgroup administrators"};

        //构造正则表达式
        string str_Regex = ".*(";
        for (int i = 0; i < strBadChar.Length - 1; i++)
        {
            str_Regex += strBadChar[i] + "|";
        }
        str_Regex += strBadChar[strBadChar.Length - 1] + ").*";

        return str_Regex;
    }
}
复制代码

 

posted on   z5337  阅读(1357)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
历史上的今天:
2018-04-25 [Html] jQuery Grid
2016-04-25 [html]CSS 小贴士
2016-04-25 [经验]PLSQL乱码解决
2014-04-25 C# 读写 ini 配置文件
2014-04-25 [转]VB 读写ini 配置文件
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示