Example usage for org.eclipse.jgit.transport JschConfigSessionFactory JschConfigSessionFactory

List of usage examples for org.eclipse.jgit.transport JschConfigSessionFactory JschConfigSessionFactory

Introduction

In this page you can find the example usage for org.eclipse.jgit.transport JschConfigSessionFactory JschConfigSessionFactory.

Prototype

JschConfigSessionFactory

Source Link

Usage

From source file:GitHelper.java

License:Apache License

public static File cloneRepository(String cloneUrl, String repoPw)
        throws GitAPIException, JSONException, IOException {
    config = ConfigParser.getConfig();//w w w .j  ava 2  s  .c  om
    File tmpDir = new File("temp_repo");
    String key = null;
    String keyPassPhrase = null;
    if (config.has("privateKey")) {
        key = config.getString("privateKey");
        keyPassPhrase = config.getString("privateKeyPassPhrase");
    }
    // git clone will fail if the directory already exists, even if empty
    if (tmpDir.exists()) {
        FileUtils.deleteDirectory(tmpDir);
    }
    String pw = null;
    if (repoPw != null) {
        pw = repoPw;
    } else if (config.has("gitClonePassword")) {
        pw = config.getString("gitClonePassword");
    }
    final String finalKeyPassPhrase = keyPassPhrase;
    final String finalKey = key;

    SshSessionFactory sessionFactory = new CustomJschConfigSessionFactory();

    // use a private key if provided
    if (finalKey != null) {
        SshSessionFactory.setInstance(sessionFactory);
    }

    // use a password if provided
    if (pw != null) {
        final String finalPw = pw;
        SshSessionFactory.setInstance(new JschConfigSessionFactory() {
            @Override
            protected void configure(OpenSshConfig.Host host, Session session) {
                session.setPassword(finalPw);
            }
        });
    }
    SshSessionFactory.setInstance(sessionFactory);
    Git.cloneRepository().setURI(cloneUrl).setDirectory(tmpDir)
            .setTransportConfigCallback(new TransportConfigCallback() {
                @Override
                public void configure(Transport transport) {
                    SshTransport sshTransport = (SshTransport) transport;
                    sshTransport.setSshSessionFactory(sessionFactory);
                }
            }).call();

    return tmpDir;
}

From source file:bluej.groupwork.git.GitCommand.java

License:Open Source License

/**
 * Prepare a TransportCommand to be executed later.
 * This method checks if the command is using ssh. if it is,
 * then it will disable SSH's fingerprint detection and use
 * username and password authentication.
 * @param command The command to be configured.
 *//* w  w  w  .  j ava2  s.  co  m*/
public void disableFingerprintCheck(TransportCommand command) {
    //check if the command is not null and conects via ssh.
    if (command != null && repository.getReposUrl().startsWith("ssh")) {
        //disable ssh host fingerprint check.
        SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
            @Override
            protected void configure(OpenSshConfig.Host host, Session sn) {
                java.util.Properties config = new java.util.Properties();
                config.put("StrictHostKeyChecking", "no");
                sn.setConfig(config);
            }

            @Override
            protected JSch createDefaultJSch(FS fs) throws JSchException {
                return super.createDefaultJSch(fs);
            }
        };

        command.setTransportConfigCallback((Transport t) -> {
            SshTransport sshTransport = (SshTransport) t;
            sshTransport.setSshSessionFactory(sshSessionFactory);
        });
        command.setCredentialsProvider(getRepository().getCredentialsProvider());
    }
}

From source file:bluej.groupwork.git.GitProvider.java

License:Open Source License

