> For the complete documentation index, see [llms.txt](https://zero-day-archives.gitbook.io/zero-day-archives/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://zero-day-archives.gitbook.io/zero-day-archives/network-pivoting-port-forwarding-and-tunneling/ssh-tunneling/ssh-local-port-forwarding.md).

# SSH Local Port Forwarding

### Understanding SSH Local Port Forwarding

SSH local port forwarding allows you to create a secure tunnel between your local machine and a remote system, forwarding traffic from a local port to a destination through the SSH connection. This is useful when you need to access services on a remote network that are not directly reachable.

### How It Works

1. An SSH connection is established between the client and the server.
2. The client opens a local listening port.
3. Traffic sent to this local port is securely forwarded through the SSH tunnel to a specified destination.

### Command Syntax

To create an SSH local port forward, use the following command:

```bash
ssh -N -L [LOCAL_IP:LOCAL_PORT]:[TARGET_IP:TARGET_PORT] [USER]@[SSH_SERVER]
```

#### Explanation:

* `-N`: Prevents SSH from executing remote commands, keeping the tunnel open.
* `-L`: Specifies local port forwarding.
* `[LOCAL_IP:LOCAL_PORT]`: The IP and port where traffic will be received on the client machine.
* `[TARGET_IP:TARGET_PORT]`: The destination where traffic will be forwarded.
* `[USER]@[SSH_SERVER]`: Credentials and address of the SSH server facilitating the tunnel.

### Example Use Case

Imagine you need to access an internal service running on port `445` of a remote machine, but it is only accessible from within the network. You can forward this port to your local machine like this:

```bash
ssh -N -L 0.0.0.0:4242:172.16.50.10:445 user@ssh-server
```

#### Breakdown:

* `0.0.0.0:4242`: The port `4242` on your local machine will now listen for incoming connections.
* `172.16.50.10:445`: The traffic is forwarded to port `445` on the internal network host.
* `user@ssh-server`: SSH credentials and server address used to establish the tunnel.

Once this command is executed, any connection made to `localhost:4242` on your machine is securely forwarded to `172.16.50.10:445` via the SSH tunnel.

### Verifying the Tunnel

After setting up the SSH tunnel, you can check if the port is listening using:

```bash
ss -ntplu | grep 4242
```

This should show the local port as open and listening.

You can then interact with the forwarded service as if it were running locally.

### Closing the Tunnel

To close the SSH tunnel, simply terminate the SSH session by pressing `Ctrl+C` or running:

```bash
kill $(pgrep -f "ssh -N -L")
```
