SQL injection vulnerabilities when using knex.raw with variable data
#92 opened on 2022/03/01
Repository metrics
- Stars
- (17 個のスター)
- PR merge metrics
- (PR metrics pending)
説明
When knex.raw() is used with template strings it may leave the application open to SQL injection attacks, especially if user submitted data is being placed into the string. Here is one example of this I was able to find in the app:
const sql = `
SELECT *
FROM
wallet.wallet
WHERE
id = '${walletIdOrName}'
OR
name = '${walletIdOrName}'`
SQL can be injected with a route like this:
https://dev-k8s.treetracker.org/query/wallets/<any uuid>' OR 1='1
Replace <any uuid> with a randomly generated uuid such as one from this website: https://www.uuidgenerator.net
The app will consider this a valid query and return a different wallet:

There are probably other injections that could be made with this vulnerability, and possibly other vulnerable routes in the app.
There is an eslint rule that can be used to place an error on any template strings being used with knex.raw, but this may be too strict.
On the topic of inserting values into SQL: Typescript's const enum is one limited option which can be safely used because it compiles to a raw value:
TS:
const id = 'hello'
const enum TableNames {
wallet = 'wallet'
}
const template = `template: ${id} ${TableNames.wallet}`
compiled JS:
const id = 'hello';
const template = `template: ${id} ${"wallet" /* wallet */}`;