javascript.audit.detect-replaceall-sanitization.detect-replaceall-sanitization

profile photo of semgrepsemgrep
Author
unknown
Download Count*

Detected a call to $FUNC() in an attempt to HTML escape the string $STR. Manually sanitizing input through a manually built list can be circumvented in many situations, and it's better to use a well known sanitization library such as sanitize-html or DOMPurify.

Run Locally

Run in CI

Defintion

rules:
  - id: detect-replaceall-sanitization
    message: Detected a call to `$FUNC()` in an attempt to HTML escape the string
      `$STR`. Manually sanitizing input through a manually built list can be
      circumvented in many situations, and it's better to use a well known
      sanitization library such as `sanitize-html` or `DOMPurify`.
    metadata:
      category: security
      technology:
        - javascript
        - typescript
      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://www.npmjs.com/package/dompurify
        - https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html
      cwe2022-top25: true
      cwe2021-top25: true
      subcategory:
        - audit
      likelihood: LOW
      impact: LOW
      confidence: LOW
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]
      vulnerability_class:
        - Cross-Site-Scripting (XSS)
    languages:
      - javascript
      - typescript
    severity: INFO
    patterns:
      - pattern-either:
          - pattern: $STR.$FUNC('<', '&lt;')
          - pattern: $STR.$FUNC('>', '&gt;')
          - pattern: $STR.$FUNC('"', '&quot;')
          - pattern: $STR.$FUNC("'", '&apos;')
          - pattern: $STR.$FUNC('&', '&amp;')
      - metavariable-regex:
          metavariable: $FUNC
          regex: (replace|replaceAll)

Examples

detect-replaceall-sanitization.ts

function encodeProductDescription (tableData: any[]) {
  for (let i = 0; i < tableData.length; i++) {
    // ruleid: detect-replaceall-sanitization
    tableData[i].description = tableData[i].description.replaceAll('<', '&lt;').replaceAll('>', '&gt;')

    // ok
    tableData[i].description = tableData[i].description.replaceAll('<', 'left angle bracket')
  }
}