ruby.rails.security.audit.xss.templates.var-in-script-tag.var-in-script-tag

profile photo of semgrepsemgrep
Author
225
Download Count*

Detected a template variable used in a script tag. Although template variables are HTML escaped, HTML escaping does not always prevent cross-site scripting (XSS) attacks when used directly in JavaScript. If you need to do this, use escape_javascript or its alias, j. However, this will not protect from XSS in all circumstances; see the references for more information. Consider placing this value in the HTML portion (outside of a script tag).

Run Locally

Run in CI

Defintion

rules:
  - id: var-in-script-tag
    message: Detected a template variable used in a script tag. Although template
      variables are HTML escaped, HTML escaping does not always prevent
      cross-site scripting (XSS) attacks when used directly in JavaScript. If
      you need to do this, use `escape_javascript` or its alias, `j`. However,
      this will not protect from XSS in all circumstances; see the references
      for more information. Consider placing this value in the HTML portion
      (outside of a script tag).
    metadata:
      cwe:
        - "CWE-79: Improper Neutralization of Input During Web Page Generation
          ('Cross-site Scripting')"
      references:
        - https://www.netsparker.com/blog/web-security/preventing-xss-ruby-on-rails-web-applications/
        - https://www.youtube.com/watch?v=yYTkLUEdIyE
        - https://www.veracode.com/blog/secure-development/nodejs-template-engines-why-default-encoders-are-not-enough
      category: security
      technology:
        - rails
      owasp:
        - A07:2017 - Cross-Site Scripting (XSS)
        - A03:2021 - Injection
      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)
    languages:
      - generic
    paths:
      include:
        - "*.erb"
    severity: WARNING
    patterns:
      - pattern-inside: <script ...> ... </script>
      - pattern-not: <%= j ... >
      - pattern-not: <%= escape_javascript ... >
      - pattern: <%= ... >

Examples

var-in-script-tag.erb

<!-- ok: var-in-script-tag -->
<script type="text/javascript" src="whatever.js"></script>

<!-- ruleid: var-in-script-tag -->
<script>current_user_id = <%=param[:id]%></script>
<!-- ok: var-in-script-tag -->
<div>Hello <%=param[:id]%></div>

<script type="text/javascript">
    <!-- ruleid: var-in-script-tag -->
    var message = <%= message %>;
</script>

<script type="text/javascript">
    <!-- ok: var-in-script-tag -->
    var message = <%= j message %>;
</script>

<script type="text/javascript">
    <!-- ok: var-in-script-tag -->
    var message = <%= escape_javascript message %>;
    console.log(message);
</script>