简体   繁体   English

这个参数化查询如何防止 SQL 注入?

[英]How can this Parametrized Query Prevent SQL Injection?

I know that parametrized queries are used to prevent SQL injection, but how can this prevent an SQL injection?我知道参数化查询用于防止 SQL 注入,但这如何防止 SQL 注入? Can't someone just set their id equal to ; DROP TABLE * --不能有人只是将他们的 id 设置为等于; DROP TABLE * -- ; DROP TABLE * -- and just insert that into the parametrized query anyway? ; DROP TABLE * --然后将其插入到参数化查询中?

let updateQueryData = `UPDATE table SET lookups = $1 WHERE id = $2`;
        let updateQueryValues = [numLookups, data.rows[0].id];
        pool.query(updateQueryData, updateQueryValues, err => {

No. The data is not simply inserted into the text representation of the query.不。数据不是简单地插入到查询的文本表示中。 It is sent separately.它是单独发送的。

To prevent injection, the data must be separate from the command, so that there is no ambiguity between the data and the command.为了防止注入,数据必须与命令分开,这样数据和命令之间就没有歧义。 This is exactly what a parameterized query does.这正是参数化查询所做的。

(Note: There are some libraries that do still send the query with the data all-in-one, but all the data is automatically "escaped" so that it is still safe for use.) (注意:有些库仍然将查询与数据一体发送,但所有数据都会自动“转义”,因此仍然可以安全使用。)

Also, I would highly recommend removing those backticks and replacing with regular quotes so you don't accidentally concatenate data into that query in the future.此外,我强烈建议删除那些反引号并替换为常规引号,这样您将来就不会意外地将数据连接到该查询中。

UPDATE table SET lookups = $1 WHERE id = $2更新表 SET 查找 = $1 WHERE id = $2

Your query is parameterized already.您的查询参数化。

Here is what would happen if someone passes a malicious value like '; DROP TABLE * --'下面是如果有人传递像'; DROP TABLE * --'这样的恶意值会发生什么'; DROP TABLE * --' '; DROP TABLE * --' : '; DROP TABLE * --' :

  • if the corresponding column is of string datatype, then the query becomes something like:如果相应的列是字符串数据类型,则查询将变为:
UPDATE table SET lookups = '; DROP TABLE * --' WHERE id = 1
  • if the column is numeric, you will get a runtime error because '; DROP TABLE * --'如果该列是数字,您将收到运行时错误,因为'; DROP TABLE * --' '; DROP TABLE * --' is not a number '; DROP TABLE * --'不是数字

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM