SQL injection in Knex queries

SQL injection in Knex queries

Description

Putting request body values directly into SQL passed to knex.raw lets input intended for a record change the statement itself.

Potential impact

The database account’s privileges determine whether altered queries can expose, modify or delete data or bypass access checks.

Remediation

Use value arguments with .insert() and .where(). If you need .raw(), keep the SQL fixed and pass bindings separately. Check the input type, format and length, and authorize the caller before writing.

Examples

Before

javascript
app.post('/user', async (req, res) => {
  const result = await knex.raw(
    `INSERT INTO users (name, email) VALUES ('${req.body.name}', '${req.body.email}')`
  );
  res.send('User added');
});

After

javascript
app.post('/user', async (req, res) => {
  const result = await knex.raw(
    'INSERT INTO users (name, email) VALUES (?, ?)',
    [req.body.name, req.body.email]
  );
  res.send('User added');
});

The two ? placeholders take req.body.name and req.body.email in array order.

References