SSH Tunneling Tricks – Executing a specific command at pubkey authentication

OpenSSH must be – by far – the most neat, handy and cool tool in the tool chain. At least when accessing remote unix boxes, that is.

Currently, I have been preparing a laptop for some remote work, and have been using OpenSSH to dig some tunnels through the company firewall, through a couple of hops and forwarding some ports along the way. One neat trick I picked up in setting this up, is how to execute a specific command when logging in through public key authentication.

Most of us know, how creating a public/private key pair with ssh-keygen and the putting the pubkey in the .ssh/authorized_keys2 file on the remote host, allows us to login to that very host without giving username and password all the time.

But what I did not know, was that the public key line in the .ssh/authorized_keys2 file can have a command-prefix. Here is an example:

command="ssh nexthop" ssh-dss AACBAJzPxSaB8B3GYgX5zUUXtYyLd...  comment-here

Yep. You simply prefix the key line in .ssh/authorized_keys2 with a command="" prefix, and then put the command inside the quotes. Each time a login is made with the private key of this public key, the command will be executed instead of a shell being spawned.

And why is this interesting for digging tunnels and forwarding ports along the way? Because the command executed can be another SSH command, which then connects to the next hop along the path to the hosts I need to reach. And the SSH command can even have -L local forwarding options on each hop, setting up a stream of forwarding into the system. I simply created a specific public/private key pair for this tunnelling setup, and added a Host section in my .ssh/config file to force login with that identity. I then login using this Host configuration, when I need the tunnelling setup.

Neat hugh!

January 11, 2009  Tags: ,   Posted in: Operating Systems, Tools

One Response

  1. Tech Per » Blog Archive » Changing Port Number of svn+ssh Subversion Protocol - January 11, 2009

    [...] sometimes this is not enough. In my previous post I just described how ssh is great for tunneling and port forwarding. To access a remote subversion server, which was hidden behind a firewall and two hops into the [...]

Leave a Reply