Jump to content
nbcommunication

MarkupContentSecurityPolicy

Recommended Posts

Wondering how to get that A+ rating on Mozilla Observatory? Now you can with MarkupContentSecurityPolicy

Of course, MarkupContentSecurityPolicy does not guarantee an A+ rating, but it does help you implement a Content Security Policy for your ProcessWire website.

Markup Content Security Policy

Configure and implement a Content Security Policy for all front-end HTML pages.

This module should only be used in production once it has been fully tested in development. Implementing a Content Security Policy on a site without testing will almost certainly break something!

Overview

Content Security Policy (CSP) is an added layer of security that helps to detect and mitigate certain types of attacks, including Cross Site Scripting (XSS) and data injection attacks. These attacks are used for everything from data theft to site defacement to distribution of malware.

... Configuring Content Security Policy involves adding the Content-Security-Policy HTTP header to a web page and giving it values to control resources the user agent is allowed to load for that page. For example, a page that uploads and displays images could allow images from anywhere, but restrict a form action to a specific endpoint. A properly designed Content Security Policy helps protect a page against a cross site scripting attack.

 https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP

Website Security Auditing Tools such as Mozilla Observatory will only return a high score if a Content Security Policy is implemented. It is therefore desirable to implement one.

A common way of adding the Content-Security-Policy header would be to add it to the .htaccess file in the site's root directory. However, this means the policy would also cover the ProcessWire admin, and this limits the level of security policy you can add.

The solution is to use the <meta> element to configure a policy, for example: <meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src https://*; child-src 'none';">. MarkupContentSecurityPolicy places this element with your configured policy at the beginning of the <head> element on each HTML page of your site.

There are some limitations to using the <meta> element:

  • Not all directives are allowed. These include frame-ancestors, report-uri, and sandbox.
  • The Content-Security-Policy-Report-Only header is not supported, so is not available for use by this module.

Configuration

To configure this module, go to Modules > Configure > MarkupContentSecurityPolicy.

Directives

The most commonly used directives are listed, with a field for each. The placeholder values given are examples, not suggestions, but they may provide a useful starting point.

You will almost certainly need to use 'unsafe-inline' in the style-src directive as this is required by some modules (e.g. TextformatterVideoEmbed) or frameworks such as UIkit.

Should you wish to add any other directives not listed, you can do so by adding them in Any other directives.

Please refer to these links for more information on how to configure your policy:

Violation Reporting

Because the report-uri directive is not available, when Violation Reporting is enabled a script is added to the <head>which listens for a SecurityPolicyViolationEvent. This script is based on https://developer.mozilla.org/en-US/docs/Web/API/SecurityPolicyViolationEvent and POSTs the generated report to ?csp-violations=1. The module then logs the violation report to csp-violations.

Unfortunately, most of the violations that are reported are false positives, and not actual attempts to violate the policy. These are most likely from browser extensions and are not easy to determine and filter.

For this reason, there is no option for the report to be emailed when a policy is violated. Instead, you can specify an endpoint for the report to be sent to. This allows you to handle additional reporting in a way that meets your needs. For example, you may want to log all reports in a central location and send out an email once a day to an administrator notifying them of all sites with violations since the last email.

Retrieving the Report

To retrieve the report at your endpoint, the following can be used:

$report = file_get_contents("php://input");
if(!empty($report)) {
	$report = json_decode($report, 1);
	if(isset($report) && is_array($report) && isset($report["documentURI"])) {
		// Do something
	}
}

Debug Mode

When this is enabled, a range of information is logged to markup-content-security-policy. This is probably most useful when debugging a reporting endpoint.

Additional .htaccess Rules

To get an A+ score on Mozilla Observatory, besides using HTTPS and enabling the HSTS header, you can also place the following prior to ProcessWire's htaccess directives:

Header set Content-Security-Policy "frame-ancestors 'self'"
Header set Referrer-Policy "no-referrer-when-downgrade"

Installation

  1. Download the zip file at Github or clone the repo into your site/modules directory.
  2. If you downloaded the zip file, extract it in your sites/modules directory.
  3. In your admin, go to Modules > Refresh, then Modules > New, then click on the Install button for this module.

ProcessWire >= 3.0.123 is required to use this module.

  • Like 12

Share this post


Link to post
Share on other sites

Fantastic timing - just about to look into this myself for a site. Thank you!

Share this post


Link to post
Share on other sites
27 minutes ago, netcarver said:

Fantastic timing - just about to look into this myself for a site. Thank you!

Please let me know how you find it - this module is really just a result of looking into it the past two weeks to try and get an A+ on Mozilla Observatory (did it😆) so I'd really appreciate any feedback!

  • Like 4

Share this post


Link to post
Share on other sites

