1 5 package org.h2.test.db; 6 7 import java.sql.Connection ; 8 import java.sql.PreparedStatement ; 9 import java.sql.ResultSet ; 10 import java.sql.SQLException ; 11 import java.sql.Statement ; 12 13 import org.h2.test.TestBase; 14 15 public class TestSQLInjection extends TestBase { 16 17 Connection conn; 18 Statement stat; 19 20 public void test() throws Exception { 21 deleteDb("sqlinjection"); 22 reconnect("sqlinjection"); 23 stat.execute("DROP TABLE IF EXISTS USERS"); 24 stat.execute("CREATE TABLE USERS(NAME VARCHAR PRIMARY KEY, PASSWORD VARCHAR, TYPE VARCHAR)"); 25 stat.execute("CREATE SCHEMA CONST"); 26 stat.execute("CREATE CONSTANT CONST.ACTIVE VALUE 'Active'"); 27 stat.execute("INSERT INTO USERS VALUES('James', '123456', CONST.ACTIVE)"); 28 check(checkPasswordInsecure("123456")); 29 checkFalse(checkPasswordInsecure("abcdef")); 30 check(checkPasswordInsecure("' OR ''='")); 31 check(checkPasswordSecure("123456")); 32 checkFalse(checkPasswordSecure("abcdef")); 33 checkFalse(checkPasswordSecure("' OR ''='")); 34 stat.execute("SET ALLOW_LITERALS NONE"); 35 36 try { 37 check(checkPasswordInsecure("123456")); 38 error("Should fail now"); 39 } catch(SQLException e) { 40 checkNotGeneralException(e); 41 } 42 check(checkPasswordSecure("123456")); 43 checkFalse(checkPasswordSecure("' OR ''='")); 44 conn.close(); 45 46 if(config.memory) { 47 return; 48 } 49 50 reconnect("sqlinjection"); 51 52 try { 53 check(checkPasswordInsecure("123456")); 54 error("Should fail now"); 55 } catch(SQLException e) { 56 checkNotGeneralException(e); 57 } 58 check(checkPasswordSecure("123456")); 59 checkFalse(checkPasswordSecure("' OR ''='")); 60 conn.close(); 61 } 62 63 boolean checkPasswordInsecure(String pwd) throws SQLException { 64 String sql = "SELECT * FROM USERS WHERE PASSWORD='"+pwd+"'"; 65 ResultSet rs = conn.createStatement().executeQuery(sql); 66 return(rs.next()); 67 } 68 69 boolean checkPasswordSecure(String pwd) throws Exception { 70 String sql = "SELECT * FROM USERS WHERE PASSWORD=?"; 71 PreparedStatement prep = conn.prepareStatement(sql); 72 prep.setString(1, pwd); 73 ResultSet rs = prep.executeQuery(); 74 return(rs.next()); 75 } 76 77 private void reconnect(String name) throws Exception { 78 if(!config.memory) { 79 if(conn != null) { 80 conn.close(); 81 conn = null; 82 } 83 } 84 if(conn == null) { 85 conn = getConnection(name); 86 stat = conn.createStatement(); 87 } 88 } 89 } 90 | Popular Tags |