Penetration Testing

Sqlmap - Automated SQL Injection Tool

It automates the process of finding and exploiting these vulnerabilities, allowing security professionals to test the robustness of their database security.

10 min read
Exploit by SQL Injection

sqlmap is a tool that automates obtaining control of database servers and injection or fault detection and exploitation.

SQLMap written in python, so to run this tool we need to install python on our system. No matter which OS we are using. We just need to install python and then run the following commands to install Sqlmap.

Requirements before install Sqlmap:

  1. Python (version: 2.6, 2.7 or 3.x)
  2. Git

You can install sqlmap in two ways.

  • clone git repo
  • using tarball
  • linux command

Install by git repo

git clone —depth 1 https://github.com/sqlmapproject/sqlmap.git sqlmap-dev && cd sqlmap-dev

To run the sqlmap, just type the following commands:

python3 sqlmap.py -h

or

python sqlmap.py -h

Install by tarball Download latest tarball from: Gihub Repo

Extract the tar and enter the root folder, then run the python command that we shared earlier.

Install by Linux Command For debian based destro:

sudo apt-get install sqlmap

For Arch based destro

sudo pacman -Syy sqlmap

For RedHat based destro

sudo yum install sqlmap

That’s it. Once SQLmap is installed, you need a vulnerable target to see its magic.

The basic command structure is straightforward. First, you write sqlmap and then URL followed by specific wildcards of where you want the injection to occur.

This following command performs SQL injection on the target database and reports back if the specified target has a vulnerability or not. But you must get the list of available databases at the target machine.

sqlmap -u “url”

–dbs option here will enlist all the available databases on the target machine if the target is vulnerable to SQL injection. Once you get the list of your databases, the next step is to get the list of all the tables of the selected database.

sqlmap -u “url” —dbs

–table option is used to extract the list of all the tables in the selected database. -D option is used to specify the database name you found in the previous step. Next, you need to enlist all the columns in the table.

sqlmap -u “url” —tables -D database-name.

Now “–columns” option will tell the sqlmap to get the name of all the columns, and an additional -T argument is used to specify the table name from which you want to enlist all the columns.

sqlmap -u “url” —columns -D database-name -T table-name

Once you get the columns’ names, either you can dump the whole columns’ data into a CSV file from the database, or you can dump the data from selected fields.

sqlmap -u “url” —dump -D database -name -T table-name

Here this command will tell the sqlmap to dump all the data from the database-name where table table-name exists. You can also dump the whole database by using the following command.

sqlmap -u “url” —dump -D database-name.

To see if the current user has root access to the database management system, issue the following command.

sqlmap -u "url" -o -b --current-user --is-dba

If current user turns out be a root user you can extract the password for that user and all the other users. Use the following command.

sqlmap -u "url" -v1 --current-user --password

SQLmap on multiple target list.

sqlmap is a very flexible tool. You can give it any number of target in a text file and it will test all the targets on time.

sqlmap -m "path-to-file" --batch 

here –batch option will process all the target with default options.
SQLmap also has password cracking capability. It can perform dictionary attack on the found hashes. Hash cracking process will take time according to your CPU power.


Basic options: The sqlmap command will not run without at least one of these options added to it.

CommandsDescriptions
-u URLThe target URL Format: -u ”http://www.target.com/path/file.htm?variable=1
-d DIRECTConnection string for direct database connection Format: -d DBMS://DATABASE_FILEPATH or -d DBMS://USER:PASSWORD@DBMS_IP:DBMS_PORT/DATABASE_NAME
-l LOGFILEParse target(s) from Burp or WebScarab proxy log file
-m BULKFILEScan multiple targets given in a textual file Format: The file should contain a URL per line
-r REQUESTFILELoad HTTP request from a file Format: The file can contain an HTTP request or an HTTPS transaction
-g GOOGLEDORKProcess Google dork results as target URLs
-c CONFIGFILELoad options from a configuration INI file
—wizardA guided execution service
—updateUpdate sqlmap to the latest version
—purgeClear out the sqlmap data folder
—purge-outputAs above
—dependenciesCheck for missing sqlmap dependencies
-hBasic help
-hhAdvanced help
—versionShow the sqlmap version number
-v VERBOSEVerbosity level

