Authenticating with Keys using the sshagent

The Maverick Synergy Java SSH API supports authenticating SSH connections with the ssh-agent process. ssh-agent is a process that holds private keys in memory to eliminate the need to continually enter passphrases every time you want to connect to an SSH server.

First, we will need to ensure we have the correct dependencies. We will need the maverick-sshagent module from the Synergy project. 

<dependency>
   <groupId>com.sshtools</groupId>
   <artifactId>maverick-sshagent</artifactId>
   <version>3.1.0</version>
</dependency>

This will allow us to load the SshAgentClient, which will connect to the local ssh-agent. The SshAgentClient supports Windows and Linux/OSX and will look for the Unix Socket location in the environment variable SSH_AUTH_SOCK. If it detects it’s running on Windows, it will automatically switch to using Named Pipes and connect to the known location of the agent service. 

To create the SshAgentClient, call the following method:

SshAgentClient agent = SshAgentClient.connectOpenSSHAgent("myApp");

Note how we are using the connectOpenSSHAgent method. There are a couple of flavours and specifications for the agent protocol. The most widely used is the OpenSSH agent, and using this method will allow you to connect to it over a Unix Socket or Named Pipe, depending on the host operating system. There are alternative methods for you to provide the Unix Socket location directly; this will also fall back to Named Pipes if Windows OS is detected.

Now you have the client instance; when you want to authenticate to a server using the agent as the source, pass it to the ExternalKeyAuthenticator you are using:

ssh.authenticate(new ExternalKeyAuthenticator(agent), 30000);

This provides all you need to authenticate against a server using the ssh-agent. The PublicKeyAuthenticator will iterate the keys supported by the agent, and when it finds a key that is acceptable to the server, it performs the authentication.