@Override
public TeamworkCommandResult checkConnection(TeamSettings settings) {

    try {//from  ww w. j  a v a  2s.c  o m
        String gitUrl = makeGitUrl(settings);

        //perform a lsRemote on the remote git repo.
        LsRemoteCommand lsRemoteCommand = Git.lsRemoteRepository();
        UsernamePasswordCredentialsProvider cp = new UsernamePasswordCredentialsProvider(settings.getUserName(),
                settings.getPassword()); // set a configuration with username and password.
        lsRemoteCommand.setRemote(gitUrl); //configure remote repository address.
        lsRemoteCommand.setCredentialsProvider(cp); //associate the repository to the username and password.
        lsRemoteCommand.setTags(false); //disable refs/tags in reference results
        lsRemoteCommand.setHeads(false); //disable refs/heads in reference results

        //It seems that ssh host fingerprint check is not working properly. 
        //Disable it in a ssh connection.
        if (gitUrl.startsWith("ssh")) {
            SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
                @Override
                protected void configure(OpenSshConfig.Host host, Session sn) {
                    java.util.Properties config = new java.util.Properties();
                    config.put("StrictHostKeyChecking", "no");
                    sn.setConfig(config);
                }

                @Override
                protected JSch createDefaultJSch(FS fs) throws JSchException {
                    return super.createDefaultJSch(fs);
                }
            };

            lsRemoteCommand.setTransportConfigCallback((Transport t) -> {
                SshTransport sshTransport = (SshTransport) t;
                sshTransport.setSshSessionFactory(sshSessionFactory);
            });
        }

        lsRemoteCommand.call(); //executes the lsRemote commnand.
    } catch (GitAPIException ex) {
        return new TeamworkCommandError(ex.getMessage(), ex.getLocalizedMessage());
    } catch (UnsupportedSettingException ex) {
        return new TeamworkCommandUnsupportedSetting(ex.getMessage());
    }
    //if we got here, it means the command was successful.
    return new TeamworkCommandResult();
}

From source file:com.fanniemae.ezpie.common.GitOperations.java

License:Open Source License

public String cloneSSH(String repo_url, String destination, String privateKey, String password, String branch) {
    if (_useProxy) {
        throw new PieException(
                "Network proxies do not support SSH, please use an http url to clone this repository.");
    }//from w  ww .  j a va  2 s .co m

    final SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
        @Override
        protected void configure(Host host, Session session) {
            // This still checks existing host keys and will disable "unsafe"
            // authentication mechanisms if the host key doesn't match.
            session.setConfig("StrictHostKeyChecking", "no");
        }

        @Override
        protected JSch createDefaultJSch(FS fs) throws JSchException {
            JSch defaultJSch = super.createDefaultJSch(fs);
            defaultJSch.addIdentity(privateKey, password);
            return defaultJSch;
        }
    };

    CloneCommand cloneCommand = Git.cloneRepository();
    cloneCommand.setURI(repo_url);
    File dir = new File(destination);
    cloneCommand.setDirectory(dir);

    if (StringUtilities.isNotNullOrEmpty(branch))
        cloneCommand.setBranch(branch);

    cloneCommand.setTransportConfigCallback(new TransportConfigCallback() {
        public void configure(Transport transport) {
            SshTransport sshTransport = (SshTransport) transport;
            sshTransport.setSshSessionFactory(sshSessionFactory);
        }
    });

    try (Writer writer = new StringWriter()) {
        TextProgressMonitor tpm = new TextProgressMonitor(writer);
        cloneCommand.setProgressMonitor(tpm);
        try (Git result = cloneCommand.call()) {
        }
        writer.flush();
        return writer.toString();
    } catch (IOException | GitAPIException e) {
        throw new PieException("Error while trying to clone the git repository. " + e.getMessage(), e);
    }
}

From source file:com.google.gerrit.acceptance.git.GitUtil.java

License:Apache License

public static void initSsh(final TestAccount a) {
    final Properties config = new Properties();
    config.put("StrictHostKeyChecking", "no");
    JSch.setConfig(config);//  www  .j  a  va2s  .  c  o  m

    // register a JschConfigSessionFactory that adds the private key as identity
    // to the JSch instance of JGit so that SSH communication via JGit can
    // succeed
    SshSessionFactory.setInstance(new JschConfigSessionFactory() {
        @Override
        protected void configure(Host hc, Session session) {
            try {
                final JSch jsch = getJSch(hc, FS.DETECTED);
                jsch.addIdentity("KeyPair", a.privateKey(), a.sshKey.getPublicKeyBlob(), null);
            } catch (JSchException e) {
                throw new RuntimeException(e);
            }
        }
    });
}

From source file:com.photon.phresco.framework.impl.SCMManagerImpl.java

License:Apache License

