使用 iframe 呈现用户提供的 html 代码

Using iframe for rendering user provided html code

我想在我的网站中嵌入用户提供的 HTML 代码。代码将为 self-contained,并将包含 scriptstyle 标记。我计划使用 Content Security Policy headers 阻止来自提供的 HTML 代码的所有网络调用。该代码将只能访问标准库,如 jquery 和其他标准资源(同样将在 CSP 中指定)。我想限制 iframe 内容和 parent 域之间的任何通信。

我的计划是使用 <iframe> 来嵌入内容。用户将提供输入,然后单击按钮,将使用给定的输入片段呈现 iframe。它将与页面的其他内容一起呈现。

我担心这对我网站安全的影响。

  1. 我可以制作 iframe 的来源 null 吗?或者我是否必须将我的内容托管在单独的域中,以便 SOP 阻止对 parent 页面的所有网络调用?
  2. 我可以单独为 iframe 设置 CSP 吗?如果是,谁能建议 CSP 应具有的所有属性?
  3. 我可以获取输入 html 并将其从 parent 页面直接注入我的 iframe 吗?

如果还有其他不使用 iframe 的替代方案,那是哪些?

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?

如果您要使用 data:-Url[=34,则可以将 iframe 的来源设置为 null =].这将防止现代浏览器中的跨域请求,但父文档的内容安全策略将在所有浏览器中继承到 iframe。
在这种情况下,一些旧浏览器 (Firefox/WinXP) 也会将 CSP 从 iframe 传播到父文档。

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

只有通过网络方案 (http:/https:) 加载时,您才能为 iframe 设置单独的 CSP - 它将创建独立的浏览上下文。如果非网络方案(data:, blob:, 等)iframe 将继承父文档的CSP。
在独立浏览上下文的情况下,您可以使用特定情况所需的任何“属性 CSP”。
注意 csp=sandbox= 属性,这些可能会有用。

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

这与您的陈述相悖:“我想限制 iframe 内容与父域之间的任何通信。”。
因此,所有通信都只能通过服务器进行。

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

可以通过 <object>/<embed> 创建独立的浏览上下文,但这些对您的情况没有用。