Jekyll Content Security Policy Plugin

May 16, 2020

Created a quick plugin for Jekyll last weekend that generates a content-security-policy HTML meta tag based on finds within the Jekyll generated site contents. The plugin is written in Ruby, an entirely new language to me, so the code is most likely terrible but hopefully works just fine.

What It Does

The plugin is designed to scan the output of a Jekyll site for images, styles, scripts, frames and others. It then builds up an internal structure of domains based on those files and subsequently generates a content securiy policy using the HTML meta tag. The script will also locate inline scripts and styles such as <script>alert("Hello World!");</script> and <style>.hello { color: red}</style>, generate an SHA256 hash based on the tag contents and append these to the policy tag. All in all, this script is designed to save you a bit of time developing your site whilst also protecting against XSS and other inline injection techniques.

Features

  • Creates policies for scripts, styles, frames and images.
  • Creates SHA256 hashes for inline scripts and styles.
  • Converts style attributes to style tags (which are passed through the above)
  • Creates new or appends an existing content-security-policy HTML tag
  • Inserts content-security-policy into HEAD.
  • Moves inline styles/scripts into the HEAD.

Install It

It has been pushed to RubyGems. You can easily install it via bundler by adding the following to your site Gemfile:

group :jekyll_plugins do
  gem 'jekyll-content-security-policy-generator'
  ... other gem files
end

and then running bundle install:

bundle install

If you have any strange errors relating to Nokogiri, sometimes bundle gets confused and adds different architecture builds into your Gemfile.lock. Delete the irrelevant ones and you are good to go.

Demo

This site is a Jekyll based site. If you “view source” you will see the generated content security policy. It’s perfect for this site as it is rushed and full of inline styles and scripts!

Help/Edit/View Source

It is an open source project, (MIT), you can help at https://github.com/strongscot/jekyll-content-security-policy-generator.