【问题标题】:CSP: Does browser check if the nonce value in header matches with the nonce value in script tag?CSP:浏览器是否检查标头中的 nonce 值是否与 script 标签中的 nonce 值匹配?
【发布时间】:2021-05-05 23:50:37
【问题描述】:

我有一个使用 Ajax 加载部分内容的页面。部分内容有 script 标签,其 nonce 值与 Content-Security-Policy 标头中定义的 nonce 不匹配。

这里是完整代码(使用 asp.net core + jQuery 2.1.1)

中间件
对于每个 http 请求中间件都会注入带有 nonce 值的 Content-Security-Policy 标头

public class CSPMiddleware
{
    private readonly RequestDelegate _next;

    public CSPMiddleware(RequestDelegate next)
    {
        _next = next;            
    }

    public async Task Invoke(HttpContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }
        
        context.Response.Headers["Content-Security-Policy"] = $"default-src 'self'; script-src 'self' 'nonce-abc' 'unsafe-eval'";

        await _next(context);
    }
}

Index.cshtml

<button type="button" id="btnGetContent">Get Partial View</button>

<div id="result">    
</div>

//this script on the main page will execute since nonce matches with the header
<script type="text/javascript" nonce="abc">
    $(function () {
        $("#btnGetContent").click(function () {
            $.ajax({
                type: "GET",
                url: "/home/getpartialview",
                processData: true,
                cache: false
            })
                .done(function (response, textStatus, jqXHR) {
                    $("#result").html(response);
                })
        })

        
    })
</script>

局部视图

@System.DateTime.Now.ToString();

<button id="btn2">Click Me. I am on Partial</button>

// this script should not execute since nonce does not match
<script type="text/javascript" nonce="xyz">
    $("#btn2").click(function () {
        alert("foo");
    })
</script>

我的期望是,部分视图上的点击事件不应触发,因为脚本的 nonce 值与标题不匹配。但是点击事件确实会触发。

浏览器是否检查Content-Security-Policy 标头中的 nonce 值是否与 script 标签中的 nonce 值匹配?

【问题讨论】:

    标签: asp.net google-chrome asp.net-core microsoft-edge content-security-policy


    【解决方案1】:

    是的,浏览器完全检查匹配标头和脚本标记中的随机数值。但是 jQuery 2.x(无意中)使用了一种技术来绕过 'nonce-value' 通过 'unsafe-eval'(你必须允许 evalfor)。
    这个框架打破了在 HTML 代码中放置脚本的所有逻辑。

    jQuery 2.x 从 HTML 中解析所有 &lt;script&gt;...&lt;/script&gt; 标签并将其放入动态生成的脚本标签中或通过 eval( ) 执行这些标签:

    这就是 Dropbox 为 jQuery 2.x 手动检查 nonce 的原因:

    您可以在 AppSec EU 2017 的 this video 中找到更多详细信息(已倒退到所需的时间)。

    【讨论】:

    猜你喜欢
    • 2019-09-04
    • 2018-10-04
    • 1970-01-01
    • 2020-11-20
    • 2018-01-22
    • 2018-06-10
    • 2021-12-24
    • 1970-01-01
    • 2021-07-31
    相关资源
    最近更新 更多