Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Google Tag Manager and Content-Security-Policy coexist?

The Content-Security-Policy (CSP) header aims to protect your application against malicious resource injection in your web apps. To make it simple, you provide a whitelist of allowed domain origins for all your images, scripts, styles and so on.

Meanwhile, Marketing team is using Google Tag Manager (GTM) to manage tags. The principle is to gather information from a page, send them to GTM and use those data as variables to generate tags, a mix of templated JS/HTML and those variables.

The problem is that most of those tags contain javascript, for sending very specific data to trackers, ad servers or whatever partners. Let's assume my marketing team is aware of security risks and will not include malicious script.

Is there a way to know which domains are imported by GTM so they can be automatically added on my CSP?

like image 275
Alain Tiemblo Avatar asked Dec 05 '16 12:12

Alain Tiemblo


1 Answers

This a big problem and I'm surprised how little information there is on this. Beware of any solutions that suggest setting unsafe-inline in your CSP as makes the policy so weak it's almost useless.

To answer your direct question, there is no way of knowing which domains are used by GTM programmatically. I recommend setting CSP to report only mode and using the errors as your guide to creating the whitelist.

To answer the broader question of how to make them coexist, the primary solution is to use a nonce value and the nonce-aware GTM script as described here by Google here https://developers.google.com/tag-manager/web/csp.

In short:

  1. Generate a nonce value - this needs to be done on every page load to be effective
  2. Whitelist the nonce in your CSP
  3. Apply it to any inline scripts inluding GTM
  4. Whitelist any hosts that resources loaded by GTM use

However, this solution is incomplete as GTM doesn't seem to propagate the nonce to any Custom HTML tags. In order to do that you must:

  1. Add an id, such as "gtm_script" to the nonce-aware version of the GTM script tag - this will be used to target the element and capture nonce
  2. Add a data attribute that will store the nonce value e.g. data-nonce="[your nonce value here]"
  3. In GTM, create a new variable to capture the nonce. Use DOM Element type, and select the ID of the GTM snippet (gtm_script in this guide), then get the nonce value from the data attribute
  4. In GTM, add the nonce value to any Custom HTML scripts
  5. In GTM, enable Support document.write using the checkbox

For a more thorough guide, including screen shots of GTM, please see this article https://rbultitudezone.medium.com/tag-manager-services-and-website-security-using-gtm-with-csp-5749a610c600

like image 181
rjbultitude Avatar answered Oct 08 '22 15:10

rjbultitude