tonado mysql_Tornado+MySQL模拟SQL注入

实验环境:

python 3.6 + Tornado 4.5 + MySQL 5.7

实验目的:

简单模拟SQL注入,实现非法用户的成功登录

先给一个SQL注入的图解,图片来自网络:

181bfe62c530fb1e20a0bccf59fa7d3a.png

一、搭建环境

1、服务端的tornado主程序app.py如下:

#!/usr/bin/env python3

# -*- coding: utf-8 -*-

import tornado.ioloop

import tornado.web

import pymysql

class LoginHandler(tornado.web.RequestHandler):

def get(self):

self.render('login.html')

def post(self, *args, **kwargs):

username = self.get_argument('username',None)

pwd = self.get_argument('pwd', None)

# 创建数据库连接

conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123456', db='shop')

cursor = conn.cursor()

# %s 要加上'' 否则会出现KeyboardInterrupt的错误

temp = "select name from userinfo where name='%s' and password='%s'" % (username, pwd)

effect_row = cursor.execute(temp)

result = cursor.fetchone()

conn.commit()

cursor.close()

conn.close()

if result:

self.write('登录成功!')

else:

self.write('登录失败!')

settings = {

'template_path':'template',

}

application = tornado.web.Application([

(r"/login", LoginHandler),

],**settings)

if __name__ == "__main__":

application.listen(8000)

tornado.ioloop.IOLoop.instance().start()

2、在template文件夹下,放入login.html文件:

Title

3、在shop数据库中建立userinfo数据表,并填入数据:

90f3cabf2e0ee3d7c43e8e2b0717fd95.png

随便添加两条就好,明文就明文吧:

38c2a1bdbcd8a444ebb54f3b3cba3e67.png

二、模拟登录

1、正常登录

1808351873d84251345921ab805d1b69.png

2c5475d92f897c1334814eeb4934f0c7.png

257c4a0e60b16fb48a66bfafbef372e3.png

43acc18fcf9cb1e6959628b0c203bfe5.png

以上都是“好用户”的正常登录,我们看一下“坏家伙”怎么做。

2、非法登录

密码不对也能登录:

8565bca016e2463a7669f58be616b87c.png

476ec1d6e702f46d33dd4dd32ef59191.png

看一下服务端执行的SQL语句,就不难理解了,密码部分被注释掉了:

select name from userinfo where name='dyan' -- n' and password='000'

账户密码都不对照样登录成功:

428adb0437af91505c2f0b66da51e784.png

476ec1d6e702f46d33dd4dd32ef59191.png

看执行的SQL语句:

select name from userinfo where name='badguy' or 1=1 -- y' and password='000'

三、使用cursor.execute方式防止注入

使用字符串拼接的方式会导致SQL注入。在cursor.execute方法中对'导致注入的符号做了转义。

将app.py中下面两行代码改为:

# 导致SQL注入

temp = "select name from userinfo where name='%s' and password='%s'" % (username, pwd)

effect_row = cursor.execute(temp)

# 防止SQL注入

effect_row = cursor.execute("select name from userinfo where name='%s' and password='%s'",(username, pwd,))

再次尝试注入:

2b4f668a5c104cdc2bf3ecdea90f3dc1.png

3fdf6ee8a4ce5dbc21262c0422317754.png

错误原因,巴拉巴拉就是语法不对:

ymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax;

看看内部执行的语句,主要是对'符号做了转义防止注入:

select name from userinfo where name=''dyan\' -- n'' and password=''123''

完!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值