Web Security 06 — CSP (Content Security Policy)

Brian Shen
3 min readApr 27, 2020

--

1. Intro: What is Content Security Policy

The HTTP Content-Security-Policy response header allows web site administrators to control resources the user agent is allowed to load for a given page. With a few exceptions, policies mostly involve specifying server origins and script endpoints (MDN). This helps guard against cross-site scripting attacks (XSS).

For example, if I open my Github Blog, it will load resources from Google. I trust Google, so it’s OK to contain google scripts.

But what if my site load some resources from other site that I don’t trust? CSP can solve this problem. The syntax and usage of CSP is simple, but we can define complex situations.

Content-Security-Policy: <policy-directive>; <policy-directive>
Content-Security-Policy: default-src 'self' http://example.com;
script-src http://example.com/

This definition means :

There are many kinds of source:

child-src / connect-src / font-src / frame-src / img-src / manifest-src / media-src / object-src / prefetch-src / script-src / style-src / worker-src

2. Sample

Assume a bad user in our blog system post a blog. The content includes some malicious scripts. And when other users read this article, the page will be rendered like this staticFile/blogView.html :

To make the demo simpler, let’s assume that we do not set httpOnly to our cookies index.js :

Since we load scripts from 8889, so let’s add a malicious script staticHack/hackCSP.js :

now let’s start our server and open http://localhost:8888/blogView.html :

npm i
npm start
npm run-script startHack

If the bad user’s malicious script get control of browser, then many things can be done, such as information steal.

3. How to fix

Actually, there are many ways to fix this problem:

  • Cookie httpOnly
  • User Content Filter
  • Content Security Policy

We will use Content Security Policy to solve this problem. So let’s do a little modification to our safe site indexSafe.js :

and run again:

npm run-script startSafe
npm run-script startHack

We can see from the console that the resources from 8889 are refused to load.

What is this place? Qianhu Lake, Nanjing, Jiangsu, China

--

--