6

I'm using this method to detect CSP with eval (also used in AngularJS):

  function noUnsafeEval() {
    try {
      new Function('');
      return false;
    } catch (err) {
      return true;
    }
  }

But I don't have a server with CSP at hand to thoroughly test it.

Is it reliable? Can the presence of new Function('') line in code cause the error that cannot be caught?

What is err? Which kind of error is caught there (Error, TypeError, etc)? What does the message of CSP error say?

I couldn't find the documentation on runtime errors in CSP.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565

1 Answers1

7

Regarding how to detect CSP, there is another stackoverflow question: How to detect Content Security Policy (CSP) and it also shows your function.

It should be safe to use it, because, as long as the code reaches the function constructor (i.e. it is not blocked before by some other restriction), you will invariably get a return value from the noUnsafeEval.

From my knowledge, it will throw an EvalError (mozilla) if CSP disallows unsafe eval. But this may differ from browser to browser.

The best way to be sure would be to test this. You can use http://mockbin.org to create a HTTP endpoint which return a page with the right CSP headers and your function. I made such a bin here: http://mockbin.org/bin/cc6029e5-8aac-4a54-8fd1-abf41e17042a. If you open it, open the dev console and debug the code, you will see the exception:

CSP Test


Later edit

You can also find this information in the W3C recommandations / drafts: CSP 1.1, CSP 2, CSP 3. In 1.1 you would get a SecurityError instead of an EvalError.

Community
  • 1
  • 1
Serban Petrescu
  • 5,127
  • 2
  • 17
  • 34
  • Thanks a lot, EvalError is what I was looking for. Thanks for the remark on SecurityError. Do you have some clues on how to get its constructor to do `err instanceof SecurityError`? It looks like there's no `SecurityError` global. – Estus Flask Mar 05 '17 at 11:55
  • 1
    Yep, apparently SecurityError is really a browser-dependent thing. It surfaces in several [MDN topics](https://developer.mozilla.org/en-US/search?q=securityerror&topic=apps&topic=html&topic=css&topic=js&topic=api&topic=canvas&topic=svg&topic=webgl&topic=mobile&topic=webdev&topic=http&topic=webext). The only documented one would be [DOMException](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) which can be a SecurityError. – Serban Petrescu Mar 05 '17 at 19:14
  • In my testing, this works well if CSP is fully enabled. However, I have found that the `EvalError`/`SecurityError` is not raised when running in report-only mode. This produces a lot of noise when evaluating a new CSP... Any suggestions for testing in report-only mode? – jcasner Mar 26 '18 at 19:05