Verbosity option values: —fingerprint As above Possible verbosity level values are:

CommandsDescriptions
0Only Python tracebacks, error, and critical messages
1Feedback of 0 plus information and warning messages
2Feedback of 1 plus debug messages
3Feedback of 2 plus the payloads injected
4Feedback of 3 plus HTTP requests
5Feedback of 4 plus the HTTP headers of responses
6Feedback of 5 plus the content of the HTTP responses

Optimization The following options can be used to improve the performance of sqlmap.

CommandsDescriptions
-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=THREADSMax number of concurrent HTTP(s) requests (default 1)

Detection: The following options are used during research in the detection phase.

CommandsDescriptions
—level=LEVELThe level of tests to perform (1-5, default 1)
—risk=RISKThe risk of tests to perform (1-3, default 1)
—string=STRINGA string to match when query is evaluated to True
—not-string=FALSE-STRINGA string to match when query is evaluated to False
—regexp=REGEXPRegexp to match when query is evaluated to True
—code=CODEHTTP code to match when query is evaluated to True
—smartPerform thorough tests only if positive heuristic(s)

Brute force: These options implement checks during the launch of a brute force attack

CommandsDescriptions
—common-tablesCheck the existence of common tables
—common-columnsCheck the existence of common columns
—common-filesCheck the existence of common files

Miscellaneous: These options do not fit into any of the above categories.

CommandsDescriptions
-z MNEMONICSUse short mnemonics (e.g. “flu,bat,ban,tec=EU”)
—alert=ALERTRun host OS command(s) when SQL injection is found
—beepBeep on the question and/or when SQLi/XSS/FI is found
—disable-coloringDisable console output coloring
—list-tampersDisplay list of available tamper scripts
—offlineWork in offline mode (only use session data)
—results-file=RESULTS-FILELocation of CSV results file in multiple targets mode
—shellPrompt for an interactive sqlmap shell
—tmp-dir=TMPDIRLocal directory for storing temporary files
—unstableAdjust options for unstable connections

Level option values: This option dictates the volume of tests to perform and the extent of the feedback that they will provide. A higher value implements more extensive checks.

CommandsDescriptions
1A limited number of tests/requests; GET AND POST parameters will be tested (default)
2Test cookies
3Test cookies plus User-Agent/Referer
4As above plus null values in parameters and other bugs
5An extensive list of tests with an input file for payloads and boundaries

Techniques: These options relate to specific attack strategies. They adjust and focus the attack on particular techniques and targets.

CommandsDescriptions
—technique=TECHNIQUEThe SQL injection techniques to use (default “BEUSTQ”)
—time-sec=TIMESECThe number of seconds to delay the DBMS response (default 5)
—union-cols=UCOLSA range of columns to test for UNION query SQL injection
—union-char=UCHARA character to use for brute-forcing columns
—union-from=UFROMThe table to use in the FROM part of a UNION query SQL injection
—dns-domain=DNS-DOMAINThe domain name to use in a DNS exfiltration attack
—second-url=SECOND-URLResulting page URL searched for a second-order response
—second-req=SECOND-REQLoad a second-order HTTP request from the file
-fPerform an extensive DBMS version fingerprint
—fingerprintAs above

Request: Add these options to a command to specify how to connect to the target URL.

