2012-10-31 18 views
0

發現這個代碼使用的HttpModules這個防止MySQL注入的代碼很好嗎?

public class SampleSqlInjectionScreeningModuleCS : IHttpModule 
{ 
    //Defines the set of characters that will be checked. 
    //You can add to this list, or remove items from this list, as appropriate for your site 
    public static string[] blackList = {"--",";--",";","/*","*/","@@","@", 
             "char","nchar","varchar","nvarchar", 
             "alter","begin","cast","create","cursor","declare","delete","drop","end","exec","execute", 
             "fetch","insert","kill","open", 
             "select", "sys","sysobjects","syscolumns", 
             "table","update"}; 

    public void Dispose() 
    { 
     //no-op 
    } 

    //Tells ASP.NET that there is code to run during BeginRequest 
    public void Init(HttpApplication app) 
    { 
     app.BeginRequest += new EventHandler(app_BeginRequest); 
    } 

    //For each incoming request, check the query-string, form and cookie values for suspicious values. 
    void app_BeginRequest(object sender, EventArgs e) 
    { 
     HttpRequest Request = (sender as HttpApplication).Context.Request; 

     foreach (string key in Request.QueryString) 
      CheckInput(Request.QueryString[key]); 
     foreach (string key in Request.Form) 
      CheckInput(Request.Form[key]); 
     foreach (string key in Request.Cookies) 
      CheckInput(Request.Cookies[key].Value); 
    } 

    //The utility method that performs the blacklist comparisons 
    //You can change the error handling, and error redirect location to whatever makes sense for your site. 
    private void CheckInput(string parameter) 
    { 
     for (int i = 0; i < blackList.Length; i++) 
     { 
      if ((parameter.IndexOf(blackList[i], StringComparison.OrdinalIgnoreCase) >= 0)) 
      { 
       // 
       //Handle the discovery of suspicious Sql characters here 
       // 
       HttpContext.Current.Response.Redirect("~/About.aspx"); //generic error page on your site 
      } 
     } 
    } 

} 

這是一個好的代碼或者你認爲我需要添加更多的東西在黑名單中,或忘了這一點,並嘗試另一種方法,以防止注射防止一些基本的MySQL注射?

+1

你應該檢查出http://codereview.stackexchange.com –

+1

忘記這種做法,你可能會阻止有效的內容。驗證適當類型的輸入,然後查看參數化查詢。 –

+0

爲什麼不爲你的SQL查詢使用參數,而不用擔心? – Bridge

回答

2

不,它不好。

它會阻止有效的輸入,並且不會保護構造查詢無效/無效數據的代​​碼。

只要構建查詢正確假設傳入數據不好,你會好得多。

3

黑名單的方法來santizing /過濾數據從未到santizing數據的最佳方式。 (雖然它是取決於權衡某些情況下,適當的)

一個簡單的解釋存在的位置:http://www.testingsecurity.com/whitelists_vs_blacklists

黑名單正在測試所需的輸入對的負輸入 的列表。基本上,您會編譯一份所有負面或惡劣條件的清單,然後確認收到的輸入不是 不良或負面情況之一。白名單正在根據可能的正確輸入列表測試期望的輸入 。爲此,您將 編譯所有良好輸入值/條件的列表,然後驗證 收到的輸入是這種正確條件之一。

你認爲哪個更好?攻擊者可以使用任何方式訪問您的基於Web的應用程序。這包括嘗試各種負面或惡劣條件的 ,各種編碼方法,以及將惡意輸入數據附加到有效數據。你是否認爲你可以想到每個可能發生的不良排列,可能會發生?白名單是驗證輸入的最佳方式。你會知道 確切的是什麼是需要的,並沒有任何不好的類型接受。 通常,創建白名單的最佳方式是使用 正則表達式。使用正則表達式是 抽象白名單的好方法,而不是手動列出每個可能的 正確的值。

你最好不要使用標準,嘗試和真正的防禦:參數化查詢參數存儲過程

4

爲什麼在parameterized queries會爲您(和更多)做這項工作時執行字符串檢查?對您從代碼發出的SQL語句使用Parameters.Add()Parameters.AddWithValue()