Content Security Policy HTTP Headers
July 5th 2016
Provides a standard method for website owners to declare approved origins of content that browsers should be allowed to load on that website
It's a solid safety net against execution of malicious content in the trusted web page context
This doesn't mean you can forget about escaping user data on the server side, but if you screw up, CSP will give you a last layer of defense.
Content-Security-Policy: script-src 'self' https://apis.google.com
This allows all javascripts file from
All other javascript files will be blocked (including inline JS)
Origin-based whitelisting doesn’t solve the biggest threat posed by XSS attacks: inline script injection.
CSP solves this problem by banning inline script entirely: it’s the only way to be sure.
<!-- amazing.html -->
<script>
function doAmazingThings() {
alert('YOU ARE AMAZING!');
}
</script>
<button onclick='doAmazingThings();'>Am I amazing?</button>
// amazing.js
function doAmazingThings() {
alert('YOU are AMAZING!');
}
document.addEventListener('DOMContentReady', function () {
document.getElementById('amazing')
.addEventListener('click', doAmazingThings);
});
<!-- amazing.html -->
<script src='amazing.js'></script>
<button id='amazing'>Am I amazing?</button>
<!-- inline script -->
<script>
console.log('test)
</script>
<!-- my whitelisted inline script -->
<script nonce=EDNnf03nceIOfn39fn3e9h3sdfa>
//notice the unique *nonce
console.log('test)
</script>
# header to whitelists the inline script
Content-Security-Policy: script-src 'nonce-EDNnf03nceIOfn39fn3e9h3sdfa'
* nonce = number used once
<!-- inline script -->
<script>
console.log('test)
</script>
# header to whitelists the inline script
Content-Security-Policy: script-src 'sha256-qznLcsROx4GACP2dm0UCKCzCG-HiZ1guq6ZZDob_Tng='
<!-- inline script -->
<script>
console.log('test)
</script>
<!-- inline script -->
<script>
console.log('test)
</script>
# header to whitelists ALL inline script (NOT RECOMMENDED)
Content-Security-Policy: script-src 'unsafe-inline'
<!-- inline script -->
<script>
console.log('test)
</script>
#application controller
before_filter :set_csp
def set_csp
response.headers['Content-Security-Policy'] = "default-src *; script-src https://assets.example.com; style-src https://assets.example.com"
end
tool for checking your security headers
quick reference guide
talk at #parisrb by @DorianLupu
slides available online : slides.com/kundigo