¯\_(ツ)_/¯

thunder@home:~$

This is my home blog, mostly to share some useful info or code snippets
~ 1 min

Hey all,

As you know, CSP headers allows you to limit resources that your site can load. This can defend against XSS attacks and other kinds of content injection.

This can be configured in varoius ways, like setting in HTML header within meta tag:

<meta
  http-equiv="Content-Security-Policy-Report-Only"
  content="default-src https:; report-uri /csp-report;"
/>

or by defining additional header via nginx configuration:

add_header Content-Security-Policy-Report-Only "default-src https:; report-uri /csp-report;";

Note, that we’re just reporting Content-Security-Policy-Report-Only.

And we’re defining here where this report will be passed: report-uri /csp-report;

As a simpliest solution, we can configure nginx to log such reports into log file.

First of all, we need to set new log formatter for such reports:

root@localhost:/etc/nginx# cat conf.d/log_csp.conf

log_format CSP escape=json '{"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"}';

Now, lets define location /csp-report in your site configuration in HTTPS server definition:

server {
  listen 443 ssl;
  server_name iam.thunder.spb.ru;
  # snipped...
  location = /csp-report {
    access_log /var/log/nginx/csp.log CSP;
    proxy_pass http://iam.thunder.spb.ru/csp-response;
  }
  # snipped...
}

About proxy_pass (Taken from the original link above)

At first glance, the proxy_pass directive may look a bit suspicious. The reason it’s there is because if you just do return 204 directly from the /_csp location, the request body is not logged in the csp.log file. By using the proxy_pass hack, it is. You may also notice in this example I’m only configuring the older report-uri directive.

server {
  listen      80;
  server_name iam.thunder.spb.ru;
  # snipped...
  location /csp-response {
    access_log off;
    return 204 "okie dokie";
  }
  # snipped...
  location / {
    return 301 https://$host$request_uri;
  }
}

Now just restart nginx and check the logs!

Remember to add logrotate configuration to that log file, otherwise you can quickly ran out of disk space if your site does not quite comply with your own policy :)

Happy CSPing!

Thank You For Reading