Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SSH KeyFile supplying as String #139

Merged
merged 2 commits into from
Jan 9, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,10 @@ The SSH protocol implementation of Overthere defines a number of additional conn
<br/>
<strong>N.B.:</strong> This connection option is only applicable for the <strong>SUDO</strong> and <strong>INTERACTIVE_SUDO</strong> connection types.</td>
</tr>
<tr>
<th align="left" valign="top"><a name="ssh_privateKey"></a>privateKey</th>
<td>The RSA private key as String to use when connecting to the remote host. When this connection option is specified, the <strong>password</strong> and <strong>privateKeyFile</strong> connection options are ignored.</td>
</tr>
<tr>
<th align="left" valign="top"><a name="ssh_privateKeyFile"></a>privateKeyFile</th>
<td>The RSA private key file to use when connecting to the remote host. When this connection option is specified, the <strong>password</strong> connection option is ignored.</td>
Expand Down
89 changes: 57 additions & 32 deletions src/main/java/com/xebialabs/overthere/ssh/SshConnection.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,9 @@
*/
package com.xebialabs.overthere.ssh;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Collections;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.xebialabs.overthere.*;
import com.xebialabs.overthere.spi.AddressPortMapper;
import com.xebialabs.overthere.spi.BaseOverthereConnection;
import net.schmizz.sshj.Config;
import net.schmizz.sshj.DefaultConfig;
import net.schmizz.sshj.SSHClient;
Expand All @@ -44,29 +40,19 @@
import net.schmizz.sshj.userauth.method.AuthPassword;
import net.schmizz.sshj.userauth.password.PasswordFinder;
import net.schmizz.sshj.userauth.password.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xebialabs.overthere.CmdLine;
import com.xebialabs.overthere.CmdLineArgument;
import com.xebialabs.overthere.ConnectionOptions;
import com.xebialabs.overthere.OverthereFile;
import com.xebialabs.overthere.OverthereProcess;
import com.xebialabs.overthere.RuntimeIOException;
import com.xebialabs.overthere.spi.AddressPortMapper;
import com.xebialabs.overthere.spi.BaseOverthereConnection;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Collections;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.xebialabs.overthere.ConnectionOptions.*;
import static com.xebialabs.overthere.ssh.SshConnectionBuilder.*;
import static com.xebialabs.overthere.util.OverthereUtils.checkArgument;
import static com.xebialabs.overthere.util.OverthereUtils.checkNotNull;
import static com.xebialabs.overthere.util.OverthereUtils.checkState;
import static com.xebialabs.overthere.ConnectionOptions.ADDRESS;
import static com.xebialabs.overthere.ConnectionOptions.PASSWORD;
import static com.xebialabs.overthere.ConnectionOptions.PORT;
import static com.xebialabs.overthere.ConnectionOptions.USERNAME;
import static com.xebialabs.overthere.util.OverthereUtils.closeQuietly;
import static com.xebialabs.overthere.util.OverthereUtils.constructPath;
import static com.xebialabs.overthere.util.OverthereUtils.*;
import static java.lang.String.format;
import static java.net.InetSocketAddress.createUnresolved;