CommandsDescriptions
-A AGENTHTTP User-Agent header value
—user-agent=AGENTAs above
-H HEADERExtra header (e.g. “X-Forwarded-For: 127.0.0.1”)
—headers=HEADERSAs above
—method=METHODSpecify an HTTP method to use, such as POST or PUT
—data=DATAData string to be sent through POST (e.g. “id=1”)
—param-del=PARAMETERA character to be used for splitting parameter values (e.g., &)
—cookie=COOKIEHTTP Cookie header value (e.g. “PHPSESSID=a8d127e..“)
—cookie-del=COOKIE-CHARA character to be used for splitting cookie values (e.g. ;)
—live-cookies=LIVE-COOKIESA file containing live cookies to be used for loading values
—load-cookies=LOAD-COOKIESAs above with cookies in Netscape/wget format
—drop-set-cookieIgnore the Set-Cookie header in the response
—mobileImitate a smartphone through HTTP User-Agent header
—random-agentUse a randomly selected HTTP User-Agent header value
—host=HOSTAn HTTP Host header value
—referer=REFERERAn HTTP Referer header value
—auth-type=AUTH-TYPEAn HTTP authentication type (Basic, Digest, NTLM or PKI)
—auth-cred=AUTH-CREDHTTP authentication credentials (name:password)
—auth-file=AUTH-FILEHTTP authentication PEM cert/private key file
—ignore-code=IGNORE-CODEIgnore (problematic) HTTP error code (e.g. 401)
—ignore-proxyIgnore system default proxy settings
—ignore-redirectsIgnore redirection attempts
—ignore-timeoutsIgnore connection timeouts
—proxy=PROXYUse a proxy to connect to the target URL
—proxy-cred=PROXY-LOGINProxy authentication credentials (name: password)
—proxy-file=PROXY-LISTLoad proxy list from a file
—proxy-freq=PROXY-RATENumber of requests between the change of proxy from a given
list
—torUse Tor anonymity network
—tor-port=TORPORTSet the Tor proxy port to be other than the default
—tor-type=TORTYPESet the Tor proxy type (HTTP, SOCKS4 or SOCKS5 (default))
—check-torCheck to see if Tor is used properly
—delay=DELAYDelay in seconds between each HTTP request
—timeout=TIMEOUTSeconds to wait before timeout connection (default 30)
—retries=RETRIESNumber of retries upon timeout (default 3)
—randomize=RPARAMRandomly change the value for a given parameter(s)
—safe-url=SAFEURLURL address to visit frequently during testing
—safe-post=SAFE-POSTPOST data to send to a safe URL
—safe-req=SAFE-REQUESTLoad safe HTTP request from a file
—safe-freq=SAFE-FREQThe number of regular requests between visits to a safe URL
—skip-urlencodeSkip URL encoding of payload data
—csrf-token=CSRF-TOKENParameter used to hold the anti-CSRF token
—csrf-url=CSRF-URLURL to visit for extraction of anti-CSRF token
—csrf-method=CSRF-METHODHTTP method to use during anti-CSRF token page visit
—csrf-retries=CSRF-RETRIESNumber of retries to get the anti-CSRF token (default 0)
—force-sslForce usage of SSL/HTTPS
—chunkedUse HTTP chunked transfer encoded (POST) requests
—hppUse HTTP parameter pollution method
—eval=EVALCODEEvaluate the provided Python code before the request (e.g. “import hashlib;id2=hashlib.md5(id).hexdigest()“)

Injection: The following options can be used to specify which parameters to test for, provide custom injection payloads and optional tampering scripts.

CommandsDescriptions
-p TESTPARAMETERTestable parameter(s)
—skip=SKIPSkip testing for given parameter(s)
—skip-staticSkip testing parameters that do not appear to be dynamic
—param-exclude=PARAM-EXCLUDERegexp to exclude parameters from testing (e.g. “ses”)
—param-filter=PARAM-FILTERSelect testable parameter(s) by place (e.g. “POST”)
—dbms=DBMSForce back-end DBMS to provided value
—dbms-cred=DBMS-CREDENTIALSDBMS authentication credentials (user:password)
—os=OSForce back-end DBMS operating system to the provided value
—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
—suffix=SUFFIXInjection payload suffix string
—tamper=TAMPERUse given script(s) for tampering injection data

