Search in sources :

Example 1 with JSchException

use of com.jcraft.jsch.JSchException in project camel by apache.

the class SftpOperations method createSession.

protected Session createSession(final RemoteFileConfiguration configuration) throws JSchException {
    final JSch jsch = new JSch();
    JSch.setLogger(new JSchLogger(endpoint.getConfiguration().getJschLoggingLevel()));
    SftpConfiguration sftpConfig = (SftpConfiguration) configuration;
    if (isNotEmpty(sftpConfig.getCiphers())) {
        LOG.debug("Using ciphers: {}", sftpConfig.getCiphers());
        Hashtable<String, String> ciphers = new Hashtable<String, String>();
        ciphers.put("cipher.s2c", sftpConfig.getCiphers());
        ciphers.put("cipher.c2s", sftpConfig.getCiphers());
        JSch.setConfig(ciphers);
    }
    if (isNotEmpty(sftpConfig.getPrivateKeyFile())) {
        LOG.debug("Using private keyfile: {}", sftpConfig.getPrivateKeyFile());
        if (isNotEmpty(sftpConfig.getPrivateKeyPassphrase())) {
            jsch.addIdentity(sftpConfig.getPrivateKeyFile(), sftpConfig.getPrivateKeyPassphrase());
        } else {
            jsch.addIdentity(sftpConfig.getPrivateKeyFile());
        }
    }
    if (sftpConfig.getPrivateKey() != null) {
        LOG.debug("Using private key information from byte array");
        byte[] passphrase = null;
        if (isNotEmpty(sftpConfig.getPrivateKeyPassphrase())) {
            try {
                passphrase = sftpConfig.getPrivateKeyPassphrase().getBytes("UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new JSchException("Cannot transform passphrase to byte[]", e);
            }
        }
        jsch.addIdentity("ID", sftpConfig.getPrivateKey(), null, passphrase);
    }
    if (sftpConfig.getPrivateKeyUri() != null) {
        LOG.debug("Using private key uri : {}", sftpConfig.getPrivateKeyUri());
        byte[] passphrase = null;
        if (isNotEmpty(sftpConfig.getPrivateKeyPassphrase())) {
            try {
                passphrase = sftpConfig.getPrivateKeyPassphrase().getBytes("UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new JSchException("Cannot transform passphrase to byte[]", e);
            }
        }
        try {
            InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(endpoint.getCamelContext(), sftpConfig.getPrivateKeyUri());
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            IOHelper.copyAndCloseInput(is, bos);
            jsch.addIdentity("ID", bos.toByteArray(), null, passphrase);
        } catch (IOException e) {
            throw new JSchException("Cannot read resource: " + sftpConfig.getPrivateKeyUri(), e);
        }
    }
    if (sftpConfig.getKeyPair() != null) {
        LOG.debug("Using private key information from key pair");
        KeyPair keyPair = sftpConfig.getKeyPair();
        if (keyPair.getPrivate() != null && keyPair.getPublic() != null) {
            if (keyPair.getPrivate() instanceof RSAPrivateKey && keyPair.getPublic() instanceof RSAPublicKey) {
                jsch.addIdentity(new RSAKeyPairIdentity("ID", keyPair), null);
            } else if (keyPair.getPrivate() instanceof DSAPrivateKey && keyPair.getPublic() instanceof DSAPublicKey) {
                jsch.addIdentity(new DSAKeyPairIdentity("ID", keyPair), null);
            } else {
                LOG.warn("Only RSA and DSA key pairs are supported");
            }
        } else {
            LOG.warn("PrivateKey and PublicKey in the KeyPair must be filled");
        }
    }
    if (isNotEmpty(sftpConfig.getKnownHostsFile())) {
        LOG.debug("Using knownhosts file: {}", sftpConfig.getKnownHostsFile());
        jsch.setKnownHosts(sftpConfig.getKnownHostsFile());
    }
    if (isNotEmpty(sftpConfig.getKnownHostsUri())) {
        LOG.debug("Using known hosts uri: {}", sftpConfig.getKnownHostsUri());
        try {
            InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(endpoint.getCamelContext(), sftpConfig.getKnownHostsUri());
            jsch.setKnownHosts(is);
        } catch (IOException e) {
            throw new JSchException("Cannot read resource: " + sftpConfig.getKnownHostsUri(), e);
        }
    }
    if (sftpConfig.getKnownHosts() != null) {
        LOG.debug("Using known hosts information from byte array");
        jsch.setKnownHosts(new ByteArrayInputStream(sftpConfig.getKnownHosts()));
    }
    String knownHostsFile = sftpConfig.getKnownHostsFile();
    if (knownHostsFile == null && sftpConfig.isUseUserKnownHostsFile()) {
        knownHostsFile = System.getProperty("user.home") + "/.ssh/known_hosts";
        LOG.info("Known host file not configured, using user known host file: {}", knownHostsFile);
    }
    if (ObjectHelper.isNotEmpty(knownHostsFile)) {
        LOG.debug("Using known hosts information from file: {}", knownHostsFile);
        jsch.setKnownHosts(knownHostsFile);
    }
    final Session session = jsch.getSession(configuration.getUsername(), configuration.getHost(), configuration.getPort());
    if (isNotEmpty(sftpConfig.getStrictHostKeyChecking())) {
        LOG.debug("Using StrickHostKeyChecking: {}", sftpConfig.getStrictHostKeyChecking());
        session.setConfig("StrictHostKeyChecking", sftpConfig.getStrictHostKeyChecking());
    }
    session.setServerAliveInterval(sftpConfig.getServerAliveInterval());
    session.setServerAliveCountMax(sftpConfig.getServerAliveCountMax());
    // compression
    if (sftpConfig.getCompression() > 0) {
        LOG.debug("Using compression: {}", sftpConfig.getCompression());
        session.setConfig("compression.s2c", "zlib@openssh.com,zlib,none");
        session.setConfig("compression.c2s", "zlib@openssh.com,zlib,none");
        session.setConfig("compression_level", Integer.toString(sftpConfig.getCompression()));
    }
    // set the PreferredAuthentications 
    if (sftpConfig.getPreferredAuthentications() != null) {
        LOG.debug("Using PreferredAuthentications: {}", sftpConfig.getPreferredAuthentications());
        session.setConfig("PreferredAuthentications", sftpConfig.getPreferredAuthentications());
    }
    // set user information
    session.setUserInfo(new ExtendedUserInfo() {

        public String getPassphrase() {
            return null;
        }

        public String getPassword() {
            return configuration.getPassword();
        }

        public boolean promptPassword(String s) {
            return true;
        }

        public boolean promptPassphrase(String s) {
            return true;
        }

        public boolean promptYesNo(String s) {
            LOG.warn("Server asks for confirmation (yes|no): " + s + ". Camel will answer no.");
            // Return 'false' indicating modification of the hosts file is disabled.
            return false;
        }

        public void showMessage(String s) {
            LOG.trace("Message received from Server: " + s);
        }

        public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) {
            // must return an empty array if password is null
            if (configuration.getPassword() == null) {
                return new String[0];
            } else {
                return new String[] { configuration.getPassword() };
            }
        }
    });
    // set the SO_TIMEOUT for the time after the connect phase
    if (configuration.getSoTimeout() > 0) {
        session.setTimeout(configuration.getSoTimeout());
    }
    // set proxy if configured
    if (proxy != null) {
        session.setProxy(proxy);
    }
    return session;
}
Also used : JSchException(com.jcraft.jsch.JSchException) KeyPair(java.security.KeyPair) Hashtable(java.util.Hashtable) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) JSch(com.jcraft.jsch.JSch) DSAPublicKey(java.security.interfaces.DSAPublicKey) RSAPublicKey(java.security.interfaces.RSAPublicKey) ByteArrayInputStream(java.io.ByteArrayInputStream) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) Session(com.jcraft.jsch.Session)

Example 2 with JSchException

use of com.jcraft.jsch.JSchException in project camel by apache.

the class ScpOperations method createSession.

private Session createSession(ScpConfiguration config) {
    ObjectHelper.notNull(config, "ScpConfiguration");
    try {
        final JSch jsch = new JSch();
        // get from configuration
        if (ObjectHelper.isNotEmpty(config.getCiphers())) {
            LOG.trace("Using ciphers: {}", config.getCiphers());
            Hashtable<String, String> ciphers = new Hashtable<String, String>();
            ciphers.put("cipher.s2c", config.getCiphers());
            ciphers.put("cipher.c2s", config.getCiphers());
            JSch.setConfig(ciphers);
        }
        if (ObjectHelper.isNotEmpty(config.getPrivateKeyFile())) {
            LOG.trace("Using private keyfile: {}", config.getPrivateKeyFile());
            String pkfp = config.getPrivateKeyFilePassphrase();
            jsch.addIdentity(config.getPrivateKeyFile(), ObjectHelper.isNotEmpty(pkfp) ? pkfp : null);
        }
        String knownHostsFile = config.getKnownHostsFile();
        if (knownHostsFile == null && config.isUseUserKnownHostsFile()) {
            if (userKnownHostFile == null) {
                userKnownHostFile = System.getProperty("user.home") + "/.ssh/known_hosts";
                LOG.info("Known host file not configured, using user known host file: " + userKnownHostFile);
            }
            knownHostsFile = userKnownHostFile;
        }
        jsch.setKnownHosts(ObjectHelper.isEmpty(knownHostsFile) ? null : knownHostsFile);
        session = jsch.getSession(config.getUsername(), config.getHost(), config.getPort());
        session.setTimeout(config.getTimeout());
        session.setUserInfo(new SessionUserInfo(config));
        if (ObjectHelper.isNotEmpty(config.getStrictHostKeyChecking())) {
            LOG.trace("Using StrickHostKeyChecking: {}", config.getStrictHostKeyChecking());
            session.setConfig("StrictHostKeyChecking", config.getStrictHostKeyChecking());
        }
        if (ObjectHelper.isNotEmpty(config.getPreferredAuthentications())) {
            LOG.trace("Using preferredAuthentications: {}", config.getPreferredAuthentications());
            session.setConfig("PreferredAuthentications", config.getPreferredAuthentications());
        }
        int timeout = config.getConnectTimeout();
        LOG.debug("Connecting to {} with {} timeout...", config.remoteServerInformation(), timeout > 0 ? (Integer.toString(timeout) + " ms") : "no");
        if (timeout > 0) {
            session.connect(timeout);
        } else {
            session.connect();
        }
    } catch (JSchException e) {
        session = null;
        LOG.warn("Could not create ssh session for " + config.remoteServerInformation(), e);
    }
    return session;
}
Also used : JSchException(com.jcraft.jsch.JSchException) Hashtable(java.util.Hashtable) JSch(com.jcraft.jsch.JSch) GenericFileEndpoint(org.apache.camel.component.file.GenericFileEndpoint)

Example 3 with JSchException

use of com.jcraft.jsch.JSchException in project camel by apache.

the class ScpOperations method storeFile.

@Override
public boolean storeFile(String name, Exchange exchange) throws GenericFileOperationFailedException {
    ObjectHelper.notNull(session, "session");
    ScpConfiguration cfg = endpoint.getConfiguration();
    int timeout = cfg.getConnectTimeout();
    if (LOG.isTraceEnabled()) {
        LOG.trace("Opening channel to {} with {} timeout...", cfg.remoteServerInformation(), timeout > 0 ? (Integer.toString(timeout) + " ms") : "no");
    }
    String file = getRemoteFile(name, cfg);
    InputStream is = null;
    if (exchange.getIn().getBody() == null) {
        // Do an explicit test for a null body and decide what to do
        if (endpoint.isAllowNullBody()) {
            LOG.trace("Writing empty file.");
            is = new ByteArrayInputStream(new byte[] {});
        } else {
            throw new GenericFileOperationFailedException("Cannot write null body to file: " + name);
        }
    }
    try {
        channel = (ChannelExec) session.openChannel("exec");
        channel.setCommand(getScpCommand(cfg, file));
        channel.connect(timeout);
        LOG.trace("Channel connected to {}", cfg.remoteServerInformation());
        try {
            if (is == null) {
                is = exchange.getIn().getMandatoryBody(InputStream.class);
            }
            write(channel, file, is, cfg);
        } catch (InvalidPayloadException e) {
            throw new GenericFileOperationFailedException("Cannot store file: " + name, e);
        } catch (IOException e) {
            throw new GenericFileOperationFailedException("Failed to write file " + file, e);
        } finally {
            // must close stream after usage
            IOHelper.close(is);
        }
    } catch (JSchException e) {
        throw new GenericFileOperationFailedException("Failed to write file " + file, e);
    } finally {
        if (channel != null) {
            LOG.trace("Disconnecting 'exec' scp channel");
            channel.disconnect();
            channel = null;
            LOG.trace("Channel disconnected from {}", cfg.remoteServerInformation());
        }
    }
    return true;
}
Also used : JSchException(com.jcraft.jsch.JSchException) ByteArrayInputStream(java.io.ByteArrayInputStream) GenericFileOperationFailedException(org.apache.camel.component.file.GenericFileOperationFailedException) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) InvalidPayloadException(org.apache.camel.InvalidPayloadException) GenericFileEndpoint(org.apache.camel.component.file.GenericFileEndpoint)

