欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#工具:防sql注入帮助类

程序员文章站 2022-07-11 09:45:53
SQL注入是比较常见的网络攻击方式之一,它不是利用操作系统的BUG来实现攻击,而是针对程序员编程时的疏忽,通过SQL语句,实现无帐号登录,甚至篡改数据库。 using System; using System.Collections.Generic; using System.Text; using ......

sql注入是比较常见的网络攻击方式之一,它不是利用操作系统的bug来实现攻击,而是针对程序员编程时的疏忽,通过sql语句,实现无帐号登录,甚至篡改数据库。

C#工具:防sql注入帮助类
using system;
using system.collections.generic;
using system.text;
using system.web;
using system.text.regularexpressions;

namespace core.common
{
    /// <summary>
    /// sql注入帮助
    /// </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)
                {
                    loghelper.info("检测出post恶意数据: 【" + httpcontext.current.request.form[i].tostring() + "】 url: 【" + httpcontext.current.request.rawurl + "】来源: 【" + httpcontext.current.request.userhostaddress + "】");
                    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)
                {
                    loghelper.info("检测出get恶意数据: 【" + httpcontext.current.request.querystring[i].tostring() + "】 url: 【" + httpcontext.current.request.rawurl + "】来源: 【" + httpcontext.current.request.userhostaddress + "】");
                    break;
                }//如果检测存在漏洞
            }
            return result;
        }

        /// <summary>
        /// 验证是否存在注入代码
        /// </summary>
        /// <param name="inputdata"></param>
        public static bool validdata(string inputdata)
        {
            //里面定义恶意字符集合
            //验证inputdata是否包含恶意集合
            if (regex.ismatch(inputdata.tolower(), 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;
        }


        /// <summary>
        /// 检测是否有sql危险字符
        /// </summary>
        /// <param name="str">要判断字符串</param>
        /// <returns>判断结果</returns>
        public static bool issafesqlstring(string str)
        {
            return !regex.ismatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']");
        }

        /// <summary> sql注入等安全验证
        /// 检测是否有危险的可能用于链接的字符串
        /// </summary>
        /// <param name="str">要判断字符串</param>
        /// <returns>判断结果</returns>
        public static bool issafeuserinfostring(string str)
        {
            return !regex.ismatch(str, @"^\s*$|^c:\\con\\con$|[%,\*" + "\"" + @"\s\t\<\>\&]|游客|^guest");
        }

        #region 检测客户的输入中是否有危险字符串
        /// <summary>
        /// 检测客户输入的字符串是否有效,并将原始字符串修改为有效字符串或空字符串。
        /// 当检测到客户的输入中有攻击性危险字符串,则返回false,有效返回true。
        /// </summary>
        /// <param name="input">要检测的字符串</param>
        public static bool isvalidinput(ref string input)
        {
            try
            {

                //替换单引号
                input = input.replace("'", "''").trim();

                //检测攻击性危险字符串
                string teststring = "and |or |exec |insert |select |delete |update |count |chr |mid |master |truncate |char |declare ";
                string[] testarray = teststring.split('|');
                foreach (string teststr in testarray)
                {
                    if (input.tolower().indexof(teststr) != -1)
                    {
                        //检测到攻击字符串,清空传入的值
                        input = "";
                        return false;
                    }
                }

                //未检测到攻击字符串
                return true;

            }
            catch (exception ex)
            {
                throw new exception(ex.message);
            }
        }
        #endregion
    }
}
sqlinjectionhelper