javascript.lang.security.html-in-template-string.html-in-template-string

profile photo of semgrepsemgrep
Author
unknown
Download Count*

This template literal looks like HTML and has interpolated variables. These variables are not HTML-encoded by default. If the variables contain HTML tags, these may be interpreted by the browser, resulting in cross-site scripting (XSS).

Run Locally

Run in CI

Defintion

rules:
  - id: html-in-template-string
    message: This template literal looks like HTML and has interpolated variables.
      These variables are not HTML-encoded by default. If the variables contain
      HTML tags, these may be interpreted by the browser, resulting in
      cross-site scripting (XSS).
    metadata:
      cwe:
        - "CWE-116: Improper Encoding or Escaping of Output"
      owasp:
        - A03:2021 - Injection
      category: security
      technology:
        - javascript
      subcategory:
        - audit
      likelihood: LOW
      impact: MEDIUM
      confidence: LOW
      references:
        - https://owasp.org/Top10/A03_2021-Injection
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]
      vulnerability_class:
        - Improper Encoding
    languages:
      - javascript
      - typescript
    severity: WARNING
    patterns:
      - pattern-either:
          - pattern: |
              `$HTML${$VAR}...`
          - pattern: |
              `...${$VAR}$HTML`
      - metavariable-regex:
          metavariable: $HTML
          regex: .*</?[a-zA-Z]

Examples

html-in-template-string.js


// ok: html-in-template-string
const planet = `world`;
const greeting = "hello";

// ok: html-in-template-string
let a = `hello ${planet}`;

// ruleid: html-in-template-string
let b = `<h1>hello ${planet}</h1>`;

// ruleid: html-in-template-string
let start = `<h1>hello ${planet}`;

// ruleid: html-in-template-string
let end = `${planet}</h1><b>foo</b>`;

// ruleid: html-in-template-string
let two = `<h1>${greeting} beautiful ${planet}</h1>`;

function createHtml() {
    // from issue #1385
    // ruleid: html-in-template-string
    return `<div style=${style.color}>${content}</div>`
}