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:    <[^>]*|&nbsp;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)
 

C#  防XSS攻击 示例

 经过多次测试,选择你所认为合适的正则表达式

下面是我目前选择的正则表达式,你可以根据需要进行修改

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;
        }

测试效果

C#  防XSS攻击 示例

相关推荐