SQL Injection Cheatsheet

Overview

SQL injection occurs when user input is not properly sanitized and is directly concatenated into SQL queries. This allows attackers to manipulate database queries and potentially extract data, bypass authentication, or execute commands.

Common Injection Points:

  • Login forms (username/password fields)

  • Search parameters

  • URL parameters

  • HTTP headers (User-Agent, X-Forwarded-For)

  • JSON/XML parameters


Authentication Bypass

Basic Auth Bypass

-- Username field payloads
admin' or '1'='1'-- -
admin' or 1=1-- -
admin'/**/or/**/1=1-- -
admin' or 'x'='x'-- -

-- Simple comment-out approach (HTB Academy example)
tom'; -- -

-- OR logic bypass approach (HTB Academy example)  
tom' OR '1' = '1' -- -

-- Password field (when username is known)
anything' or '1'='1'-- -

SQL Comments Deep Dive

Comment Syntax Rules

Why Comments Work

Auth Bypass with Comments

Complex Query Scenarios

Scenario 1: Simple Query

Scenario 2: Parenthesis Challenge

Scenario 3: Targeting Specific ID (HTB Academy)

Scenario 4: Multiple Conditions

Troubleshooting Syntax Errors

Advanced Auth Bypass


UNION Injection

Understanding UNION Clause

What is UNION?

UNION clause combines results from multiple SELECT statements into a single result set. This allows SQL injection to extract data from multiple tables and databases.

Basic UNION Example:

Critical UNION Requirements

1. Equal Column Count

2. Compatible Data Types

How UNION Injection Works

Handling Uneven Columns

Problem: Different Column Counts

Solution: Junk Data

Why Numbers Work Best:

  • Tracking: Numbers help identify which column displays where

  • Universal: Numbers work with most data types

  • Simple: Easy to increment (1,2,3,4,5...)

Example with 4 Columns:

HTB Academy Practical Example: employees/departments UNION

Scenario: Combine all records from employees and departments tables with different column counts.

Step 1: Connect to MySQL

Step 2: Analyze Table Structure

Step 3: Handle Column Mismatch

Step 4: Result Analysis

Key Learning Points:

  • DESCRIBE reveals table structure before UNION

  • Dummy columns (3,4,5,6) fill missing positions

  • Subquery with COUNT() gets total without displaying all data

  • Data type compatibility - numbers work as universal placeholders

Column Detection

Method 1: ORDER BY Technique

How ORDER BY Works for Column Detection: ORDER BY sorts results by specified column number. If column doesn't exist β†’ error.

Step-by-Step Process:

Error Indicators:

  • Unknown column 'X' in 'order clause' β†’ Column X doesn't exist

  • Empty/no results β†’ Column X doesn't exist

  • Database error β†’ Column X doesn't exist

Method 2: UNION Technique

How UNION Works for Column Detection: UNION requires equal column count. Mismatch β†’ error. Match β†’ success.

Step-by-Step Process:

Comparison: ORDER BY vs UNION

  • ORDER BY: Always succeeds until error (incremental success β†’ failure)

  • UNION: Always fails until success (incremental failure β†’ success)

  • Recommendation: ORDER BY is often faster and more reliable

Location of Injection (Critical Concept!)

Problem: Not all columns display output on the webpage!

Example Scenario:

Testing Which Columns Display:

Practical Data Extraction:

HTB Academy Question Solution:

Basic UNION Injection

Step-by-Step UNION Injection Process

1. Detect Injection Point

2. Detect Number of Columns

3. Identify Displayed Columns

4. Extract Data

Data Extraction via UNION


Database Enumeration

MySQL Fingerprinting

Why Fingerprint? Different DBMS use different syntax. Knowing the database type determines which payloads to use.

MySQL Fingerprinting Techniques:

Payload
When to Use
Expected Output (MySQL)
Wrong Output (Other DBMS)

SELECT @@version

Full query output

10.3.22-MariaDB-1ubuntu1

MSSQL version / Error

SELECT POW(1,1)

Numeric output only

1

Error

SELECT SLEEP(5)

Blind/No output

5-second delay + returns 0

No delay

Practical Fingerprinting:

INFORMATION_SCHEMA Database

What is INFORMATION_SCHEMA?

  • Built-in MySQL database containing metadata about all databases/tables

  • Contains structure information, not actual user data

  • Critical for SQL injection enumeration

  • Always present in MySQL installations

