前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C#笔记:XSS攻击防御

C#笔记:XSS攻击防御

作者头像
超级大猪
发布2019-11-22 09:45:49
1.2K0
发布2019-11-22 09:45:49
举报
文章被收录于专栏:大猪的笔记大猪的笔记

白名单法:

 public static string XssWhiteListFilter(string html)
        {
            html = HttpUtility.HtmlEncode(html);
            //p 相关
            string pattern1 = @"<p>|" +
                "</p>|" +
                @"<p style="([\s\S](?!<))*">";
            //img
            string pattern2 = @"<img src="http://www.yinzihao.com.cn/.*"/>"+
                "|<img src="http://img.baidu.com/(.(?!<))*"/>";
            //a
            string pattern3 = "<a href="http://www.yinzihao.com.cn/(.(?!<))*">(.(?!<))*</a>";
            //br strong
            string pattern4 = "<br/>|<strong>|</strong>";
            //span
            string pattern5 = @"<span style="([\s\S](?!<))*">" +
                "|</span>";

            List<string> lstPattern = new List<string>() { pattern1, pattern2, pattern3, pattern4, pattern5 };

            foreach (string pat in lstPattern)
            {
                Regex reg = new Regex(pat, RegexOptions.IgnoreCase);
                MatchCollection mc = reg.Matches(html);

                foreach (Match item in mc)
                {
                    html = html.Replace(item.Value, HttpUtility.HtmlDecode(item.Value));
                }
            }

            return html;
        }

filter:

  public class XssFilter:ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var parameters = filterContext.ActionDescriptor.GetParameters();
            foreach (var parameter in parameters)
            {
                if (parameter.ParameterType == typeof(string))
                {
                    //获取字符串参数原值
                    var orginalValue = filterContext.ActionParameters[parameter.ParameterName] as string;
                    //使用过滤算法处理字符串
                    var filteredValue = MvcDatu.Controllers.Helper.XssWhiteListFilter(orginalValue);
                    //将处理后值赋给参数
                    filterContext.ActionParameters[parameter.ParameterName] = filteredValue;
                }
            }
        }
    }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015-02-06 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档