Using AutoSSH for SSH Tunneling and Internal Port Forwarding

Overview

The Secure Shell (SSH) protocol was developed by Finnish researcher Tatu Ylonen in 1995 to address security concerns in early internet communications. As plaintext communication was vulnerable to interception, SSH introduced encryption to protect login credentials and data. Today, SSH is a standard component of Linux systems and widely adopted globally.

The security of SSH relies on public-key cryptography. It's important to note that SSH is a protocol with various implementations, both commercial and open-source. This discussion focuses on OpenSSH, a free and extensively used implementation.

Prerequisites

  • A public VPS
  • An internal VPS

Public Host Configuration

Modify /etc/ssh/sshd_config to enable port forwarding:

GatewayPorts yes

The GatewayPorts directive in SSH controls which IP addresses the server binds to when listaning on a port. By default, SSH binds only to the loopback interface (127.0.0.1), restricting access to local connections. Setting GatewayPorts to yes allows the server to bind to all available network interfaces, enabling remote hosts to connect via SSH to those ports.

Internal Host Setup

  1. Generate an SSH key pair:

    ssh-keygen
    
  2. Copy the public key to the public host:

    ssh-copy-id -i /root/.ssh/id_rsa.pub -p 22 root@public_host_ip
    
  3. Install AutoSSH on the internal host (update package lists if needed):

    sudo apt-get install autossh
    

Testing the Setup

Initiate the tunnel using AutoSSH:

autossh -p 22 -M 23451 -NR 23452:localhost:22 root@public_host_ip

Parameter explanation:

  • -p 22: Specifies the SSH port on the internal VPS (default is 22).
  • -M 23451: Sets the monitoring port for the proxy service on the public VPS; ensure it's not in use.
  • -NR 23452:localhost:22: Maps port 23452 on the public VPS to port 22 on the internal VPS.

To run the process in the background:

nohup autossh -p 22 -M $listen_port -NR $mapped_port:localhost:22 root@$host &

Additional Notes

Use netstat -ant to inspect active TCP ports.

Tags: ssh autossh tunneling port-forwarding network-security

Posted on Thu, 14 May 2026 00:57:52 +0000 by rkstevens