码迷,mamicode.com
首页 > 数据库 > 详细

防止sql注入

时间:2018-08-07 12:50:58      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:orm   \n   sele   lower   rhel   int   except   delete   ==   

 public static class SQLDefenderHelper
    {
      

        public static string SQLFilter(string inText)
        {
            string word = "and|exec|insert|select|delete|update|chr|mid|master|or|truncate|char|declare|join|--|on|=|‘|+";
            if (inText == null)
                return inText;
            //防止\**\代替空格
            if (inText.Contains("\\") || inText.Contains("/"))
            {
                InitInfo.LogOperation._OperationInfoLog("", "SQLDefenderHelper.SqlFilter", string.Format("语句{0}存在风险,禁止执行!", inText), "");
                throw new Exception("SQL语句存在风险,禁止执行!");
            }
            if (inText.Count(a => a.Equals(‘\‘‘)) % 2 != 0)//单引号为奇数则认为有风险
            {
                InitInfo.LogOperation._OperationInfoLog("", "SQLDefenderHelper.SqlFilter", string.Format("语句{0}存在风险,禁止执行!", inText), "");
                throw new Exception("SQL语句存在风险,禁止执行!");
            }

            foreach (string i in word.Split(‘|‘))
            {
                if ((inText.ToLower().IndexOf(i + " ") > -1) || (inText.ToLower().IndexOf(" " + i) > -1) ||//防止空格
                  (i!= "‘"&&inText.ToLower().IndexOf(i + "(") > -1) || (i != "‘" & inText.ToLower().IndexOf(")" + i) > -1) || //防止括号代替空格
                  (inText.ToLower().IndexOf(i + "\n") > -1) || (inText.ToLower().IndexOf("\n" + i) > -1) ||  //防止回车代替空格
                  (inText.ToLower().IndexOf(i + "\t") > -1) || (inText.ToLower().IndexOf("\t" + i) > -1))   //防止TAB代替空格
                {
                    InitInfo.LogOperation._OperationInfoLog("", "SQLDefenderHelper.SqlFilter", string.Format("语句{0}存在风险,禁止执行!", inText), "");
                    throw new System.Exception("SQL语句存在风险,禁止执行!");
                }
            }

            Regex regex = new Regex(@"[^0-9a-zA-Z,‘\(\)\*\.\-]+");
            if (regex.IsMatch(inText))
            {
                InitInfo.LogOperation._OperationInfoLog("", "SQLDefenderHelper.SqlFilter", string.Format("语句{0}存在风险,禁止执行!", inText), "");
                throw new System.Exception("SQL语句存在风险,禁止执行!");
            }
            return inText;
        }

    }

防止sql注入

标签:orm   \n   sele   lower   rhel   int   except   delete   ==   

原文地址:https://www.cnblogs.com/ZX-LMY/p/9435783.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!