void additionalAuthentication(String passPhrase) {
    final String passwordPhrase = passPhrase;
    JschConfigSessionFactory sessionFactory = new JschConfigSessionFactory() {
        @Override// w  w w  .  ja  v  a  2 s. c  om
        protected void configure(OpenSshConfig.Host hc, Session session) {
            CredentialsProvider provider = new CredentialsProvider() {
                @Override
                public boolean isInteractive() {
                    return false;
                }

                @Override
                public boolean supports(CredentialItem... items) {
                    return true;
                }

                @Override
                public boolean get(URIish uri, CredentialItem... items) throws UnsupportedCredentialItem {
                    for (CredentialItem item : items) {
                        if (item instanceof CredentialItem.StringType) {
                            ((CredentialItem.StringType) item).setValue(passwordPhrase);
                        }
                    }
                    return true;
                }
            };
            UserInfo userInfo = new CredentialsProviderUserInfo(session, provider);
            // Unknown host key for ssh
            java.util.Properties config = new java.util.Properties();
            config.put(STRICT_HOST_KEY_CHECKING, NO);
            session.setConfig(config);

            session.setUserInfo(userInfo);
        }
    };

    SshSessionFactory.setInstance(sessionFactory);

    /*
     * Enable clone of https url by trusting those urls
     */
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };

    final String https_proxy = System.getenv(HTTPS_PROXY);
    final String http_proxy = System.getenv(HTTP_PROXY);

    ProxySelector.setDefault(new ProxySelector() {
        final ProxySelector delegate = ProxySelector.getDefault();

        @Override
        public List<Proxy> select(URI uri) {
            // Filter the URIs to be proxied

            if (uri.toString().contains(HTTPS) && StringUtils.isNotEmpty(http_proxy) && http_proxy != null) {
                try {
                    URI httpsUri = new URI(https_proxy);
                    String host = httpsUri.getHost();
                    int port = httpsUri.getPort();
                    return Arrays.asList(new Proxy(Type.HTTP, InetSocketAddress.createUnresolved(host, port)));
                } catch (URISyntaxException e) {
                    if (debugEnabled) {
                        S_LOGGER.debug("Url exception caught in https block of additionalAuthentication()");
                    }
                }
            }

            if (uri.toString().contains(HTTP) && StringUtils.isNotEmpty(http_proxy) && http_proxy != null) {
                try {
                    URI httpUri = new URI(http_proxy);
                    String host = httpUri.getHost();
                    int port = httpUri.getPort();
                    return Arrays.asList(new Proxy(Type.HTTP, InetSocketAddress.createUnresolved(host, port)));
                } catch (URISyntaxException e) {
                    if (debugEnabled) {
                        S_LOGGER.debug("Url exception caught in http block of additionalAuthentication()");
                    }
                }
            }

            // revert to the default behaviour
            return delegate == null ? Arrays.asList(Proxy.NO_PROXY) : delegate.select(uri);
        }

        @Override
        public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
            if (uri == null || sa == null || ioe == null) {
                throw new IllegalArgumentException("Arguments can't be null.");
            }
        }
    });

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance(SSL);
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (GeneralSecurityException e) {
        e.getLocalizedMessage();
    }
}

From source file:com.stormcloud.ide.api.git.GitManager.java

License:Open Source License

@Override
public String cloneRemoteRepository(String uri) throws GitManagerException {

    SshSessionFactory.setInstance(new JschConfigSessionFactory() {

        @Override/*w ww.  j av a 2  s. co m*/
        protected void configure(Host hc, Session session) {

            try {

                session.setConfig("StrictHostKeyChecking", "no");

                String keyLocation = RemoteUser.get().getSetting(UserSettings.SSH_HOME) + "/"
                        + RemoteUser.get().getUserName();
                String knownHosts = RemoteUser.get().getSetting(UserSettings.SSH_HOME) + "/known_hosts";

                LOG.debug("KeyLoacation " + keyLocation);
                LOG.debug("KnownHosts " + knownHosts);

                JSch jsch = getJSch(hc, FS.DETECTED);
                jsch.addIdentity(keyLocation);
                jsch.setKnownHosts(knownHosts);

            } catch (JSchException e) {
                LOG.error(e);
            }
        }
    });

    CloneCommand cloneCommand = Git.cloneRepository();

    int start = uri.lastIndexOf("/");

    if (start == -1) {
        start = uri.lastIndexOf(":");
    }

    String folder = uri.substring(start + 1, uri.length());

    LOG.info("Cloning : " + uri + " into " + folder);

    cloneCommand
            .setDirectory(new File(RemoteUser.get().getSetting(UserSettings.PROJECT_FOLDER) + "/" + folder));
    cloneCommand.setURI(uri);

    try {

        cloneCommand.call();

    } catch (GitAPIException e) {
        LOG.error(e);
        throw new GitManagerException(e);
    }

    return "0";
}

