# 19.11. Secure TCP/IP Connections with SSH Tunnels

It is possible to use SSH to encrypt the network connection between clients and a PostgreSQL server. Done properly, this provides an adequately secure network connection, even for non-SSL-capable clients.

First make sure that an SSH server is running properly on the same machine as the PostgreSQL server and that you can log in usingsshas some user; you then can establish a secure tunnel to the remote server. A secure tunnel listens on a local port and forwards all traffic to a port on the remote machine. Traffic sent to the remote port can arrive on itslocalhostaddress, or different bind address if desired; it does not appear as coming from your local machine. This command creates a secure tunnel from the client machine to the remote machinefoo.com:

ssh -L 63333:localhost:5432 joe@foo.com

The first number in the-Largument, 63333, is the local port number of the tunnel; it can be any unused port. (IANA reserves ports 49152 through 65535 for private use.) The name or IP address after this is the remote bind address you are connecting to, i.e.,localhost, which is the default. The second number, 5432, is the remote end of the tunnel, e.g., the port number your database server is using. In order to connect to the database server using this tunnel, you connect to port 63333 on the local machine:

psql -h localhost -p 63333 postgres

To the database server it will then look as though you are userjoeon hostfoo.comconnecting to thelocalhostbind address, and it will use whatever authentication procedure was configured for connections by that user to that bind address. Note that the server will not think the connection is SSL-encrypted, since in fact it is not encrypted between the SSH server and the PostgreSQL server. This should not pose any extra security risk because they are on the same machine.

为了使隧道设置成功,您必须被允许通过以下方式连接ssh作为joe@foo.com,就像你试图使用ssh创建终端会话。

您还可以将端口转发设置为

ssh -L 63333:foo.com:5432 joe@foo.com

但随后数据库服务器将看到连接进入其foo.com绑定地址,默认不开启听地址 = '本地主机'.这通常不是你想要的。

如果您必须通过某个登录主机“跳”到数据库服务器,一种可能的设置可能如下所示:

ssh -L 63333:db.foo.com:5432 joe@shell.foo.com

请注意,这种方式从shell.foo.comdb.foo.com不会被 SSH 隧道加密。当网络以各种方式受到限制时,SSH 提供了相当多的配置可能性。有关详细信息,请参阅 SSH 文档。

# 提示

存在几个其他应用程序,它们可以使用与刚刚描述的概念类似的过程来提供安全隧道。