Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Analytics and Content-Security-Policy header

The Content-Security-Policy HTTP header is meant to block inline script and resources from untrusted servers. However, the sample Google Analytics code snippet depends on both. What are the best practices in this area?

This is the Content-Security-Policy header that I'm currently using:

default-src 'self'; script-src 'self' https://ssl.google-analytics.com; img-src 'self'  http://www.google-analytics.com/__utm.gif https://ssl.google-analytics.com/__utm.gif;

So far, I've done the following:

I added two script tags to my html:

<script src="/js/google-analytics.js"></script>
<script src="https://ssl.google-analytics.com/ga.js" async="true"></script>

google-analytics.js sets up the _gaq array with _setAccount and _trackPageview.

I added the domain for ga.js to the script-src.

I noticed that ga.js was loading two images, so I added them to img-src.

Is there anything I'm missing? Will Google change things on me and break all of this? Is there any official recommendation?

like image 359
Greg Avatar asked Jan 29 '13 21:01

Greg


People also ask

How do I add CSP to Google Analytics?

The easiest, but least secure, way to allow Google Analytics to run is to add the special string 'unsafe-inline' (with quotes) to the source list for your script-src directive. As its name implies, this allows all inline snippets to run, and may allow unsafe code to run.

Is Content-Security-Policy a header?

Content-Security-Policy is the name of a HTTP response header that modern browsers use to enhance the security of the document (or web page). The Content-Security-Policy header allows you to restrict how resources such as JavaScript, CSS, or pretty much anything that the browser loads.

How do I fix the Content-Security-Policy of your site blocks the use of eval in JavaScript?

The Content Security Policy (CSP) prevents the evaluation of arbitrary strings as JavaScript to make it more difficult for an attacker to inject unauthorized code on your site. To solve this issue, avoid using eval() , new Function() , setTimeout([string], ...) and setInterval([string], ...) for evaluating strings.


1 Answers

This is mostly right:

  1. You don't need the path to the image, just the protocol + host + (implied) port

  2. Firefox differs slightly in its CSP implementation. For older versions, replace default-src with allow. There was a cutoff where Firefox supported default-src as equal to allow but most still implement with allow until it fully supports the spec (no citation included).

like image 128
oreoshake Avatar answered Oct 02 '22 14:10

oreoshake