隐藏

ASP.NET 修改Global.asax文件,防SQL注入式攻击

发布:2022/3/4 10:40:55作者:管理员 来源:本站 浏览次数:995

只需在Global.asax文件中加入如下方法即可:

#region SQL注入式攻击代码分析
    /// <summary>
    /// 处理用户提交的请求
    /// </summary>
    private void StartProcessRequest()
    {undefined
        try
        {undefined
            string getkeys = "";

            if (System.Web.HttpContext.Current.Request.QueryString != null)
            {undefined

                for (int i = 0; i < System.Web.HttpContext.Current.Request.QueryString.Count; i++)
                {undefined
                    getkeys = System.Web.HttpContext.Current.Request.QueryString.Keys[i];
                    if (!ProcessSqlStr(System.Web.HttpContext.Current.Request.QueryString[getkeys]))
                    {undefined
                        System.Web.HttpContext.Current.Response.Write(" <h3>不能包含执行语句 </h3>");
                        System.Web.HttpContext.Current.Response.End();
                    }
                }
            }
            if (System.Web.HttpContext.Current.Request.Form != null)
            {undefined
                for (int i = 0; i < System.Web.HttpContext.Current.Request.Form.Count; i++)
                {undefined
                    getkeys = System.Web.HttpContext.Current.Request.Form.Keys[i];
                    if (getkeys == "__VIEWSTATE") continue;
                    if (!ProcessSqlStr(System.Web.HttpContext.Current.Request.Form[getkeys]))
                    {undefined
                        //jcFAQApp.FAQ_Util.Log.WriteMessage(" <font color:red>注入攻击 </red>", System.Web.HttpContext.Current.Request.UserHostAddress.ToString());
                        System.Web.HttpContext.Current.Response.Write(" <h3>不能包含执行语句 </h3>");
                        System.Web.HttpContext.Current.Response.End();
                    }
                }
            }
        }
        catch
        {undefined

        }
    }
    /// <summary>
    /// 分析用户请求是否正常
    /// </summary>
    /// <param name="Str">传入用户提交数据 </param>
    /// <returns>返回是否含有SQL注入式攻击代码 </returns>
    private bool ProcessSqlStr(string Str)
    {undefined
        bool ReturnValue = true;
        try
        {undefined
            if (Str.Trim() != "")
            {undefined
                //string SqlStr = "and ¦exec ¦insert ¦select ¦delete ¦update ¦count ¦* ¦chr ¦mid ¦master ¦truncate ¦char ¦declare";
                string SqlStr = "exec ¦insert ¦select ¦delete ¦update ¦mid ¦master ¦truncate ¦declare";
                string[] anySqlStr = SqlStr.Split('¦');
                foreach (string ss in anySqlStr)
                {undefined
                    if (Str.ToLower().IndexOf(ss) >= 0)
                    {undefined
                        ReturnValue = false;
                        break;
                    }
                }
            }
        }
        catch
        {undefined
            ReturnValue = false;
        }
        return ReturnValue;
    }
    #endregion