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
- OpenSSH version 6.7 or newer installed on both the local machine and the remote Ubuntu server (modern Ubuntu versions have this by default).
- SSH access to the remote Ubuntu server with appropriate permissions to create socket files in the target directory.
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-serverIn 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:
Open the SSH daemon configuration file on your remote Ubuntu server:
sudo nano /etc/ssh/sshd_configAdd or uncomment the following line:
StreamLocalBindUnlink yesSave 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-serverStep 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.sockYou can test the communication flow through the forwarded socket
using netcat on the remote server:
nc -U /var/run/remote.sock