简体   繁体   English

注入安全“SELECT FROM table WHERE column IN list;” 使用 python3 和 sqlite3

[英]Injection safe “SELECT FROM table WHERE column IN list;” using python3 and sqlite3

I want to take a user input from an html form, and do a SELECT by matching a column to the user input, and be safe for injection.我想从 html 表单中获取用户输入,并通过将列与用户输入匹配来执行 SELECT,并确保注射安全。 BUT I want the user input to be a comma separated list.但我希望用户输入是一个逗号分隔的列表。 For example, if the column is called "name" and user_input is "Alice,Bob,Carrol" I wan to execute the query例如,如果列名为“name”且 user_input 为“Alice,Bob,Carrol”,我想执行查询

SELECT FROM table WHERE name IN ("Alice","Bob","Carrol");

Which means I have the same problem as in this question select from sqlite table where rowid in list using python sqlite3 — DB-API 2.0 .这意味着我在sqlite table where rowid in list using python sqlite3 — DB-API 2.0 中遇到了与这个问题 select相同的问题。 But of course I do not want to do string concatenation myself to avoid injections.但是我当然不想自己进行字符串连接以避免注入。 At the same time, because there could be any number of commas in user_input, I cannot do this:同时,由于 user_input 中可能有任意数量的逗号,我不能这样做:

db.execute('SELECT FROM table WHERE name IN (?,?,?)', user_input_splited)

I looked for a way to sanitize or escape the input by hand, to be able to do something like that:我寻找了一种手动清理或转义输入的方法,以便能够执行以下操作:

db.execute('SELECT FROM table WHERE name IN?', user_input_sanitized)

But I didn't find it.但我没找到。 What's the best approach here?这里最好的方法是什么?

Write your own code to take the user's input, split() it by comma, then iterate through that list.编写您自己的代码来获取用户的输入,用逗号split()它,然后遍历该列表。 As you accept each value, push it onto one array, and push a literal "?"当您接受每个值时,将其推送到一个数组中,然后推送一个文字"?" onto the other.到另一个。

Of course, now verify that you have at least one acceptable value.当然,现在验证您至少有一个可接受的值。

Now, construct your SQL statement by to include, say, join(", ", $qmarks_array) to automatically construct a string that looks like ?, ?, ? ...现在,构造您的 SQL 语句,例如包含join(", ", $qmarks_array)以自动构造一个看起来像?, ?, ? ...的字符串?, ?, ? ... with an appropriate number of question-marks. ?, ?, ? ...带有适当数量的问号。 (It won't insert any comma if there's only one element.) Then, having constructed the SQL statement in this way, supply the other array as input to the function which executes that query. (如果只有一个元素,它不会插入任何逗号。)然后,以这种方式构造了 SQL 语句,将另一个数组作为输入提供给执行该查询的 function。

In this way, you supply each value as a parameter, which you should always do, and you allow the number of parameters to vary.通过这种方式,您将每个值作为参数提供,您应该始终这样做,并且您允许参数的数量变化。

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

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