为什么内联 JavaScript 安全性很差? [英] Why is inline JavaScript security bad?
问题描述
我知道内联 JS 对性能不利,但为什么对安全不利?你能解释一下为什么吗?举些例子?
I know that inline JS is bad for performance, but why is it bad for security? Can you please explain to me why? With some examples?
推荐答案
限制性 内容安全策略 可以通过禁止除具有特定哈希值的脚本之外的所有脚本¹ 来帮助减少脚本注入漏洞的影响.
A restrictive content security policy can help to reduce the impact of script injection vulnerabilities by disallowing all scripts except those with a certain hash¹.
如果您以
on*
属性或javascript:
网址的形式使用内联 JavaScript,则根本无法实施此类政策,因此那肯定不太安全.
If you use inline JavaScript in the form of
on*
attributes orjavascript:
URLs, you can’t implement this type of policy at all, so that’s definitely less safe.
如果您以 <script>
s 的形式使用内联 JavaScript,而没有 src
,那么创建哈希或随机数用于在一个 CSP,这可能会诱使人们根本不添加一个.nonce 策略还允许动态脚本,这通常是坏主意(几乎是动态脚本的唯一用途 - 在 中插入 JSON,因为它看起来兼容使用 JavaScript – 是错误和脚本注入的秘诀²).
If you use inline JavaScript in the form of <script>
s without a src
, it’s less convenient to create a hash or nonce for use in a CSP, which might tempt people not to add one at all. A nonce policy also allows for dynamic scripts, which are generally bad ideas (just about the only use for dynamic scripts – inserting JSON in a <script>
because it looks compatible with JavaScript – is a recipe for bugs and script injection²).
¹ 或位于您仅用于静态内容的特定域中.小心允许域(包括源!)为可以充当脚本的用户内容提供服务!
² 由不转义 <
、U+2028 和 U+2029 引起 - JSON 与内联 JavaScript 的 3 个不兼容性.我建议使用典型的 HTML 转义和读取 data-
属性.
¹ or located on a certain domain that you only use for static content. careful about allowing domains (including the origin!) serving user content that can act as scripts!
² caused by not escaping <
, U+2028, and U+2029 – JSON’s 3 incompatibilities with inline JavaScript. I recommend using your typical HTML escaping and reading from a data-
attribute instead.
这篇关于为什么内联 JavaScript 安全性很差?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!