Forwarding port at localhost
First case: we have an application that is hardcoded to connect to the localhost server with a specified port. Our goal is to use a remote server with another port instead. Another point here is: transmit data secure (encrypted) way. Code for localhost test from client and server-side followed next.
Local redirecting overview:
At this schema, the server runs on the remote host at port 9000. But our client application expects it at localhost port 5000 only. Let’s expect it hardcoded in-app code.
Forwarding port at localhost script body:
#!/usr/bin/env bash nc -l 9000 & PID0=$! ssh alexey@localhost -L 5000:localhost:9000 sleep 4 & PID1=$! sleep 1 echo done | nc -N localhost 5000 sleep 1 kill -9 $PID0 $PID1 2> /dev/null
Forwarding port at localhost script executing console:
At the first string we create a TCP server at port 9000 in background mode (look that command ends with ‘&’ symbol). Next, we store server PID (process identity) at the local variable PID0. Then we run an ssh session to our own host with options that redirect connections incoming to local port 5000 to remote host 9000. -L option syntax: -L <local host port>:<remote host>:<remote host port to redirect connections from localhost port>. We run a session with the “sleep 4” command in background mode to turn on redirecting for 4 seconds and end the session then. Next, we store the PID of the ssh session to the PID1 variable. Next line we sleep for 1 second to be sure that the server starts and the ssh session started. Next line we send “done” text to port 5000 by using of nc command and close the session with -N. Next, we sleep for 1 second to process traffic redirection over a secure tunnel and get “done” at the output. Then sanity kill of run server and ssh tunneled session followed. As you can see it is possible to use any <remote server> against <localhost> in this script – to be able to work with remote server secure way. Even if the client app is not designed to work with it.
How to Create SSH Tunneling or Port Forwarding in Linux?
SSH is a secure shell standard client utility for Linux. It is used to establish secure connections to remote (or even local) ssh servers. But some programs are not designed flexible enough to be processed by ssh trivial way: the program can work with local connections only or some related network addresses be hard to code defined. That is why SSH contains several options to redirect secure traffic to match use cases like that. Let’s go from case to case to see how does it work.