利用HttpApplicaton请求管道防止SQL注入
HttpApplication
通过事件管道的方式处理请求,注意对请求的数据过滤filter
和根据请求的类型交由相应的处理程序Handler
处理。
管道注入由两种一种实现接口IHttpModule
,另一种直接Global
类中添加方法。
SQL注入网站安全的威胁,关防止的方法:一种不允许敏感数据请求,一种将敏感数据重字符串中过滤。要求针对所有的用户请求,所有在BeginRequest
事件中处理(也可以说是一种AOP编程)。
CODE
SQL注入处理类
public class SQLInjectionHelper
{
public static bool ValidUrlData(string request)
{
bool result = false;
//获取pos数据
if(request == "POST")
{
for(int i = 0; i < HttpContext.Current.Request.Form.Count; i++)
{
result = ValidData(HttpContext.Current.Request.Form[i].ToString());
if (result)
{
break;
}
}
}
//获取QueryString中的数据
else
{
for(int i = 0; i < HttpContext.Current.Request.QueryString.Count; i++)
{
result = ValidData(HttpContext.Current.Request.QueryString[i].ToString());
if (result)
{
break;
}
}
}
return result;
}
/// <summary>
/// 判断是否存在注入代码
/// </summary>
/// <param name="inputData"></param>
/// <returns></returns>
private static bool ValidData(string inputData)
{
if (Regex.IsMatch(inputData, GetRegexString())){
return true;
}
else
{
return false;
}
}
/// <summary>
/// 获取正则表达式
/// </summary>
/// <returns></returns>
private static string GetRegexString()
{
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;
}
}
添加到Global
类
void Application_BeginRequest(object sender,EventArgs e)
{
bool result = false;
result = SQLInjectionHelper.ValidUrlData(Request.RequestType.ToUpper());
if (result)
{
Response.Write("您提交的数据有恶意字符");
Response.End();
}
}