当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET Core中使用Csp标头对抗Xss攻击

ASP.NET Core中使用Csp标头对抗Xss攻击

2019年09月04日  | 移动技术网IT编程  | 我要评论

异界之冥帝重生,偃师,戚晓晴

内容安全策略(csp)是一个增加的安全层,可帮助检测和缓解某些类型的攻击,包括跨站点脚本(xss)和数据注入攻击。这些攻击用于从数据窃取到站点破坏或恶意软件分发的所有内容(深入csp

简而言之,csp是网页控制允许加载哪些资源的一种方式。例如,页面可以显式声明允许从中加载javascript,css和图像资源。这有助于防止跨站点脚本(xss)攻击等问题。

它也可用于限制协议,例如限制通过https加载的内容。csp通过 content-security-policy http响应中的标头实现。

启用csp,您需要配置web服务器以返回content-security-policyhttp标头。那么在这篇文章中,我们将要尝试将csp添加到asp.net core应用程序中。

app.use(async (ctx, next) =>
            {
                ctx.response.headers.add("content-security-policy",
                            "default-src 'self'; report-uri /cspreport");
                await next();
            });

  在home/index中引入cdn文件,然后我们启动项目,看看会发生什么!

运行并观察错误。加载页面时,浏览器拒绝从远程源加载。

 

 所以我们可以组织csp来控制我们的白名单,在配置当中需要填写来源以及内容,以下是常用限制的选项。

来源:

*: 允许任何网址。
‘self’: 允许所提供页面的来源。请注意,单引号是必需的。
‘none’: 不允许任何来源。请注意,单引号是必需的。
host: 允许指定的互联网主机(按名称或ip地址)。通配符(星号字符)可用于包括所有子域,例如http://*.foo.com
‘unsafe-line’: 允许内联脚本
‘nonce-[base64-value]’: 允许具有特定nonce的内联脚本(使用一次的数字)。对于每个http请求/响应,应该对nonce进行加密和唯一。

 指令:

script-src:定义有效的javascript源
style-src:定义样式表的有效来源
img-src:定义有效的图像源
connect-src:定义可以进行ajax调用的有效源
font-src:定义有效的字体来源
object-src:定义<object>,<embed>和<applet>元素的有效源
media-src:定义有效的音频和视频源
form-action:定义可用作html <form>操作的有效源。
default-src:指定加载内容的默认策略

我们可以在可重用的中间件中封装构建和添加csp头。以下是一个让您入门的示例。你可以根据需要扩展它。首先,创建一个用于保存源的类。

public class cspoptions
    {
        public list<string> defaults { get; set; } = new list<string>();
        public list<string> scripts { get; set; } = new list<string>();
        public list<string> styles { get; set; } = new list<string>();
        public list<string> images { get; set; } = new list<string>();
        public list<string> fonts { get; set; } = new list<string>();
        public list<string> media { get; set; } = new list<string>();
    }

 开发一个中间件一定是需要一个构造器的,这将用于.net core 的注入到运行环境中。

public sealed class cspoptionsbuilder  
 {  
     private readonly cspoptions options = new cspoptions();  
       
     internal cspoptionsbuilder() { }  
  
     public cspdirectivebuilder defaults { get; set; } = new cspdirectivebuilder();  
     public cspdirectivebuilder scripts { get; set; } = new cspdirectivebuilder();  
     public cspdirectivebuilder styles { get; set; } = new cspdirectivebuilder();  
     public cspdirectivebuilder images { get; set; } = new cspdirectivebuilder();  
     public cspdirectivebuilder fonts { get; set; } = new cspdirectivebuilder();  
     public cspdirectivebuilder media { get; set; } = new cspdirectivebuilder();  
  
     internal cspoptions build()  
     {  
         this.options.defaults = this.defaults.sources;  
         this.options.scripts = this.scripts.sources;  
         this.options.styles = this.styles.sources;  
         this.options.images = this.images.sources;  
         this.options.fonts = this.fonts.sources;  
         this.options.media = this.media.sources;  
         return this.options;  
     }  
 }  
  
 public sealed class cspdirectivebuilder  
 {  
     internal cspdirectivebuilder() { }  
  
     internal list<string> sources { get; set; } = new list<string>();  
  
     public cspdirectivebuilder allowself() => allow("'self'");  
     public cspdirectivebuilder allownone() => allow("none");  
     public cspdirectivebuilder allowany() => allow("*");  
  
     public cspdirectivebuilder allow(string source)  
     {  
         this.sources.add(source);  
         return this;  
     }  
 }  

 好了,我们创建一个中间件。

namespace xssdefenses.xssdefenses.middlerware
{
    public sealed class cspoptionmiddlerware
    {
        private const string header = "content-security-policy";
        private readonly requestdelegate next;
        private readonly cspoptions options;

        public cspoptionmiddlerware(
            requestdelegate next, cspoptions options)
        {
            this.next = next;
            this.options = options;
        }

        public async task invoke(httpcontext context)
        {
            context.response.headers.add(header, getheadervalue());
            await this.next(context);
        }

        private string getheadervalue()
        {
            var value = "";
            value += getdirective("default-src", this.options.defaults);
            value += getdirective("script-src", this.options.scripts);
            value += getdirective("style-src", this.options.styles);
            value += getdirective("img-src", this.options.images);
            value += getdirective("font-src", this.options.fonts);
            value += getdirective("media-src", this.options.media);
            return value;
        }
        private string getdirective(string directive, list<string> sources)
            => sources.count > 0 ? $"{directive} {string.join(" ", sources)}; " : "";
    }
}

 以及设置它的扩展方法。

namespace xssdefenses.xssdefenses.extensions
{
    public static class cspmiddlewareextensions
    {
        public static iapplicationbuilder usecsp(
             this iapplicationbuilder app, action<cspoptionsbuilder> builder)
        {
            var newbuilder = new cspoptionsbuilder();
            builder(newbuilder);

            var options = newbuilder.build();
            return app.usemiddleware<cspoptionmiddlerware>(options);
        }
    }
}

我们现在可以在startup类中配置中间件。

app.usecsp(builder =>
            {
                builder.styles.allowself()
                .allow(@"https://ajax.aspnetcdn.com/");
            });

 启动发现,观察网络资源。浏览器已经允许本地和远程资源。

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网