我希望用户能够选择显示结果的顺序,例如按年龄),并且我不想在从数据库中获得它们之后对它们进行分类。我该如何参数化pysqlite中的列名以避免SQL注入
显然,如果用户能够指定影响SQL命令的输入,那么需要对它进行消毒处理,而且我通常会使用参数化,但pysqlite似乎忽略除参数以外的任何参数。
示例代码如下显示参数化不适用于ORDER BY
,也是一种使用字符串格式化的解决方法,但容易受SQL注入影响。
什么是推荐的解决方案,允许用户输入影响排序顺序而不暴露SQLi漏洞?我必须使用字符串格式并手动检查每个用户输入吗?
#!/user/bin/env python3
import sqlite3
con = sqlite3.connect(':memory:')
cur = con.cursor()
cur.execute('CREATE TABLE test (name, age)')
cur.execute('INSERT INTO test VALUES (:name, :age)', {'name': 'Aaron', 'age': 75})
cur.execute('INSERT INTO test VALUES (:name, :age)', {'name': 'Zebedee', 'age': 5})
cur.execute('SELECT * FROM test ORDER BY age ASC')
results = cur.fetchall()
print('\nGood, but hard coded:\n', results)
# Good, but hard coded:
# [('Zebedee', 5), ('Aaron', 75)]
cur.execute('SELECT * FROM test ORDER BY :order_by ASC', {'order_by': 'age'})
results = cur.fetchall()
print('\norder_by parameter ignored:\n', results)
# order_by parameter ignored:
# [('Aaron', 75), ('Zebedee', 5)]
cur.execute('SELECT * FROM test ORDER BY {order_by} ASC'.format(order_by='age'))
results = cur.fetchall()
print('\nRight order, but vulnerable to SQL injection:\n', results)
# Right order, but vulnerable to SQL injection:
# [('Zebedee', 5), ('Aaron', 75)]
con.close()
顺便说一句,我只是用SQLI与该输入尝试''年龄; DROP TABLE测试;''到第三个SQL命令和pysqlite引发一个异常说'sqlite3.Warning:你一次只能执行一个语句.',所以也许我不应该担心?在我看来,使用字符串格式仍然很危险,但... – Grezzo
用户是否可以以任何方式影响字符串的实际内容? (在这个问题中,你使用了'age'这个常量字符串,这是没有道理的。) –
它来自http请求。如果他们使用正确的客户端(网页),它应该是6列名称中的任何一个,但如果有人决定是恶意的,它可能是他们选择的任何东西。 – Grezzo