Skip to content

Instantly share code, notes, and snippets.

@april
Created July 12, 2016 19:08
Show Gist options
  • Save april/f2608876f2d0ccce8339448423809ea5 to your computer and use it in GitHub Desktop.
Save april/f2608876f2d0ccce8339448423809ea5 to your computer and use it in GitHub Desktop.
Simple NGINX config to dump CSP reports
server {
listen 80;
server_name site.mozilla.org;
location / {
return 301 https://$server_name$request_uri;
}
location /twohundredinator {
access_log off;
allow 127.0.0.1;
return 200;
}
}
server {
listen 443;
server_name site.mozilla.org;
root /var/www/site.mozilla.org;
index index.html;
add_header Content-Security-Policy "default-src 'none'; frame-ancestors 'self'";
add_header Strict-Transport-Security "max-age=31536000";
add_header X-Content-Type-Options "nosniff";
add_header X-Frame-Options "DENY";
add_header X-XSS-Protection "1; mode=block";
location /__cspreporting__ {
access_log /var/log/nginx/report-uri-csp.log CSP;
proxy_pass http://127.0.0.1/twohundredinator;
}
ssl on;
ssl_certificate /etc/certificates/site.mozilla.org.crt;
ssl_certificate_key /etc/certificates/site.mozilla.org.org.key;
ssl_protocols TLSv1.2;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256';
ssl_prefer_server_ciphers on;
}
@basilmusa
Copy link

basilmusa commented Jan 23, 2019

Why is a proxy_pass being used to forward to port 80? Why not use the following directly:

location /__cspreporting__ {
    access_log /var/log/nginx/report-uri-csp.log CSP;
}

@chloesoe
Copy link

chloesoe commented Apr 16, 2019

Thanks for that code snipped, that leads me to the correct solution. The log format 'CSP' has to be defined somewhere in the http directive in nginx configuration:

log_format CSP escape=json $request_body;

or a longer definition (from [1]):

log_format  CSP '$remote_addr - [$time_local] '
        '"$http_referer" "$content_type" "$http_user_agent" "$request_body"';

@basilmusa: According to [2] you "Nginx doesn't parse the client request body unless it really needs to, so it usually does not fill the $request_body variable."

Edit: I optimized the log_format so it's all JSON:

log_format CSP '{"date":"$time_local", "IP address":"$remote_addr", "http_x_forwarded_for":"$http_x_forwarded_for", "status":"$status", "http_user_agent":"$http_user_agent", "body_bytes_sent":"$body_bytes_sent", "request":"$request","request-body": $request_body}';

The log file escapes the double quotes with \x22 so with a sed an jq you get a proper JSON log of the CSP report:

sed 's/\\x22//g' csp2.log | jq

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment