【问题标题】:Compare with substring without injection与没有注入的子串进行比较
【发布时间】:2017-10-01 14:53:25
【问题描述】:

sql-query在python模块中生成。
数据库是 PostgreSQL。

在 sql-query 中有一个与子字符串的比较:

'''
SELECT *
FROM TableTemp
WHERE "SomeColumn" LIKE '%{0}%'
'''.format(<some_string>)

如果字符串是:

%' --

那么检查将始终返回“True”。
此外,这是一个进行 sql-injection 的机会

提示,如何正确处理在搜索时考虑但没有崩溃请求并且存在 sql 注入的字符串?

UPD:
问题解决了。评论中的决定

【问题讨论】:

标签: python sql postgresql


【解决方案1】:

您可以将字符串作为一个整体传递给psycopg2,作为.execute() 的第二个参数。参考:http://initd.org/psycopg/docs/usage.html#passing-parameters-to-sql-queries

import psycopg2    

conn = psycopg2.connect("dbname=test user=postgres")
curs = conn.cursor()
search_term = 'some string'
search_tuple = ('%{0}%'.format(search_term),) # note that this has to be a container
curs.execute('''select  
                from TableTemp 
                where SomeColumn like %s''',search_tuple).fetchall()

演示:

>>> conn.execute('select * from t').fetchall()
[(u'10:00',), (u'8:00',)]
>>> conn.execute('select * from t where c like ?',('%8%',)).fetchall()
[(u'8:00',)]
>>> conn.execute('select * from t where c like ?',('%:%',)).fetchall()
[(u'10:00',), (u'8:00',)]

【讨论】:

  • 谢谢,这个答案适合自引用数据库。在工作中,我使用一个框架,在该框架中,可以只传输一条带有 sql-request 和一组参数的行。参数可以指定类型,但它不适合我。有自屏蔽字符等选项,但最好的解决方案是用双引号替换引号。
  • @YuraKharpaev(以及任何其他尝试 Yura 建议的人):来自 psycopg2 文档的以下警告不能得到足够的强调:“永远,永远,永远不要使用 Python 字符串连接 (+) 或字符串参数插值 ( %) 将变量传递给 SQL 查询字符串。甚至在枪口下也不行。” str.format() 函数也应该包含在该列表中。
猜你喜欢
  • 2020-07-10
  • 1970-01-01
  • 2017-02-20
  • 1970-01-01
  • 2021-04-06
  • 2021-11-20
  • 1970-01-01
  • 2012-08-31
  • 1970-01-01
相关资源
最近更新 更多