网站安全性:C#防SQL注入代码的实现方法

来源:互联网 发布:淘宝鼠标垫护腕 编辑:程序博客网 时间:2024/05/22 13:44
对于网站的安全性,是每个网站开发者和运营者最关心的问题。网站一旦出现漏洞,那势必将造成很大的损失。为了提高网站的安全性,首先网站要防注入,最重要的是服务器的安全设施要做到位。

    下面说下网站防注入的几点要素。

    一:丢弃SQL语句直接拼接,虽然这个写起来很快很方便。

    二:如果用SQL语句,那就使用参数化,添加Param

    三:尽可能的使用存储过程,安全性能高而且处理速度也快

    四:屏蔽SQL,javascript等注入(很是主要的),对于每个文件写是不太可能的。所以要找到对所有文件起作用的办法。我在网上收集了以下3种方法

    C#防SQL注入方法一

    在Web.config文件中, < appSettings>下面增加一个标签:如下

  1. < appSettings>
  2. < add key="safeParameters" value="OrderID-int32,CustomerEmail-email,ShippingZipcode-USzip" />
  3. < /appSettings>  

    其中key是 < saveParameters>后面的值为"OrderId-int32"等,其中"-"前面表示参数的名称比如:OrderId,后面的int32表示数据类型。

    C#防SQL注入方法二

    在Global.asax中增加下面一段:  

  1. protected void Application_BeginRequest(Object sender, EventArgs e){
  2. String[] safeParameters = System.Configuration.ConfigurationSettings.AppSettings["safeParameters"].ToString().Split(',');
  3. for(int i= 0 ;i <   safeParameters.Length; i++){
  4. String parameterName = safeParameters[i].Split('-')[0];
  5. String parameterType = safeParameters[i].Split('-')[1];
  6. isValidParameter(parameterName, parameterType);
  7. }
  8. }
  9. public void isValidParameter(string parameterName, string parameterType){
  10. string parameterValue = Request.QueryString[parameterName];
  11. if(parameterValue == null) return;
  12. if(parameterType.Equals("int32")){
  13. if(!parameterCheck.isInt(parameterValue)) Response.Redirect("parameterError.aspx");
  14. }
  15. else if (parameterType.Equals("USzip")){
  16. if(!parameterCheck.isUSZip(parameterValue)) Response.Redirect("parameterError.aspx");
  17. }
  18. else if (parameterType.Equals("email")){
  19. if(!parameterCheck.isEmail(parameterValue)) Response.Redirect("parameterError.aspx");
  20. }
  21. }  

    C#防SQL注入方法

    使用字符串过滤类

  1. using System;
  2. namespace web.comm
  3. {
  4.     /**//// < summary>
  5.     /// ProcessRequest 的摘要说明。
  6.     /// < /summary>
  7.     public class ProcessRequest
  8.      {
  9.         public ProcessRequest()
  10.          {
  11.             //
  12.             // TODO: 在此处添加构造函数逻辑
  13.             //
  14.          }
  15.          SQL注入式攻击代码分析#region SQL注入式攻击代码分析
  16.         /**//// < summary>
  17.         /// 处理用户提交的请求
  18.         /// < /summary>
  19.         public static void StartProcessRequest()
  20.          {
  21.             
  22. //             System.Web.HttpContext.Current.Response.Write("< script>alert('dddd');< /script>");
  23.             try
  24.              {
  25.                 string getkeys = "";
  26.                 //string sqlErrorPage = System.Configuration.ConfigurationSettings.AppSettings["CustomErrorPage"].ToString();
  27.                 if (System.Web.HttpContext.Current.Request.QueryString != null)
  28.                  {
  29.     
  30.                     for(int i=0;i< System.Web.HttpContext.Current.Request.QueryString.Count;i++)
  31.                      {
  32.                          getkeys = System.Web.HttpContext.Current.Request.QueryString.Keys[i];
  33.                         if (!ProcessSqlStr(System.Web.HttpContext.Current.Request.QueryString[getkeys],0))
  34.                          {
  35.                             //System.Web.HttpContext.Current.Response.Redirect (sqlErrorPage+"?errmsg=sqlserver&sqlprocess=true");
  36.                              System.Web.HttpContext.Current.Response.Write("< script>alert('请勿非法提交!');history.back();< /script>");
  37.                              System.Web.HttpContext.Current.Response.End();
  38.                          }
  39.                      }
  40.                  }
  41.                 if (System.Web.HttpContext.Current.Request.Form != null)
  42.                  {
  43.                     for(int i=0;i< System.Web.HttpContext.Current.Request.Form.Count;i++)
  44.                      {
  45.                          getkeys = System.Web.HttpContext.Current.Request.Form.Keys[i];
  46.                         if (!ProcessSqlStr(System.Web.HttpContext.Current.Request.Form[getkeys],1))
  47.                          {
  48.                             //System.Web.HttpContext.Current.Response.Redirect (sqlErrorPage+"?errmsg=sqlserver&sqlprocess=true");
  49.                              System.Web.HttpContext.Current.Response.Write("< script>alert('请勿非法提交!');history.back();< /script>");
  50.                              System.Web.HttpContext.Current.Response.End();
  51.                          }
  52.                      }
  53.                  }
  54.              }
  55.             catch
  56.              {
  57.                 // 错误处理: 处理用户提交信息!
  58.              }
  59.          }
  60.         /**//// < summary>
  61.         /// 分析用户请求是否正常
  62.         /// < /summary>
  63.         /// < param name="Str">传入用户提交数据< /param>
  64.         /// < returns>返回是否含有SQL注入式攻击代码< /returns>
  65.         private static bool ProcessSqlStr(string Str,int type)
  66.          {
  67.             string SqlStr;
  68.             if(type == 1)
  69.                  SqlStr = "exec |insert |select |delete |update |count |chr |mid |master |truncate |char |declare ";
  70.             else
  71.                  SqlStr = "'|and|exec|insert|select|delete|update|count|*|chr|mid|master|truncate|char|declare";
  72.             bool ReturnValue = true;
  73.             try
  74.              {
  75.                 if (Str != "")
  76.                  {
  77.                     string[] anySqlStr = SqlStr.Split('|');
  78.                     foreach (string ss in anySqlStr)
  79.                      {
  80.                         if (Str.IndexOf(ss)>=0)
  81.                          {
  82.                              ReturnValue = false;
  83.                          }
  84.                      }
  85.                  }
  86.              }
  87.             catch
  88.              {
  89.                  ReturnValue = false;
  90.              }
  91.             return ReturnValue;
  92.          }
  93.          #endregion
  94.      }
  95. }
0 0