Does Knex.js prevent sql injection?

限于喜欢 提交于 2019-12-21 07:27:32

问题


I'm using a MySql database and was trying to find a MySQL alternative to tedious.js (a SQL server parameterised query builder).I'm using Node.js for my backend.

I read that the .raw() command from knex.js is susceptible to sql injection, if not used with bindings. But are the other commands and knex.js as a whole safe to use to prevent sql injection? Or am I barking up the wrong tree?


回答1:


Read carefully from knex documentation how to pass values to knex raw (http://knexjs.org/#Raw).

If you are passing values as parameter binding to raw like:

knex.raw('select * from foo where id = ?', [1])

In that case parameters and query string are passed separately to database driver protecting query from SQL injection.

Other query builder methods always uses binding format internally so they are safe too.

To see how certain query is passed to database driver one can do:

knex('foo').where('id', 1).toSQL().toNative()

Which will output SQL string and bindings that are given to driver for running the query (https://runkit.com/embed/2yhqebv6pte6).

Biggest mistake that one can do with knex raw queries is to use javascript template string and interpolate variables directly to SQL string format like:

knex.raw(`select * from foo where id = ${id}`) // NEVER DO THIS 

One thing to note is that knex table/identifier names cannot be passed as bindings to driver, so with those one should be extra careful to not read table / column names from user and use them without properly validating them first.

Edit:

By saying that identifier names cannot be passed as bindings I mean that when one is using ?? knex -binding for identifier name, that will be rendered as part of SQL string when passed to the database driver.



来源:https://stackoverflow.com/questions/49665023/does-knex-js-prevent-sql-injection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!