SQL注入原理及防御
SQL注入尤其是字符串型注入尤為明顯且容易,下面以登錄校驗(yàn)為例簡單介紹其原理和防御策略。
登錄接口SQL
根據(jù)用戶名和密碼獲取用戶數(shù)據(jù):
sql = """select uid, email, phone from tb_user where username='{username}' and pwd='{pwd}'""".format(username=username, pwd=pwd)
正常情況下的請求體application/json:
{
"username": "ridingroad",
"pwd": "加密后的密碼"
}
所得到的SQL:
select uid, email, phone from tb_user
where username='ridingroad' and pwd='加密后的密碼'
SQL注入下的請求體
{
"username": "ridingroad' or 1=1#",
"pwd": ""
}
此時(shí)得到的SQL將是:
select uid, email, phone from tb_user
where username='ridingroad' or 1=1#' and pwd='加密后的密碼'
成功注入的原因:
ridingroad’和原來的username='{username}'.format(username)結(jié)合
'{username}'.format("ridingroad' or 1=1#")
得到:
username='ridingroad' or 1=1#'
#后面的sql組成部分變成了注釋,失去了原來的and邏輯判斷作用
where username='ridingroad' or 1=1#' and pwd='加密后的密碼'
且
or 1=1永遠(yuǎn)為真
結(jié)果:
將會造成用戶表所有數(shù)據(jù)的泄露
SQL注入防御
阻止SQL注入的方法主要是利用現(xiàn)有數(shù)據(jù)庫第三方庫完善的防SQL注入的特性,避免重復(fù)造輪子
原始SQL情況下
使用%s占位符,利用PyMySQL自帶的防注入特性
sql = """select uid, email, phone from tb_user
where username=%s and pwd=%s"""
cursor.excute(sql, (username, pwd))
ORM情況下
SQLAlchemy ORM已經(jīng)對SQL注入進(jìn)行了處理,直接使用ORM語法即可,不需要特別處理。
評論
圖片
表情
