javascript.lang.security.audit.incomplete-sanitization.incomplete-sanitization

profile photo of semgrepsemgrep
Author
328
Download Count*

$STR.replace method will only replace the first occurrence when used with a string argument ($CHAR). If this method is used for escaping of dangerous data then there is a possibility for a bypass. Try to use sanitization library instead or use a Regex with a global flag.

Run Locally

Run in CI

Defintion

rules:
  - id: incomplete-sanitization
    message: "`$STR.replace` method will only replace the first occurrence when used
      with a string argument ($CHAR). If this method is used for escaping of
      dangerous data then there is a possibility for a bypass. Try to use
      sanitization library instead or use a Regex with a global flag."
    metadata:
      cwe:
        - "CWE-116: Improper Encoding or Escaping of Output"
      category: security
      technology:
        - javascript
      owasp:
        - A03:2021 - Injection
      subcategory:
        - audit
      likelihood: LOW
      impact: LOW
      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: |
          $STR.replace(($CHAR: string), ...)
      - metavariable-regex:
          metavariable: $CHAR
          regex: ^[\"\']([\'\"\<\>\*\|\{\}\[\]\%\$]{1}|\\n|\\r|\\t|\\&)[\"\']$

Examples

incomplete-sanitization.js

function escapeQuotes(s) {
    // ruleid:incomplete-sanitization
    return s.replace("'", "''");
}

function removeTabs(s) {
    // ruleid:incomplete-sanitization
    return s.replace('\t', "");
}

function escapeHtml(html) {
  // ruleid:incomplete-sanitization
  return html
    .replace("<", "")
    .replace(">", "");
}

function okTest(s) {
    return s.replace("foo", "bar");
}

function okEscapeQuotes(s) {
    return s.replace(/'/g, "''");
}