如何让脚本使用 setAttribute 'style' 而不会破坏 CSP
我正在努力使我的 CSP 政策尽可能严格.我需要在我的捆绑包中包含 3d 派对组件.但它使用了破坏 CSP 的 element.setAttribute('style'...)
方法.有没有办法让这个特定的脚本以这种方式内联样式?
Im am trying to keep my CSP policy as strict as possible. I need to include 3d party component in my bundle. But it uses element.setAttribute('style'...)
method which breaks CSP. Is there a way to allow this particular script to inline styles in that manner?
推荐答案
2018-10-06更新
这里的原始答案仍然是正确的现在 - 因为至少使用 CSP目前在浏览器中实现,仍然没有办法动态注入样式指定 unsafe-inline
和指定 unsafe-inline
基本上否定了 CSP 的全部目的.
The original answer here is still correct for now — because with CSP as currently implemented in browsers at least, there’s still no way to have dynamically injected styles at all without specifying unsafe-inline
, and specifying unsafe-inline
basically negates the whole purpose of CSP.
然而,CSP3 添加了一个新的 unsafe-hashes
表达式,使您能够允许特定的内联脚本/样式.请参阅 https://w3c.github.io/webappsec-csp/#unsafe-hashes-usage,并查看 解释器:'unsafe-hashes'、'unsafe-inline-attributes' 和 CSP 指令版本控制.不过,它还没有在任何浏览器中发布.所以目前,下面的答案仍然完全适用.
However, CSP3 adds a new unsafe-hashes
expression for enabling you to allow particular inline scripts/styles. See https://w3c.github.io/webappsec-csp/#unsafe-hashes-usage, and see Explainer: ‘unsafe-hashes’, ‘unsafe-inline-attributes’ and CSP directive versioning. It hasn’t shipped in any browsers yet, though. So for the time being, the answer below still fully applies.
允许style
属性的唯一方法是使用unsafe-inline
.style
属性是来自不同的来源还是来自 self
并不重要——除非你有 ,否则它们仍将被视为违反 CSP不安全内联
.
The only way to allow style
attributes is to use unsafe-inline
. It doesn’t matter whether the style
attributes are coming from a different origin or from self
—they’re still going to be considered a CSP violation unless you have unsafe-inline
.
具体来说,不会对 style
属性起作用的一种解决方案是使用 nonce 或 hash——因为在 CSP 中,nonce 和 hash 的使用只针对 style
和 script
elements;该规范具有 样式元素的哈希用法 部分明确省略了为样式属性定义散列使用.
Specifically, one solution that won’t work for style
attributes is to use a nonce or hash—because in CSP, nonce and hash usage are only defined for style
and script
elements; the spec has a Hash usage for style elements section that explicitly omits defining hash use for style attributes.
因此,即使您在策略中为 style
属性的内容指定了正确的哈希值,您的浏览器仍会将其视为违规处理.
So even if in your policy you specify the correct hash for the contents of a style
attribute, your browser will still handle it as a violation.
底线是,因为 unsafe-inline
是允许 style
属性的唯一方法,但使用 unsafe-inline
几乎完全违背了制定任何 CSP 策略的目的——从 CSP 的角度来看,唯一安全的解决方案就是永远不要使用 style
属性——既不是直接来自你自己的标记/代码,也不是通过任何第三方——党的代码.
The bottom line is that since unsafe-inline
is the only way to allow style
attributes—but using unsafe-inline
pretty much completely defeats the purpose of having any CSP policy to begin with—the only safe solution from a CSP perspective is just to never use style
attributes—neither directly from your own markup/code nor by way of any third-party code.
相关文章