Dynamically inserting CSP

13 views
Skip to first unread message

Simon Pelchat

unread,
Mar 27, 2018, 5:20:04 PM3/27/18
to Security-dev, Tom Bergan
Hi,

I have a use case where I'd like to only allow a single script to execute in a web page I'm writing. The script in question can run in head. For complex reasons, I can't trust what is contained in the body of the document (i.e. it may contains scripts that I do not want to execute).

Dynamically inserting a CSP header from our script running in head works fine in practice (in Chrome at least). E.g. the following page does not execute the script in body, but lets the script in <head> run and install event handlers:

<html>
  <head>
    <script>
      setInterval(() => console.log('running'), 1000);
      document.write(`<meta http-equiv="Content-Security-Policy" content="script-src 'none'">`);
    </script>
  <body>
  <script>
    console.log("FAILURE this shouldn't execute");
  </script>
  </body>
</html>

My reading of the spec is that this behavior is prescribed by the spec and is not simply a Chrome implementation detail (https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type and https://w3c.github.io/webappsec-csp/#enforced).

Is my reading of the spec correct? I want to make sure I'm not relying on an implementation detail from Chrome (note that I don't care about other browsers at all, so I don't mind if they don't implement the spec correctly).

Thanks!

Eric Lawrence

unread,
Mar 27, 2018, 6:05:44 PM3/27/18
to spel...@chromium.org, Security-dev, tomb...@chromium.org
Historically, use of document.write has been a source of myriad problems and relying upon script execution to disable script execution seems unnecessarily fragile.

Is there a reason your page cannot deliver its policy using the Content-Security-Policy response header containing either a hash-source or nonce-source directive?

spel...@chromium.org

unread,
Mar 27, 2018, 6:15:16 PM3/27/18
to Security-dev, spel...@chromium.org, tomb...@chromium.org, elaw...@google.com
> Is there a reason your page cannot deliver its policy using the Content-Security-Policy response header containing either a hash-source or nonce-source directive?
I completely forgot that CSP supported this! That's a lot better, thanks and sorry for the noise!

Mike West

unread,
Mar 28, 2018, 1:08:55 AM3/28/18
to spel...@chromium.org, Security-dev, tomb...@chromium.org, Eric Lawrence
We do support injecting a policy at runtime by adding a `<meta>` element to the document's `<head>`, as do other browsers. But I agree with Eric that if you can do so, allowing specific scripts via nonces or hashes is a far more robust solution.

-mike
Reply all
Reply to author
Forward
0 new messages