不少狀況由於過濾不嚴致使不少網站存在sql注入,這裏以用戶登錄爲例,簡單舉例java
首先建立一個測試的數據庫mysql
比較基礎,不寫建立過程了sql
java代碼以下:數據庫
package cn.basic.jdbc; import java.awt.image.RescaleOp; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import org.junit.jupiter.api.Test; public class Test1 { /* * public static void main(String[] args) throws ClassNotFoundException, * SQLException { login("aa","aa"); } */ @Test public void testlogin() throws ClassNotFoundException, SQLException { login("aa", "aa"); } public static void login(String username, String password) throws SQLException, ClassNotFoundException { Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1/test", "root", "root"); Statement st = conn.createStatement(); String sql = "select * from xxx where username=" + "'" + username + "'" + "and password=" + "'" + password + "'"; ResultSet rs = st.executeQuery(sql); if (rs.next()) { System.out.println("恭喜" + username + "登錄成功"); System.out.println(sql); } else { System.out.println("登陸失敗"); } if (rs != null) { rs.close(); } /* * if (st != null) { st.close(); } */ if (conn != null) { conn.close(); } } }
運行api
輸入正確帳號密碼能夠登錄成功。這裏能夠被繞過。安全
很顯然這是萬能密碼。那麼如何去修復sql注入呢,這裏比較好的方法是採用預編譯的開發方式,這是個開發習慣問題。測試
修復後的預編譯代碼以下:網站
package cn.basic.jdbc; import java.awt.image.RescaleOp; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import org.junit.jupiter.api.Test; public class Test1 { /* * public static void main(String[] args) throws ClassNotFoundException, * SQLException { login("aa","aa"); } */ @Test public void testlogin() throws ClassNotFoundException, SQLException { login("aa", "aa"); } public static void login(String username, String password) throws SQLException, ClassNotFoundException { Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1/test", "root", "root"); String sql="select * from xxx where username=? and password=?"; //使用預編譯 PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, username); ps.setString(2, password); ResultSet rs = ps.executeQuery(); if (rs.next()) { System.out.println("恭喜" + username + "登錄成功"); System.out.println(sql); } else { System.out.println("登陸失敗"); } if (rs != null) { rs.close(); } if(ps!=null) { ps.close(); } /* * if (st != null) { st.close(); } */ if (conn != null) { conn.close(); } } }
再來測試下是否存在安全漏洞:spa
輸入正確密碼:code
嘗試萬能密碼繞過:
這裏杜絕了sql注入的產生,在不少時候,要養成用預編譯編方式實現增刪改查,這裏以查詢爲例子,增刪改同理!
預編譯並不表明百分百防止sql注入的,這只是一種防止sql注入的措施。
不忘初心,方得始終。