W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
1.9.1 【必須】SQL 語句默認(rèn)使用預(yù)編譯并綁定變量
// bad:拼接 SQL 語句查詢,存在安全風(fēng)險
const mysql = require("mysql");
const connection = mysql.createConnection(options);
connection.connect();
const sql = util.format("SELECT * from some_table WHERE Id = %s and Name = %s", req.body.id, req.body.name);
connection.query(sql, (err, result) => {
// handle err..
});
// good:使用預(yù)編譯綁定變量構(gòu)造SQL語句
const mysql = require("mysql");
const connection = mysql.createConnection(options);
connection.connect();
const sql = "SELECT * from some_table WHERE Id = ? and Name = ?";
const sqlParams = [req.body.id, req.body.name];
connection.query(sql, sqlParams, (err, result) => {
// handle err..
});
__user_input__
拼接到比如 limit
, order by
, group by
, from tablename
語句中。請使用以下方法:方案1:使用白名單校驗表名/列名
// good
const tableSuffix = req.body.type;
if (["expected1", "expected2"].indexOf(tableSuffix) < 0) {
// 不在表名白名單中,拒絕請求
return ;
}
const sql = `SELECT * from t_business_${tableSuffix}`;
connection.query(sql, (err, result) => {
// handle err..
});
方案2:使用反引號包裹表名/
列名,并過濾 __user_input__
中的反引號
// good
let { orderType } = req.body;
// 過濾掉__user_input__中的反引號
orderType = orderType.replace("`", "");
const sql = util.format("SELECT * from t_business_feeds order by `%s`", orderType);
connection.query(sql, (err, result) => {
// handle err..
});
方案3:將 __user_input__
轉(zhuǎn)換為整數(shù)
// good
let { orderType } = req.body;
// 強(qiáng)制轉(zhuǎn)換為整數(shù)
orderType = parseInt(orderType, 10);
const sql = `SELECT * from t_business_feeds order by ${orderType}`;
connection.query(sql, (err, result) => {
// handle err..
});
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: