SQL注入的简单例子
程序员文章站
2022-05-15 09:18:34
...
动态拼接SQL语句导致SQL注入
直接在SQL查询语句拼接查询参数
def getUsers(user_id):
conn = psycopg2.connect("dbname='demo1' user='postgres' host='127.0.0.1' password='admin'")
cur = conn.cursor()
if user_id == None:
str = 'select distinct * from company'
else:
str = 'select distinct * from company where id=%s' % user_id
print str
res = cur.execute(str)
res = cur.fetchall()
conn.close()
return res
破坏者输入:‘1’ OR ‘1’ = '1’将查询出该表的所有数据!
最后的SQL语句:
select distinct * from company where id='1' OR '1' = '1'
where条件实际结果变成了False or True,成功盗取该表所有数据!
一种解决示例:使用列表/元组传入参数
def getUsers(user_id):
conn = psycopg2.connect("dbname='demo1' user='postgres' host='127.0.0.1' password='admin'")
cur = conn.cursor()
if user_id == None:
str = 'select distinct * from company'
else:
str = 'select distinct * from company where id=%s'
print str
res = cur.execute(str, [user_id]) # 使用参数替换直接拼接
res = cur.fetchall()
conn.close()
return res
实际使用记得try处理一下异常
上一篇: 变量覆盖和正则表达式/e漏洞
下一篇: 简单的sql注入——实验吧