1

I am trying to implement Content Security Protection on my web site which uses dynamic iframes to render user provided HTML:

var html = '<html><body><p style="color: red;">Hello</p></body></html>';

document.getElementById('div').innerHTML = '<iframe srcdoc="' + html.replace(/"/g, "&quot;") + ''"></iframe>';

I have disabled the use of inline scripts by setting default-src to self, but to allow the user to use inline styles (as per the above example) I have to globally permit unsafe-inline for style-src by sending the following header:

Content-Security-Policy: "default-src 'self'; style-src 'self' 'unsafe-inline'"

I don't really want to do this as it underminds the security of my whole site just for the purpose of a single iframe, where the risk of using inline styles is limited to inside the iframe which is all user provided.

I have looked at trying to set a nonce on the iframe element, but it only appears to be supported on script and style blocks. The frame-src/child-src only controls where the source content can be loaded from, so that doesn't help.

I am effectively looking for something like frame-style-src, but it doesn't exist. Hoping that someone has an idea how to achieve what I am trying to do as I can't be the only one who wants to do this?

Further testing has shown I am able to further restrict CSP within the iframe using the following (assuming I set unsafe-inline via page headers):

<html>
  <head>
    <meta http-equiv="Content-Security-Policy" content="style-src 'none'">
  </head>
  <body>
    <p style="color: red;">Hello</p>
  </body>
</html>

Although it doesn't work in the other direction (i.e. not setting unsafe-inline via headers and trying to define it within the iframe), which is answered by What is happening when I have two CSP (Content Security Policies) policies - header & meta?

chrixm
  • 942
  • 6
  • 26

1 Answers1

1

Yes, an iframe loaded through the non-network scheme always inherits the CSP of the parent document. It doesn't matter if it was done through srcdoc= attribute or using javascript or a data:/blob: Url.

If you wish to have totally isolated context, you have to load iframe using network scheme http:/https:. Even loaded from the self-domain, iframe will have CSP independent from the parent document. But iframe from the self domain will have the same origin, therefore you can easily manage it's content via javascript from parent page.

granty
  • 7,234
  • 1
  • 14
  • 21