SQL injection in node-mssql queries

SQL injection in node-mssql queries

Description

Inserting a request ID directly into SQL lets the caller change the query conditions.

Potential impact

Depending on the connection account’s privileges, this can expose, change or delete sensitive data or disrupt service.

Remediation

Use request.input to specify the parameter name, SQL type and value, then reference the name in your query. Validate input format and length. Choose table and column names from an allow-list in code.

Examples

Before

javascript
const express = require('express');
const mssql = require('mssql');

app.get('/user', async (req, res) => {
  const id = req.query.id;
  const pool = mssql.connect(/* config */);
  const request = (await pool).request();
  // User input is inserted directly into the query
  const result = await request.query(`SELECT * FROM users WHERE id = ${id}`);
  res.json(result);
});

After

javascript
const express = require('express');
const mssql = require('mssql');

app.get('/user', async (req, res) => {
  const id = parseInt(req.query.id, 10); // Integer conversion only: validate the input separately
  const pool = mssql.connect(/* config */);
  const request = (await pool).request();
  // Bind the value as a parameter
  request.input('userId', mssql.Int, id);
  const result = await request.query('SELECT * FROM users WHERE id = @userId');
  res.json(result);
});

The example binds id as mssql.Int and refers to it as @userId. Because parseInt can accept a numeric prefix, check the entire input, reject NaN and enforce the SQL Int range. The handler also needs connection configuration, error handling and permission checks for the requested record.

References