C# 防XSS攻击 示例
新建控制台程序,编写代码测试过滤效果
class Program { static void Main(string[] args) { //GetStrRegex(); Console.WriteLine("请输入字符串:"); string str = Console.ReadLine(); for (int i = 0; i < 100; i++) { Test(str); } } static void Test(string str) { Console.WriteLine("请输入正则表达式:"); string StrRegex = Console.ReadLine(); str = Regex.Replace(str, StrRegex, "", RegexOptions.IgnoreCase); Console.WriteLine($"处理后的字符串为:{str}"); } }
输入字符串测试及正则表达式,观察测试效果
字符串:<script>(script)</script><style>alert("中国伟大复兴")</style><h1>111</h1><h2>222</h2>drop delete <div style=""> select update exec trunc database table index @@@hao好的// 中国。湖北。武汉&& 湖北-- 中国加油! 正则表达式: a: <[^>]*| b: <[^>]+?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)
经过多次测试,选择你所认为合适的正则表达式
下面是我目前选择的正则表达式,你可以根据需要进行修改
static string GetStrRegex() { List<string> strList = new List<string>(); List<string> htmlList = new List<string>() { "<h1>","<h2>","<h3>","<h4>","<h5>","<h6>","<style>","<script>","javascript","onload","onerror","eval","alert","prompt"}; List<string> sqlList = new List<string>() { "select","update","delete","drop","trunc","exec","table","database","or","and"}; List<string> chList = new List<string>() { "//","--", "@", "&" ,"||"}; strList.AddRange(htmlList); strList.AddRange(sqlList); strList.AddRange(chList); string strRegex = string.Join("|", strList.ToArray()); Console.WriteLine($"你的正则表达式是{strRegex}"); return strRegex; }
测试效果
相关推荐
sswqycbailong 2020-07-28
csxiaoqiang 2020-07-26
码农成长记 2020-07-19
layloge 2020-07-05
layloge 2020-06-26
liangjielaoshi 2020-06-25
csxiaoqiang 2020-06-16
某先生 2020-06-13
ItBJLan 2020-06-11
layloge 2020-06-07
csxiaoqiang 2020-06-03
sswqycbailong 2020-06-01
layloge 2020-05-30
码农成长记 2020-05-28
zhuangnet 2020-05-20
zhuangnet 2020-05-19
xiaoemo0 2020-05-16
码农成长记 2020-05-10
today0 2020-05-04