Refused to load the image because it violates content-securtiy-policy -- Cordova

Nuru Salihu picture Nuru Salihu · Jun 21, 2016 · Viewed 43.2k times · Source

I am trying to deploy my app following the code-push doc. I then added the following content-security to my app index.html

<meta http-equiv="Content-Security-Policy" content="default-src https://codepush.azurewebsites.net 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">

Immediately i added, my app does not run again. When i run my cordova browser. I saw many errors in the console. It turns out my styles files referenced from github, my images referenced from mysite.com/... and my other external scripts, goopleapis are my security policy to below

<meta http-equiv="Content-Security-Policy" content="default-src * 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">

It now works fine. My question is, What is the security ramification ? Should i leave it that way? How better should i do this ? Any help or opinion would be appreciated. I am worried leaving * may allow the attacks intended to stopped.

Answer

Phonolog picture Phonolog · Jun 21, 2016

You're right, leaving your CSP like this might make things easier for an attacker. The main idea behind using a CSP is url whitelisting as described here.

By whitelisting everything with the * wildcard you allow an attacker to load code (and execute) from everywhere once he is able to inject code into your application. Check out the linked article on this, it's a lot better than what I'm writing here ;)

So what's the right way to do this?

  1. Find out what domains you want to whitelist and what kind of resources this domain provides.
  2. Get rid of the wildcard and whitelist exactly those domains for exactly those resources you need. Let's, for example, take a look at your stylesheets from GitHub. You will have to add GitHub as a trustworthy domain for styles somewhat like this: style-src 'self' https://github.com 'unsafe-inline';

Note: Be careful with the default-src policy as it overrides the other policies. And when it comes to whitelisting images, you might have to add the data: keyword like so: img-src 'self' http://somedomain.com data:;

Mozilla's documentation is quite good if you're looking for an overview of all the policies and keywords...