using
System;
using
System.Web;
using
System.Data;
namespace
MaliciousAccess.Service
{
public
class
HttpModule : IHttpModule
{
private
int
errorcount = 20;
/// <summary>
/// 您将需要在您网站的 web.config 文件中配置此模块,
/// 并向 IIS 注册此模块,然后才能使用。有关详细信息,
/// </summary>
#region IHttpModule Members
public
void
Dispose()
{
}
public
void
Init(HttpApplication context)
{
context.PreRequestHandlerExecute +=
new
EventHandler(OnPreRequest);
}
#endregion
public
void
OnPreRequest(Object source, EventArgs e)
{
goErr(Uri.UnescapeDataString(HttpContext.Current.Request.Url.AbsoluteUri));
if
(HttpContext.Current.Request.Url.AbsolutePath.IndexOf(
"Error.aspx"
) <= -1)
{
DataTable dt = Service.MaliciousAccessService.Instance.db.FromSql(
"select count(*) from MaliciousAccess where convert(varchar(10),CreateTime,120)='"
+ DateTime.Now.ToString(
"yyyy-MM-dd"
) +
"' "
).ToTable()
as
DataTable;
if
(
int
.Parse(dt.Rows[0][0].ToString()) > errorcount)
{
HttpContext.Current.Response.Redirect(
"Error.aspx"
);
}
}
}
/// <summary>
/// SQL注入过滤
/// </summary>
/// <param name="InText">要过滤的字符串 </param>
/// <returns>如果参数存在不安全字符,则返回true </returns>
public
bool
SqlFilter(
string
InText)
{
string
word =
"and|exec|insert|select|delete|update|chr|mid|master|or|truncate|char|declare|join|cmd"
;
if
(InText ==
null
)
return
false
;
foreach
(
string
i
in
word.Split(
'|'
))
{
if
((InText.ToLower().IndexOf(i +
" "
) > -1) || (InText.ToLower().IndexOf(
" "
+ i) > -1))
{
return
true
;
}
}
return
false
;
}
/// <summary>
/// 校验参数是否存在SQL字符
/// </summary>
/// <param name="tm"> </param>
private
void
goErr(
string
tm)
{
if
(SqlFilter(tm))
{
string
ip = HttpContext.Current.Request.UserHostAddress;
MaliciousAccessService.Instance.Add_Entity(
new
Service.MaliciousAccess()
{
IP = ip,
CreateTime = DateTime.Now
});
HttpContext.Current.Response.Redirect(
"Error.html"
);
}
}
}
}