ruby.rails.security.audit.xss.avoid-html-safe.avoid-html-safe

profile photo of semgrepsemgrep
Author
6,305
Download Count*

'html_safe()' does not make the supplied string safe. 'html_safe()' bypasses HTML escaping. If external data can reach here, this exposes your application to cross-site scripting (XSS) attacks. Ensure no external data reaches here.

Run Locally

Run in CI

Defintion

rules:
  - id: avoid-html-safe
    metadata:
      source-rule-url: https://github.com/presidentbeef/brakeman/blob/main/lib/brakeman/checks/check_cross_site_scripting.rb
      owasp:
        - A07:2017 - Cross-Site Scripting (XSS)
        - A03:2021 - Injection
      cwe:
        - "CWE-79: Improper Neutralization of Input During Web Page Generation
          ('Cross-site Scripting')"
      references:
        - https://github.com/presidentbeef/brakeman/blob/main/docs/warning_types/cross_site_scripting/index.markdown
        - https://www.netsparker.com/blog/web-security/preventing-xss-ruby-on-rails-web-applications/
      category: security
      technology:
        - rails
      cwe2022-top25: true
      cwe2021-top25: true
      subcategory:
        - audit
      likelihood: LOW
      impact: MEDIUM
      confidence: LOW
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]
      vulnerability_class:
        - Cross-Site-Scripting (XSS)
    message: "'html_safe()' does not make the supplied string safe. 'html_safe()'
      bypasses HTML escaping. If external data can reach here, this exposes your
      application to cross-site scripting (XSS) attacks. Ensure no external data
      reaches here."
    languages:
      - ruby
    severity: WARNING
    pattern-either:
      - pattern: $STR.html_safe
      - pattern: $STR.html_safe.$MORE

Examples

avoid-html-safe.rb

# cf. https://makandracards.com/makandra/2579-everything-you-know-about-html_safe-is-wrong

# ok: avoid-html-safe
"foo".length

# ruleid: avoid-html-safe
"foo".html_safe

# ruleid: avoid-html-safe
"<div>foo</div>".html_safe + "<bar>"

# ruleid: avoid-html-safe
html = "<div>".html_safe

# ok: avoid-html-safe
html = "<div>"

# ruleid: avoid-html-safe
"<div>".html_safe.tap