detect-non-literal-require

Try in Playground
javascript-security

oscar143

SecurityWarning

0

No tags

No CWE or CVE

security/detect-non-literal-require

Detects "require(variable)", which might allow an attacker to load and run arbitrary code, or access arbitrary files on disk

More information: Where does Node.js and require look for modules?

Ast Rule: assignment


detect-non-literal-require

How to write a rule
function visit(node, filename, code) {
  if (node?.right?.functionName?.value === "require") {
    if (node.right?.arguments?.values?.length) {
      const argument = node.right?.arguments?.values[0];

      if (
        argument.value.astType === "string" &&
        (
          argument.value.value.startsWith(`\"`) &&
          argument.value.value.endsWith(`"`) ||
          argument.value.value.startsWith(`'`) &&
          argument.value.value.endsWith(`'`)
        )
      ) {
        return;
      }

      addError(buildError(
        argument.value.start.line,
        argument.value.start.col,
        argument.value.end.line,
        argument.value.end.col,
        `Found non-literal argument in require`,
        "WARNING",
        "SECURITY",
      ));
    }
  }
}

good.js

Expected test result: no error


var a = require('b')

bad.js

Expected test result: no error


var a = require(process.env.VAR)
var a = require(c)
Add comment

Log in to add a comment


    Be the first one to leave a comment!

Codiga Logo
Codiga Hub
  • Rulesets
  • Playground
  • Snippets
  • Cookbooks
Legal
  • Security
  • Privacy Policy
  • Code Privacy
  • Terms of Service
soc-2 icon

We are SOC-2 Compliance Certified

G2 high performer medal

Codiga – All rights reserved 2022.