asp網站空間過濾xss攻擊的方法:1、在web.config增加httpModules節點;2、編寫一個過濾器,過濾危險關鍵詞,并增加安全的header。
具體內容如下:
1、在web.config增加httpModules節點
<httpModules><add name="HttpAccessInterceptModule" type="Org.Core.Commons.HttpAccessInterceptModule, Org.Core.Commons"/>
</httpModules>
2、再編寫一個過濾器
using System;using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;namespace Org.Core.Commons
{
/// <summary>
/// http訪問攔截器模塊
/// 1.過濾危險關鍵詞
/// 2.增加安全Header
/// </summary>
public class HttpAccessInterceptModule : IHttpModule
{
private static List<string> _RegexWords;
static HttpAccessInterceptModule()
{
_RegexWords = new List<string>()
{
@"<[^>]+>'",
@"</[^>]+>'",
@"<[^>]+?style=[\w]+?:expression\(|\b(alert|confirm|prompt|window|location|eval|console|debugger|new|Function|var|let)\b|^\+/v(8|9)|<[^>]*?=[^>]*?&#[^>]*?>|\b(and|or)\b.{1,6}?(=|>|<|\bin\b|\blike\b)|/\*.+?\*/|<\s*script\b|\bEXEC\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\s+(TABLE|DATABASE)"
};
string[] keyWords = { };
//{"'", "alert", "script","case","catch","const","continue","debugge","delete","export*","final","finally","for","function","goto","if","implements","import*","return","switch","synchronized","throw","throws","transient","try","break"}
//new string[] { "select", "insert", "update", "delete", "drop", "truncate" };_RegexWords.AddRange(keyWords.Select(o => @"(^|(\W+))" + o + @"((\W+)|$)"));
}public void Dispose()
{
}public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(Context_BeginRequest);
context.EndRequest += new EventHandler(Context_EndRequest);
}private void Context_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication) sender;
try
{
if (IgnoreRequest(app.Request.CurrentExecutionFilePath))
return;RequestFiller(app.Request);
AddHeader(app.Response);
}
catch (Exception ex)
{
if (!(ex is PSBaseException))
PSLog4net.Error(this, ex);
app.Response.Write(ex.Message);
app.Response.Flush();
app.Response.End();
}
}private void Context_EndRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication) sender;SetContentType(app);
}private void RequestFiller(HttpRequest request)
{
string error = "";if (request.Path.IndexOf("/log/", StringComparison.CurrentCultureIgnoreCase) >= 0)
error = "不允許訪問/log/目錄";
if (string.IsNullOrEmpty(error) &&
request.Path.IndexOf("/bak/", StringComparison.CurrentCultureIgnoreCase) >= 0)
error = "不允許訪問/bak/目錄";
if (string.IsNullOrEmpty(error))
{
foreach (string key in request.Params.AllKeys)
{
if (key == "aspxerrorpath")
continue;
string value = request.Params[key];
if (!string.IsNullOrEmpty(value) && (value.Contains("jquery.alert") || value.Contains("image")))
continue;
if (!string.IsNullOrEmpty(key))
{
//if (Regex.IsMatch(key, @"\W+"))
//{
// error = string.Format("存在訪問風險,參數[{0}={1}]無法通過“{2}”校驗.", key, value, @"\W+");
// break;
//}
foreach (string regex in _RegexWords)
{
if (Regex.IsMatch(key, regex, RegexOptions.IgnoreCase))
{
error = $"存在訪問風險,參數[{key}={value}]無法通過“{regex}”校驗.";
break;
}
}
}if (!string.IsNullOrEmpty(error))
break;
if (!string.IsNullOrEmpty(value))
{
foreach (string regex in _RegexWords)
{
if (Regex.IsMatch(value, regex, RegexOptions.IgnoreCase))
{
error = $"存在訪問風險,參數[{key}={value}]無法通過“{regex}”校驗.";
break;
}
}
}if (!string.IsNullOrEmpty(error))
break;
}
}if (!string.IsNullOrEmpty(error))
{
Log4net.Error(this, error);
throw new PSBaseException("存在訪問風險,請求無法通過系統校驗規則.");
}
}private void AddHeader(HttpResponse response)
{}private void SetContentType(HttpApplication app)
{
if (app.Request.Url.AbsolutePath.EndsWith(".png", StringComparison.CurrentCultureIgnoreCase))
app.Response.ContentType = "image/png";
if (string.IsNullOrEmpty(app.Response.ContentType))
app.Response.ContentType = "text/plain; charset=utf-8";
}private bool IgnoreRequest(string requestPath)
{
if (requestPath.EndsWith(".assx", StringComparison.CurrentCultureIgnoreCase) ||
requestPath.EndsWith(".sjs", StringComparison.CurrentCultureIgnoreCase) ||
requestPath.EndsWith(".asmx", StringComparison.CurrentCultureIgnoreCase))
return true;
else
return false;
}
}
}