C#驗(yàn)證是否存在Sql注入代碼
構(gòu)造SQL的注入關(guān)鍵字符
//QueryString 數(shù)據(jù)檢測GET惡意數(shù)據(jù) private const string StrKeyWord = @".*(select|insert|delete|from|count(|drop table|update|truncate|asc(|mid(|char(|xp_cmdshell|exec master|netlocalgroup administrators|:|net user|""|or|and).*"; private const string StrRegex = @"[-|;|,|/|(|)|[|]|}|{|%|@|*|!|']"; /// <summary> /// 獲取Post的數(shù)據(jù) /// </summary> public static string ValidUrlPostData() { bool result = false; string res = string.Empty; for (int i = 0; i < HttpContext.Current.Request.Form.Count; i ) { result = ValidData(HttpContext.Current.Request.Form[i].ToString()); if (result) { res = "檢測出POST惡意數(shù)據(jù): 【" HttpContext.Current.Request.Form[i].ToString() "】 URL: 【" HttpContext.Current.Request.RawUrl "】來源: 【" HttpContext.Current.Request.UserHostAddress "】"; break; }//如果檢測存在漏洞 } return res; } /// <summary> /// 獲取QueryString中的數(shù)據(jù) /// </summary> public static string ValidUrlGetData() { bool result = false; string res = string.Empty; for (int i = 0; i < HttpContext.Current.Request.QueryString.Count; i ) { result = ValidData(HttpContext.Current.Request.QueryString[i].ToString()); if (result) { res = "檢測出GET惡意數(shù)據(jù): 【" HttpContext.Current.Request.QueryString[i].ToString() "】 URL: 【" HttpContext.Current.Request.RawUrl "】來源: 【" HttpContext.Current.Request.UserHostAddress "】"; break; }//如果檢測存在漏洞 } return res; } /// <summary> /// 驗(yàn)證是否存在注入代碼 /// </summary> /// <param name="inputData"></param> public static bool ValidData(string inputData) { //里面定義惡意字符集合 //驗(yàn)證inputData是否包含惡意集合 if (Regex.IsMatch(inputData.ToLower(), GetRegexString())) { return true; } else { return false; } } /// <summary> /// 獲取正則表達(dá)式 /// </summary> /// <param name="queryConditions"></param> /// <returns></returns> private static string GetRegexString() { //構(gòu)造SQL的注入關(guān)鍵字符 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" }; //構(gòu)造正則表達(dá)式 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; }
原文鏈接:C#驗(yàn)證防止阻斷Sql注入代碼