Using iframe for rendering user provided html code

Viewed 174

I want to embed user provided HTML code in my website. The code will be self-contained, and will contain script and style tags. I am planning to block all network calls from the the provided HTML code by using Content Security Policy headers. The code will only be able to access standard libraries like jquery and other standard resources (the same will be specified in the CSP). I want to restrict any communication between the iframe content and the parent domain.

My plan is to use an <iframe> to embed the content. The user will give an input, and then on clicking a button, an iframe will be rendered with the given input snippet. It will be rendered inline with other content of the page.

I am concerned about the effect of this on the security of my website.

  1. Can I make the origin of the iframe null? Or will I have to host my content on a separate domain so that SOP blocks all the network calls to the parent page?
  2. Will I be able to set up CSP for the iframe separately? If yes, can anyone suggest what all attributes the CSP should have?
  3. Can I take the input html and inject it directly to my iframe from the parent page?

If there are other alternatives which don't use iframe, which are those?

1 Answers

Can I make the origin of the iframe null? Or will I have to host my content on a separate domain so that SOP blocks all the network calls to the parent page?

You can make the origin of the iframe null if you'll use, for instance, a data:-Url. This will prevent cross-origin requests in modern browsers, but Content Security Policy of parent document will be inherited into iframe in all browsers.
In this case some old browsers (Firefox/WinXP) will spread CSP from the iframe to parent document too.

Will I be able to set up CSP for the iframe separately? If yes, can anyone suggest what all attributes the CSP should have?

You are able to set separate CSP for iframe only if it's loaded via network scheme (http:/https:) - it will be created isolated browsing context. If non-network schemes (data:, blob:, etc) iframe will inherit CSP of parent document.
In case of isolated browsing context you can use any "attributes the CSP" what you need for your specific case.
Pay attention to csp=, sandbox= attributes, these can be useful.

Can I take the input html and inject it directly to my iframe from the parent page?

This is contravert your statement: "I want to restrict any communication between the iframe content and the parent domain.".
Therefore all communications are possible via server only.

If there are other alternatives which don't use iframe, which are those?

Isolated browsing contexts can be created via <object>/<embed>, but these are not useful in your case.

Related