aspnet core2中使用csp内容安全策略

aspnet core2中使用csp内容安全策略


问题:aspnet core2如何使用csp防止xss的攻击

方法:


 public void ConfigureServices(
            IServiceCollection services)
        {
            services.AddMvc();
        }
 
        public void Configure(
            IApplicationBuilder app, 
            IHostingEnvironment env)
        {
            app.UseDeveloperExceptionPage();
 
            app.Use(async (context, next) =>
            {
                context.Response.Headers.Add(
                    "Content-Security-Policy",
                    "script-src 'self'; " +
                    "style-src 'self'; " +
                    "img-src 'self'");
 
                await next();
            });
 
            app.UseStaticFiles();
            app.UseMvcWithDefaultRoute();
        }
    }
    

_Layout页面 (普通html页面也可以,不一定是mvc)添加如下代码

<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
 
    <link rel="stylesheet" href="~/css/site.css" />
    <link rel="stylesheet" 
          href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.5/css/bootstrap.min.css" />
</head>
<body>
    <img src="~/img/site-banner.jpg" />
    <img src="https://media-www-asp.azureedge.net/media/5245130/home-hero-2.png" />
 
    <div>
        @RenderBody()
    </div>
 
    <script src="~/js/site.js"></script>
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
</body>
</html>

按f12调试 ,会看到类似下面的信息,bootstrap.min.css文件被浏览器拒绝了。

bootstrap.min.css blocked:csp


什么是 csp

这里也有介绍 https://www.zhihu.com/question/21979782
CSP指的是内容安全策略,为了缓解很大一部分潜在的跨站脚本问题,浏览器的扩展程序系统引入了内容安全策略(CSP)的一般概念。这将引入一些相当严格的策略,会使扩展程序在默认情况下更加安全,开发者可以创建并强制应用一些规则,管理网站允许加载的内容。

看上面的代码就知道了,就是在header里加了Content-Security-Policy的安全策略。

来源的控制有哪些策略呢

1 : 允许所有
2 ‘self’: 网站自身,记得有单引号
3 Host: 服务器。可以设置其他的服务器地址,ip和域名都可以,如http://
.foo.com cdn的资源可以这么做。
4 ‘unsafe-line’: 不安全的行内代码。如

 <a href="#" onclick="al()">保存</a>

5 ‘nonce-[base64-value]’:allow inline scripts with a specific nonce (number used once). The nonce should be encrypted and unique for every HTTP request/response .没用过。

能控制哪些内容呢?

script-src: JavaScript 脚本
style-src: css样式表
img-src: 图片地址
connect-src: ajax调用请求
font-src: 字体
object-src: 之类的元素
media-src: 音视频
form-action: form中的action
default-src: 加载内容的默认策略
更详细的看这里https://www.zhihu.com/question/21979782

以上内容可以用中间件实现。

原文:https://tahirnaushad.com/2017/09/12/using-csp-header-in-asp-net-core-2-0/

参考 https://www.zhihu.com/question/21979782

https://linux.cn/article-5848-1.html

https://yq.aliyun.com/articles/87712?utm_campaign=wenzhang&utm_medium=article&utm_source=QQ-qun&201767&utm_content=m_22674

原文作者实现了的中间件源码
GitHub: https://github.com/TahirNaushad/Fiver.Security.BrowserHeaders

源码中除了实现了csp,还有实现HTTP Strict Transport Security(从http跳转到https)的代码

posted @ 2017-11-05 00:00  过错  阅读(1265)  评论(1编辑  收藏  举报