Content-Security-Policy

In this lesson, we'll look at an xss attack and learn how to protect against them with the Content-Security-Policy header.

Introduction

The Content-Security-Policy header, often abbreviated to CSP, provides a next-generation utility belt for preventing a plethora of attacks, ranging from XSS (cross-site scripting) to clickjacking.

To understand how CSP helps us, we should first think of an attack vector. Let’s say we built our own Google Search, a simple input text with a submit button. Try running it below.

var qs = require('querystring')
var url = require('url')
var fs = require('fs')

require('http').createServer((req, res) => {
  let query = qs.parse(url.parse(req.url).query)
  let headers = {
    'X-XSS-Protection': 0
  }

  if (query.xss === "on") {
    headers['X-XSS-Protection'] = 1
  }

  if (query.xss === "off") {
    delete headers['X-XSS-Protection'];
  }

  if (query.csp === 'on') {
    headers['Content-Security-Policy'] = `default-src 'self'`
  }

  if (query.csp === 'report') {
    headers['Content-Security-Policy-Report-Only'] = `default-src 'self'`
  }

  res.writeHead(200, headers)
  let keyword = query.search || ''
  let results = keyword ? `You searched for "${keyword}", we found:</br><img src="http://placekitten.com/200/300" />` : `Try searching...`

  res.end(fs.readFileSync(__dirname + '/index.html').toString().replace('__KEYWORD__', keyword).replace('__RESULTS__', results))
}).listen(7888)

The output should look like this:

This web application does nothing magical. It displays a form, lets the user execute a search and displays the search results alongside the keyword the user searched for. When we execute a simple search, this is what the application returns:

Injecting arbitrary JavaScript

Amazing! Our application understood our search and found a related image. If we dig deeper into the source code, we will realize that the application presents a security issue, as whatever keyword the user searches for is directly printed in the HTML served to the client. Check out the source code in the app above.

This presents a nasty consequence, an attacker can craft a specific link that executes arbitrary JavaScript on the victim’s ...

Access this course and 1400+ top-rated courses and projects.