Jump to content

(Pretty) easy A+ Content Security Policy (CSP) for Processwire


Chris Bennett
 Share

Recommended Posts

Plenty of posts on the forum relating to Content Security Policy (CSP) and how to integrate it with Processwire.

It's not too hard to implement a decent htaccess CSP that will get you a solid B+ at Mozilla Observatory.
If you're after A+ it's a little harder because of all the back-end stuff... until you realize it's surprisingly easy.

After a lot of testing, the easiest way I found was to specify only what is needed in the htaccess and then add your required CSP as a meta in your page template.
Plenty of people have suggested similar. Works very easily for back-end vs front-end, but gets complicated if you want front page editing.

Luckily, a little php will preserve back-end and front page editing capabilities while allowing you to lock down the site for anyone not logged in. 
None of this is rocket science, but CSPs are a bit of a pain the rear, so the easier the better, I reckon 😉

The only CSP I'd suggest you include in your site htaccess is:

Header set Content-Security-Policy "frame-ancestors 'self'"

The reason for this is you can't set "frame-ancestors" via meta tags.
In addition, you can only make your CSP more restrictive using meta tags, not less, so leaving the back-end free is a solid plan to avoid frustration.

Then in your public front-facing page template/s, add your desired Content Security Policy as a meta tag.
Please note: your CSP should be the first meta tag after your <head>.

For example:
 

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Security-Policy" content="Your CSP goes here">
<!-- followed by whatever your normal meta tags are -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="format-detection" content="telephone=no">

If you haven't got Front Page Editing enabled, this works fine by itself.
Just one extra step is needed to make sure you don't have to worry either way. 

The easiest way I found to allow both CSP and front page editing capabilities is the addition of a little php, according to whatever your needs are.
Basically, if the user is a guest, throw in your CSP, if they're not do nothing.
It's so simple I could have kicked myself when it finally dawned on me.
I wish it had clicked for me earlier in my testing, but it didn't so I'm here to try to save some other person a little time.

Example:

<!DOCTYPE html>
<html>
<head>
<?php if ($user->isGuest()): ?>
<meta http-equiv="Content-Security-Policy" content="Your CSP goes here">
<?php endif; ?>
<!-- followed by whatever your normal meta tags are -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="format-detection" content="telephone=no">

 

If you want it a bit more involved then you can add additional tests and be as specific as you like about what pages should get which CSP.

For example, the following is what I use to expand the scope of the CSP only for my "map" page:

<?php
$loadMap = $page->name === "map";
?>
<!DOCTYPE html>
<html>
<head>
<?php if ($user->isGuest()): ?>
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; base-uri 'self'; manifest-src 'self'; form-action 'self'; font-src 'self' data: https://fonts.gstatic.com; frame-src 'self' https://www.youtube.com; img-src 'self' data:<?php echo ($loadMap) ? " https://maps.googleapis.com https://maps.gstatic.com" : ""; ?> https://www.google-analytics.com; script-src 'self' <?php echo ($loadMap) ? "https://maps.googleapis.com " : ""; ?>https://www.google-analytics.com https://www.googletagmanager.com; style-src 'self' <?php echo ($loadMap) ? "'unsafe-inline' https://fonts.googleapis.com" : ""; ?>">
<?php endif; ?>

 Hope this saves someone a little time testing.

https://observatory.mozilla.org/analyze/bene.net.au

  • Like 16
Link to comment
Share on other sites

You are right; whilst it is possible to get a vhost/.htaccess-based A+ on security headers while keeping the admin interface fully operational, it is a pain and leaves the apache config files in a bit of a mess. Getting the admin interface sorted in the vhosts file prompted this post over in dev-talk that might also help someone out if they go down that route.

What you've posted seems to be a fairly nice approach to the issue - thanks!

  • Like 1
Link to comment
Share on other sites

  • 1 year later...

2021 update: bit easier, better security, no warnings about using <meta http-equiv="Content-Security-Policy">.

Rather than rely on <meta http-equiv="Content-Security-Policy"> I have tweaked things a little.
Bit more secure, bit easier to do and added nonce function as well to further lock down script-src.

If we remove all CSP from htaccess we can define everything in one place and set header() with php instead, right before <!DOCTYPE html>
I find it cleaner and easier to customize that way. Allows as much logic and conditional loading as you need.

For example:

<?php if ($user->isGuest()):

