8

I have a page that I set the script-src of the content security policy like this:

script-src 'self' *.uservoice.com *.intuit.com ajax.googleapis.com localhost:* 

When I load the page with a hard-coded inline script I have created myself to test, it is blocked like expected:

Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' *.uservoice.com *.intuit.com ajax.googleapis.com localhost:* ". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.

However, when I insert a new script tag dynamically, the script isn't blocked, for example, this still executes:

$("body").append("<script>alert('xss');</script>")

I am using Chrome as the browser here for testing. I was hoping that this script would be blocked as well, since that would really help to prevent xss. Is there something I can change to block this type of script injection as well?

  • 2
    Why do you need to block this? This is perfectly secure, unless you don't trust your own code that you're appending (in that case, you need to sanitize it). – soktinpk Jul 21 '14 at 00:05
  • 1
    Write secure JavaScript? – Ry- Jul 21 '14 at 00:06
  • 3
    jQuery `eval`uates ` – Jonathan Lonowski Jul 21 '14 at 00:11
  • @soktinpk So, it won't protect me from errors I might make in sanitization...? – user3152280 Jul 21 '14 at 00:13
  • @user3152280 No, if you don't trust a script, don't run it. – soktinpk Jul 21 '14 at 00:20
  • @user3152280: You shouldn't really be doing any sanitization. If you need to use dynamic values securely, [see here](http://stackoverflow.com/q/21428259/413180). – SilverlightFox Jul 21 '14 at 09:36
  • @user3152280 you want to create some kind of sandbox on your page? If so, you should looking for solutions like [Google Caja](https://code.google.com/p/google-caja/). Anyway, giving users access to jQuery (as of any other 3rd party lib) isn't good idea at all. – raidendev Aug 03 '14 at 11:57
  • @JonathanLonowski if you made your comment into an answer, i'd accept it, since it answers the question and it is what i needed to know. – user3152280 Aug 10 '14 at 19:13

1 Answers1

3

The script you add with append or innerHtml won't be executed unless you use eval(). So it's not violating CSP.

Although this may look like a cross-site scripting attack, the result is harmless. HTML5 specifies that a tag inserted via innerHTML should not execute. 1

See script elements inserted using innerHTML do not execute when they are inserted.

Sheng
  • 451
  • 5
  • 11
  • Note that `.append()` does just that -- "*unless you use eval()*." You should also include the source of content you quote -- ["Security considerations" of `element.innerHTML` on MDN](https://developer.mozilla.org/en-US/docs/Web/API/element.innerHTML). – Jonathan Lonowski Aug 06 '14 at 22:38