Linux Administration Cookbook
上QQ阅读APP看书,第一时间看更新

Using SSH to create a SOCKS Proxy

SSH is great.

I never get tired of talking about how great it is, and it would be remiss of me to not mention one of its best features: the ability to quickly and easily set up a SOCKS proxy.

In the previous sections, we forwarded individual ports, but what if we were using a bastion host to connect to a slew of different websites within a network? Would you like to add tens of lines to your SSH config file? Or manually type out each port and mapping every time?

I didn't think so.

That's where the -D flag comes in.

See -D [bind_address:]port in the SSH manual page (https://man.openbsd.org/ssh):

Specifies a local "dynamic" application-level port forwarding. This works by allocating a socket to listen to port on the local side, optionally bound to the specified bind_address. Whenever a connection is made to this port, the connection is forwarded over the secure channel, and the application protocol is then used to determine where to connect to from the remote machine. Currently the SOCKS4 and SOCKS5 protocols are supported, and ssh will act as a SOCKS server. Only root can forward privileged ports. Dynamic port forwardings can also be specified in the configuration file.
IPv6 addresses can be specified by enclosing the address in square brackets. Only the superuser can forward privileged ports. By default, the local port is bound in accordance with the GatewayPorts setting. However, an explicit bind_address may be used to bind the connection to a specific address. The bind_address of "localhost" indicates that the listening port be bound for local use only, while an empty address or '*' indicates that the port should be available from all interfaces.

What this means is that with a single command, you can set up a connection that you can then forward traffic through (from a web browser, or other applications that support SOCKS proxies). You don't have to punch holes through firewalls, and you don't have to manually map ports.

SOCKS itself is an internet protocol, and quite an old one at that, though we still actively use SOCKS5, which was approved by the Internet Engineering Task Force in 1996! It's like any other proxy server, allowing you to exchange packets over a connection; in this case, our SSH tunnel. Applications may choose to natively support SOCKS proxies or not, but a lot of commons ones will (Firefox, for example).

Let's get started.