Add Content Security Policy to WordPress [1/4]

Policy: a principle of behavior, wise conduct, a tool of governance, overall intention and direction as formally expressed by management.

By adding a Content Security Policy (CSP) to a blog, we can specify resources a reader’s browser (Chrome, Firefox, Edge) is allowed to use on a site. We can specify from where a browser can load scripts, styles, images, media, and objects. Specify to where a form can post data. Enable or disable inline scripts and styles; even exactly specify the fingerprint of allowed scripts and styles. Require that each file must have a specified fingerprint to make sure it was not modified.

You may have heard of a recent British Airways hack, or how thousands of UK and Australian governments’ sites were hijacked to mine crypto-currency. Both were compromised via a modified script file. Also a fresh news story about scripts injected into shopping carts. Attacking WordPress sites en masse is nothing new, and in most cases malicious scripts are injected into sites through some weakness, completely out of site owners’ control. Something should be done. Fortunately some smart people figured out how to remedy the situation, at least reduce the risk, so all we have to do is implement few recommendations.

To see how a CSP on a WordPress site looks, check out the source of this site. Right-click anywhere on the page and select “View Page Source” or type Ctrl+U. Take a look at the first <meta> tag, just below the <head>.

What does this do? The policy:

  • disables defaults for directives requiring sources (-src),
  • specifies two sha256- integrity attributes of inline scripts allowed to run,
  • allows loading of scripts from this domain and Cloudflare cdn,
  • specifies one sha256- integrity attribute of an allowed inline style,
  • allows loading of styles only from this domain,
  • allows loading of images only from this domain,
  • prevents loading of fonts,
  • prevents loading of objects,
  • allows forms to post only to this domain,
  • requires integrity attributes (sri) to be specified for styles and scripts.

Mozilla has a good reference of policy directives. This is likely to change as new specifications are introduced, but it is a good start. Once the policy is in place it is easy to tinker with.
Continue reading “Add Content Security Policy to WordPress [1/4]”