Asp.net防御XSS攻击组件库

一、AntiXss

翻看mvc4高级编程,偶看到作者强烈推荐使用AntiXss防御XSS攻击,收集资料看下。

目前类库已融入到.netframework中,类库主页不再更新。

使用方法:使用Nuget,搜索AntiXss

在项目中添加命名空间引用:using Microsoft.Security.Application;

 示例代码:

 string xssstr="<script>alert(0);</script>,;<insert into table";
            string encodedstr= Encoder.HtmlEncode(xssstr, false);
            
            string safestr = Sanitizer.GetSafeHtml(xssstr);
            string safestrfrag = Sanitizer.GetSafeHtml(xssstr);
            encodedstr = Encoder.HtmlEncode(xssstr, false);
View Code

代码运行后,会过滤敏感字符进行转义操作。

使用Sanitizer.GetSafeHtml()会得到过滤过敏感字符的html字符串结果。

 参考资料:

  类库官网

  博客园榨菜小生文章

  csdnVinoYang专栏文章

二、HtmlSanitizer

  VS中使用Nuget控制台安装。

  

  HtmlSanitizer依赖AngleShart库

       public ISet<string> AllowedAttributes { get; }
        public ISet<string> AllowedCssProperties { get; }
        public ISet<string> AllowedSchemes { get; }
        public ISet<string> AllowedTags { get; } 

  通过上述属性可以查看Allowed标签信息。

  HtmlSanitizer可以添加白名单到标签中,类库简单使用示例如下:

  

            //初始化对象
            HtmlSanitizer htmlSanitizer = new HtmlSanitizer();          
            StringBuilder alltag = new StringBuilder();
            foreach (var item in htmlSanitizer.AllowedTags)
            {
                alltag.Append(item + "\r\n");
            }

            //获得AllowedTags
            string allTagsstr = alltag.ToString();

            //过滤操作
            string filterstr = htmlSanitizer.Sanitize(xssstr);
            //添加script到白名单中
            htmlSanitizer.AllowedTags.Add("script");
            //查看过滤后的结果
            filterstr = htmlSanitizer.Sanitize(xssstr);

  HtmlSanitizer以标签为基础单进行过滤,上例中script设置白名单后alert不会被过滤。

 

posted @ 2017-04-27 23:04  mopheify  阅读(671)  评论(0编辑  收藏  举报