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.
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:
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
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 ;)