raw-sql-injection

Try in Playground
javascript-knexSecurityError

0

No tags

CWE-89

Using hardcoded values in whereRaw with knew may lead to SQL injection. Instead, use parameters as explained in the documentation.

For example, if you have the code

1knex.select('e.lastname', 'e.salary', subcolumn)
2  .from('employee as e')
3  .whereRaw(`dept_no = ${val}`)

replace with

1knex.select('e.lastname', 'e.salary', subcolumn)
2  .from('employee as e')
3  .whereRaw('dept_no = ?', val)

Ast Rule: function call


raw-sql-injection

How to write a rule
const isTemplateString = (value) => {
  if (/^`.+`$/.test(value)) {
    return true;
  }
  return false;
};

function visit(node, filename, code) {
  if (node.functionName.astType === "member") {
    if (node.functionName.name.astType === "string" &&
      node.functionName.name.value === "whereRaw") {
      const arguments = node.arguments.values;
      if (arguments.length > 0) {

        const firstArgument = arguments[0].value;
        if (firstArgument.astType === "string") {
          if (isTemplateString(firstArgument.value)) {
            const error = buildError(firstArgument.start.line,
              firstArgument.start.col,
              firstArgument.end.line,
              firstArgument.end.col,
              "use of string template leads to SQL injection", "WARNING", "SECURITY");
            addError(error);
          }

        }
      }
    }
  }
}

test-where-raw-ok1.js

Expected test result: no error

knex.select('e.lastname', 'e.salary', subcolumn)
  .from('employee as e')
  .whereRaw('dept_no = e.dept_no')

test-where-raw-failure.js

Expected test result: has error

knex.select('e.lastname', 'e.salary', subcolumn)
  .from('employee as e')
  .whereRaw(`dept_no = ${variable}`)
Add comment

Log in to add a comment


    Be the first one to leave a comment!

Codiga Logo
Codiga Hub
  • Rulesets
  • Playground
  • Snippets
  • Cookbooks
soc-2 icon

We are SOC-2 Compliance Certified

G2 high performer medal

Codiga – All rights reserved 2022.