Content Security Policy中使用Google Analytics

Content Security Policy中使用Google Analytics

防範XSS攻擊

CSP是由Google提出的安全性工具,主要是因為多年來網站很容易受到Cross-site Scripting XXS攻擊。

完全封鎖

首先是試一試最安全的設定,根據CSP Evaluator的設定如下

script-src 'strict-dynamic' 'nonce-rAnd0m123' 'unsafe-inline' http: https:;
object-src 'none';
base-uri 'none';
report-uri https://csp.example.com;

這個設定下....幾乎什麼script也不可能運作!連本地的script也被封死了...

default-src 'self' https://*.google.com https://*.googleapis.com https://www.google-analytics.com https://*.gstatic.com;

不過我需要Google Analytics,因為Google Analytics需要多個source,所以我了default-src。

這樣設定雖然只被Google通過,但是也會在CSP Evaluator中被評定為危險,因為在JSONP endpoints中是可以經Google進行攻擊的。

所以Google也有提供本地的Javascript file

<!-- Google Analytics -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');
</script>
<!-- End Google Analytics -->

這樣子用全本地的soure也可以使用Google Analytics了!

default-src 'self';
script-src 'self';