javascriptpostgresqlsql-injectionnode-postgressqlmap

Is this javascript vulnerable to SQL Injection?


I am using node-postgres library.

  const sql = `
  SELECT * 
  FROM "Employees"
  where employee_id = '${employee_id}' ; 
  `;
  console.log(`Query formatted: ${sql}`);
  const result = await this.db.run(sql)

// DB Run method looks like this

async run(sql) {
    let retVal = "";
    let client;
    try {
      await this.init();
      console.log(`Connecting to ${this.connection.host}`);
      client = new pg.Client(this.connection);
      await client.connect();
      console.log(`inner sql:  ${sql}`);
      const res = await client.query(sql);
      
      retVal = res.rows;
 
      client.end();
    } catch (e) {
      console.log(`ERROR: ${e}`);
      retVal = e;
      client.end();
    }
    return retVal;
  }

employee_id is passed via user input as POST call.

SQLMAP tells me this is vulnerable but I tried different inputs like

employee_id = "123'; SELECT * from employees;'"

But it seems to always execute the queries together telling me No results found.

  1. I will be parametrizing the queries but wondering what the current vulnerability level is?
  2. And for parametrizing how would I go about it if I have the same 3 statements above in a lot of different places in my code? Each query is shaped differently so not quite sure I can move them to a common method. Instead I will have to refactor all places?

Solution

  • JavaScript doesn't sanitise inputs automatically and neither does Node, so this is absolutely vulnerable.

    See https://github.com/mysqljs/mysql#escaping-query-values (first answer from Preventing SQL injection in Node.js for more)