python - 这段 Python 代码容易受到 SQL 注入(inject)的攻击吗? (SQLite3)

标签 python sql security sqlite

正如标题所暗示的,我想知道这段代码是否存在 SQL 注入(inject)漏洞?如果是这样,是否有更好、更安全的方法来实现同样的目标?

def add(table,*args):
    statement="INSERT INTO %s VALUES %s" % (table,args)
    cursor.execute(statement)

最佳答案

是的,是的。使用这样的东西来防止它:

cursor.execute("INSERT INTO table VALUES ?", args)

注意不能这样输入表格。理想情况下,表格应该是硬编码的,在任何情况下都不应来自任何类型的用户输入。您可以使用类似于您为表所做的字符串,但您最好 100% 确定用户无法以某种方式更改它...参见 Can I use parameters for the table name in sqlite3?更多细节。

本质上,您希望将参数放在游标命令中,因为这将确保数据数据库安全。使用您的第一个命令,创建一个特殊的 tableargs 将一些不安全的内容放入您的 SQL 代码中会相对容易。查看python pages ,以及引用的 http://xkcd.com/327/ .具体来说,python 页面引用:

Usually your SQL operations will need to use values from Python variables. You shouldn’t assemble your query using Python’s string operations because doing so is insecure; it makes your program vulnerable to an SQL injection attack (see http://xkcd.com/327/ for humorous example of what can go wrong).

Instead, use the DB-API’s parameter substitution. Put ? as a placeholder wherever you want to use a value, and then provide a tuple of values as the second argument to the cursor’s execute() method. (Other database modules may use a different placeholder, such as %s or :1.)

基本上,有人可以设置一个执行另一个命令的参数,像这样:

args="name; DELETE table"

使用 cursor.execute 将填充给定的值,这样参数就可以像列出的那样,当你对其进行查询时,这正是你将得到的结果。 XKCD也幽默地解释了这一点。

enter image description here

关于python - 这段 Python 代码容易受到 SQL 注入(inject)的攻击吗? (SQLite3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13613037/

相关文章:

MySQL - 编写一个应该很简单的查询时遇到麻烦

安全性——可以通过 HTTP GET 发送用户名和密码吗?

security - XP 上的 WMI 访问被拒绝

php - 如何保护php和mySql访问以防止f?

python - 如何将 python 列表中的第 n 个条目相互添加?

python - 使用 csv.reader() 加载和访问数据时获取 AttributeError

php - 是否有在开发组中共享数据库 SQL 更改的标准?

python - 如何使用 Python 解析和修改 .odg 文件?

python - doc2vec 时出现“utf-8”编解码器错误

sql - 如何找到表列数据中最长的字符串