Authenticating with Keys using the sshagent

Lee Painter

The Maverick Synergy Java SSH API provides support for authenticating SSH connections with the sshagent process. sshagent 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.

The actual process of authenticating is to use the PublicKeyAuthenticator; however the source of the private keys will come from the agent.

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.0.0-SNAPSHOT</version>
</dependency>

 

This will allow us to load the SshAgentClient which will connect to the local sshagent. The SshAgentClient supports both Windows and Linux/OSX and will look for the Unix Socket location in the environment variable SSH_AUTH_SOCK. If it detects its 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 simply call the following method:

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

 

Note how we are using the connectOpenSSHAgent method. There are a couple of flavors and specifications out there 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 fallback 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 PublicKeyAuthenticator you are using:

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

 

This provides all you need to authenticate against a server using the sshagent. 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.