Expand Down Expand Up @@ -95,6 +81,8 @@ abstract class SshConnection extends BaseOverthereConnection {

protected String interactiveKeyboardAuthPromptRegex;

protected String privateKey;

protected String privateKeyFile;

protected String passphrase;
Expand Down Expand Up @@ -133,6 +121,7 @@ public SshConnection(final String protocol, final ConnectionOptions options, fin
username = options.get(USERNAME);
password = options.getOptional(PASSWORD);
interactiveKeyboardAuthPromptRegex = options.get(INTERACTIVE_KEYBOARD_AUTH_PROMPT_REGEX, INTERACTIVE_KEYBOARD_AUTH_PROMPT_REGEX_DEFAULT);
privateKey = options.getOptional(PRIVATE_KEY);
privateKeyFile = options.getOptional(PRIVATE_KEY_FILE);
passphrase = options.getOptional(PASSPHRASE);
allocateDefaultPty = options.getBoolean(ALLOCATE_DEFAULT_PTY, ALLOCATE_DEFAULT_PTY_DEFAULT);
Expand Down Expand Up @@ -161,18 +150,30 @@ protected void connect() {
throw new RuntimeIOException("Cannot connect to " + host + ":" + port, e);
}

if (privateKeyFile != null) {
if (password != null) {
logger.warn("The " + PRIVATE_KEY_FILE + " and " + PASSWORD + " connection options have both been set for the connection {}. Ignoring "
+ PASSWORD
+ " and using " + PRIVATE_KEY_FILE + ".", this);
if (!onlyOneNotNull(privateKey, privateKeyFile, password))
{
String[] vars = { PRIVATE_KEY, PRIVATE_KEY_FILE, PASSWORD };
logger.warn("You should only set one connection options between: {}, {}, {}. They are evaluated in this order, and latter would have no effect on the connection.", vars);
}

KeyProvider keys;
if (privateKey != null) {
try {
if (passphrase == null) {
keys = client.loadKeys(privateKey, null, null);
} else {
keys = client.loadKeys(privateKey, null, getPassphraseFinder());
}
} catch (IOException e) {
throw new RuntimeIOException("The supplied key is not in a recognized format", e);
}
KeyProvider keys;
client.authPublickey(username, keys);
} else if (privateKeyFile != null) {
try {
if (passphrase == null) {
keys = client.loadKeys(privateKeyFile);
} else {
keys = client.loadKeys(privateKeyFile, passphrase);
keys = client.loadKeys(privateKeyFile, getPassphraseFinder());
}
} catch (IOException e) {
throw new RuntimeIOException("Cannot read key from private key file " + privateKeyFile, e);
Expand All @@ -183,6 +184,7 @@ protected void connect() {
client.auth(username, new AuthPassword(passwordFinder),
new AuthKeyboardInteractive(new RegularExpressionPasswordResponseProvider(passwordFinder, interactiveKeyboardAuthPromptRegex)));
}

sshClient = client;
connected();
} catch (SSHException e) {
Expand All @@ -205,6 +207,29 @@ public boolean shouldRetry(Resource<?> resource) {
};
}

private PasswordFinder getPassphraseFinder() {
return new PasswordFinder() {

@Override
public char[] reqPassword(Resource<?> resource) {
return passphrase.toCharArray();
}

@Override
public boolean shouldRetry(Resource<?> resource) {
return false;
}
};
}

private boolean onlyOneNotNull(Object... objs) {
int guard = 0;
for (Object obj: objs) {
guard += obj != null ? 1 : 0;
}
return guard == 1;
}

@Override
public void doClose() {
if (sshClient == null) return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,11 @@ public class SshConnectionBuilder implements OverthereConnectionBuilder {
*/
public static final String PASSPHRASE = "passphrase";

/**
* See <a href="https://github.com/xebialabs/overthere/blob/master/README.md#ssh_passphrase">the online documentation</a>
*/
public static final String PRIVATE_KEY = "privateKey";

/**
* See <a href="https://github.com/xebialabs/overthere/blob/master/README.md#ssh_passphrase">the online documentation</a>
*/
Expand Down
46 changes: 26 additions & 20 deletions src/test/java/com/xebialabs/overthere/ssh/SshConnectionTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,39 +22,33 @@
*/
package com.xebialabs.overthere.ssh;

import java.io.IOException;

import com.xebialabs.overthere.CmdLine;
import com.xebialabs.overthere.ConnectionOptions;
import net.schmizz.sshj.MockitoFriendlySSHClient;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.connection.ConnectionException;
import net.schmizz.sshj.connection.channel.direct.Session;
import net.schmizz.sshj.transport.Transport;
import net.schmizz.sshj.transport.TransportException;
import net.schmizz.sshj.userauth.keyprovider.KeyProvider;
import net.schmizz.sshj.userauth.method.AuthMethod;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import com.xebialabs.overthere.CmdLine;
import com.xebialabs.overthere.ConnectionOptions;

import net.schmizz.sshj.MockitoFriendlySSHClient;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.connection.channel.direct.Session;
import net.schmizz.sshj.userauth.keyprovider.KeyProvider;
import net.schmizz.sshj.userauth.method.AuthMethod;
import java.io.IOException;

import static com.xebialabs.overthere.ConnectionOptions.ADDRESS;
import static com.xebialabs.overthere.ConnectionOptions.OPERATING_SYSTEM;
import static com.xebialabs.overthere.ConnectionOptions.PASSWORD;
import static com.xebialabs.overthere.ConnectionOptions.USERNAME;
import static com.xebialabs.overthere.ConnectionOptions.*;
import static com.xebialabs.overthere.OperatingSystemFamily.UNIX;
import static com.xebialabs.overthere.ssh.SshConnectionBuilder.*;
import static com.xebialabs.overthere.ssh.SshConnectionType.SFTP;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Matchers.anyMap;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.*;

/**
* Unit tests for {@link SshConnection}
Expand Down Expand Up @@ -117,7 +111,19 @@ public void keyfileShouldOverridePassword() throws IOException {
verify(client).authPublickey(eq("some-user"), Matchers.<KeyProvider>anyVararg());
verify(client, never()).authPassword(anyString(), anyString());
connection.close();
}

@Test
public void keyShouldOverrideKeyFile() throws IOException {
String keyFile = "/path/to/keyfile";
connectionOptions.set(PRIVATE_KEY_FILE, keyFile);
connectionOptions.set(PRIVATE_KEY, "RANDOM");
SshConnection connection = newConnectionWithClient(client);
connection.connect();

verify(client).authPublickey(eq("some-user"), Matchers.<KeyProvider>anyVararg());
verify(client, never()).authPublickey(Matchers.eq(keyFile), anyString());
connection.close();
}

@Test
Expand Down