Knex.js是否可以防止SQL注入? [英] Does Knex.js prevent sql injection?

查看:488
本文介绍了Knex.js是否可以防止SQL注入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MySql数据库,并试图找到MySQL替代tedious.js(SQL Server参数化查询生成器).我在后端使用Node.js.

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.

我读到knex.js中的.raw()命令很容易受到sql注入的影响,如果不与绑定一起使用的话. 但是,其他命令和knex.js整体上可以安全使用来防止sql注入吗?还是我吠错了树?

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?

推荐答案

从knex文档中仔细阅读如何将值传递给knex raw(

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

如果您将值作为参数绑定传递给raw,例如:

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

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

在这种情况下,参数和查询字符串分别传递到数据库驱动程序,以保护查询免受SQL注入.

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()

这将输出给驱动程序以运行查询的SQL字符串和绑定( https://runkit.com /embed/2yhqebv6pte6 ).

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

使用knex原始查询可能犯的最大错误是使用javascript模板字符串并将变量直接插值为SQL字符串格式,例如:

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 

要注意的一件事是,不能将knex表/标识符名称作为绑定传递给驱动程序,因此对于这些名称,应格外小心,不要从用户那里读取表/列名称,并在未首先正确验证它们的情况下使用它们.

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.

说标识符名称不能作为绑定传递,我的意思是当使用?? knex -binding作为标识符名称时,传递给数据库驱动程序时,它将作为SQL字符串的一部分呈现.

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.

这篇关于Knex.js是否可以防止SQL注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