use of com.jcraft.jsch.JSch in project airavata by apache.
the class SSHCredentialGenerator method generateCredential.
/**
* @return a SSH Credential generated and encrypted using a randomly generated password
* @throws CredentialStoreException
*/
public SSHCredential generateCredential(String tokenId) throws CredentialStoreException {
JSch jsch = new JSch();
try {
KeyPair kpair = KeyPair.genKeyPair(jsch, KeyPair.RSA);
File file;
file = File.createTempFile("id_rsa", "");
String fileName = file.getAbsolutePath();
String password = generateRandomString();
// We are encrypting the private key with the hash of (tokenId+password).
// Any client which wants to use this private key will also generate a hash and then use it to decrypt the key.
kpair.writePrivateKey(fileName, password.getBytes());
kpair.writePublicKey(fileName + ".pub", "");
kpair.dispose();
byte[] priKey = FileUtils.readFileToByteArray(new File(fileName));
byte[] pubKey = FileUtils.readFileToByteArray(new File(fileName + ".pub"));
SSHCredential sshCredential = new SSHCredential();
sshCredential.setPrivateKey(priKey);
sshCredential.setPublicKey(pubKey);
sshCredential.setPassphrase(password);
return sshCredential;
} catch (IOException e) {
logger.error("IO Exception when creating SSH credential ", e);
throw new CredentialStoreException("Unable to generate SSH Credential", e);
} catch (JSchException e) {
logger.error("JSch SSH credential creation exception ", e);
throw new CredentialStoreException("Unable to generate SSH Credential. JSch exception ", e);
}
}
use of com.jcraft.jsch.JSch in project airavata by apache.
the class Utility method generateKeyPair.
public static org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential generateKeyPair(SSHCredential credential) throws Exception {
JSch jsch = new JSch();
try {
KeyPair kpair = KeyPair.genKeyPair(jsch, KeyPair.RSA, 2048);
File file = File.createTempFile("id_rsa", "");
String fileName = file.getAbsolutePath();
kpair.writePrivateKey(fileName, credential.getPassphrase().getBytes());
kpair.writePublicKey(fileName + ".pub", "");
kpair.dispose();
byte[] priKey = FileUtils.readFileToByteArray(new File(fileName));
byte[] pubKey = FileUtils.readFileToByteArray(new File(fileName + ".pub"));
credential.setPrivateKey(priKey);
credential.setPublicKey(pubKey);
return credential;
} catch (Exception e) {
log.error("Error while creating key pair", e);
throw new Exception("Error while creating key pair", e);
}
}
use of com.jcraft.jsch.JSch in project compss by bsc-wdc.
the class AbstractSSHConnector method getSession.
private Session getSession(String host, String user, boolean password, String keyPairOrPassword) throws ConnectorException {
// String[] client2server =
// ("aes256-ctr,aes192-ctr,aes128-ctr,blowfish-ctr,aes256-cbc,aes192-cbc,aes128-cbc,blowfish-cbc").split(",");
// String[] server2client =
// ("aes256-ctr,aes192-ctr,aes128-ctr,blowfish-ctr,aes256-cbc,aes192-cbc,aes128-cbc,blowfish-cbc").split(",");
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
if (keyPairOrPassword == null) {
password = false;
keyPairOrPassword = KeyManager.getKeyPair();
LOGGER.warn(WARN_DEFAULT_KEYPAIR + " (" + KeyManager.getKeyPair() + ")");
}
int errors = 0;
JSchException exception = null;
while (errors < MAX_ALLOWED_ERRORS) {
Session session = null;
JSch jsch = new JSch();
try {
// Connect session
if (password) {
session = jsch.getSession(user, host, 22);
session.setPassword(keyPairOrPassword);
} else {
jsch.addIdentity(keyPairOrPassword);
session = jsch.getSession(user, host, 22);
}
session.setConfig(config);
session.connect();
// Check creation status
if (session.isConnected()) {
if (LOGGER.isDebugEnabled()) {
if (password) {
LOGGER.debug("Session created as " + user + "@" + host + " with password.");
} else {
LOGGER.debug("Session created as " + user + "@" + host + " with public key " + keyPairOrPassword);
}
}
return session;
} else {
++errors;
if (password) {
LOGGER.warn("Error connecting to " + user + "@" + host + " with password.");
} else {
LOGGER.warn("Error connecting to " + user + "@" + host + " with public key" + keyPairOrPassword);
}
LOGGER.warn("Retrying after " + RETRY_TIME * errors + " seconds...");
}
} catch (JSchException e) {
++errors;
exception = e;
LOGGER.warn("Error creating session to " + user + "@" + host + "(" + e.getMessage() + ").");
LOGGER.warn("Retrying after " + RETRY_TIME * errors + " seconds...");
if (session != null && session.isConnected()) {
session.disconnect();
}
}
// Sleep between retries
try {
Thread.sleep(RETRY_TIME * errors * S_TO_MS);
} catch (InterruptedException e) {
LOGGER.debug("Sleep interrupted", e);
Thread.currentThread().interrupt();
}
}
// If we reach this point the session has not been correctly initialized
if (exception != null) {
LOGGER.error(ERROR_SESSION_CREATION + user + "@" + host, exception);
throw new ConnectorException(ERROR_SESSION_CREATION + user + "@" + host, exception);
} else {
LOGGER.error(ERROR_SESSION_CREATION + user + "@" + host);
throw new ConnectorException(ERROR_SESSION_CREATION + user + "@" + host);
}
}
use of com.jcraft.jsch.JSch in project cdap by caskdata.
the class SFTPConnectionPool method connect.
public ChannelSftp connect(String host, int port, String user, String password, String keyFile) throws IOException {
// get connection from pool
ConnectionInfo info = new ConnectionInfo(host, port, user);
ChannelSftp channel = getFromPool(info);
if (channel != null) {
if (channel.isConnected()) {
return channel;
} else {
channel = null;
synchronized (this) {
--liveConnectionCount;
con2infoMap.remove(channel);
}
}
}
// create a new connection and add to pool
JSch jsch = new JSch();
Session session = null;
try {
if (user == null || user.length() == 0) {
user = System.getProperty("user.name");
}
if (password == null) {
password = "";
}
if (keyFile != null && keyFile.length() > 0) {
jsch.addIdentity(keyFile);
}
if (port <= 0) {
session = jsch.getSession(user, host);
} else {
session = jsch.getSession(user, host, port);
}
session.setPassword(password);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
channel = (ChannelSftp) session.openChannel("sftp");
channel.connect();
synchronized (this) {
con2infoMap.put(channel, info);
liveConnectionCount++;
}
return channel;
} catch (JSchException e) {
throw new IOException(StringUtils.stringifyException(e));
}
}
use of com.jcraft.jsch.JSch in project CommandHelper by EngineHub.
the class SSHWrapper method SCP.
/**
* Copies a file from/to a remote host, via ssh. Currently, both paths being remote is not supported. A path can
* look like the following: user@remote[:port[:password]]:path/to/remote/file If the password is not specified, then
* public key authentication will be assumed. The port must be specified if the password is specified, but setting
* it to 0 will use the default (22), allowing it to be bypassed.
*
* @param from
* @param to
* @return false, if the file is being pushed to the remote, yet it was already the same, thus no changes were made,
* true otherwise
*/
public static boolean SCP(String from, String to) throws IOException {
if ((from.contains("@") && to.contains("@")) || (!from.contains("@") && !to.contains("@"))) {
throw new IOException("Paths cannot be both remote, or both local.");
}
// Now that we've handled the case where both paths are remote, we
// can determine which one is the remote path, and proceed from there.
String remote = to;
if (from.contains("@")) {
remote = from;
}
// Now, parse the remote connection for information
Matcher m = Pattern.compile("(.+?)@(.+?)(?:\\:(.+?)(?:\\:(.+?))?)?\\:(.+)").matcher(remote);
String syntaxErrorMsg = "Remote host connection must match the following syntax: user@host[:port[:password]]:path/to/file";
if (m.find()) {
String user = m.group(1);
String host = m.group(2);
String sport = m.group(3);
int port = 22;
final String password = m.group(4);
String file = m.group(5);
try {
if (sport != null) {
port = Integer.parseInt(sport);
}
if (port == 0) {
port = 22;
}
} catch (NumberFormatException e) {
// be null, so let's give them a better error message.
if (password == null) {
throw new IOException(syntaxErrorMsg + " (It appears as though you may have been trying a password" + " in place of the port. You may specify the port to be 0 if you want it to use the default," + " to bypass the port parameter.)");
}
}
if (port < 1 || port > 65535) {
throw new IOException("Port numbers must be between 1 and 65535");
}
try {
JSch jsch = new JSch();
Session sshSession = null;
File known_hosts = new File(System.getProperty("user.home") + "/.ssh/known_hosts");
if (!known_hosts.exists()) {
if (password == null) {
throw new IOException("No known hosts file exists at " + known_hosts.getAbsolutePath() + ", and no password was provided");
}
} else {
jsch.setKnownHosts(known_hosts.getAbsolutePath());
}
if (password == null) {
// We need to try public key authentication
File privKey = new File(System.getProperty("user.home") + "/.ssh/id_rsa");
if (privKey.exists()) {
jsch.addIdentity(privKey.getAbsolutePath());
} else {
throw new IOException("No password provided, and no private key exists at " + privKey.getAbsolutePath());
}
}
if (!sessionList.containsKey(user + host + port)) {
sshSession = jsch.getSession(user, host, port);
sshSession.setUserInfo(new UserInfo() {
@Override
public String getPassphrase() {
// This may need to be made more granular later
return password;
}
@Override
public String getPassword() {
return password;
}
@Override
public boolean promptPassword(String message) {
return true;
}
@Override
public boolean promptPassphrase(String message) {
return true;
}
@Override
public boolean promptYesNo(String message) {
StreamUtils.GetSystemOut().println(message + " (Automatically responding with 'Yes')");
return true;
}
@Override
public void showMessage(String message) {
StreamUtils.GetSystemOut().println(message);
}
});
// 15 second timeout
sshSession.connect(10 * 1500);
sessionList.put(user + host + port, sshSession);
} else {
sshSession = sessionList.get(user + host + port);
}
// http://www.jcraft.com/jsch/examples/
if (from.contains("@")) {
// We are pulling a remote file here, so we need to use SCPFrom
File localFile = new File(to);
SCPFrom(file, localFile, sshSession);
} else {
// We are pushing a local file to a remote, so we need to use SCPTo
File localFile = new File(from);
return SCPTo(localFile, file, sshSession);
}
return true;
} catch (JSchException | SftpException ex) {
throw new IOException(ex);
}
} else {
throw new IOException(syntaxErrorMsg);
}
}
Aggregations