惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Tenable Blog
博客园_首页
Vercel News
Vercel News
WordPress大学
WordPress大学
美团技术团队
G
Google Developers Blog
大猫的无限游戏
大猫的无限游戏
小众软件
小众软件
Y
Y Combinator Blog
博客园 - 【当耐特】
量子位
酷 壳 – CoolShell
酷 壳 – CoolShell
The Cloudflare Blog
T
The Blog of Author Tim Ferriss
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google DeepMind News
Google DeepMind News
云风的 BLOG
云风的 BLOG
腾讯CDC
M
MIT News - Artificial intelligence
爱范儿
爱范儿
Recent Announcements
Recent Announcements
雷峰网
雷峰网
Last Week in AI
Last Week in AI
宝玉的分享
宝玉的分享
The Register - Security
The Register - Security
Jina AI
Jina AI
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Hugging Face - Blog
Hugging Face - Blog
P
Privacy & Cybersecurity Law Blog
Recorded Future
Recorded Future
Help Net Security
Help Net Security
N
News and Events Feed by Topic
博客园 - Franky
P
Proofpoint News Feed
L
LINUX DO - 热门话题
S
SegmentFault 最新的问题
The GitHub Blog
The GitHub Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
月光博客
月光博客
D
Docker
Google DeepMind News
Google DeepMind News
有赞技术团队
有赞技术团队
IT之家
IT之家
Security Latest
Security Latest
L
LangChain Blog
V
V2EX
阮一峰的网络日志
阮一峰的网络日志
J
Java Code Geeks

Mathias Bynens

A horrifying globalThis polyfill in universal JavaScript JavaScript engine fundamentals: optimizing prototypes JavaScript engine fundamentals: Shapes and Inline Caches Asynchronous stack traces: why await beats Promise#then() ECMAScript regular expressions are getting better! Unicode property escapes in JavaScript regular expressions ES2015 const is not about immutability Valid JavaScript variable names in ES2015 Unicode-aware regular expressions in ES2015 Dear Google, please fix plain text emails in Gmail PBKDF2+HMAC hash collisions explained JavaScript has a Unicode problem Hiding JSON-formatted data in the DOM with CSP enabled Loading JSON-formatted data with Ajax and xhr.responseType='json' Reserved keywords in JavaScript How to support full Unicode in MySQL databases How to speedrun Dropbox’s Dropquest 2012 Unquoted font family names in CSS Unquoted property names / object keys in JavaScript Valid JavaScript variable names in ES5 CSS character escape sequences JavaScript’s internal character encoding: UCS-2 or UTF-16? The smallest possible valid (X)HTML documents JavaScript character escape sequences JavaScript foo.prototype.bar notation Ambiguous ampersands HTML element + attribute notation How I detect and use localStorage: a simple JavaScript pattern Unquoted attribute values in HTML and CSS/JS selectors The end-tag open (ETAGO) delimiter Using the oninput event handler with onkeyup/onkeydown as its fallback Everything you always wanted to know about touch icons In defense of CSS hacks — introducing “safe CSS hacks” AirPlay video support in iOS Safari — a bookmarklet Completing Dropbox’s Dropquest 2011 in 60 seconds Using CSS without HTML How to create simple Mac apps from shell scripts Using setTimeout to speed up window.onload Bulletproof JavaScript benchmarks Thoughts on Safari Reader’s generated HTML How to enable Safari Reader on your site? The XML serialization of HTML5, aka ‘XHTML5’ The id attribute got more classy in HTML5 The three levels of HTML5 usage The HTML5 document.head DOM tree accessor Bulletproof HTML5 <details> fallback using jQuery Displaying hidden elements like <head> using CSS Inline <script> and <style> vs. external .js and .css — what’s the size threshold? Using Showdown/PageDown with and without jQuery
Processing Content Security Policy violation reports
Mathias · 2013-09-19 · via Mathias Bynens

Content Security Policy can be used to generate reports describing attempts to attack your site. This post briefly explains how this works, and presents a simple example script that can be used to process these reports.

How CSP’s report-uri directive works

CSP violation reporting can be enabled by specifying one or more endpoints using the report-uri policy directive:

Content-Security-Policy: default-src self; report-uri /csp-hotline.php

Now, whenever someone visits your site, and his browser blocks scripts, styles, fonts, or other resources based on your CSP configuration, it makes an HTTP POST request to /csp-hotline.php passing along a JSON-formatted report of the violation.

The earlier CSP configuration example blocks any resources that are not on the same origin as the current document. Let’s say this policy is in effect on https://example.com. In that case, if an attempt is made to load a script from, say, http://evilhackerscripts.com, the browser POSTs the following data to https://example.com/csp-hotline.php:

{"csp-report":{"document-uri":"https://example.com/foo/bar","referrer":"https://www.google.com/","violated-directive":"default-src self","original-policy":"default-src self; report-uri /csp-hotline.php","blocked-uri":"http://evilhackerscripts.com"}}

…which can be pretty-printed as:

{
	"csp-report": {
		"document-uri": "https://example.com/foo/bar",
		"referrer": "https://www.google.com/",
		"violated-directive": "default-src self",
		"original-policy": "default-src self; report-uri /csp-hotline.php",
		"blocked-uri": "http://evilhackerscripts.com"
	}
}

This data can then be processed by a server-side script (in this case, https://example.com/csp-hotline.php). I’d like to show you a minimal example of such a script.

Example script

Here’s a simple script that sends an email for each CSP violation that gets reported. I’m using PHP, but the example below should give you a good indication on how to implement this in your language of choice.

<?php // Note: this script requires PHP ≥ 5.4.

// Specify the email address that receives the reports.
define('EMAIL', 'mathias@example.com');
// Specify the desired email subject for violation reports.
define('SUBJECT', 'CSP violation');

// Send `204 No Content` status code.
http_response_code(204);

// Get the raw POST data.
$data = file_get_contents('php://input');
// Only continue if it’s valid JSON that is not just `null`, `0`, `false` or an
// empty string, i.e. if it could be a CSP violation report.
if ($data = json_decode($data)) {
	// Prettify the JSON-formatted data.
	$data = json_encode(
		$data,
		JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES
	);
	// Mail the CSP violation report.
	mail(EMAIL, SUBJECT, $data, 'Content-Type: text/plain;charset=utf-8');
}

?>

This can easily be extended to write the report info to a log file, or to store it in a database.

To verify the script works as intended, either visit a page on your site that violates your CSP settings, or submit a dummy report through curl and see if you get an email or not:

curl -H 'Content-Type: application/csp-report;charset=utf-8' --data '{"csp-report":{"document-uri":"https://example.com/foo/bar","referrer":"https://www.google.com/","violated-directive":"default-src self","original-policy":"default-src self; report-uri /csp-hotline.php","blocked-uri":"http://evilhackerscripts.com"}}' 'https://example.com/csp-hotline.php'

The email messages sent by this script look something like this:

Report-only mode

It’s possible to run CSP in “report-only” mode. In that case, CSP generates violation reports without actually blocking any content on your site. This gives you the opportunity to “dry-run” a CSP configuration, getting notified whenever a violation is encountered.

To enable “report-only” mode, simply send the Content-Security-Policy-Report-Only header instead of the Content-Security-Policy header:

Content-Security-Policy-Report-Only: default-src self; report-uri /csp-hotline.php

The CSP header generator tool includes a checkbox to enable/disable report-only mode. Check it out!