9Python全站之路系列之MySQL SL注入

Python全棧之路系列之MySQL SQL注入


SQL注入是一種代碼注入技術,過去常常用於***數據驅動性的應用,比如將惡意的SQL代碼注入到特定字段用於實施******等。

SQL注入的成功必須藉助應用程序的安全漏洞,例如用戶輸入沒有經過正確地過濾(針對某些特定字符串)或者沒有特別強調類型的時候,都容易造成異常地執行SQL語句。

SQL注入是網站***中最常用的***技術,但是其實SQL注入可以用來***所有的SQL數據庫。


SQL注入的實現

創建SQLdb數據庫

CREATE DATABASE SQLdb;

創建user_info

CREATE TABLE `user_info` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(32) DEFAULT NULL,
  `password` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

插入一條用戶數據

測試的用戶名是ansheng,密碼as

insert into user_info(username,password) values("ansheng","as");

Python代碼

app.py文件

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import tornado.ioloop
import tornado.web
import pymysql

class LoginHandler(tornado.web.RequestHandler):
    def get(self, *args, **kwargs):
        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='as', db='sqldb')
        cursor = conn.cursor()
        temp = "select username from user_info where username='%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('登錄失敗')
            
application = tornado.web.Application([
    (r"/login", LoginHandler),
])


if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

HTML代碼

login.htmlapp.py文件在同級

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/login" method="post">
    <input type="text" name="username" placeholder="用戶名" />
    <input type="text" name="pwd" placeholder="密碼" />
    <input type="submit" />
</form>
</body>
</html>

演示效果

打開瀏覽器,輸入地址http://127.0.0.1:8888/login

填寫內容如下:

用戶名:asas ' or 1 = 1-- asd
密碼:隨便填寫一串字母

如圖:

sql-injection-01

當點擊提交的時候是否會跳轉到登陸成功頁面?如果你的代碼和我一樣,那麼就會跳轉到登陸成頁面

爲什麼出現這種問題?

出現這個問題的主要原因就是因爲我們使用了字符串拼接的方式來進行SQL指令的拼接。

SQL指令拼接代碼

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

這是一個正常的SQL拼接出來的結果

select username from user_info where username='ansheng' and password = 'as'

這是一個非正常的SQL拼接出來的結果

select username from user_info where username='asas' or 1 = 1  -- asd' and password = 's'

聰明的你是否已經看到其中的玄機了呢?--

如何防止?

通過Pythonpymysql模塊來進行SQL的執行,在pymysql模塊內部會自動把”'“(單引號做一個特殊的處理,來預防上述的錯誤

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

#Python全棧之路 #Sql注入


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章