码迷,mamicode.com
首页 > Windows程序 > 详细

C# 防XSS攻击 示例

时间:2020-05-26 22:03:16      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:写代码   int   new   insert   test   range   ret   case   amp   

新建控制台程序,编写代码测试过滤效果

    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)

 

技术图片

 

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

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

   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攻击 示例

标签:写代码   int   new   insert   test   range   ret   case   amp   

原文地址:https://www.cnblogs.com/for-easy-fast/p/12968860.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!