SQL injection High

User-provided inputs must be sanitized before being used to generate a SQL database query. An attacker can create and use untrusted input to run query statements that read, modify, or delete database content.

Detector ID
typescript/sql-injection@v1.0
Category
Common Weakness Enumeration (CWE) external icon

Noncompliant example

1import sql from 'mysql'
2import express, { Request, Response } from 'express'
3var app = express()
4
5var connection = sql.createConnection({
6    host     : 'localhost',
7    user     : 'myUserName',
8    password : 'myPass',
9    database : 'myDatabase'
10})
11
12function sqlInjectionNoncompliant() {
13    app.get("/user/:id", (req: Request, res: Response) => {
14        // Noncompliant: user input is not sanitized before use.
15        var query = "SELECT * FROM Employees WHERE ID = " + req.params.id
16
17        connection.query(query, (error: any, results: any, fields: any) => {
18            if (error) throw error
19        })
20    })
21}

Compliant example

1import sql from 'mysql'
2import express, { Request, Response } from 'express'
3var app = express()
4
5var connection = sql.createConnection({
6    host     : 'localhost',
7    user     : 'myUserName',
8    password : 'myPass',
9    database : 'myDatabase'
10});
11
12function sqlInjectionCompliant() {
13    app.get("/user/:id", (req: Request, res: Response) => {
14        // Compliant: user input is sanitized before use.
15        var query = "SELECT * FROM Employees WHERE ID = " + connection.escape(req.params.id)
16
17        connection.query(query, (error: any, results: any, fields: any) => {
18            if (error) throw error
19        })
20    })
21}