Search code examples
mobile-safaricontent-security-policy

Content Security Policy works as expected on desktop but not on mobile


Having a content security policy on one's website is a good way to provide an extra layer of security on one's site.

I have a content security policy that works as expected on desktop, but it breaks the site on mobile (safari). The content security policy is inside meta tags. I am using nonces and hashes. On mobile I get the error stating that it refused to execute inline script because it violates the Content Security Policy directive which includes the hashes and nonces. The error also states that I need either a hash or nonce in the code to execute the code, but they are already present there, and that's how it works well on desktop. The problem is that on mobile it's acting as if the hashes and nonces didn't exist. Any tips are appreciated.


Solution

  • In CSP, if you include a nonce for script-src or style-src, unsafe-inline will be ignored if the browser understands nonces. Therefore, in order to be compatible with older browsers that don't understand CSP2 (for example, Safari on iOS 9 and earlier), include both your nonce AND unsafe-inline.

    The newer browsers will follow the nonce and ignore the unsafe-inline. The older browsers will not understand the nonce, and thus fall back to the unsafe-inline.

    See https://csp.withgoogle.com/docs/strict-csp.html

    script-src nonce-{random} 'unsafe-inline'

    The nonce directive means that elements will be allowed to execute only if they contain a nonce attribute matching the randomly-generated value which appears in the policy.

    Note: In the presence of a CSP nonce the unsafe-inline directive will be ignored by modern browsers. Older browsers, which don't support nonces, will see unsafe-inline and allow inline scripts to execute.