/// <summary>
/// 安全类
/// </summary>
public class SafeCommon
{
private static string StrRegex = @"<[^>]+?style=[\w]+?:expression\(|\b(alert|confirm|prompt|onmouseover|onmouseout)\b|^\+/v(8|9)|<[^>]*?=[^>]*?&#[^>]*?>|\b(and|or)\b.{1,6}?(=|%|&|>|<|\bin\b|\blike\b)|/\*.+?\*/|<\s*script\b|<\s*img\b|\bEXEC\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\s+(TABLE|DATABASE)";
private static bool CheckData(string inputData)
{
if (Regex.IsMatch(inputData.ToLower(), StrRegex))
{
return true;
}
else
{
return false;
}
}
#region 检查危险字符
/// <summary>
/// 检查危险字符
/// </summary>
/// <param name="sInput"></param>
/// <returns></returns>
public static bool IsSafeString(Microsoft.AspNetCore.Http.HttpContext context,string sInput)
{
bool b = CheckData(sInput);
if (b)
{
string url = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase + context.Request.Path + context.Request.QueryString;
string ip = context.Request.HttpContext.Connection.RemoteIpAddress+":"+context.Request.HttpContext.Connection.RemotePort;
string type = context.Request.Method;
string postParam = "";
if (context.Request.Method.ToLower().Equals("post"))
{
foreach (var key in context.Request.Form.Keys.ToList())
{
postParam = postParam + "{\"key\":\""+key+"\",\"value\":\""+ context.Request.Form["key"] + "\"},";
}
postParam = postParam.Trim(',');
postParam = "[" + postParam + "]";
}
string msg = string.Format("\r\n 请勿非法提交,提交数据中有非法字符!\r\n 攻击时间是:{0}\r\n 被攻击URL是:{1}\r\n 攻击者的IP是:{2}\r\n 请求方式是{3}\r\n POST参数是{4}\r\n", System.DateTime.Now.ToString(), url, ip,type,postParam);
string path = string.Format("{0}/log/safe", AppContext.BaseDirectory);
string fileName =path+"/"+System.DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
DirFile.DirFileSheep.CreateDirectory(path);
DirFile.DirFileSheep.CreateFile(fileName);
DirFile.DirFileSheep.AppendText(fileName, msg);
throw new Exception("请勿非法提交,提交数据中有非法字符!");
}
return b;
}
#endregion
}
本文介绍了一个用于检查HTTP请求中潜在危险字符的安全类实现。该类通过正则表达式匹配恶意输入,如SQL注入、XSS攻击等,并记录非法提交尝试。
1361

被折叠的 条评论
为什么被折叠?



