简体   繁体   中英

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. 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

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 . 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:

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. 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 ?, ?, ? ...?, ?, ? ... 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.

In this way, you supply each value as a parameter, which you should always do, and you allow the number of parameters to vary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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