網站安全性:C#防SQL注入代碼的實現方法

來源:互聯網
上載者:User
對於網站的安全性,是每個網站開發人員和運營者最關心的問題。網站一旦出現漏洞,那勢必將造成很大的損失。為了提高網站的安全性,首先網站要防注入,最重要的是伺服器的安全設施要做到位。

    下面說下網站防注入的幾點要素。

    一:丟棄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. }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.