Does Knex.js prevent sql injection?

前端 未结 1 407
一向
一向 2020-12-31 00:01

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

相关标签:
1条回答
  • 2020-12-31 00:31

    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.

    0 讨论(0)
提交回复
热议问题