CSP 不接受内联脚本哈希或随机数

Inline-script hash or nonce not accepted by CSP

我正在开发一个 Flask 应用程序,它使用 Flask-Talisman 来合并一个 CSP。我想在我的一个模板中创建一个内联脚本,而不是将 'unsafe-inline' 添加到 CSP 的 'script-src' 数组,这可能对 XSS 攻击有害,我想使用哈希或随机数允许脚本。我在 Opera 的开发工具中复制了控制台错误消息中给出的哈希值,并将其放在 CSP 的 'script-src' 数组中(在 init.py 文件中)。但是,CSP 出于某种原因不接受哈希,我不知道如何修复它。我也用随机数试过这个,同样的问题发生了。这是控制台输出(出于安全原因我删除了哈希):

The source list for Content Security Policy directive 'script-src' contains an invalid source: 'sha256-(hash goes here)'. 
It will be ignored.

这是我在 init.py:

中的 CSP
csp = {
    "default-src": [
        "'self'",
        'https://www.youtube.com',
        'https://img.youtube.com'
    ],
    'script-src': [ 'sha256-(hash goes here)',
                    'https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js',
                    'https://code.jquery.com/jquery-3.3.1.slim.min.js',
                    'https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js'],
    'style-src': ["'self'",'https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css']
}

A hashnonce 需要用引号引起来,因此您应该替换为:

'script-src': [ 'sha256-(hash goes here)',

有了这个:

'script-src': [ "'sha256-(hash goes here)'",

类似于您包含 'self' 的方式。

另请注意,flask-talisman 内置 nonce 支持,因此无需手动指定。它将自动添加。看这个例子:https://github.com/GoogleCloudPlatform/flask-talisman#example-6