SSH:TDG
SSH: The Secure Shell (The Definitive Guide)
Barrett, Silverman, & Byrnes / O’Reilly

SSH Frequently Asked Questions

TCP port forwarding and the -g (GatewayPorts) option


When you forward a TCP port (either locally or remotely), by default SSH only listens for connections to the forwarded port on the loopback address (localhost, 127.0.0.1). This means only other programs running on the same host as the listening side of the forwarding can connect to the forwarded port. This is a security feature, since there is no authentication applied to such connections. Also, such a forwarded connection is potentially insecure, since a portion of it is carried over the network in a plain TCP connection and not protected by SSH.

However, in some circumstances you may need to connect to a forwarded port from off-host. Or, you may need to connect to it from the same host, but using the host's real IP address rather than the loopback address (usually this is because you're forwarding a protocol which cares about such things, like FTP). To do this for local forwardings, use the -g option (or set GatewayPorts yes in the client configuration file).

For remote forwardings with SSH-2, you may use the same option (although note that as of OpenSSH-2.3.0, remote forwarding is still not implemented in protocol 2). However, for remote forwardings in SSH-1, the situation is more complicated. There is no provision in the SSH-1 protocol to allow the client to indicate which addresses it wants the server to listen on for a remote forwarding; the message contains only a port number. So the GatewayPorts setting is global on the server side. In SSH1, this is not configurable: GatewayPorts is always turned on on the server side, and so all remote forwardings are accessible from anywhere. If you compile SSH1 with TCP-wrappers, then you can limit access to remotely forwarded ports using the /etc/hosts.{allow,deny} files; the service name for forwarded port n is sshfwd-n. Note that this technique is global to the server machine and can't be changed on a per-connection or per-user basis. It is also an easy source code fix to change this behavior of sshd1: in SSH-1.2.30, file newchannels.c, line 1632 is:

channel_request_local_forwarding(port, hostname, host_port, 1);

Simply change the 1 to a 0 to limit all remote forwardings to localhost.

In OpenSSH/1, the server recognizes the GatewayPorts option in its configuration file. Again, the default setting is "no", and setting it to "yes" affects all remote forwardings, so think carefully before doing this.