Update to 0.0.2

  • Deploy mode (only enable for superuser when off)
  • Define params to exclude from reporting (e.g. originalPolicy)
  • Filtering of selected false positive patterns
  • Improvements to HTML page check
  • Like 1

Share this post


Link to post
Share on other sites

Hello,

I thought it might be useful to post a CSP I've recently deployed using this module. Every site is different - there's no prescriptive policy and that's the main caveat here.

This is for a site with an embedded Shopify store, an Issuu embed, a Google Tour embed and Google Maps implementation (JS API). It also uses Font Awesome 5 from their CDN, jQuery from CDNJS, and some Google Fonts. It also has TextformatterVideoEmbed installed alongside its extended options module.

default-src 'none'; 
script-src 'self' cdnjs.cloudflare.com *.google.com *.gstatic.com *.googleapis.com www.google-analytics.com www.googletagmanager.com e.issuu.com sdks.shopifycdn.com; 
style-src 'self' 'unsafe-inline' cdnjs.cloudflare.com *.googleapis.com use.fontawesome.com; 
img-src 'self' data: *.google.com *.googleapis.com *.gstatic.com *.ggpht.com www.google-analytics.com www.googletagmanager.com brand.nbcommunication.com *.shopify.com sdks.shopifycdn.com; 
connect-src 'self' www.google-analytics.com ocean-kinetics.myshopify.com; 
font-src 'self' fonts.gstatic.com use.fontawesome.com; 
object-src 'self'; 
media-src 'self' data:; 
manifest-src 'self'; 
frame-src www.google.com www.youtube.com www.youtube-nocookie.com player.vimeo.com w.soundcloud.com e.issuu.com; 
form-action 'self'; 
base-uri 'self'

The Shopify embed script and Google Analytics initialisation have been moved into script files so there are no inline scripts at all. The script-src 'unsafe-inline' directive is an obstacle to getting that A+ on Observatory. 

Google Analytics is also a bit of an impediment to getting a top-drawer score, as its script doesn't use SRI. However, there is a reason for that as I understand it - it is a script that just loads other scripts so SRI implementation would just be token, it wouldn't actually be improving security. Still, it is possible to get A+ without dealing with this.

It would be great to get some discussion going on CSP implementation - I'm only a few weeks in myself, so have much to learn!

Cheers,

Chris
NB

 

  • Like 2

Share this post


Link to post
Share on other sites

Hi Chris,

I had a chance to try this out today, and it's been pretty useful though I still have a lot to learn about CSPs. One quick observation is that it inserts at the start of the <head> block, before the charset and viewport meta tags. IIRC, the charset and viewport meta-tags are meant to be the first tags in the head block.

Will keep experimenting with the module.

  • Like 2

Share this post


Link to post
Share on other sites
36 minutes ago, nbcommunication said:

Thanks for the feedback - I'll have a look at this soon and see if I can get it placed better.

Hi and thanks for this useful module. I added to my list of things I need to explore soon. ;-)

A common usage for modules that need to inject content in the head or body output of pages, is to optionally serve a manual way per API call besides the automatic way. 

Share this post


Link to post
Share on other sites

@netcarver- I've got it automatically placed after the <title> element now, if that element exists (which it should!). 

