MySQL注入问题

语言:python

 

sql注入原理:

首先看一下登录程序代码

import  pymysql

username = input('username:')
pwd = input('password:')
conn = pymysql.connect(host='localhost', user='root', password='123',database='du', charset='utf8')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

sql = "select * from student where sname = '%s' and sid = '%s'" % (username, pwd)

cursor.execute(sql)
res = cursor.fetchone()
if res:
    print('登录成功')
else:
    print('登录失败')

cursor.close()
conn.close()
==》
username:aaa
password:3
登录成功

正常用户输入用户名和密码不会出现问题但是当输入带有意义的字符时也会登陆成功

username:aaa'#
password:
登录成功

这是因为在我们采用拼接字符串的方法来生成mysql指令但是如上生成的指令为

select * from student where sname = 'aaa'#' and sid = ''

#后面的代码被注释掉了,而且语句也依然合法通过sname来搜索到的用户存在就可以正常登录,这就是sql注入攻击

如何防御sql注入

通过前面的讲解我们得知,要想成功利用SQL注入漏洞,需要同时满足两个条件,一是攻击者可以控制用户的输入,二是注入的代码要被成功执行。

 1. 自己手工对用户输入的值进行转义
            
 2. 使用execute()自动进行过滤
    

sql = "select * from t4 where name = %s and pwd = %s"
cursor.execute(sql,(username, pwd))
插入一条
cursor.execute(sql, ('lxxx', '1234'))
插入多条
        data = [
            ('aaaaa', 'aaa'),
            ('bbbb', 'bbb'),
            ('ffff', '666'),
            ('rrrr', '888'),
        ]
        cursor.executemany(sql, data)

 

posted @ 2019-06-17 15:56  adiugy  阅读(391)  评论(0编辑  收藏  举报