How do you whitelist a specific domain for a specific content security policy directive, while having a less specific directive for other domains?

Viewed 4652

I want to allow unsafe-eval for a script-src policy, but only for a specific domain.

For example, I only want scripts from *.example.net to be able to use eval().

script-src 'unsafe-inline' *;script-src 'unsafe-eval' 'unsafe-inline' *.example.net blob:;

The above does not work. How can I achieve this behavior?

1 Answers

I want to allow 'unsafe-eval' for a 'script-src' policy, but only for a specific domain.
How can I achieve this behavior?

You can’t. Content Security Policy doesn’t provide a way to do that.

Both 'unsafe-eval' and *.example.net are just different types of what the CSP spec calls a “source expression”, and the values of CSP directives such as script-src are what the CSP spec calls “source lists” — lists of separate individual source expressions.

And source expressions in a CSP source list have no internal association with each other — instead they each apply globally to the directive they’re associated with.

So if you specify 'unsafe-eval' for the value of a script-src directive, then that always has the effect of globally allowing eval() in any JavaScript code in the document relies on.

There is no other syntax in CSP to express “only allow 'unsafe-eval' for *.example.net”. There’s just no way to express that in CSP.


From https://w3c.github.io/webappsec-csp/#framework-directive-source-list:

Many directives' values consist of source lists: sets of strings which identify content that can be fetched and potentially embedded or executed. Each string represents one of the following types of source expression:

  1. Keywords such as 'none' and 'self' (which match nothing and the current URL’s origin, respectively)

  2. Serialized URLs such as https://example.com/path/to/file.js (which matches a specific file) or https://example.com/ (which matches everything on that origin)

  3. Schemes such as https: (which matches any resource having the specified scheme)

  4. Hosts such as example.com (which matches any resource on the host, regardless of scheme) or *.example.com (which matches any resource on the host’s subdomains (and any of its subdomains' subdomains, and so on))

  5. Nonces such as 'nonce-ch4hvvbHDpv7xCSvXCs3BrNggHdTzxUA' (which can match specific elements on a page)

  6. Digests such as 'sha256-abcd...' (which can match specific elements on a page)

Related