Key Tables in INFORMATION_SCHEMA:

  • SCHEMATA β†’ Database names

  • TABLES β†’ Table names per database

  • COLUMNS β†’ Column names per table

Cross-Database Queries with Dot Operator:

Step-by-Step Enumeration Process

Step 1: Identify Current Database

Step 2: Discover All Databases

Filter Strategy:

Step 3: Enumerate Tables in Target Database

Step 4: Enumerate Columns in Target Table

Step 5: Extract Data

HTB Academy Practical Example

Scenario: ilfreight application with dev database containing credentials

Complete Enumeration Walkthrough:

HTB Academy Question Solution:

Quick Reference Payloads

One-liner enumeration payloads for quick testing:

Data Extraction


Privilege and Configuration Enumeration

User Information

Privilege Enumeration


File Operations

Prerequisites: Privilege Verification

Why Check Privileges? File operations require special database privileges. Not all users can read/write files.

Step 1: Identify Current Database User

Analysis:

  • root = High privileges (DBA) β†’ Likely has FILE privilege

  • app_user = Limited privileges β†’ May not have FILE privilege

Step 2: Check Superuser Privileges

Step 3: Enumerate Specific Privileges

Step 4: Check FILE Privilege Restrictions

HTB Academy Complete Walkthrough

Scenario: Reading Application Source Code to Find Database Credentials

Step 1: Verify User and Privileges

Step 2: Read Target Application Source

Step 3: Analyze Source Code for Include/Require

Step 4: Read Configuration Files

HTB Academy Question Solution:

Common File Reading Targets

System Information

Web Application Files

Log Files (Information Gathering)

Windows File Reading

Quick Reference: File Reading Payloads

Prerequisites: FILE privilege verified above βœ…

File Writing

⚠️ High Risk Operation: File writing can lead to Remote Code Execution (RCE) and complete server compromise.

Prerequisites Verification (Critical!)

3 Requirements for File Writing:

  1. User with FILE privilege βœ… (verified above)

  2. secure_file_priv allows writing ❓ (must check)

  3. Write access to target directory ❓ (must test)

Step 1: Verify secure_file_priv Setting

What is secure_file_priv?

  • MySQL security variable that restricts file operations

  • Controls WHERE files can be read/written

  • Critical for determining write capabilities

Check secure_file_priv Value:

Expected HTB Academy Result:

Step 2: Test Write Permissions

Verify write access with test file:

Result Analysis:

  • No SQL errors = Write operation succeeded βœ…

  • File accessible via web = Web path correct βœ…

  • Shows "1...3 4" = UNION columns included in output

Step 3: Deploy Web Shell

Clean Output Technique:

Step 4: Execute Commands

Web Shell Usage:

HTB Academy Complete Walkthrough

Scenario: Complete File Writing Attack Chain

Step 1: Verify Prerequisites

Step 2: Deploy Web Shell

Step 3: Verify Web Shell

Step 4: Find Flag (HTB Academy Question)

Advanced Web Shell Variants

Enhanced Web Shells

Binary Data Writing

Web Root Discovery Techniques

When /var/www/html doesn't work:

Configuration File Analysis

Common Web Root Locations

Quick Reference: File Writing Payloads

HTB Academy Solution Path:

  1. βœ… Verify secure_file_priv (empty = unrestricted)

  2. βœ… Test write with proof.txt

  3. βœ… Deploy shell.php with clean output

  4. βœ… Execute commands via ?0= parameter

  5. βœ… Find and read flag file


HTB Academy Skills Assessment: Complete Attack Chain

Scenario: Web Application with Login Form β†’ Remote Code Execution β†’ Flag Capture

Target: Web application with login form and search functionality Goal: Gain RCE and find flag in / root directory

Phase 1: Authentication Bypass

Step 1: Identify Login Form

Step 2: SQL Injection Authentication Bypass

Phase 2: SQL Injection Discovery & Exploitation

Step 3: Find Injectable Parameter

Step 4: Column Detection

Phase 3: Privilege Enumeration

Step 5: Identify Database User

Step 6: Enumerate User Privileges

Phase 4: File Operations

Step 7: Test File Reading

Step 8: Verify Write Restrictions

Phase 5: Web Shell Deployment

Step 9: Deploy Web Shell

Step 10: Verify Web Shell

Phase 6: Flag Capture

Step 11: Search for Flag

Step 12: Read Flag