Risk option values: The number given as a parameter to the risk option specifies the extent to which the actions of the tests will expose the attacker. Tests performed in the lowest level will be hardly noticeable to the user, while tests in the higher category can result in mass changes to data.

CommandsDescriptions
1Quick, unnoticeable tests (default)
2Tests that involve lengthy, heavy data processing, such as time-based SQLI
3Adds OR-based SQLI and possible data manipulation

Operating system access: These options can be used to access the operating system supporting the DBMS.

CommandsDescriptions
—os-cmd=OSCMDExecute an operating system command
—os-shellPrompt for an interactive operating system shell
—os-pwnPrompt for an OOB shell, Meterpreter or VNC
—os-smbrelayOne-click prompt for an OOB shell, Meterpreter or VNC
—os-bofStored procedure buffer overflow exploitation
—priv-escDatabase process user privilege escalation
—msf-path=MSFPATHLocal path where Metasploit Framework is installed
—tmp-path=TMPPATHRemote absolute path of temporary files directory

General: These options provide the opportunity to set general operating parameters.

CommandsDescriptions
-s SESSIONFILELoad session from a stored (.sqlite) file
-t TRAFFICFILELog all HTTP traffic into a text file
—answers=ANSWERSSet predefined answers (e.g. “quit=N,follow=N”)
—base64=BASE64PARAMSParameter(s) containing Base64 encoded data
—base64-safeUse URL and filename safe Base64 alphabet (RFC 4648)
—batchNever ask for user input; use the default behavior
—binary-fields=BINARY-FIELDSThe result fields in binary format (e.g., “digest”)
—check-internetCheck the Internet connection before assessing the target
—cleanupClean up sqlmap-specific UDF and tables from the database
—crawl=CRAWLDEPTHCrawl the website starting from the target URL
—crawl-exclude=CRAWL-EXCLUDERegexp to exclude pages from crawling (e.g. “logout”)
—csv-del=CSVDELThe delimiter to use in CSV output (default ”,“)
—charset=CHARSETBlind SQL injection charset (e.g. “0123456789abcdef”)
—dump-format=DUMP-FORMATThe format of the data dump (CSV (default), HTML or SQLITE)
—encoding=ENCODINGCharacter encoding to use for data retrieval (e.g., GBK)
—etaDisplay the estimated time of arrival for each output
—flush-sessionFlush session files for the current target
—formsParse and test forms on the target URL
—fresh-queriesIgnore query results stored in the session file
—gpage=GOOGLEPAGEUse Google dork results starting from the given page number
—har=HARFILELog all HTTP traffic into a HAR file
—hexUse hex conversion during data retrieval
—output-dir=OUTPUT-DIRThe custom output directory path
—parse-errorsParse and display DBMS error messages from responses
—preprocess=PREPROCESSUse the named script(s) for preprocessing (request)
—postprocess=POSTPROCESSUse the named script(s) for postprocessing (response)
—repairRedump entries having an unknown character marker (?)
—save=SAVECONFIGSave options to a configuration INI file
—scope=SCOPERegexp for filtering targets
—skip-heuristicsSkip heuristic detection of SQLi/XSS vulnerabilities
—skip-wafSkip heuristic detection of WAF/IPS protection
—table-prefix=TABLE-PREFIXThe prefix to use for temporary tables (default: “sqlmap”)
—test-filter=TEST-FILTERSelect tests by payloads and titles (e.g. ROW)
—test-skip=TEST-SKIPSkip tests by payloads and titles (e.g., BENCHMARK)
—web-root=WEBROOTThe Web server document root directory (e.g. “/var/www”)

Subscribe to my newsletter

Receive my case study and the latest articles on my WhatsApp Channel.