Python SQLite3 SQL注入易受攻击的代码
我知道由于.format,下面的代码片段容易受到SQL注入的攻击,但我不知道为什么。是否有人理解此代码易受攻击的原因以及我将从何处着手修复它?我知道这些代码片段使输入字段保持打开状态,以便通过SQL注入执行其他恶意命令,但不知道为什么Python SQLite3 SQL注入易受攻击的代码,python,sql,sqlite,sql-injection,Python,Sql,Sqlite,Sql Injection,我知道由于.format,下面的代码片段容易受到SQL注入的攻击,但我不知道为什么。是否有人理解此代码易受攻击的原因以及我将从何处着手修复它?我知道这些代码片段使输入字段保持打开状态,以便通过SQL注入执行其他恶意命令,但不知道为什么 cursor.execute("insert into user(username, password)" " values('{0}', '{1}')".format(username, password)) handle[0].execu
cursor.execute("insert into user(username, password)"
" values('{0}', '{1}')".format(username, password))
handle[0].execute("insert into auditlog(userid, event)"
" values({0}, ‘{1}')".format(handle[2],event))
audit((cursor, connection, 0),
"registeration error for {0}”.format(username))
sql="""insert into activitylog(userid, activity, start, stop)
values({0}, '{1}', '{2}', '{3}')
""".format(handle[2], activity, start, stop)
发件人:
通常,SQL操作需要使用Python中的值
变量。您不应该使用Python的字符串组合查询
因为这样做是不安全的;它使你的程序
易受SQL注入攻击(有关详细信息,请参阅
可以出错的幽默例子)
相反,使用DB-API的参数替换。放?作为一个
在需要使用值的任何位置使用占位符,然后提供元组
作为游标的execute()方法的第二个参数的值。
(其他数据库模块可能使用不同的占位符,例如%s或%s。)
:1.)例如:
# Never do this -- insecure!
symbol = 'RHAT'
c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)
# Do this instead
t = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)
print c.fetchone()
使用第一条SQL语句的SQL注入示例:
cursor.execute("insert into user(username, password) values('{0}', '{1}')".format(username, password))
如果用户名
和密码
是的“废话”
则生成的SQL语句是:
insert into user(username, password) values('blah', 'blah')
这句话没有问题
但是,如果用户能够输入密码
的值(可能来自HTML表单),则:
blah'); drop table user; --
生成的SQL语句将是:
insert into user(username, password) values('blah', 'blah'); drop table user; --
这实际上是3条语句,用分号分隔:一个插入,一个删除表,然后是一条注释。某些数据库(例如Postgres)将执行所有这些语句,这将导致删除用户表。但是,在使用SQLite进行实验时,SQLite似乎不允许一次执行多个语句。然而,可能还有其他方法来注入SQL。在这个话题上有很好的参考
解决此问题很容易,请使用如下参数化查询:
cursor.execute("insert into user(username, password) values(?, ?)", (username, password))
占位符使用?
添加到查询中,db引擎将正确地转义这些值以避免SQL注入。结果查询将是:
insert into user(username, password) values('blah', 'blah''); drop table users; --')
其中'blah\'
中的终止'
已正确转义。价值
blah'); drop table users; --
将出现在插入记录的密码字段中。每当您使用字符串操作和外部用户提供的数据构造SQL语句时,您会遇到两种漏洞:
O'Reilly
的人。当插入到字符串中时,多余的撇号将使生成的SQL无效想想如果用户声称他的密码是“密码>秘密”会发生什么;删除表用户--代码>。