SSH tunneling, a fundamental aspect of secure shell client utility in Linux, allows for establishing secure connections
to remote or local SSH servers. While some programs may be inflexible in processing via SSH due to their design
limitations, SSH offers multiple options for redirecting secure traffic to accommodate such scenarios. Let’s explore
various cases and delve into how SSH tunneling functions.
Forwarding Ports at Localhost
Consider a scenario where an application is hardcoded to connect exclusively to the localhost server via a specified
port. Our objective is to redirect the traffic to a remote server using a different port, ensuring the transmission of
data in a secure, encrypted manner.
Script Body for Local Redirection:
#!/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
The script initiates a TCP server at port 9000 in the background. The SSH session redirects connections incoming to the
local port 5000 to the remote host 9000, allowing for secure redirection within the specified duration. The subsequent
commands verify the tunnel’s functionality before terminating it securely.
Forwarding Ports at the Remote Host
In scenarios where remote servers operate within a NAT, creating a secure connection is essential. Redirecting ports at
a central host to allow clients behind a NAT to connect is a viable solution.
Script Body for Remote Host Port Forwarding:
#!/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
The process remains similar to local port forwarding but involves redirecting remote host port 5000 to the localhost
port 9000. This method allows for secure communication even with hosts operating behind a NAT.
SSH Interface Tunneling
An alternative approach involves tunneling interfaces using SSH, exposing IP addresses securely to connect with remote
servers. Let’s consider a practical example.
Script for SSH Interface Tunneling:
#!/usr/bin/env bash
(ssh -tt root@192.168.144.207 -w 2:2 << EOF ifconfig tun2 10.1.1.1/24 pointopoint 10.1.1.2 up nc -l 10.1.1.1 9000 EOF ) 2>/dev/null | grep ok &
PID=$!
sleep 1
ifconfig tun2 10.1.1.2/24 pointopoint 10.1.1.1 up
echo ok | nc -N 10.1.1.1 9000
This script establishes a secure SSH connection and creates tun interfaces to facilitate secure communication between
localhost and the remote server. The commands configure interfaces, set up IP addresses, and initiate a TCP server for
secure transmission.
These advanced SSH tunneling techniques offer versatile solutions for redirecting ports and establishing secure
connections in Linux systems, catering to diverse networking requirements.