GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • CodeQL documentation
  • CodeQL overview
  • Writing CodeQL queries
  • CodeQL language guides
  • QL language reference
  • CodeQL standard-libraries
  • CodeQL query help
  • CodeQL repository
  • QL publications
  • CodeQL query help for C and C++
  • CodeQL query help for C#
  • CodeQL query help for GitHub Actions
  • CodeQL query help for Go
  • CodeQL query help for Java and Kotlin

This view

  • Original page
  • New address

GeezerVison is showing codeql.github.com — Improper code sanitization — CodeQL query help documentation

Improper code sanitization¶

ID: js/bad-code-sanitization
Kind: path-problem
Security severity: 6.1
Severity: error
Precision: high
Tags:
   - security
   - external/cwe/cwe-094
   - external/cwe/cwe-079
   - external/cwe/cwe-116
Query suites:
   - javascript-code-scanning.qls
   - javascript-security-extended.qls
   - javascript-security-and-quality.qls

Click to see the query in the CodeQL repository

Using string concatenation to construct JavaScript code can be error-prone, or in the worst case, enable code injection if an input is constructed by an attacker.

Recommendation¶

If using JSON.stringify or an HTML sanitizer to sanitize a string inserted into JavaScript code, then make sure to perform additional sanitization or remove potentially dangerous characters.

Example¶

The example below constructs a function that assigns the number 42 to the property key on an object obj. However, if key contains </script>, then the generated code will break out of a </script> if inserted into a </script> tag.

function createObjectWrite() {
    const assignment = `obj[${JSON.stringify(key)}]=42`;
    return `(function(){${assignment}})` // NOT OK
}

The issue has been fixed by escaping potentially dangerous characters, as shown below.

const charMap = {
    '<': '\\u003C',
    '>' : '\\u003E',
    '/': '\\u002F',
    '\\': '\\\\',
    '\b': '\\b',
    '\f': '\\f',
    '\n': '\\n',
    '\r': '\\r',
    '\t': '\\t',
    '\0': '\\0',
    '\u2028': '\\u2028',
    '\u2029': '\\u2029'
};

function escapeUnsafeChars(str) {
    return str.replace(/[<>\b\f\n\r\t\0\u2028\u2029]/g, x => charMap[x])
}

function createObjectWrite() {
    const assignment = `obj[${escapeUnsafeChars(JSON.stringify(key))}]=42`;
    return `(function(){${assignment}})` // OK
}

References¶

  • OWASP: Code Injection.

  • Common Weakness Enumeration: CWE-94.

  • Common Weakness Enumeration: CWE-79.

  • Common Weakness Enumeration: CWE-116.

  • © GitHub, Inc.
  • Terms
  • Privacy
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.