From source file:eu.atos.paas.git.Repository.java

License:Open Source License

private SshSessionFactory getSshSessionFactory() {

    if (sshSessionFactory == null) {
        sshSessionFactory = new JschConfigSessionFactory() {

            @Override// w w  w.ja  v  a 2  s  .co m
            protected void configure(Host hc, Session session) {
                /*
                 * does nothing
                 */
            }

        };
    }
    return sshSessionFactory;
}

From source file:gov.va.isaac.sync.git.SyncServiceGIT.java

License:Apache License

private SyncServiceGIT() {
    //Constructor for HK2

    synchronized (jschConfigured) {
        if (jschConfigured.getCount() > 0) {
            log.debug("Disabling strict host key checking");
            SshSessionFactory factory = new JschConfigSessionFactory() {
                @Override//from   w  w  w. j a v  a 2  s  .c o m
                protected void configure(Host hc, Session session) {
                    session.setConfig("StrictHostKeyChecking", "no");
                }
            };

            SshSessionFactory.setInstance(factory);

            JSch.setLogger(new com.jcraft.jsch.Logger() {
                private HashMap<Integer, Consumer<String>> logMap = new HashMap<>();
                private HashMap<Integer, BooleanSupplier> enabledMap = new HashMap<>();

                {
                    //Note- JSCH is _really_  verbose at the INFO level, so I'm mapping info to DEBUG.
                    logMap.put(com.jcraft.jsch.Logger.DEBUG, log::debug);
                    logMap.put(com.jcraft.jsch.Logger.ERROR, log::error);
                    logMap.put(com.jcraft.jsch.Logger.FATAL, log::error);
                    logMap.put(com.jcraft.jsch.Logger.INFO, log::debug);
                    logMap.put(com.jcraft.jsch.Logger.WARN, log::warn);

                    enabledMap.put(com.jcraft.jsch.Logger.DEBUG, log::isDebugEnabled);
                    enabledMap.put(com.jcraft.jsch.Logger.ERROR, log::isErrorEnabled);
                    enabledMap.put(com.jcraft.jsch.Logger.FATAL, log::isErrorEnabled);
                    enabledMap.put(com.jcraft.jsch.Logger.INFO, log::isDebugEnabled);
                    enabledMap.put(com.jcraft.jsch.Logger.WARN, log::isWarnEnabled);
                }

                @Override
                public void log(int level, String message) {
                    logMap.get(level).accept(message);
                }

                @Override
                public boolean isEnabled(int level) {
                    return enabledMap.get(level).getAsBoolean();
                }
            });
            jschConfigured.countDown();
        }
    }
}

From source file:io.fabric8.collector.git.GitHelpers.java

License:Apache License

/**
 * Configures the transport of the command to deal with things like SSH
 *///from   w  ww .  j  ava2  s.c  o m
public static <C extends GitCommand> void configureCommand(TransportCommand<C, ?> command,
        CredentialsProvider credentialsProvider, final File sshPrivateKey, final File sshPublicKey) {
    if (sshPrivateKey != null) {
        final CredentialsProvider provider = credentialsProvider;
        command.setTransportConfigCallback(new TransportConfigCallback() {
            @Override
            public void configure(Transport transport) {
                if (transport instanceof SshTransport) {
                    SshTransport sshTransport = (SshTransport) transport;
                    SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
                        @Override
                        protected void configure(OpenSshConfig.Host host, Session session) {
                            session.setConfig("StrictHostKeyChecking", "no");
                            UserInfo userInfo = new CredentialsProviderUserInfo(session, provider);
                            session.setUserInfo(userInfo);
                        }

                        @Override
                        protected JSch createDefaultJSch(FS fs) throws JSchException {
                            JSch jsch = super.createDefaultJSch(fs);
                            jsch.removeAllIdentity();
                            String absolutePath = sshPrivateKey.getAbsolutePath();
                            if (LOG.isDebugEnabled()) {
                                LOG.debug("Adding identity privateKey: " + sshPrivateKey + " publicKey: "
                                        + sshPublicKey);
                            }
                            if (sshPublicKey != null) {
                                jsch.addIdentity(absolutePath, sshPublicKey.getAbsolutePath(), null);
                            } else {
                                jsch.addIdentity(absolutePath);
                            }
                            return jsch;
                        }
                    };
                    sshTransport.setSshSessionFactory(sshSessionFactory);
                }
            }
        });
    }
}