Forward Local Unix Socket Over SSH to Ubuntu

This guide explains how to securely forward a local Unix domain socket to a remote Ubuntu Linux server using SSH. By leveraging SSH stream local forwarding, you can bridge local and remote socket-based applications without exposing them to the public internet. This article covers the exact SSH commands, configuration requirements, and troubleshooting steps needed to establish this connection.

Prerequisites

Step 1: The SSH Forwarding Command

To forward a local Unix socket to a remote server, use the SSH remote port forwarding flag (-R). The syntax requires specifying the path to the remote socket followed by the path to the local socket.

Run the following command on your local machine:

ssh -R /var/run/remote.sock:/tmp/local.sock user@ubuntu-server

In this command: * /var/run/remote.sock is the path where the socket will be created on the remote Ubuntu server. * /tmp/local.sock is the path to your existing local Unix socket. * user@ubuntu-server represents your remote SSH login credentials.

Step 2: Configure Automatic Socket Cleanup

By default, if the remote socket file already exists from a previous session, OpenSSH will fail to recreate it, resulting in a “bind: Address already in use” error.

To configure the Ubuntu server to automatically delete the old socket file when a new connection is established:

  1. Open the SSH daemon configuration file on your remote Ubuntu server:

    sudo nano /etc/ssh/sshd_config
  2. Add or uncomment the following line:

    StreamLocalBindUnlink yes
  3. Save the file and restart the SSH service to apply the changes:

    sudo systemctl restart ssh

If you do not have administrative access to modify sshd_config, you must manually remove the remote socket file before running the SSH command:

ssh user@ubuntu-server "rm -f /var/run/remote.sock" && ssh -R /var/run/remote.sock:/tmp/local.sock user@ubuntu-server

Step 3: Verify the Connection

Once the SSH session is active, verify that the socket has been successfully created on the remote Ubuntu server by listing the file:

ls -la /var/run/remote.sock

You can test the communication flow through the forwarded socket using netcat on the remote server:

nc -U /var/run/remote.sock