Skip to content
Advertisement

Is knex.where prone to sql injection attacks?

This is a follow up question to https://stackoverflow.com/a/50337990/1370984 .

It mentions knex('table').where('description', 'like', '%${term}%') as prone to sql injection attacks. Even a comment mentions the first case as prone to injection attacks. Yet the reference provided never mentions .where being prone to injection attacks.

Is this a mistake? Why would knex allow .where to be prone to injection attacks but not .whereRaw('description like '%??%'', [term]) . Aren’t the arguments being parameterized in both cases?

Advertisement

Answer

This is a follow up question to https://stackoverflow.com/a/50337990/1370984 .

It mentions knex(‘table’).where(‘description’, ‘like’, ‘%${term}%’) as prone to sql injection attacks. Even a comment mentions the first case as prone to injection attacks. Yet the reference provided never mentions .where being prone to injection attacks.

I’m knex maintainer and I have commented there that

knex('table').where('description', 'like', `%${term}%`)

is NOT vulnerable to SQL injection attacks.

Is this a mistake? Why would knex allow .where to be prone to injection attacks but not .whereRaw(‘description like ‘%??%”, [term]) . Aren’t the arguments being parameterized in both cases?

That .whereRaw is vulnerable when you interpolate values directly to sql string (like for example ?? identifier replacement does).

Correct use for .whereRaw in this case would be for example:

.whereRaw("?? like '%' || ? || '%'", ['description', term])

Where all identifiers are quoted correctly and term is sent to DB as parameter binding.

So the answer and most of the comments added to that answer are just plain wrong.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement