Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CSP_INCLUDE_NONCE_IN not working? #182

Closed
javulticat opened this issue Nov 18, 2021 · 4 comments · Fixed by #185
Closed

CSP_INCLUDE_NONCE_IN not working? #182

javulticat opened this issue Nov 18, 2021 · 4 comments · Fixed by #185

Comments

@javulticat
Copy link

javulticat commented Nov 18, 2021

I've been unable to get a nonce included in the CSP header generated by django-csp. I've followed the instructions in the docs, and everything else seems to be working - other than getting a nonce to show up in the CSP header sent in my responses.

My settings.py:

MIDDLEWARE = [
    # ...,
    "csp.middleware.CSPMiddleware",
]
CSP_DEFAULT_SRC = ["foo", "bar", "'self'"]
CSP_INCLUDE_NONCE_IN = ["default-src"]

Header: Content-Security-Policy: default-src foo bar 'self'

I'd expect something like: Content-Security-Policy: default-src foo bar 'self' nonce-h893hjkfhdsu9hf8fd8a773hda

Am I doing something wrong or looking in the wrong place? Thanks!

@javulticat
Copy link
Author

javulticat commented Nov 18, 2021

It looks like the nonce does not get sent in the header if no nonce is being evaluated in your template. Once my template was evaluating a nonce, things work as expected. Perhaps the docs should be updated to reflect this? I'd be happy to give it a shot if folks are open to it.

@sgelis
Copy link

sgelis commented Dec 16, 2021

Thanks for opening this issue. Was hit with the exact same one today.

@DylanYoung
Copy link
Contributor

Took a stab at a PR here.

I wonder if it makes sense to change this behaviour slightly though as it seems somewhat unsafe. If the nonce isn't used and it's not going to be included in the header, shouldn't the source list be set to 'none'?

@some1ataplace
Copy link

It might be because of the middleware SimpleLazyObject. The SimpleLazyObject may not be properly calling the _make_nonce method. To fix this, you can change the process_request method to directly call the _make_nonce method:

class CSPMiddleware(MiddlewareMixin):
    def _make_nonce(self, request):
        if not getattr(request, '_csp_nonce', None):
            request._csp_nonce = (
                base64
                .b64encode(os.urandom(16))
                .decode("ascii")
            )
        return request._csp_nonce

    def process_request(self, request):
        request.csp_nonce = self._make_nonce(request)

    # rest of the code remains unchanged

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants