Deploy different Content Security Policies (CSPs) using Apache conditional statements

Having a strict content Content Security Policy (CSP) can be a useful addition for your website security. However, when running a content management system (CMS) like WordPress, you’re often forced to make a few a undesired compromises.

To work around the problem, I previously had two different policies available within my virtual host configuration that I toggled on and off (by hand) depending on whether I needed to use the dashboard or not. Imagine how much simpler life would be if Apache could work with if/else statements.

Oh.. right Apache 2.4 does support conditional statements. I’ll then add a strict CSP for everyone and their mother while providing a more lenient CSP for myself, being the only user with access to the WordPress dashboard. To summarize: if the remote address matches my static IP then serve a lenient CSP, else serve the strict CSP:

<IfModule mod_headers.c>
  Header always set Strict-Transport-Security: "max-age=63072000; includeSubDomains; preload"     
  Header always set Public-Key-Pins "pin-sha256=\"+hReE4xfHXOZfSBOvDCmpORYCfn2VlYVMB4nRVUeLns=\"; pin-sha256=\"C8gw6A3tgLpxbpcE0J5rDd/P88yxiUhqUUalkGjTO8M=\"; max-age=2592000; includeSubDomains"

  # Serve CSP based on client IP
  <If "-R '192.168.37.104/32'">
    Header always set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src * data:; object-src 'none'; font-src 'self' data:"
  </If>
  <Else>
    Header always set Content-Security-Policy "default-src 'self'; script-src 'none'; style-src 'self' 'unsafe-inline'; object-src 'none'; font-src 'self'"
    Header always set X-Frame-Options DENY
  </Else>

  Header edit Set-Cookie ^(.*)$ $1;HttpOnly;Secure        
  ...
</IfModule>

Now that’s useful!
I’ll be coming for you soon, my old and too complicated mod_rewrite rules.

References:
Apache Core Features
Expressions in Apache HTTP Server

Thank you for reading!
Feel free to waste more time by subscribing to my RSS feed or find me on Keybase.

Related posts