W3Cschool
恭喜您成為首批注冊用戶
獲得88經驗值獎勵
有使用 SQL 語句操作數(shù)據(jù)庫的經驗朋友,應該都知道使用 SQL 過程中有一個安全問題叫 SQL 注入。所謂 SQL 注入,就是通過把 SQL 命令插入到 Web 表單提交或輸入域名或頁面請求的查詢字符串,最終達到欺騙服務器執(zhí)行惡意的 SQL 命令。 為了防止 SQL 注入,在生產環(huán)境中使用 OpenResty 的時候就要注意添加防范代碼。
延續(xù)之前的 ngx_postgres 調用代碼的使用,
local sql_normal = [[select id, name from user where name=']] .. ngx.var.arg_name .. [[' and password=']] .. ngx.var.arg_password .. [[' limit 1;]]
local res = ngx.location.capture('/postgres',
{ args = {sql = sql } }
)
local body = json.decode(res.body)
if (table.getn(res) > 0) {
return res[1];
}
return nil;
假設我們在用戶登錄使用上 SQL 語句查詢賬號是否賬號密碼正確,用戶可以通過 GET 方式請求并發(fā)送登錄信息比如:
# http://localhost/login?name=person&password=12345
那么我們上面的代碼通過 ngx.var.arg_name 和 ngx.var.arg_password 獲取查詢參數(shù),并且與 SQL 語句格式進行字符串拼接,最終 sql_normal 會是這個樣子的:
local sql_normal = [[select id, name from user where name='person' and password='12345' limit 1;]]
正常情況下,如果 person 賬號存在并且 password 是 12345,那么 sql 執(zhí)行結果就應該是能返回 id 號的。這個接口如果暴露在攻擊者面前,那么攻擊者很可能會讓參數(shù)這樣傳入:
name="' or ''='"
password="' or ''='"
那么這個 sql_normal 就會變成一個永遠都能執(zhí)行成功的語句了。
local sql_normal = [[select id, name from user where name='' or ''='' and password='' or ''='' limit 1;]]
這就是一個簡單的 sql inject(注入)的案例,那么問題來了,面對這么兇猛的攻擊者,我們有什么辦法防止這種 SQL 注入呢?
很簡單,我們只要 把 傳入?yún)?shù)的變量 做一次字符轉義,把不該作為破壞 SQL 查詢語句結構的雙引號或者單引號等做轉義,把 ' 轉義成 \',那么變量 name 和 password 的內容還是乖乖的作為查詢條件傳入,他們再也不能為非作歹了。
那么怎么做到字符轉義呢?要知道每個數(shù)據(jù)庫支持的 SQL 語句格式都不太一樣啊,尤其是雙引號和單引號的應用上。有幾個選擇:
ndk.set_var.set_quote_sql_str()
ndk.set_var.set_quote_pgsql_str()
ngx.quote_sql_str()
這三個函數(shù),前面兩個是 ndk.set_var 跳轉調用,其實是 HttpSetMiscModule 這個模塊提供的函數(shù),是一個 C 模塊實現(xiàn)的函數(shù),ndk.set_var.set_quote_sql_str() 是用于 MySQL 格式的 SQL 語句字符轉義,而 set_quote_pgsql_str 是用于 PostgreSQL 格式的 SQL 語句字符轉義。最后 ngx.quote_sql_str 是一個 ngx_lua 模塊中實現(xiàn)的函數(shù),也是用于 MySQL 格式的 SQL 語句字符轉義。
讓我們看看代碼怎么寫:
local name = ngx.quote_sql_str(ngx.var.arg_name)
local password = ngx.quote_sql_str(ngx.var.arg_password)
local sql_normal = [[select id, name from user where name=]] .. name .. [[ and password=]] .. password .. [[ limit 1;]]
local res = ngx.location.capture('/postgres',
{ args = {sql = sql } }
)
local body = json.decode(res.body)
if (table.getn(res) > 0) {
return res[1];
}
return nil;
注意上述代碼有兩個變化:
* 用 ngx.quote_sql_str 把 ngx.var.arg_name 和 ngx.var.arg_password 包了一層,把返回值作為 sql 語句拼湊起來。
* 原本在 sql 語句中添加的單引號去掉了,因為 ngx.quote_sql_str 的返回值正確的帶上引號了。
這樣已經可以抵御 SQL 注入的攻擊手段了,但開發(fā)過程中需要不斷的產生新功能新代碼,這時候也一定注意不要忽視 SQL 注入的防護,安全防御代碼就想織網一樣,只要有一處漏洞,魚兒可就游走了。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: