nelmio / NelmioSecurityBundle

Adds extra security-related features in your Symfony application
https://symfony.com/bundles/NelmioSecurityBundle/
MIT License
651 stars 82 forks source link

Unexpecting appearance of unsafe-inline on CSP #346

Open spyridonas opened 3 months ago

spyridonas commented 3 months ago

Hello, I believe i have found a bug, or that my knowledge of CSP is lacking. Given the following csp configuration:

    csp:
        enforce:
            level1_fallback: false
            browser_adaptive:
                enabled: false
            connect-src:
                - 'self'

The content security policy correctly show the connect-src policy only.

If i add the same thing on default-src, making the configuration look like this:

    csp:
        enforce:
            level1_fallback: false
            browser_adaptive:
                enabled: false
            connect-src:
                - 'self'
            default-src:
                - 'self'

Then the response includes unsafe-inline as well. Is this a known issue ? Or is it expected behaviour ?

martijnc commented 3 months ago

The bundle only injects unsafe-inline automatically when you use nonces or hashes and level1_fallback is set to true. This is done in DirectiveSet::buildHeaderValue. With your example, the bundle should not include unsafe-inline

Some bundles (like the Symfony WebprofilerBundle) modify the CSP headers to include their own nonces/hashes (along with unsafe-inline for older browsers). Maybe this is what's happening here?

Can you check if the generated header value in ContentSecurityPolicyListener::buildHeaders is incorrect in your application?

spyridonas commented 2 months ago

@martijnc I do utilize nonces, but as you can see from the example the level1_fallback is set to false. The issue appeared on the staging of our app, where the symfony is running under 'production' mode (APP_ENV=prod) and without any dev dependencies installed/running (such as WebprofilerBundle). I will look at the ContentSecurityPolicyListener::buildHeaders output and report back

Seldaek commented 2 months ago

I am not sure why it's being injected right now, I'd have to check too, but note that unsafe-inline is ignored if a nonce or a hash is present (with browsers supporting CSP2 and above). So it is completely safe.

mbrodala commented 1 month ago

One option would be symfony/web-profiler-bundle:

https://github.com/symfony/web-profiler-bundle/blob/b9357f73d2c14dcd36783a67386f510654828668/Csp/ContentSecurityPolicyHandler.php#L152