Complete Attack Chain Summary

1. Authentication Bypass:

2. SQL Injection Discovery:

3. UNION Exploitation:

4. Privilege Verification:

5. Web Shell Deployment:

6. Remote Code Execution:

Key Learning Points

Practical Considerations:

  • Directory permissions matter β†’ /var/www/html/dashboard/ vs /var/www/html/

  • Clean output techniques β†’ "" for empty columns, sed -e '1,2d' for curl

  • URL encoding β†’ + for spaces in commands

  • File path discovery β†’ Root directory flag location

Attack Chain Dependencies:

  1. Authentication bypass β†’ Access to vulnerable functionality

  2. SQL injection discovery β†’ Entry point for exploitation

  3. Column detection β†’ Required for UNION queries

  4. Privilege enumeration β†’ Determines attack capabilities

  5. File operations β†’ Enables web shell deployment

  6. RCE execution β†’ Achieves ultimate goal

Success Indicators:

  • βœ… No SQL errors = Operations succeeded

  • βœ… Clean web shell output = Proper deployment

  • βœ… Command execution = RCE achieved

  • βœ… Flag content = Mission accomplished


Blind SQL Injection

Boolean-based Blind

Time-based Blind

Manual Time-based Payloads

Advanced Time-based Data Extraction

SQLMap Advanced Time-based Attacks

High-Performance Time-based (Maximum Aggressiveness):

JSON Time-based Injection:

Complex Headers + Time-based:

Time-based with WAF Bypass:

Time-based Performance Optimization

Speed vs Accuracy Trade-offs:

Network-Optimized Time-based:

Time-based Troubleshooting

Common Time-based Issues:

1. False Positives (Network Delays):

2. WAF Blocking Time-based:

3. Timeout Issues:

4. No Time-based Detection:

Advanced Time-based Scenarios

Bypassing Length Restrictions:

Multi-Parameter Time-based:

Quick Reference: Advanced Time-based


Error-based Injection

MySQL Error-based

SQL Server Error-based


WAF Bypass Techniques

Comment Variations

Case Variations

Character Encoding

Alternative Operators


Second-Order SQL Injection

Concept

Second-order injections occur when:

  1. Malicious input is stored in database

  2. Later retrieved and used in another SQL query

  3. No sanitization on retrieval/usage

Example Payload Storage


Advanced Techniques

Stacked Queries

NoSQL Injection (for comparison)


Prevention and Detection

Secure Coding Practices

Detection Indicators

  • Unusual SQL keywords in logs

  • Unexpected database errors

  • Abnormal response times

  • Multiple similar requests with variations

  • File system access attempts

  • Large data extractions


Quick Reference Commands

Essential Testing Payloads

Tool Integration

SQLMap Comprehensive Cheat Sheet

Basic Usage & Help

Request Types & Methods

Headers & Authentication

Output & Verbosity

Attack Tuning & Advanced Options

Prefix/Suffix Customization

What are Boundaries? Every SQLMap payload consists of:

  • Vector: Core SQL code (e.g., UNION ALL SELECT 1,2,VERSION())

  • Boundaries: Prefix/suffix formations for proper injection

When to Use Prefix/Suffix:

