是否可以让 CSP 仅适用于父框架,而不适用于任何 iframe?
Is it possible to have CSP only apply to the parent frame, not any iframes?
如果我的网页 CSP 设置为:
default-src 'self'; img-src *
或类似的,我有一个这样的 iframe:
some legal content
<iframe sandbox="allow-scripts" srcdoc="<script>alert('arbitrary code')</script>"></iframe>
是否可以允许 iframe 中的代码违反父框架的 CSP 并允许内联 scripts/styles、来自其他域的内容或任何其他不违反的任意 HTML沙盒限制?
目前这将给出:
[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)
CSP spec 确认这是正确的行为:
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 <a href="http://www.w3.org/TR/html5/embedded-content-0.html#the-iframe-element" rel="noreferrer">iframe</a>
srcdoc
document as well.
不可能。
只有两种方法可以实现您的目标:
- 更改父页面的 CSP 规则以将您的任意代码列入白名单(我建议对您的任意内容使用 CSP 随机数或哈希,而不是不安全内联)。
- 将您的 iframe 指向具有您可以控制的规则的外部(子)域,并使用
frame-src
和 child-src
将其列入白名单(参见第 1 点)。
如果我的网页 CSP 设置为:
default-src 'self'; img-src *
或类似的,我有一个这样的 iframe:
some legal content
<iframe sandbox="allow-scripts" srcdoc="<script>alert('arbitrary code')</script>"></iframe>
是否可以允许 iframe 中的代码违反父框架的 CSP 并允许内联 scripts/styles、来自其他域的内容或任何其他不违反的任意 HTML沙盒限制?
目前这将给出:
[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)
CSP spec 确认这是正确的行为:
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<a href="http://www.w3.org/TR/html5/embedded-content-0.html#the-iframe-element" rel="noreferrer">iframe</a>
srcdoc
document as well.
不可能。
只有两种方法可以实现您的目标:
- 更改父页面的 CSP 规则以将您的任意代码列入白名单(我建议对您的任意内容使用 CSP 随机数或哈希,而不是不安全内联)。
- 将您的 iframe 指向具有您可以控制的规则的外部(子)域,并使用
frame-src
和child-src
将其列入白名单(参见第 1 点)。