$loadMap      = $page->name === "map";
$hasMapImgs   = ($loadMap) ? " https://*.googleapis.com https://maps.gstatic.com https://*.ggpht.com" : "";
$hasMapStyles = ($loadMap) ? " 'unsafe-inline' https://fonts.googleapis.com" : "";
$cspImgSrc    = " img-src 'self' https://www.google-analytics.com data: 'self'" . $hasMapImgs . ";"; 
$cspStyleSrc  = " style-src 'self'" . $hasMapStyles . ";";

$cspCond  = $cspImgSrc.$cspStyleSrc;

function generateRandomString($length = 25) {
    $characters = '0123456789';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
$nonce = generateRandomString(35);

$csp = "Content-Security-Policy: base-uri 'self'; frame-ancestors 'self'; default-src 'none'; child-src 'self'; manifest-src 'self'; form-action 'self'; connect-src 'self' https://www.google-analytics.com https://maps.googleapis.com; font-src 'self' data: https://fonts.gstatic.com; frame-src 'self' https://www.youtube.com; script-src 'self' https: 'unsafe-inline' 'nonce-" . $nonce . "' 'strict-dynamic';" . $cspCond ;

header($csp);
?>
<?php endif; ?> 
<!DOCTYPE html>

https://observatory.mozilla.org/analyze/www.alfresco-bar-bistro.com.au

  • Like 1
Link to comment
Share on other sites

19 minutes ago, DV-JF said:

@Chris Bennett is your approach compatible with ProCache or are there any edge cases that have to be considered?

Sorry @DV-JF I can't be sure as I don't use ProCache.
I can't imagine why it would, but I just can't say for sure. If there was a problem, I guess nonces could be replaced by URLs instead.

Naturally, you'd want to make sure your CSP settings are suitable for your site or the devtools will quickly fill with lots of red :)

  • Like 1
Link to comment
Share on other sites

@Chris Bennett Thx for responding.

What makes me think a bit is the following circumstance: if I understood the specification (https://content-security-policy.com/nonce/ - see "Rules for Using a CSP Nonce") correctly, it is necessary that for each "HTTP response" nonce must have a unique value. However, this will not work if ProCache caches the pages.

Maybe someone else has an idea about this?

Link to comment
Share on other sites

5 hours ago, DV-JF said:

@Chris Bennett Thx for responding.

What makes me think a bit is the following circumstance: if I understood the specification (https://content-security-policy.com/nonce/ - see "Rules for Using a CSP Nonce") correctly, it is necessary that for each "HTTP response" nonce must have a unique value. However, this will not work if ProCache caches the pages.

Maybe someone else has an idea about this?

Yes, you are absolutely correct that the nonce should be unique for each HTTP request.  The nonce is basically just a handy way to load a number of scripts from different domains and have those permissions filter through to other scripts that might be loaded by the allowed scripts.

So for a static page you'd probably want to go with the url allowlist method instead, similar to the $hasMapStyles / $cspStyleSrc combo.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Similar Content

    • By MoritzLost
      I've been working with ProcessWire for a while now, and I've noticed that using Composer to manage dependencies and autoload external libraries isn't as prevalent in ProcessWire development as in other areas of PHP programming. I started out by using the default setup recommend in this blogpost. However, one major problem I have with this approach is that all external dependencies live in the webroot (the directory the server points to), which is unfavourable from a security standpoint and, in my opinion, just feels a bit messy.
      In this tutorial, I want to go through a quick setup of Composer and ProcessWire that keeps the dependencies, all custom-written code and other source material outside of the webroot, and makes full usage of the Composer autoloader. This setup is pretty basic, so this tutorial is probably more useful to beginners (this is why I'll also include some general information on Composer), but hopefully everyone can take something away from this for their personal workflow.
      Site structure after setup
      This is what the directory structure can look like after the setup:
      . ├── composer.json ├── composer.lock ├── node_modules │   └── ... ├── public │   ├── index.php │   ├── site │   ├── wire │   └── ... ├── packacke-lock.json ├── package.json ├── sass │   ├── main.scss │   ├── _variables.scss │   └── ... ├── src │   ├── ContentBag.php │   └── ... └── vendor ├── autoload.php ├── composer ├── league ├── symfony └── ... As mentioned, the main point of this setup is to keep all external libraries, all other custom source code and resources out of the webroot. That includes Composer's vendor folder, your node_modules and JavaScript source folder if you are compiling JavaScript with webpack or something similar and including external scripts via NPM, or your CSS preprocessor files if you are using SASS or LESS. In this setup, the public directory acts as the webroot (the directory that is used as the entry point by the server, DocumentRoot in the Apache configuration). So all other files and directories in the mysite folder aren't accessible over the web, even if something goes wrong.
      One caveat of this setup is that it's not possible to install ProcessWire modules through Composer using the PW Module Installer (see Blogpost above), but that's just a minor inconvenience in my experience.
      Installation
      You'll need to have composer installed on your system for this. Installation guides can be found on getcomposer.org.
      First, open up your shell and navigate to the mysite folder.
      $ cd /path/to/mysite/ Now, we'll initialize a new Composer project:
      $ composer init The CLI will ask some questions about your projects. Some hints if you are unsure how to answer the prompts:
      Package names are in the format <vendor>/<project>, where vendor is your developer handle. I use my Github account, so I'll put moritzlost/mysite (all lowercase). Project type is project if you are creating a website. Author should be in the format Name <email>. Minimum Stability: I prefer stable, this way you only get stable versions of dependencies. License will be proprietary unless you plan on sharing your code under a FOSS license. Answer no to the interactive dependencies prompts. This creates the composer.json file, which will be used to keep track of your dependencies. For now, you only need to run the composer install command to initialize the vendor directory and the autoloader:
      $ composer install Now it's time to download and install ProcessWire into the public directory:
      $ git clone https://github.com/processwire/processwire public If you don't use git, you can also download ProcessWire manually. I like to clean up the directory after that:
      $ cd public $ rm -r .git .gitattributes .gitignore CONTRIBUTING.md LICENSE.TXT README.md Now, setup your development server to point to the /path/to/mysite/public/ directory (mind the public/ at the end!) and install ProcessWire normally.
      Including & using the autoloader
      With ProcessWire installed, we need to include the composer autoloader. If you check ProcessWire's index.php file, you'll see that it tries to include the autoloader if present. However, this assumes the vendor folder is inside the webroot, so it won't work in our case.
      One good place to include the autoloader is using a site hook file. We need the autoloader as early as possible, so we'll use init.php:
      EDIT: As @horst pointed out, it's much better to put this code inside the config.php file instead, as the autoloader will be included much earlier:
      // public/site/config.php <?php namespace Processwire; require '../../vendor/autoload.php'; The following also doesn't apply when including the autoloader in the config-file.
      This has one caveat: Since this file is executed by ProcessWire after all modules had their init methods called, the autoloader will not be available in those. I haven't come across a case where I needed it this early so far; however, if you really need to include the autoloader earlier than that, you could just edit the lines in the index.php file linked above to include the correct autoloader path. In this case, make sure not to overwrite this when you update the core!
      Now we can finally include external libraries and use them in our code without hassle! I'll give you an example. For one project, I needed to parse URLs and check some properties of the path, host et c. I could use parse_url, however that has a couple of downsides (specifically, it doesn't throw exceptions, but just fails silently). Since I didn't want to write a huge error-prone regex myself, I looked for a package that would help me out. I decided to use this URI parser, since it's included in the PHP League directory, which generally stands for high quality.
      First, install the dependency (from the project root, the folder your composer.json file lives in):
      $ composer require league/uri-parser This will download the package into your vendor directory and refresh the autoloader.
      Now you can just use the package in your own code, and composer will autoload the required class files:
      // public/site/templates/basic-page.php <?php namespace Processwire; use \League\Uri\Parser; // ... if ($url = $page->get('url')) { $parser = new Parser(); $parsed_url = $parser->parse($url); // do stuff with $parsed_url ... } Wiring up custom classes and code
      Another topic that I find really useful but often gets overlooked in Composer tutorials is the ability to wire up your own namespace to a folder. So if you want to write some object-oriented code outside of your template files, this gives you an easy way to autoload those using Composer as well. If you look at the tree above, you'll see there's a src/ directory inside the project root, and a ContentBag.php file inside. I want to connect classes in this directory with a custom namespace to be able to have them autoloaded when I use them in my templates.
      To do this, you need to edit your composer.json file:
      { "name": "moritzlost/mysite", "type": "project", "license": "proprietary", "authors": [ { "name": "Moritz L'Hoest", "email": "info@herebedragons.world" } ], "minimum-stability": "stable", "require": {}, "autoload": { "psr-4": { "MoritzLost\\MySite\\": "src/" } } } Most of this stuff was added during initialization, for now take note of the autoload information. The syntax is a bit tricky, since you have to escape the namespace seperator (backslash) with another backslash (see the documentation for more information). Also note the PSR-4 key, since that's the standard I use to namespace my classes.
      The line "MoritzLost\\MySite\\": "src/" tells Composer to look for classes under the namespace \MoritzLost\MySite\ in the src/ directory in my project root. After adding the autoload information, you have to tell composer to refresh the autoloader information:
      $ composer dump-autoload Now I'm ready to use my classes in my templates. So, if I have this file:
      // src/ContentBag.php <?php namespace MoritzLost\MySite; class ContentBag { // class stuff } I can now use the ContentBag class freely in my templates without having to include those files manually:
      // public/site/templates/home.php <?php namespace Processwire; use MoritzLost\MySite\ContentBag; $contentbag = new ContentBag(); // do stuff with contentbag ... Awesome!
      By the way, in PSR-4, sub-namespaces correspond to folders, so I can put the class MoritzLost\MySite\Stuff\SomeStuff in src/Stuff/SomeStuff.php and it will get autoloaded as well. If you have a lot of classes, you can group them this way.
      Conclusion
      With this setup, you are following secure practices and have much flexibility over what you want to include in your project. For example, you can just as well initialize a JavaScript project by typing npm init in the project root. You can also start tracking the source code of your project inside your src/ directory independently of the ProcessWire installation. All in all, you have good seperation of concerns between ProcessWire, external dependencies, your templates and your OOP-code, as well as another level of security should your Server or CGI-handler ever go AWOL. You can also build upon this approach. For example, it's good practice to keep credentials for your database outside the webroot. So you could modify the public/site/config.php file to include a config or .env file in your project root and read the database credentials from there.
      Anyway, that's the setup I came up with. I'm sure it's not perfect yet; also this tutorial is probably missing some information or isn't detailed enough in some areas depending on your level of experience. Feel free to ask for clarification, and to point out the things I got wrong. I like to learn as well 🙂
      Thanks for making it all the way to the bottom. Cheers!
    • By humanafterall
      Hi,
      I would like to set an admin template to 'https only' as recommended in the Processwire security docs.
      However if I do this it forces this setting locally too, resulting in https://localhost requests which result in an error page.
      Is there a simple way round this? Setting https for templates in the config?
      Thanks!
    • By nuel
      Dear PW Community
      Let me shout out my question here, I really don't know where to start and hope someone can give me a hint or tell me to resign and go home and cry.
      I want to create a subpage that is only accessible to people with unique access codes. It's gonna be an online concert streaming page (thanks Corona!). People who buy tickets through a local ticketing service should be able to access and stream the show with their individual access code. These codes should work only for this person and show. If someone in the «audience» closes and reopens the page, they should get in again, but not their friends who were given the code of course, basically just like in a club with a ticket and a stamp on the wrist.
      Now, is there a possibility to achieve that with more or less basic Processwire skills? In my imagination I have a field where I list the given access codes, another two to add start and ending date/time of the show, maybe one for a unique ID/title of the show.
      Is there an existing module for something like that? Should I get into the module development field and create that? How?? Haha. Any comments are welcome here.
      Thanks,
      Nuél
       
    • By theoretic
      Hi guys and ladies! And thanks for Processwire!
      It appears i've got an interesting issue concerning the template-settings-based PW redirects dealing with access control. Any PW template has some access control options i.e. "Login redirect URL or page ID to render". If this option is used for a page having a template with this option filled, a redirect will occur if user is not logged in and/or has insufficient access rights.
      I like to hook PW events. In one of my current projects i decided to write an addHookBefore('Session::redirect', ...) which should store the page we are being redirected from. With "regular" redirects like $session->redirect('/somewhere/') this hook works like a charm. But it was strange to see that it doesn't work with the template-settings-based redirect.
      I'm too dumb to dive deep inside PW and to examine the whole PW session mechanism. But it could be rather logical if ANY redirect ( no matter template-settings-based or using $session->redirect() ) could be hooked in the same manner.
      Okay okay i can forget about template-settings-based redirect and write my own. Just a couple of lines of code, and it works. But it's less elegant than hooking the template-settings-based redirects.
      So am i missing something? It this behavior a bug, or is it intended by PW team? Thanks in advance for any comment!
    • By Guy Incognito
      What's the best process for adding another user with TfaTotp 2FA? Just using it for the first time.
      Should I supply them with them with the secret when I first create their account? Seems like a security risk?
      Otherwise how do I create a 2FA user and let them login for the first time?
×
×
  • Create New...