javascriptsecuritygoogle-analyticscontent-security-policyastrojs

How to make external scripts work with hash-based CSP without allowlists in Astro?


I'm using a strict CSP without allowlists on my statically generated Astro website. I have no access to nonce-based CSP, only hash-based.

  1. Do I need to add permitted domains to a CSP allowlist if I'm using a hash-based approach?

  2. Can I hash external scripts and add an integrity parameter with this hash to the actual script tag for it to work? I've read that Safari does not support integrity (comment from 2021), but I see that subresource integrity is supported from 2018 according to caniuse.

  3. Do I hash <script> tags too? MDN says I don't, but the external script would be empty then.

The CSP I am using:

Content-Security-Policy: script-src 'sha256-placeholder' 'strict-dynamic'; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none';

Google Analytics scripts I want to get working:

<script is:inline src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script is:inline>
  window.dataLayer = window.dataLayer || [];
  function gtag() {
    dataLayer.push(arguments);
  }
  gtag("js", new Date());
  gtag("config", "G-XXXXXXXXXX");
</script>

Solution

    1. In CSP3 you can do a hash based approach only, but make sure that all references resources are static or that the hashes are dynamically computed. When you using 'strict-dynamic' only hashes and nonces can be used for scripts.

    2. Yes, you can use the integrity attribute. If it is not supported somewhere, you don't get the added security, but it shouldn't break. The CSP option to require integrity attribute has been removed.

    3. You should only hash what is between "<script ...>" and "" for inline scripts. Include all whitespace and remember that CSP uses UTF-8 representation even though you might have specified something else.

    For Google Tag Manager, see https://developers.google.com/tag-platform/security/guides/csp. It doesn't seem like they offer a hash based approach, nonces seem to be required if you want to have a strict CSP.