@horst - I've added a renderMeta method to allow for manual outputting of the meta tag in the <head>. If this is used, it shouldn't output automatically.

  • Like 3

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By teppo
      This module tracks changes, additions, removals etc. of public (as in "not under admin") pages of your site. Like it's name says, it doesn't attempt to be a version control system or anything like that - just a log of what's happened.
      At the moment it's still a work in progress and will most likely be a victim of many ruthless this-won't-work-let's-try-that-instead cycles, but I believe I've nailed basic functionality well enough to post it here.. so, once again, I'll be happy to hear any comments you folks can provide
      https://modules.processwire.com/modules/process-changelog/
      https://github.com/teppokoivula/ProcessChangelog
      How does it work?
      Exactly like it's (sort of) predecessor, Process Changelog actually consists of two modules: Process Changelog and Process Changelog Hooks. Hooks module exists only to serve main module by hooking into various functions within Pages class, collecting data of performed operations, refining it and keeping up a log of events in it's own custom database table (process_changelog.) Visible part is managed by Process Changelog, which provides users a (relatively) pretty view of the contents of said log table.
      How do you use it?
      When installed this module adds new page called Changelog under Admin > Setup which provides you with a table view of collected data and basic filtering tools See attached screenshots to get a general idea about what that page should look like after a while.
      For detailed installation instructions etc. see README.md.
       


    • By Gadgetto
      Status update links (inside this thread) for SnipWire development will be always posted here:
      2019-08-08
      2019-06-15
      2019-06-02
      2019-05-25
      If you are interested, you can test the current state of development:
      https://github.com/gadgetto/SnipWire
      Please note that the software is not yet intended for use in a production system (alpha version).
      If you like, you can also submit feature requests and suggestions for improvement. I also accept pull requests.
      ---- INITIAL POST FROM 2019-05-25 ----
      I wanted to let you know that I am currently working on a new ProcessWire module that fully integrates the Snipcart Shopping Cart System into ProcessWire. (this is a customer project, so I had to postpone the development of my other module GroupMailer).
      The new module SnipWire offers full integration of the Snipcart Shopping Cart System into ProcessWire.
      Here are some highlights:
      simple setup with (optional) pre-installed templates, product fields, sample products (quasi a complete shop system to get started immediately) store dashboard with all data from the snipcart system (no change to the snipcart dashboard itself required) Integrated REST API for controlling and querying snipcart data webhooks to trigger events from Snipcart (new order, new customer, etc.) multi currency support self-defined/configurable tax rates etc. Development is already well advanced and I plan to release the module in the next 2-3 months.
      I'm not sure yet if this will be a "Pro" module or if it will be made available for free.
      I would be grateful for suggestions and hints!
      (please have a look at the screenshots to get an idea what I'm talking about)
       




    • By apeisa
      Update 31.7.2019: AdminBar is now maintained by @teppo. Modules directory entry has been updated, as well as the "grab the code" link below.
      ***
      Latest screencast: http://www.screencas...73-ab3ba1fea30c
      Grab the code: https://github.com/teppokoivula/AdminBar
      ***
      I put this Adminbar thingy (from here: http://processwire.c...topic,50.0.html) to modules section and to it's own topic.
      I recorded quick and messy screencast (really, my first screencast ever) to show what I have made so far. You can see it from here: http://www.screencas...18-1bc0d49841b4
      When the modal goes off, I click on the "dark side". I make it so fast on screencast, so it might seem a little bit confusing. Current way is, that you can edit, go back to see the site (without saving anything), continue editing and save. After that you still have the edit window, but if you click "dark side" after saving, then the whole page will be reloaded and you see new edits live.
      I am not sure if that is best way: there are some strengths in this thinking, but it is probably better that after saving there shouldn't be a possibility to continue editing. It might confuse because then if you make edits, click on dark side -> *page refresh* -> You lose your edits.
      ***
      When I get my "starting module" from Ryan, I will turn this into real module. Now I had to make some little tweaks to ProcessPageEdit.module (to keep modal after form submits). These probably won't hurt anything:
      if($this->redirectUrl) $this->session->redirect($this->redirectUrl); if(!empty($_GET['modal'])) $this->session->redirect("./?id={$this->page->id}&modal=true"); // NEW LINE else $this->session->redirect("./?id={$this->page->id}");   and...
      if(!empty($_GET['modal'])) { $form->attr('action', './?id=' . $this->id . '&modal=true'); } else { $form->attr('action', './?id=' . $this->id); // OLD LINE }  
    • By Mike Rockett
      Jumplinks for ProcessWire
      Release: 1.5.54
      Composer: rockett/jumplinks
      Jumplinks is an enhanced version of the original ProcessRedirects by Antti Peisa.
      The Process module manages your permanent and temporary redirects (we'll call these "jumplinks" from now on, unless in reference to redirects from another module), useful for when you're migrating over to ProcessWire from another system/platform. Each jumplink supports wildcards, shortening the time needed to create them.
      Unlike similar modules for other platforms, wildcards in Jumplinks are much easier to work with, as Regular Expressions are not fully exposed. Instead, parameters wrapped in curly braces are used - these are described in the documentation.
      Under Development: 2.0, to be powered by FastRoute
      As of version 1.5.0, Jumplinks requires at least ProcessWire 2.6.1 to run.
      View on GitLab
      Download via the Modules Directory
      Read the docs
      Features
      The most prominent features include:
      Basic jumplinks (from one fixed route to another) Parameter-based wildcards with "Smart" equivalents Mapping Collections (for converting ID-based routes to their named-equivalents without the need to create multiple jumplinks) Destination Selectors (for finding and redirecting to pages containing legacy location information) Timed Activation (activate and/or deactivate jumplinks at specific times) 404-Monitor (for creating jumplinks based on 404 hits) Additionally, the following features may come in handy:
      Stale jumplink management Legacy domain support for slow migrations An importer (from CSV or ProcessRedirects) Feedback & Feature Requests
      I’d love to know what you think of this module. Please provide some feedback on the module as a whole, or even regarding smaller things that make it whole. Also, please feel free to submit feature requests and their use-cases.
      Note: Features requested so far have been added to the to-do list, and will be added to 2.0, and not the current dev/master branches.
      Open Source

      Jumplinks is an open-source project, and is free to use. In fact, Jumplinks will always be open-source, and will always remain free to use. Forever. If you would like to support the development of Jumplinks, please consider making a small donation via PayPal.
      Enjoy! :)
×
×
  • Create New...