Search code examples
htmliframesandboxcontent-security-policy

Is it possible to have CSP only apply to the parent frame, not any iframes?


If I have a webpage with CSP set to:

default-src 'self'; img-src *

Or similar, and I have an iframe like such:

some legal content
<iframe sandbox="allow-scripts" srcdoc="&lt;script>alert('arbitrary code')&lt;/script>"></iframe>

Is it possible to allow the code in the iframe to disobey the parent frame's CSP and allow inline scripts/styles, content from other domains, or any other arbitrary HTML thing that doesn't violate the sandbox restrictions?

Currently this will give:

[Error] Refused to execute inline script because it violates the following Content Security Policy directive: "default-src 'self'". Note that 'script-src' was not explicitly set, so 'default-src' is used as a fallback. (about:srcdoc, line 1)

The CSP spec confirms this is correct behavior:

Whenever a user agent creates an iframe srcdoc document in a browsing context nested in the protected resource, if the user agent is enforcing any policies for the protected resource, the user agent MUST enforce those policies on the iframe srcdoc document as well.


Solution

  • It is not possible.

    The are only two ways to accomplish what you're after:

    1. Alter the CSP rules of the parent page to whitelist your arbitrary code (I would suggest using a CSP nonce or hash for your arbitrary content rather than unsafe-inline).
    2. Point your iframe to an external (sub)domain with rules you can control and whitelist it with frame-src & child-src (see point 1).