javascript.lang.security.audit.detect-non-literal-require.detect-non-literal-require

profile photo of semgrepsemgrep
Author
unknown
Download Count*

Detected the use of require(variable). Calling require with a non-literal argument might allow an attacker to load and run arbitrary code, or access arbitrary files.

Run Locally

Run in CI

Defintion

rules:
  - id: detect-non-literal-require
    message: Detected the use of require(variable). Calling require with a
      non-literal argument might allow an attacker to load and run arbitrary
      code, or access arbitrary files.
    metadata:
      cwe:
        - "CWE-95: Improper Neutralization of Directives in Dynamically
          Evaluated Code ('Eval Injection')"
      owasp:
        - A03:2021 - Injection
      source-rule-url: https://github.com/nodesecurity/eslint-plugin-security/blob/master/rules/detect-non-literal-require.js
      references:
        - https://github.com/nodesecurity/eslint-plugin-security/blob/master/rules/detect-non-literal-require.js
      category: security
      technology:
        - javascript
      subcategory:
        - vuln
      likelihood: MEDIUM
      impact: MEDIUM
      confidence: LOW
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]
      vulnerability_class:
        - Code Injection
    languages:
      - javascript
      - typescript
    severity: WARNING
    mode: taint
    pattern-sources:
      - patterns:
          - pattern-inside: function ... (..., $ARG,...) {...}
          - focus-metavariable: $ARG
    pattern-sinks:
      - pattern: require(...)

Examples

detect-non-literal-require.js

function dynamicRequire1(packageName) {
    // ruleid: detect-non-literal-require
    var a = require(packageName)
    return a;
}

function dynamicRequire2(source, file) {
    // ruleid: detect-non-literal-require
    require(path.resolve(process.cwd(), file, source));
}

function okDynamicRequire1() {
    var lib = path.join(path.dirname(fs.realpathSync(__filename)), "index.js");
    // ok: detect-non-literal-require
    require(lib).run(process.argv.slice(2)); 
}

function okDynamicRequire2(userInput) {
    var name = process.env.NAME
    var path = name + '/smth/path';
    var mod = path + '/module.js';
    // ok: detect-non-literal-require
    require(mk).main(top, userInput);
}

function okDynamicRequire3(userInput) {
    var lib  = path.join(path.dirname(fs.realpathSync(__filename)), 'lib');
    // ok: detect-non-literal-require
    require(lib + '/foobar').run(userInput);
}

function okDynamicRequire4(userInput) {
    // ok:detect-non-literal-require
    var a = require('b')
}
function okDynamicRequire5(userInput) {
    // ok:detect-non-literal-require
    var a = require(process.env.VAR)
}