SSH GatewayPorts and Port Forwarding
The GatewayPorts setting in the Ubuntu Linux SSH server
configuration determines whether remote hosts are allowed to connect to
ports forwarded via SSH tunnel. By default, SSH restricts forwarded
ports to the local loopback interface (127.0.0.1), meaning
only the SSH server itself can access them. Enabling
GatewayPorts allows the SSH daemon to bind forwarded ports
to external network interfaces, making the forwarded services accessible
to other devices on the local network or the internet.
The Default Behavior: GatewayPorts No
When GatewayPorts is set to no (the default
configuration), any remote port forwarding request initiated by an SSH
client (using the ssh -R command) will bind exclusively to
the server’s loopback address (127.0.0.1 or
::1).
For example, if you run the following command on a client machine:
ssh -R 8080:localhost:80 user@ubuntu-serverThe Ubuntu server will only listen for connections to port
8080 originating from within the server itself. Outside
users attempting to access
http://<ubuntu-server-IP>:8080 will have their
connections refused. This is a security measure designed to prevent
accidental exposure of internal services.
Enabling External Access: GatewayPorts Yes
Setting GatewayPorts to yes forces the SSH
server to bind remote port forwardings to the wildcard address
(0.0.0.0 or ::).
If this is enabled, the same command:
ssh -R 8080:localhost:80 user@ubuntu-serverwill cause the Ubuntu server to listen on port 8080
across all of its network interfaces. Consequently, any device that can
reach the Ubuntu server’s IP address can access the service being
forwarded from your local client machine.
Flexible Configuration: GatewayPorts Clientspecified
Setting GatewayPorts to clientspecified
offers a middle ground. It allows the SSH client to define how the
forwarded port should bind on the server.
- If the client specifies a bind address, the server respects it.
- If the client does not specify a bind address, the server binds to
the loopback interface (
127.0.0.1).
For example, with clientspecified enabled, the client
can choose to bind to all interfaces by prepending the port with an
asterisk or an empty IP:
ssh -R *:8080:localhost:80 user@ubuntu-serverOr bind strictly to a specific network interface IP on the server:
ssh -R 192.168.1.50:8080:localhost:80 user@ubuntu-serverHow to Configure GatewayPorts on Ubuntu
To modify this setting on an Ubuntu Linux SSH server, follow these steps:
Open the SSH daemon configuration file with root privileges:
sudo nano /etc/ssh/sshd_configLocate the line containing
GatewayPorts. If it is commented out with a#or does not exist, add or modify it to your desired setting:GatewayPorts yes(Alternatively, use
GatewayPorts clientspecifiedorGatewayPorts no).Save the file and exit the editor (in Nano, press
Ctrl+O,Enter, thenCtrl+X).Restart the SSH service to apply the changes:
sudo systemctl restart ssh