實現目的
在網頁上提交引數或post資料,可能存在危險的SQL語句,為了阻止SQL注入的攻擊,可以進行資料進行嚴格審查,提供系統安全。
程式碼如下
public class SQLInjectionHelper
{
/// <summary>
/// 獲取Post的資料
/// </summary>
public static bool ValidUrlPostData()
{
bool result = false;
for (int i = 0; i < HttpContext.Current.Request.Form.Count; i++)
{
result = HasInjectionData(HttpContext.Current.Request.Form[i].ToString());
if (result)
{
LogTextHelper.Info("檢測出POST惡意資料: 【" + HttpContext.Current.Request.Form[i].ToString() + "】 URL: 【" + HttpContext.Current.Request.RawUrl + "】來源: 【" + HttpContext.Current.Request.UserHostAddress + "】");
break;
}
}
return result;
}
/// <summary>
/// 獲取QueryString中的資料
/// </summary>
public static bool ValidUrlGetData()
{
bool result = false;
for (int i = 0; i < HttpContext.Current.Request.QueryString.Count; i++)
{
result = HasInjectionData(HttpContext.Current.Request.QueryString[i].ToString());
if (result)
{
LogTextHelper.Info("檢測出GET惡意資料: 【" + HttpContext.Current.Request.QueryString[i].ToString() + "】 URL: 【" + HttpContext.Current.Request.RawUrl + "】來源: 【" + HttpContext.Current.Request.UserHostAddress + "】");
break;
}
}
return result;
}
/// <summary>
/// 驗證是否存在注入程式碼(條件語句)
/// </summary>
/// <param name="inputData"></param>
public static bool HasInjectionData(string inputData)
{
if (string.IsNullOrEmpty(inputData))
return false;
//裡面定義惡意字元集合
//驗證inputData是否包含惡意集合
if (Regex.IsMatch(inputData.ToLower(), GetRegexString()))
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 獲取正則表示式
/// </summary>
/// <returns></returns>
private static string GetRegexString()
{
//構造SQL的注入關鍵字元
string[] strBadChar =
{
"select\\s",
"from\\s",
"insert\\s",
"delete\\s",
"update\\s",
"drop\\s",
"truncate\\s",
"exec\\s",
"count\\(",
"declare\\s",
"asc\\(",
"mid\\(",
"\\schar\\(",
"net user",
"xp_cmdshell",
"/add\\s",
"exec master.dbo.xp_cmdshell",
"net localgroup administrators"
};
//構造正則表示式
string str_Regex = ".*(";
for (int i = 0; i < strBadChar.Length - 1; i++)
{
str_Regex += strBadChar[i] + "|";
}
str_Regex += strBadChar[strBadChar.Length - 1] + ").*";
return str_Regex;
}
/// <summary>
/// 獲取正則表示式(太嚴格的函式,暫時不用)
/// </summary>
/// <returns></returns>
private static string GetRegexString2()
{
//構造SQL的注入關鍵字元
string[] strBadChar =
{
"and"
,"exec"
,"insert"
,"select"
,"delete"
,"update"
,"count"
,"from"
,"drop"
,"asc"
,"char"
,"or"
,"%"
,";"
,":"
,"\'"
,"\""
,"-"
,"chr"
,"mid"
,"master"
,"truncate"
,"char"
,"declare"
,"SiteName"
,"net user"
,"xp_cmdshell"
,"/add"
,"exec master.dbo.xp_cmdshell"
,"net localgroup administrators"
};
//構造正則表示式
string str_Regex = ".*(";
for (int i = 0; i < strBadChar.Length - 1; i++)
{
str_Regex += strBadChar[i] + "|";
}
str_Regex += strBadChar[strBadChar.Length - 1] + ").*";
return str_Regex;
}
}