sql注入检测

 bool CheckMain()
  { 
   //false 非模拟执行,记录且阻断执行
   //true 模拟执行,只记录,不阻断执行
   bool Simulate = true;
   String para;
   int loop0, loop1, loop2;
   //Load NameValueCollection object.
   NameValueCollection[] col = new NameValueCollection[2];
   //Get names of all keys into a string array.
   String[][] key = new String[2][];

   col[0] = Request.QueryString;
   col[1] = Request.Form;

   for(loop0 = 0; loop0 < col.Length; loop0++)
   {
    key[loop0] = col[loop0].AllKeys;
    for (loop1 = 0; loop1 < key[loop0].Length; loop1++)
    { 
     String[] value = col[loop0].GetValues(key[loop0][loop1]);
     for (loop2 = 0; loop2 < value.Length; loop2++)
     {
      if(CheckParams(value[loop2]) == false)
      {
       para =  "?Method="+Request.HttpMethod;
       para += "&url="+Request.ServerVariables.GetValues("URL")[0];
       para += "&key=【"+key[loop0][loop1]+"】";
       para += "&value=【"+DoReplace(value[loop2])+"】";
       if(Simulate == true)
       {
        String scriptString;
        scriptString = "<script languge='javascript'>";
        scriptString += "function DoPopup(){";
        scriptString += "window.open('/parameter_error2.html";
        scriptString += para;
        scriptString += "')";
        scriptString += "}";
        scriptString += "DoPopup();";
        scriptString += "<";
        scriptString += "/script>";
        Response.Write(scriptString);
       }
       else
       {
        Response.Redirect("/parameter_error1.html"+para);
        Response.End();
       }
      }  
     }//end of loop2
    }//end of loop1
   }//end of loop0
   return true;
  }

  //返回flase表示检测到关键字
  bool CheckParams(String para)
  {
   String str_Regex = "((create|declare|delete|drop|exec|execute|fetch|insert|select|update|having|db_name|xp_cmdshell|sp_oamethod|sp_makewebtask)[\\x01-\\x20\\(\\+]|0x|[;])";
   if(Regex.Matches(para, str_Regex, RegexOptions.IgnoreCase ).Count>0)
    return false;
   else
    return true;
  }

  //替换参数中的特殊字符'
  String DoReplace(String str) 
  {
   str = str.Trim();
   return str.Replace("'", "");
  }

posted @ 2005-11-23 13:47  烈马狂生  阅读(766)  评论(0编辑  收藏  举报