从库输入构建的不安全 HTML¶
ID: rb/html-constructed-from-input
Kind: path-problem
Security severity: 6.1
Severity: error
Precision: high
Tags:
- security
- external/cwe/cwe-079
- external/cwe/cwe-116
Query suites:
- ruby-code-scanning.qls
- ruby-security-extended.qls
- ruby-security-and-quality.qls
当库函数以可能不安全的方式动态构建 HTML 时,重要的是要向库的客户端记录该函数应该只用于受信任的输入。如果该函数未被记录为可能不安全,那么客户端可能会无意中使用包含不安全 HTML 片段的输入,从而使客户端容易受到跨站点脚本攻击。
建议¶
记录所有可能导致跨站点脚本攻击的库函数,并在不打算进行动态 HTML 构建的地方防止不安全输入。
示例¶
以下示例包含一个库函数,该函数通过创建包含 <b>
的字符串来呈现粗体名称,其中嵌入了名称。
class UsersController < ActionController::Base
# BAD - create a user description, where the name is not escaped
def create_user_description (name)
"<b>#{name}</b>".html_safe
end
end
但是,此库函数不会转义不安全的 HTML,因此使用用户提供的输入调用该函数的客户端可能会容易受到跨站点脚本攻击。
库可以记录该函数不应与不安全输入一起使用,也可以在将输入嵌入到 HTML 片段之前对其进行转义。
class UsersController < ActionController::Base
# Good - create a user description, where the name is escaped
def create_user_description (name)
"<b>#{ERB::Util.html_escape(name)}</b>".html_safe
end
end
参考资料¶
OWASP:基于 DOM 的 XSS 防护备忘单.
OWASP:XSS(跨站点脚本攻击)防治备忘单.
OWASP 基于 DOM 的 XSS.
OWASP 跨站点脚本攻击的类型.
维基百科:跨站点脚本攻击.
常见弱点枚举:CWE-79.
常见弱点枚举:CWE-116.