SQL Injection 預防攻擊的方法

對輸入的資料進行驗證

在 Web 應用程式中適當的輸入驗證,可避免大多數的攻擊,包含 SQL Injection。
例如:使用 Regex 過濾掉非法的字元。

使用參數化查詢

使用動態組合查詢是 SQL Injection 成功的原因之一,攻擊者能在動態組合查詢中插入 SQL 語法,進一步取得資料庫資料。

有 SQL Injection 弱點動態組合查詢的寫法:

String username = request.getParameter("username");
String password = request.getParameter("password");
String sql = "select * from user_table where username = '" + username + "' and password = '" + password + "'";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);

參數化查詢安全的寫法:

String username = request.getParameter("username");
String password = request.getParameter("password");
PreparedStatement pstmt = con.prepareStatement("Select * from user_table where username = ? and password = ?");
pstmt.setString(1, username);
pstmt.setString(2, password);
ResultSet rs = pstmt.execute();

使用預存程序取代原始SQL

雖然預存程序還有 SQL Injection 的風險,但攻擊者較難從系統中去操控 SQL 查詢。

避免將資料庫錯誤和系統錯誤訊息透漏給使用者

系統應隱藏原始的錯誤訊息,只顯示一般的錯誤訊息給使用者,像是「請重新再試一次」,以避免被攻擊者分析和濫用。

選擇不容被猜到的資料表和欄位名稱

避免攻擊者輕易猜測到資料表與欄位名稱。

參考網站

http://www.gss.com.tw/index.php/security/997-gss0072

results matching ""

    No results matching ""