C# 檢查字符串,防SQL注入攻擊

SQL注入攻擊如下,CheckParams函數,接收參數任意,如參數中有字符串,則對字符串進行檢查,如參數中有集合(如Array之類,總之是實現了ICollection的),則對集合中的字符串元素進行檢查.大家可根據具體情況來定要過濾的字符,我這個例子裏暫定爲=號和'號,實際上我個人認爲,過濾了這兩個,似乎要進行SQL注入就已經比較困難了,當然,我對SQL是菜鳥,歡迎高手指正,謝謝.

方法一

bool CheckParams(params object[] args)
{ string[] Lawlesses={"=","'"};
if(Lawlesses==null||Lawlesses.Length<=0)return true; //構造正則表達式,
例:Lawlesses是=號和'號,則正則表達式爲 .*[=}'].* (正則表達式相關內容請見MSDN) 另外,由於我是想做通用而且容易修改的函數,所以多了一步由字符數組到正則表達式,實際使用中,直接寫正則表達式亦可;
string str_Regex=".*[";
for(int i=0;i< Lawlesses.Length-1;i++)
str_Regex+=Lawlesses[i]+"|";
str_Regex+=Lawlesses[Lawlesses.Length-1]+"].*";
// foreach(object arg in args)
{ if(arg is string)//如果是字符串,直接檢查
{ if(Regex.Matches(arg.ToString(),str_Regex).Count>0)
return false; }
else if(arg is ICollection)//如果是一個集合,則檢查集合內元素是否字符串,是字符串,就進行檢查 { foreach(object obj in (ICollection)arg)
{ if(obj is string)
{ if(Regex.Matches(obj.ToString(),str_Regex).Count>0)
return false;
}
}
}
}
return true;}

方法二

一.如果參數全爲數字:
// 檢查字符串是否全爲數字
public static bool IsNum(string Str)
{
     bool blResult = true;
     if (Str == "")
         blResult = false;
     else
     {
         foreach (char Char in Str)
         {
             if (!Char.IsNumber(Char))
             {
                 blResult = false;
                 break;
             }
         }
         if (blResult)
             if (int.Parse(Str) == 0)
                 blResult = false;
     }
     return blResult;
}http://www.pconcool.com

應用:
string Topicid = Request.QueryString["Topicid"];
if (!IsNum(Topicid))
     Server.Transfer("Error.aspx?ErrID=404");


二.如果參數爲文本.

// Html轉換
public static string htmlstr(string chr)
{
     if(chr==null)
         return "";
     chr=chr.Replace("<","<");
     chr=chr.Replace(">",">");
     chr=chr.Replace("/n","<br>");
     chr=chr.Replace("/"",""");
     chr=chr.Replace("'","'");
     chr=chr.Replace(" ","?");
     chr=chr.Replace("/r","");
     return(chr);
}
應用:string strClass = htmlstr(Request.QueryString["ClassName"]);

方法三:.net整站防sql注入

將下面的代碼加入到Global.asax文件中:
     /// <summary>
    /// 防止SQL注入
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
void Application_BeginRequest(Object sender, EventArgs e)
     {
         StartProcessRequest();

     }

     #region SQL注入式攻擊代碼分析
     /// <summary>
     /// 處理用戶提交的請求
     /// </summary>
     private void StartProcessRequest()
     {
         try
         {
             string getkeys = "";
             string sqlErrorPage = "error.aspx";//轉向的錯誤提示頁面
             if (System.Web.HttpContext.Current.Request.QueryString != null)
             {

                 for (int i = 0; i < System.Web.HttpContext.Current.Request.QueryString.Count; i++)
                 {
                     getkeys = System.Web.HttpContext.Current.Request.QueryString.Keys[i];
                     if (!ProcessSqlStr(System.Web.HttpContext.Current.Request.QueryString[getkeys]))
                     {
                         System.Web.HttpContext.Current.Response.Redirect(sqlErrorPage);
                         System.Web.HttpContext.Current.Response.End();
                     }
                 }
             }
             if (System.Web.HttpContext.Current.Request.Form != null)
             {
                 for (int i = 0; i < System.Web.HttpContext.Current.Request.Form.Count; i++)
                 {
                     getkeys = System.Web.HttpContext.Current.Request.Form.Keys[i];
                     if (getkeys == "__VIEWSTATE") continue;
                     if (!ProcessSqlStr(System.Web.HttpContext.Current.Request.Form[getkeys]))
                     {
                         System.Web.HttpContext.Current.Response.Redirect(sqlErrorPage);
                         System.Web.HttpContext.Current.Response.End();
                     }
                 }
             }
         }
         catch
         {
             // 錯誤處理: 處理用戶提交信息!
         }
     }
     /// <summary>
     /// 分析用戶請求是否正常
     /// </summary>
     /// <param name="Str">傳入用戶提交數據 </param>
     /// <returns>返回是否含有SQL注入式攻擊代碼 </returns>
     private bool ProcessSqlStr(string Str)
     {
         bool ReturnValue = true;
         try
         {
             if (Str.Trim() != "")
             {
                 string SqlStr = "and .exec .insert .select .delete .update .count .* .chr .mid .master .truncate .char .declare";

                 string[] anySqlStr = SqlStr.Split('.');
                 foreach (string ss in anySqlStr)
                 {
                     if (Str.ToLower().IndexOf(ss) >= 0)
                     {
                         ReturnValue = false;
                         break;
                     }
                 }
             }
         }
         catch
         {
             ReturnValue = false;
         }
         return ReturnValue;
     }
     #endregion

個人網站:歡迎交流 www.tripbee.cn

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章