Real Example (HTB Academy Case #6):

Level/Risk Settings

Level (1-5, default 1):

  • Level 1: 72 payloads (most common boundaries/vectors)

  • Level 5: 7,865 payloads (extensive boundary combinations)

  • Higher level = more boundaries tested = slower but more thorough

Risk (1-3, default 1):

  • Risk 1: Safe payloads only

  • Risk 2: Includes medium-risk payloads

  • Risk 3: Includes OR payloads (dangerous - can modify data)

Usage Examples:

Risk Level Considerations:

Advanced Tuning Options

Status Code Detection:

Title-based Detection:

String-based Detection:

Text-only Comparison:

Technique Selection

Available Techniques:

  • B: Boolean-based blind

  • E: Error-based

  • U: UNION query-based

  • S: Stacked queries

  • T: Time-based blind

Custom Technique Selection:

UNION SQLi Tuning

Column Number Specification:

Oracle FROM Clause:

Bypassing Web Application Protections

Anti-CSRF Token Bypass

Problem: Modern web applications use anti-CSRF tokens that change with each request, breaking automation.

Solution: SQLMap can automatically handle CSRF tokens.

Process Example:

Unique Value Bypass

Problem: Application requires unique parameter values to prevent automation.

Solution: Randomize parameter values with --randomize.

Calculated Parameter Bypass

Problem: Application expects calculated parameter values (e.g., MD5 hash validation).

Solution: Use --eval to calculate parameters dynamically.

Common Eval Examples:

IP Address Concealing

Proxy Usage:

Tor Network Usage:

User-Agent Blacklisting Bypass

Problem: Default SQLMap user-agent is blacklisted (User-agent: sqlmap/1.4.9).

Solution: Use random browser user-agents.

WAF Detection & Bypass

WAF Detection Process:

Comprehensive Tamper Scripts Reference

Popular Tamper Scripts:

Script
Description
Use Case

between

Replaces > with NOT BETWEEN 0 AND #, = with BETWEEN # AND #

Bypass XSS-focused filters

space2comment

Replaces spaces with /**/ comments

Common WAF bypass

randomcase

Randomizes keyword case (SELECT β†’ SEleCt)

Case-sensitive filters

charencode

URL-encodes all characters

Character-based filtering

base64encode

Base64-encodes entire payload

Content inspection bypass

percentage

Adds % before each character (SELECT β†’ %S%E%L%E%C%T)

Character obfuscation

space2plus

Replaces spaces with +

URL encoding bypass

space2dash

Replaces spaces with -- comments

SQL comment injection

versionedkeywords

Encloses keywords in MySQL version comments

MySQL-specific bypass

modsecurityversioned

Wraps query in MySQL versioned comments

ModSecurity bypass

Advanced Tamper Examples:

Advanced Bypass Techniques

Chunked Transfer Encoding:

HTTP Parameter Pollution (HPP):

HTB Academy Case Solutions

Case #8 (WAF Bypass):

Case #9 (CSRF Protection):

Case #10 (User-Agent Filtering):

Case #11 (Advanced Protection):

Quick Reference: Protection Bypass

HTB Academy Examples

Case #5 (High Risk):

Case #6 (Custom Boundaries):

Case #7 (Advanced Tuning):

Quick Reference: Attack Tuning

Advanced Database Enumeration

Database Schema Analysis

Complete Schema Enumeration:

Example Schema Output:

Analysis Benefits:

  • Complete architecture overview - all databases, tables, columns

  • Data type identification - varchar, int, datetime, blob

  • Column count verification - useful for manual UNION attacks

  • Target identification - spot interesting tables/columns

Advanced Search Functionality

Search Tables by Name:

Search Columns by Name:

Search Pattern Examples:

Automatic Password Hash Cracking

Password Table Enumeration:

Hash Cracking Process:

Cracked Results Display:

Database User Password Cracking

System User Password Enumeration:

Example Database User Results:

Complete Automatic Enumeration

All-in-One Enumeration:

Caution with --all:

  • Very time-consuming - can run for hours

  • Generates massive output - requires manual analysis

  • May trigger detection - extensive database queries

  • Use selectively - better to target specific data

HTB Academy Examples

Case #1 - Column Search:

Case #1 - Password Extraction:

Quick Reference: Advanced Enumeration

Database Enumeration

Privilege & Security

OS Exploitation

DBA Privilege Verification

Why Check DBA Privileges?

  • File operations require special database privileges

  • DBA status greatly increases success probability

  • Modern DBMS restrict file operations for security

Check DBA Status:

File Read Operations

Prerequisites for File Reading:

  • MySQL: LOAD DATA and INSERT privileges

  • DBA privileges (preferred but not always required)

  • File system permissions on target files

Basic File Reading:

View Retrieved File:

Common Target Files:

File Write Operations

Prerequisites for File Writing:

  • DBA privileges (usually required)

  • --secure-file-priv disabled or unrestricted

  • Write permissions on target directory

  • Web server access to written files

Basic File Writing Process:

Alternative Web Shells:

Automated OS Shell

Direct OS Shell Access:

OS Shell Deployment Process:

Troubleshooting OS Shell Issues

Common Problems & Solutions:

1. No Output from UNION Technique:

2. Permission Denied Errors:

3. Web Root Discovery:

Advanced OS Exploitation Techniques

Multiple Technique Testing:

Custom Shell Upload:

HTB Academy Examples

Flag Reading Challenge:

Interactive OS Shell Challenge:

Quick Reference: OS Exploitation

Complete Enumeration Workflow

Quick Reference Commands

Burp Suite Integration

Last updated