Security Policy Error Detection (CSP)

I use 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 on hand to test it thoroughly.

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

What is err ? What error gets there ( Error , TypeError , etc.)? What does the CSP error message say?

I could not find runtime error documentation in CSP.

+6
source share
1 answer

Regarding the definition of CSP, there is another question about stackoverflow: How to define a Content Security Policy (CSP) and also shows your function.

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

To my knowledge, it will throw an EvalError ( mozilla ) if the CSP prohibits an insecure evaluation. But this may vary from browser to browser.

The best way to verify this. You can use http://mockbin.org to create an HTTP endpoint that returns a page with the correct CSP headers and your function. I made such trash 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 an exception:

CSP test


Edit later

You can also find this information in the W3C guidelines / drafts: CSP 1.1 ,

+6
source

Source: https://habr.com/ru/post/1015271/


All Articles