SQL Injection 은 사용자가 요상한 문자열을 입력해서 쿼리를 요상하게 바꿔 버려서 아무 아이디로나 로그인이 훅 되버린다던지 하는 쪼금은 싱거운 해킹방법중의 하나라고 나는 알고 있다.


뭐 예를들어 아이디 비번을 입력하고 로그인 할때

아이디로  
admin' OR '1'='1 요런걸 입력하고 로그인을 했을때 admin 으로 싹 로그인 되 버리는 어처구니 없는 일이 발생하는 것이 SQL Injection 처리를 쪽바로 해주지 않았을때 일어나는 참혹한 일이다.


SQL Injection 이 발생하는 전형적인 코드는 다음과 같다.

1
2
3
4
5
6
7
8
9
10
11
12
String userid=request.getParameter("userid");
String password=request.getParameter("password");
 
....
....
 
Statement stmt = conn.createStatement();
ResultSet rs =
   stmt.executeQuery("select count(*) as cnt from member where userid='"+userid+"' and password='"+password+"'");
 
....
....




위 코드처럼 사용자 정보를 받아서 쿼리를 실행하고 실행결과가 1 이면 로그인 시켜주는 코드가 있다.

그런데 사용자가 아디디로 admin' OR '1'='1  을 입력하고 비밀번호로 abcd 를 입력한 후 로그인 시켜주셈~ 이라고 하면 우째될까?

위 코드대로라면  select count(*) from member where userid='amdin' OR '1'='1' and password = 'abcd'   이 쿼리가 실행되 버린다 -_-;;;

무섭다. 만약 사용자 테이블에 userid 가 admin 이라는 레코드가 있다면 admin 으로 로그인 되버리는 것이다. 

이런 어처구니 없는일이 놀랍게도 몇몇 허접한 사이트에서는 더러 통하는데도 있다 . -_-



아무튼 헛소리는 고만하고 본론으로 들어가서 SQL Injection 을 방지하려면 우째해야 될까? 

Statement 대신  PreparedStatement 를 쓰면 된다. 요렇게.

1
2
3
4
5
6
7
8
9
10
11
....
....
 
PreparedStatement stmt = conn.prepareStatement("select count(*) from member where userid=? and password=?");
stmt.setString(1, userid);
stmt.setString(2, password);
 
ResultSet rs = stmt.executeQuery();
 
....
....




PreparedStatement 만 쓰면 해결된다고 해서 또 요렇게는 쓰지 말길 -.-;

1
2
PreparedStatement stmt =
   conn.prepareStatement("select count(*) from member where userid='" + userid + "'" and password='" + password + "'");




※ 하이버네이트는 한번도 안써봐서 잘 모르겠는데 mybatis 나 ibatis 같은 경우는 무난하게 #{xxxx} 요런것만 썼다면 SQL Injection 이 방지된다. 

그런데 WHERE 절에 ${xxxx} 이렇게 있다면 다시 한번 생각해 보기 바란다. 

${xxxx} 이거는 문자열 더하는것과 똑같기 때문에 위험하다. ${xxxx} 요런건 ORDER BY 절 같은데만 사용하자.

'Computer > JSP Servlet JavaScript' 카테고리의 다른 글

JavaScript 예제  (0) 2015.01.15
JSP navigation 마우스오버 Script  (0) 2015.01.14
JSP 버튼이벤트  (0) 2014.08.19
JQUERY 화면전환 없이 비동기 업로드  (0) 2014.08.18
JSP Modal 사용하기  (0) 2014.08.14

+ Recent posts