Example 4 with JSchException

use of com.jcraft.jsch.JSchException in project camel by apache.

the class ScpServerTestSupport method setupKnownHosts.

protected void setupKnownHosts() {
    knownHostsFile = SCP_ROOT_DIR + "/" + KNOWN_HOSTS;
    if (!acceptLocalhostConnections) {
        return;
    }
    // For security reasons (avoiding man in the middle attacks),
    // camel-jsch will only connect to known hosts. For unit testing
    // we use a known key, but since the port is dynamic, the 
    // known_hosts file will be generated by the following code and 
    // should contain a line like below (if 
    // "HashKnownHosts"=="yes" the hostname:port part will be 
    // hashed and look a bit more complicated).
    //
    // [localhost]:21000 ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDd \
    // fIWeSV4o68dRrKSzFd/Bk51E65UTmmSrmW0O1ohtzi6HzsDPjXgCtlTt3F \
    // qTcfFfI92IlTr4JWqC9UK1QT1ZTeng0MkPQmv68hDANHbt5CpETZHjW5q4 \
    // OOgWhVvj5IyOC2NZHtKlJBkdsMAa15ouOOJLzBvAvbqOR/yUROsEiQ==
    JSch jsch = new JSch();
    try {
        LOG.debug("Using '{}' for known hosts.", knownHostsFile);
        jsch.setKnownHosts(knownHostsFile);
        Session s = jsch.getSession("admin", "localhost", getPort());
        s.setConfig("StrictHostKeyChecking", "ask");
        // TODO: by the current jsch (0.1.51) setting "HashKnownHosts" to "no" is a workaround
        // to make the tests run green, see also http://sourceforge.net/p/jsch/bugs/63/
        s.setConfig("HashKnownHosts", "no");
        s.setUserInfo(new UserInfo() {

            @Override
            public String getPassphrase() {
                return null;
            }

            @Override
            public String getPassword() {
                return "admin";
            }

            @Override
            public boolean promptPassword(String message) {
                return true;
            }

            @Override
            public boolean promptPassphrase(String message) {
                return false;
            }

            @Override
            public boolean promptYesNo(String message) {
                // accept host authenticity
                return true;
            }

            @Override
            public void showMessage(String message) {
            }
        });
        // in the process of connecting, "[localhost]:<port>" is added to the knownHostsFile
        s.connect();
        s.disconnect();
    } catch (JSchException e) {
        LOG.info("Could not add [localhost] to known hosts", e);
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) UserInfo(com.jcraft.jsch.UserInfo) JSch(com.jcraft.jsch.JSch) ServerSession(org.apache.sshd.server.session.ServerSession) Session(com.jcraft.jsch.Session)

Example 5 with JSchException

use of com.jcraft.jsch.JSchException in project hadoop by apache.

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));
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) ChannelSftp(com.jcraft.jsch.ChannelSftp) IOException(java.io.IOException) JSch(com.jcraft.jsch.JSch) Session(com.jcraft.jsch.Session)

Aggregations

JSchException (com.jcraft.jsch.JSchException)40 IOException (java.io.IOException)20 Session (com.jcraft.jsch.Session)19 JSch (com.jcraft.jsch.JSch)14 ChannelSftp (com.jcraft.jsch.ChannelSftp)11 Channel (com.jcraft.jsch.Channel)9 SftpException (com.jcraft.jsch.SftpException)9 ChannelExec (com.jcraft.jsch.ChannelExec)6 InputStream (java.io.InputStream)6 ArrayList (java.util.ArrayList)6 UserInfo (com.jcraft.jsch.UserInfo)5 File (java.io.File)5 MachineException (org.eclipse.che.api.machine.server.exception.MachineException)5 SSHShell (com.microsoft.azure.management.samples.SSHShell)4 Properties (java.util.Properties)4 BufferedReader (java.io.BufferedReader)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3 FileInputStream (java.io.FileInputStream)3 InputStreamReader (java.io.InputStreamReader)3 OutputStream (java.io.OutputStream)3