CodeQL 文档

从库输入构建的非安全 HTML<a class="headerlink" href="#unsafe-html-constructed-from-library-input" title="Link to this heading">¶</a>

ID: js/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:
   - javascript-code-scanning.qls
   - javascript-security-extended.qls
   - javascript-security-and-quality.qls

点击查看 CodeQL 存储库中的查询

当库函数以可能不安全的方式动态构建 HTML 时,必须向库的客户端说明该函数应仅与受信任的输入一起使用。如果未将该函数记录为可能不安全,那么客户端可能会无意中使用包含不安全 HTML 片段的输入,从而使客户端容易受到跨站脚本攻击。

建议<a class="headerlink" href="#recommendation" title="Link to this heading">¶</a>

记录所有可能导致跨站脚本攻击的库函数,并在不打算进行动态 HTML 构建的情况下防止不安全输入。

示例<a class="headerlink" href="#example" title="Link to this heading">¶</a>

以下示例包含一个库函数,该函数通过写入元素的<code class="docutils literal notranslate"><span class="pre">innerHTML</span></code> 属性来渲染粗体名称。

module.exports = function showBoldName(name) {
  document.getElementById('name').innerHTML = "<b>" + name + "</b>";
}

但是,此库函数不会转义不安全的 HTML,使用用户提供输入调用该函数的客户端可能会容易受到跨站脚本攻击。

库可以记录此函数不应与不安全的输入一起使用,或者使用安全的 API,例如<code class="docutils literal notranslate"><span class="pre">innerText</span></code>。

module.exports = function showBoldName(name) {
  const bold = document.createElement('b');
  bold.innerText = name;
  document.getElementById('name').appendChild(bold);
}

或者,可以使用 HTML 清理器来删除不安全的内容。

const striptags = require('striptags');
module.exports = function showBoldName(name) {
  document.getElementById('name').innerHTML = "<b>" + striptags(name) + "</b>";
}

参考<a class="headerlink" href="#references" title="Link to this heading">¶</a>

  • OWASP:<a class="reference external" href="https://www.owasp.org/index.php/DOM_based_XSS_Prevention_Cheat_Sheet">基于 DOM 的 XSS 防范备忘单</a>。

  • OWASP:<a class="reference external" href="https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet">XSS(跨站脚本攻击)防范备忘单</a>。

  • OWASP <a class="reference external" href="https://www.owasp.org/index.php/DOM_Based_XSS">基于 DOM 的 XSS</a>。

  • OWASP <a class="reference external" href="https://www.owasp.org/index.php/Types_of_Cross-Site_Scripting">跨站脚本攻击的类型</a>。

  • 维基百科:<a class="reference external" href="http://en.wikipedia.org/wiki/Cross-site_scripting">跨站脚本攻击</a>。

  • 常见弱点枚举:<a class="reference external" href="https://cwe.mitre.org/data/definitions/79.html">CWE-79</a>。

  • 常见弱点枚举:<a class="reference external" href="https://cwe.mitre.org/data/definitions/116.html">CWE-116</a>。

  • ©GitHub, Inc.
  • 条款
  • 隐私