Directly jump to the content and enable reader mode
Article image

have read aloud


Reading time: about 2 min Print version

Content Security Policy (CSP)

This is part 3 of the securing your website series. In part 1 I wrote about the permissions and in part 2 how to handle user uploads on the server side. This part is about how to handle it on client side.

 

First line: on site Javascript

The first line of defense is by trying to limit the Javascript injection in the input text (here the article text). This can be done partially by the code running on the page (Javascript). But this can be tricked by creating the form data and uploading it via a separate tool.

Second line: server side filtering

Always assume someone tricked out your first line and the upload/submitted code contains a <script> tag with stuff in it. So apply server side filtering by trying to find all possible ways script could be executed by some tags. This should filter out almost all attempts.

Third line of defense: The CSP or Content Security Policy

If for whatever magic ways a <script> tag land on your rendered content you can hopefully rely on the browser by establishing the CSP rules.
For example, on this page you will see a HTTP header like this:

Content-Security-Policy:
default-src 'self';
script-src 'self';
img-src data: 'self' userdata.contentnation.net;
connect-src 'self' userdata.contentnation.net;
style-src 'unsafe-inline' 'self';
media-src 'self' userdata.contentnation.net

(split for better readability)

With this you can instruct the browser to only allow certain file types from a list of sources.
Take a look at the part "img-src data: 'self' userdata.contentnation.net
This limits the source for images to inline data: (needed for the website editors), 'self': the domain of the source of the html and all the userdata.contentnationnet subdomain (user uploads).
That way your browser should never load images from other domains.

Similar should be used for scripts, css a.s.o but exclude the domain where your user uploads are coming from.
So for example here it is set to script-src 'self' to only allow scripts coming from the main domain where no user uploads are happening, no inline Javascript, no external Javascript.

So even if a user might get a bad Javascript onto the site the browser should prevent any kind of mis-usage.

If the browser protection fails, you are screwed anyway.

And yes, being so strict prevents external analytics, tracking and ads from third parties. Isn't this great ;)

0 comments
Report article

Our algorithm thinks, these articles are relevant: