Python操作MySQL時防止SQL注入下面是網(wǎng)上搜到的一篇關(guān)于SQL注入的文章。最近在項目中涉及到防止SQL注入的部分,但是由于使用的是PYTHON和MYSQL,使用不了JAVA代碼中提供的一些現(xiàn)成的方法,而且MYSQLDB模塊中的EXECUTE方法不支持表名使用占位符。 execute(self,query, args=None)Execute a query. query -- string, query to execute on serverargs -- optional sequence or mapping, parameters to use with query. Note: If args is a sequence, then %s must be used as theparameter placeholder in the query. If a mapping is used,%(key)s must be used as the placeholder. Returns long integer rows affected, if any Placeholders are supposed to be used for *values*, not other parts of the SQL statement. To insert table names, column names and stuff like that, use Python-level formatting. cur.execute("select * from %s where name=%s",('t1','xx')) --python-level formatting,執(zhí)行失敗 cur.execute("select * from %s where name=%s"%('t1','xx')) --execute()-level formatting,執(zhí)行成功,但是并沒有達(dá)到防止SQL注入的效果 下面是文檔上的一個例子 To perform a query, you first need a cursor, and then you can executequeries on it: In this example, max_price=5 Why, then, use%s in thestring? Because MySQLdb will convert it to a SQL literal value, whichis the string '5'. When it's finished, the query will actually say,"...WHERE price < 5". 無奈之下手工實現(xiàn),需要兩步: 1、把變量值中的單引號逃逸掉 2、給變量值兩端加上單引號 #######################應(yīng)該說,您即使沒有處理 HTML 或 JavaScript 的特殊字符,也不會帶來災(zāi)難性的后果,但是如果不在動態(tài)構(gòu)造 SQL 語句時對變量中特殊字符進(jìn)行處理,將可能導(dǎo)致程序漏洞、數(shù)據(jù)盜取、數(shù)據(jù)破壞等嚴(yán)重的安全問題。網(wǎng)絡(luò)中有大量講解 SQL 注入的文章,感興趣的讀者可以搜索相關(guān)的資料深入研究。 雖然 SQL 注入的后果很嚴(yán)重,但是只要對動態(tài)構(gòu)造的 SQL 語句的變量進(jìn)行特殊字符轉(zhuǎn)義處理,就可以避免這一問題的發(fā)生了。來看一個存在安全漏洞的經(jīng)典例子: 以上 SQL 語句根據(jù)返回的結(jié)果數(shù)判斷用戶提供的登錄信息是否正確,如果 userName 變量不經(jīng)過特殊字符轉(zhuǎn)義處理就直接合并到 SQL 語句中,黑客就可以通過將 userName 設(shè)置為 “1' or '1'='1”繞過用戶名/密碼的檢查直接進(jìn)入系統(tǒng)了。 所 以除非必要,一般建議通過 PreparedStatement 參數(shù)綁定的方式構(gòu)造動態(tài) SQL 語句,因為這種方式可以避免 SQL 注入的潛在安全問題。但是往往很難在應(yīng)用中完全避免通過拼接字符串構(gòu)造動態(tài) SQL 語句的方式。為了防止他人使用特殊 SQL 字符破壞 SQL 的語句結(jié)構(gòu)或植入惡意操作,必須在變量拼接到 SQL 語句之前對其中的特殊字符進(jìn)行轉(zhuǎn)義處理。Spring 并沒有提供相應(yīng)的工具類,您可以通過 jakarta commons lang 通用類包中(spring/lib/jakarta-commons/commons-lang.jar)的 StringEscapeUtils 完成這一工作: 清單 4. SqlEscapeExample
package com.baobaotao.escape; import ormons.lang.StringEscapeUtils; publicclass SqlEscapeExample { publicstaticvoid main(String[] args) { String userName = "1' or '1'='1"; String password = "123456"; userName = StringEscapeUtils.escapeSql(userName); password = StringEscapeUtils.escapeSql(password); String sql = "SELECT COUNT(userId) FROM t_user WHERE userName='" + userName + "' AND password ='" + password + "'"; System.out.println(sql); } } 事實上, StringEscapeUtils 不但提供了 SQL 特殊字符轉(zhuǎn)義處理的功能,還提供了 HTML、XML、JavaScript、Java 特殊字符的轉(zhuǎn)義和還原的方法。如果您不介意引入 jakarta commons lang 類包,我們更推薦您使用 StringEscapeUtils 工具類完成特殊字符轉(zhuǎn)義處理的工作。 來自:http://www.educity.cn/shujuku/1599437.html |
|
|