每一个开发者都会意识到,网站发布之前,需要进行安全及系统漏洞检查。
那么如何拦截攻击者注入恶意脚本或代码?如何防御诸如跨站脚本攻击(XSS)、SQL注入攻击等恶意攻击行为?
针对目前常见的一些安全问题,结合目前一些常见的防护办法,可在系统底层增加了安全防护代码。
[Description("网站安全通用防护代码(用户读写数据库对用户输入或者发送(Post、Get)数据等进行检测过滤等),跨站脚本攻击(XSS)、SQL注入攻击等恶意攻击")] public partial class SafeUtils { //正则过滤字符 private const string StrRegex = @"<[^>]+?style=[\w]+?:expression\(|\b(alert|confirm|prompt)\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)"; /// <summary> /// POST请求 /// </summary> /// <param name="putData">输出非法字符串</param> /// <returns></returns> public static bool PostData(out string putData) { bool result = false; putData = string.Empty; for (int i = 0; i < HttpContext.Current.Request.Form.Count; i++) { result = CheckData(HttpContext.Current.Request.Form[i].ToString(), out putData); if (result) { putData = HttpContext.Current.Request.Form[i].ToString(); break; } } return result; } /// <summary> /// GET请求 /// </summary> /// <param name="putData">输出非法字符串</param> /// <returns></returns> public static bool GetData(out string putData) { bool result = false; putData = string.Empty; for (int i = 0; i < HttpContext.Current.Request.QueryString.Count; i++) { result = CheckData(HttpContext.Current.Request.QueryString[i].ToString(), out putData); if (result) { putData = HttpContext.Current.Request.QueryString[i].ToString(); break; } } return result; } /// <summary> /// COOKIE数据 /// </summary> /// <param name="putData">输出非法字符串</param> /// <returns></returns> public static bool CookieData(out string putData) { bool result = false; putData = string.Empty; for (int i = 0; i < HttpContext.Current.Request.Cookies.Count; i++) { result = CheckData(HttpContext.Current.Request.Cookies[i].Value.ToLower(), out putData); if (result) { putData = HttpContext.Current.Request.Cookies[i].Value.ToLower(); break; } } return result; } /// <summary> /// UrlReferrer请求来源 /// </summary> /// <param name="putData">输出非法字符串</param> /// <returns></returns> public static bool Referer(out string putData) { bool result = false; result = CheckData(HttpContext.Current.Request.UrlReferrer.ToString(), out putData); if (result) { putData = HttpContext.Current.Request.UrlReferrer.ToString(); } return result; } /// <summary> /// 正则检查 /// </summary> /// <param name="inputData">字符串</param> /// <param name="putData">输出非法字符串</param> /// <returns></returns> public static bool CheckData(string inputData, out string putData) { putData = string.Empty; //if (Regex.IsMatch(inputData.ToUpper(), StrRegex.ToUpper(),RegexOptions.IgnoreCase)) if (Regex.IsMatch(inputData, StrRegex, RegexOptions.IgnoreCase)) //忽略大小写 { putData = inputData; return true; } else { return false; } } }
原文地址:https://www.cnblogs.com/sharing1986687846/p/10281676.html
时间: 2024-10-25 05:43:32