如何有效防止SQL注入攻擊
SQL注入攻擊是黑客對(duì)數(shù)據(jù)庫(kù)進(jìn)行攻擊常用的手段之一,隨著B(niǎo)/S模式應(yīng)用開(kāi)發(fā)的發(fā)展,使用這種模式編寫(xiě)應(yīng)用程序的程序員也越來(lái)越多。但是由于程序員的水平及經(jīng)驗(yàn)參差不齊,相當(dāng)大一部分程序員在編寫(xiě)代碼的時(shí)候,沒(méi)有對(duì)用戶輸入數(shù)據(jù)的合法性進(jìn)行判斷,使應(yīng)用程序存在安全隱患。用戶可以提交一段數(shù)據(jù)庫(kù)查詢代碼,根據(jù)程序返回的結(jié)果,獲得某些他想獲取的數(shù)據(jù),這就是所謂的SQL Injection,即SQL注入。
一 背景
假如某高校開(kāi)發(fā)了一個(gè)網(wǎng)課系統(tǒng),要求學(xué)生選課后完成學(xué)習(xí),數(shù)據(jù)庫(kù)中有一張表course,這張表存放著每個(gè)學(xué)生的選課信息及完成情況,具體設(shè)計(jì)如下:
數(shù)據(jù)如下:
本系統(tǒng)采用mysql做為數(shù)據(jù)庫(kù),使用Jdbc來(lái)進(jìn)行數(shù)據(jù)庫(kù)的相關(guān)操作。系統(tǒng)提供了一個(gè)功能查詢?cè)搶W(xué)生的課程完成情況,代碼如下。
- @RestController
- public class Controller {
- @Autowired
- SqlInject sqlInject;
- @GetMapping("list")
- public List<Course> courseList(@RequestParam("studentId") String studentId){
- List<Course> orders = sqlInject.orderList(studentId);
- return orders;
- }
- }
- @Service
- public class SqlInject {
- @Autowired
- private JdbcTemplate jdbcTemplate;
- public List<Course> orderList(String studentId){
- String sql = "select id,course_id,student_id,status from course where student_id = "+ studentId;
- return jdbcTemplate.query(sql,new BeanPropertyRowMapper(Course.class));
- }
- }
二 注入攻擊演示
1. 正常情況下查詢一個(gè)學(xué)生所選課程及完成情況只需要傳入student_id,便可以查到相關(guān)數(shù)據(jù)。
根據(jù)響應(yīng)結(jié)果,我們很快便能寫(xiě)出對(duì)應(yīng)的sql,如下:
- select id,course_id,student_id,status
- from course
- where student_id = 4
2. 如果我們想要獲取這張表的所有數(shù)據(jù),只需要保證上面這個(gè)sql的where條件恒真就可以了。
- select id,course_id,student_id,status
- from course
- where student_id = 4 or 1 = 1
請(qǐng)求接口的時(shí)候?qū)tudendId 設(shè)置為4 or 1 = 1,這樣這條sql的where條件就恒真了。sql也就等同于下面這樣
- select id,course_id,student_id,status
- from course
請(qǐng)求結(jié)果如下,我們拿到了這張表的所有數(shù)據(jù)
3. 查詢mysql版本號(hào),使用union拼接sql
- union select 1,1,database(),1
4. 查詢數(shù)據(jù)庫(kù)名
union select 1,1,database(),1
5. 查詢mysql當(dāng)前用戶的所有庫(kù)
union select 1,1, (SELECT GROUP_CONCAT(schema_name) FROM information_schema.schemata) schemaName,1
看完上面這些演示后,你害怕了嗎?你所有的數(shù)據(jù)配置都完全暴露出來(lái)了,除此之外,還可以完成很多操作,更新數(shù)據(jù)、刪庫(kù)、刪表等等。
三 如何防止sql注入
1. 代碼層防止sql注入攻擊的最佳方案就是sql預(yù)編譯
- public List<Course> orderList(String studentId){
- String sql = "select id,course_id,student_id,status from course where student_id = ?";
- return jdbcTemplate.query(sql,new Object[]{studentId},new BeanPropertyRowMapper(Course.class));
- }
這樣我們傳進(jìn)來(lái)的參數(shù) 4 or 1 = 1就會(huì)被當(dāng)作是一個(gè)student_id,所以就不會(huì)出現(xiàn)sql注入了。
2. 確認(rèn)每種數(shù)據(jù)的類(lèi)型,比如是數(shù)字,數(shù)據(jù)庫(kù)則必須使用int類(lèi)型來(lái)存儲(chǔ)
3. 規(guī)定數(shù)據(jù)長(zhǎng)度,能在一定程度上防止sql注入
4. 嚴(yán)格限制數(shù)據(jù)庫(kù)權(quán)限,能最大程度減少sql注入的危害
5. 避免直接響應(yīng)一些sql異常信息,sql發(fā)生異常后,自定義異常進(jìn)行響應(yīng)
6. 過(guò)濾參數(shù)中含有的一些數(shù)據(jù)庫(kù)關(guān)鍵詞
- @Component
- public class SqlInjectionFilter implements Filter {
- @Override
- public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
- HttpServletRequest req=(HttpServletRequest)servletRequest;
- HttpServletRequest res=(HttpServletRequest)servletResponse;
- //獲得所有請(qǐng)求參數(shù)名
- Enumeration params = req.getParameterNames();
- String sql = "";
- while (params.hasMoreElements()) {
- // 得到參數(shù)名
- String name = params.nextElement().toString();
- // 得到參數(shù)對(duì)應(yīng)值
- String[] value = req.getParameterValues(name);
- for (int i = 0; i < value.length; i++) {
- sql = sql + value[i];
- }
- }
- if (sqlValidate(sql)) {
- throw new IOException("您發(fā)送請(qǐng)求中的參數(shù)中含有非法字符");
- } else {
- chain.doFilter(servletRequest,servletResponse);
- }
- }
- /**
- * 關(guān)鍵詞校驗(yàn)
- * @param str
- * @return
- */
- protected static boolean sqlValidate(String str) {
- // 統(tǒng)一轉(zhuǎn)為小寫(xiě)
- str = str.toLowerCase();
- // 過(guò)濾掉的sql關(guān)鍵字,可以手動(dòng)添加
- String badStr = "'|and|exec|execute|insert|select|delete|update|count|drop|*|%|chr|mid|master|truncate|" +
- "char|declare|sitename|net user|xp_cmdshell|;|or|-|+|,|like'|and|exec|execute|insert|create|drop|" +
- "table|from|grant|use|group_concat|column_name|" +
- "information_schema.columns|table_schema|union|where|select|delete|update|order|by|count|*|" +
- "chr|mid|master|truncate|char|declare|or|;|-|--|+|,|like|//|/|%|#";
- String[] badStrs = badStr.split("\\|");
- for (int i = 0; i < badStrs.length; i++) {
- if (str.indexOf(badStrs[i]) >= 0) {
- return true;
- }
- }
- return false;
- }
- }
本文轉(zhuǎn)載自微信公眾號(hào)「 Java旅途」,可以通過(guò)以下二維碼關(guān)注。轉(zhuǎn)載本文請(qǐng)聯(lián)系 Java旅途公眾號(hào)。