分析Sql注入攻擊的原理不難知道主要還是在網站編製過程中沒有考慮防此類攻擊的有效性驗證,同時說明使用預存程序在防止此類攻擊有很好的效果,因為通常它會對輸入參數進行類型轉化,這些參數只可能是欄位值,而不會被理解為sql語句中的一部分。當然有些網站在開發過程中並沒有考慮這種防範措施,改起代碼來工作量比較大,網上有很多方法,我整理了一下,測試的效果還可以,供參考,在此不標明原始出處了。
此類方法就是在全域Application類的Application_BeginRequest方法中對使用者輸入的資料進行過濾,濾去不應該出現在地址欄中的Sql敏感單詞。
一、若aps.net工程中沒有全域類,則建立一個全域應用程式類;
二、為此類添加以下方法,SqlStr就是要屏蔽的Sql關鍵字,可以根據需要變化其中內容。
private bool ProcessSqlStr(string Str)<br /> {<br /> bool ReturnValue = true;<br /> try<br /> {<br /> if (Str != "")<br /> {<br /> string SqlStr = "select*|and'|or'|insertinto|deletefrom|altertable|update|createtable|createview|dropview|createindex|dropindex|createprocedure|dropprocedure|createtrigger|droptrigger|createschema|dropschema|createdomain|alterdomain|dropdomain|);|select@|declare@|print@|char(|select";<br /> string[] anySqlStr = SqlStr.Split('|');<br /> foreach (string ss in anySqlStr)<br /> {<br /> if (Str.IndexOf(ss) >= 0)<br /> {<br /> ReturnValue = false;<br /> }<br /> }<br /> }<br /> }<br /> catch<br /> {<br /> ReturnValue = false;<br /> }<br /> return ReturnValue;<br /> }<br />
三、為Application類添加Application_BeginRequest方法,如下:
protected void Application_BeginRequest(Object sender, EventArgs e)<br /> {<br /> ////遍曆Post參數,隱藏欄位除外<br /> //foreach (string i in this.Request.Form)<br /> //{<br /> // if (i == "__VIEWSTATE") continue;<br /> // this.goErr(this.Request.Form[i].ToString());<br /> //}<br /> ////遍曆Get參數。<br /> //foreach (string i in this.Request.QueryString)<br /> //{<br /> // this.goErr(this.Request.QueryString[i].ToString());<br /> //}<br /> try<br /> {<br /> string getkeys = "";<br /> string sqlErrorPage = System.Configuration.ConfigurationSettings.AppSettings["CustomErrorPage"].ToString();<br /> if (System.Web.HttpContext.Current.Request.QueryString != null)<br /> {</p><p> for (int i = 0; i < System.Web.HttpContext.Current.Request.QueryString.Count; i++)<br /> {<br /> getkeys = System.Web.HttpContext.Current.Request.QueryString.Keys[i];<br /> if (!ProcessSqlStr(System.Web.HttpContext.Current.Request.QueryString[getkeys]))<br /> {<br /> System.Web.HttpContext.Current.Response.Redirect(sqlErrorPage + "?errmsg=sqlserver&sqlprocess=true");<br /> System.Web.HttpContext.Current.Response.End();<br /> }<br /> }<br /> }<br /> if (System.Web.HttpContext.Current.Request.Form != null)<br /> {<br /> for (int i = 0; i < System.Web.HttpContext.Current.Request.Form.Count; i++)<br /> {<br /> getkeys = System.Web.HttpContext.Current.Request.Form.Keys[i];<br /> if (!ProcessSqlStr(System.Web.HttpContext.Current.Request.Form[getkeys]))<br /> {<br /> System.Web.HttpContext.Current.Response.Redirect(sqlErrorPage + "?errmsg=sqlserver&sqlprocess=true");<br /> System.Web.HttpContext.Current.Response.End();<br /> }<br /> }<br /> }<br /> }<br /> catch<br /> {<br /> // 錯誤處理: 處理使用者提交資訊!<br /> }<br /> }<br />
四、建立一個錯誤警告頁,將可疑輸入定向到錯誤頁,如ErrorPage.html
在web.config中加入的 <appSettings>中加入參數
<add key="CustomErrorPage" value="../ErrorPage.html" />
五、關鍵還是在於要寫安全的代碼,合理使用預存程序。