Inline-script hash or nonce not accepted by CSP

2.7k views Asked by At

I am developing a Flask App and it uses Flask-Talisman to incorporate a CSP. I wanted to create an inline script in one of my templates and instead of adding 'unsafe-inline' to the 'script-src' array of the CSP which could be potentially harmful to XSS attacks, I wanted to use either a hash or a nonce to allow the script. I copied the hash given in the error message of the console in dev tools on Opera and placed it inside my 'script-src' array of the CSP (in the init.py file). However, the CSP won't accept the hash for some reason and I don't know how to fix it. I also tried this with a nonce and the same issue occurred. This is the console output (I removed the hash for security reasons):

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

And here is my CSP in init.py:

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']
}
1

There are 1 answers

0
Barry Pollard On BEST ANSWER

A hash and a nonce needs to be in quotes, so you should replace this:

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

with this:

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

similar to how you are including 'self'.

Note also that flask-talisman has nonce support built in, so doesn't need to be manually specified. It will be added automatically. See this example: https://github.com/GoogleCloudPlatform/flask-talisman#example-6