In the articles Authenticating with ssh-agent and Authenticating with the Maverick Key Agent we demonstrated how to use a local ssh-agent to authenticate your SshClient instances. One of the useful things about the agent feature is that from a remote shell you can forward authentication requests to your local agent. This is called Agent Forwarding. Whether you use the ssh-agent or the Maverick Key Agent you can implement Agent Forwarding in your implementation.
The Code
There are two changes you need to make to support Agent Forwarding. The first is to add a ChannelFactory so that when the remote side requests an agent forwarding channel, your client is able to respond and open an appropriate channel. We have provided an implementation of this that makes this easy.
ssh.addChannelFactory(new AgentForwardingChannelFactory(
System.getenv("SSH_AUTH_SOCK"),
AgentSocketType.UNIX_DOMAIN));
The constructor takes 2 arguments, the location of the agent listener and the type of socket connection it uses. In the above case this is a Unix Domain socket to the ssh-agent program which we have automatically picked up from the SSH_AUTH_SOCK environment variable common on most *nix platforms.
You can also create the same with our Maverick Key Agent which uses a standard Socket.
ssh.addChannelFactory(new AgentForwardingChannelFactory(
"localhost:12345",
AgentSocketType.TCPIP));
This configures the client ready to accept forwarding request. In order to ensure the remote side uses agent forwarding you need to send a request to start forwarding. This is done after you have created a session, but before you have configured it with startShell.
Ssh2Session ssh2Session = (Ssh2Session) session; if(!ssh2Session.sendRequest("auth-agent-req@openssh.com", true, null)) { System.out.println("Agent request failed"); }
You can check the return value of sendRequest to see if the server accepted the request or not. The request name will change depending on whether you are using the Maverick Key Agent or the ssh-agent program. For Maverick Key Agent use "auth-agent-req" and for ssh-agent use "auth-agent-req@openssh.com". This is required because the 2 agent implementations use differing protocols. Our implementation follows the IETF Draft whereas OpenSSH implements its own protocol.
Once these changes have been made, any SSH connection you make within the remote server's shell will use agent forwarding.