Last active
September 3, 2023 21:42
-
-
Save mrcgrtz/8e209c13c1d1b0c925df2a3f3f0c8052 to your computer and use it in GitHub Desktop.
A PHP-based CSP reporter sending mails when a violation occurs.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
// Configuration: Set mail from/to. | |
$from = $_SERVER['SERVER_ADMIN']; | |
$to = $_SERVER['SERVER_ADMIN']; | |
// Get the raw POST data. | |
$data = file_get_contents('php://input'); | |
// Only continue if it is valid JSON that is not just `null`, `0`, `false` or an | |
// empty string, i.e. if it could be a violation report. | |
if ($data = json_decode($data)) { | |
// Validate data (a.k.a. do not send me useless reports). | |
if (isset($data->{'csp-report'}, $data->{'csp-report'}->{'blocked-uri'}) && empty($data->{'csp-report'}->{'blocked-uri'})) { | |
// Sorry, this report misses a blocked URI, therefore I file a bad request. | |
http_response_code(400); | |
exit(); | |
} | |
// Validate data even more (a.k.a. do not send me a report for extensions, I couldn’t care less). | |
if (isset($data->{'csp-report'}, $data->{'csp-report'}->{'source-file'}) && stripos($data->{'csp-report'}->{'source-file'}, 'moz-extension') === 0) { | |
// This is OK, because the report by itself is valid, but no mail was created. | |
http_response_code(200); | |
exit(); | |
} | |
// Prepare the mail. | |
$subject = 'CSP Violation'; | |
$headers = [ | |
'MIME-Version' => '1.0', | |
'Content-Type' => 'text/plain; charset="utf-8"', | |
'Content-Transfer-Encoding' => '8bit', | |
'From' => $from, | |
'X-Mailer' => 'PHP/' . phpversion(), | |
]; | |
$body = $data; | |
// Mail the violation report. | |
if (!mail($to, $subject, $body, $headers)) { | |
// Sending a report did not work, respond with server error. | |
http_response_code(500); | |
exit(); | |
} | |
// Sending the report worked, a report mail was created. | |
http_response_code(201); | |
exit(); | |
} | |
// The request was bad. | |
http_response_code(400); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment