Search in sources :

Example 6 with JschConfigSessionFactory

use of org.eclipse.jgit.transport.JschConfigSessionFactory in project che by eclipse.

the class JGitConnection method executeRemoteCommand.

/**
     * Execute remote jgit command.
     *
     * @param remoteUrl
     *         remote url
     * @param command
     *         command to execute
     * @return executed command
     * @throws GitException
     * @throws GitAPIException
     * @throws UnauthorizedException
     */
@VisibleForTesting
Object executeRemoteCommand(String remoteUrl, TransportCommand command, @Nullable String username, @Nullable String password) throws GitException, GitAPIException, UnauthorizedException {
    File keyDirectory = null;
    UserCredential credentials = null;
    try {
        if (GitUrlUtils.isSSH(remoteUrl)) {
            keyDirectory = Files.createTempDir();
            final File sshKey = writePrivateKeyFile(remoteUrl, keyDirectory);
            SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {

                @Override
                protected void configure(OpenSshConfig.Host host, Session session) {
                    session.setConfig("StrictHostKeyChecking", "no");
                }

                @Override
                protected JSch getJSch(final OpenSshConfig.Host hc, FS fs) throws JSchException {
                    JSch jsch = super.getJSch(hc, fs);
                    jsch.removeAllIdentity();
                    jsch.addIdentity(sshKey.getAbsolutePath());
                    return jsch;
                }
            };
            command.setTransportConfigCallback(transport -> {
                if (transport instanceof SshTransport) {
                    ((SshTransport) transport).setSshSessionFactory(sshSessionFactory);
                }
            });
        } else {
            if (remoteUrl != null && GIT_URL_WITH_CREDENTIALS_PATTERN.matcher(remoteUrl).matches()) {
                username = remoteUrl.substring(remoteUrl.indexOf("://") + 3, remoteUrl.lastIndexOf(":"));
                password = remoteUrl.substring(remoteUrl.lastIndexOf(":") + 1, remoteUrl.indexOf("@"));
                command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password));
            } else {
                if (username != null && password != null) {
                    command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password));
                } else {
                    credentials = credentialsLoader.getUserCredential(remoteUrl);
                    if (credentials != null) {
                        command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(credentials.getUserName(), credentials.getPassword()));
                    }
                }
            }
        }
        ProxyAuthenticator.initAuthenticator(remoteUrl);
        return command.call();
    } catch (GitException | TransportException exception) {
        if ("Unable get private ssh key".equals(exception.getMessage())) {
            throw new UnauthorizedException(exception.getMessage(), ErrorCodes.UNABLE_GET_PRIVATE_SSH_KEY);
        } else if (exception.getMessage().contains(ERROR_AUTHENTICATION_REQUIRED)) {
            final ProviderInfo info = credentialsLoader.getProviderInfo(remoteUrl);
            if (info != null) {
                throw new UnauthorizedException(exception.getMessage(), ErrorCodes.UNAUTHORIZED_GIT_OPERATION, ImmutableMap.of(PROVIDER_NAME, info.getProviderName(), AUTHENTICATE_URL, info.getAuthenticateUrl(), "authenticated", Boolean.toString(credentials != null)));
            }
            throw new UnauthorizedException(exception.getMessage(), ErrorCodes.UNAUTHORIZED_GIT_OPERATION);
        } else {
            throw exception;
        }
    } finally {
        if (keyDirectory != null && keyDirectory.exists()) {
            try {
                FileUtils.delete(keyDirectory, FileUtils.RECURSIVE);
            } catch (IOException exception) {
                throw new GitException("Can't remove SSH key directory", exception);
            }
        }
        ProxyAuthenticator.resetAuthenticator();
    }
}
Also used : UserCredential(org.eclipse.che.api.git.UserCredential) UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) GitException(org.eclipse.che.api.git.exception.GitException) IOException(java.io.IOException) SshSessionFactory(org.eclipse.jgit.transport.SshSessionFactory) JSch(com.jcraft.jsch.JSch) FS(org.eclipse.jgit.util.FS) TransportException(org.eclipse.jgit.api.errors.TransportException) ProviderInfo(org.eclipse.che.api.git.shared.ProviderInfo) UnauthorizedException(org.eclipse.che.api.core.UnauthorizedException) JschConfigSessionFactory(org.eclipse.jgit.transport.JschConfigSessionFactory) DiffCommitFile(org.eclipse.che.api.git.shared.DiffCommitFile) File(java.io.File) SshTransport(org.eclipse.jgit.transport.SshTransport) Session(com.jcraft.jsch.Session) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 7 with JschConfigSessionFactory

use of org.eclipse.jgit.transport.JschConfigSessionFactory in project blueocean-plugin by jenkinsci.

the class GitUtils method getSSHKeyTransport.

private static TransportConfigCallback getSSHKeyTransport(final BasicSSHUserPrivateKey privateKey) {
    final SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {

        @Override
        protected void configure(OpenSshConfig.Host hc, com.jcraft.jsch.Session session) {
            // jenkins user doesn't likely have the host key
            session.setConfig("StrictHostKeyChecking", "no");
        }

        @Override
        protected JSch getJSch(OpenSshConfig.Host hc, FS fs) throws JSchException {
            JSch jsch = new JSch();
            configureJSch(jsch);
            // TODO: might need this: jsch.setHostKeyRepository(new KnownHosts(this));
            KeyPair pair = KeyPair.load(jsch, privateKey.getPrivateKey().getBytes(StandardCharsets.UTF_8), null);
            byte[] passphrase = new byte[0];
            jsch.addIdentity(privateKey.getUsername(), pair.forSSHAgent(), null, passphrase);
            return jsch;
        }
    };
    return transport -> {
        if (transport instanceof SshTransport) {
            SshTransport sshTransport = (SshTransport) transport;
            sshTransport.setSshSessionFactory(sshSessionFactory);
        }
    };
}
Also used : BlueOceanDomainRequirement(io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainRequirement) StringUtils(org.apache.commons.lang.StringUtils) KeyPair(com.jcraft.jsch.KeyPair) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) DirCacheEditor(org.eclipse.jgit.dircache.DirCacheEditor) Date(java.util.Date) JGitText(org.eclipse.jgit.internal.JGitText) LoggerFactory(org.slf4j.LoggerFactory) SshTransport(org.eclipse.jgit.transport.SshTransport) RevWalk(org.eclipse.jgit.revwalk.RevWalk) BasicSSHUserPrivateKey(com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey) CredentialsMatchers(com.cloudbees.plugins.credentials.CredentialsMatchers) ByteArrayInputStream(java.io.ByteArrayInputStream) GitClient(org.jenkinsci.plugins.gitclient.GitClient) CredentialsUtils(io.jenkins.blueocean.credential.CredentialsUtils) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) FileMode(org.eclipse.jgit.lib.FileMode) RefSpec(org.eclipse.jgit.transport.RefSpec) TimeZone(java.util.TimeZone) RefUpdate(org.eclipse.jgit.lib.RefUpdate) OpenSshConfig(org.eclipse.jgit.transport.OpenSshConfig) Constants(org.eclipse.jgit.lib.Constants) TransportCommand(org.eclipse.jgit.api.TransportCommand) ItemGroup(hudson.model.ItemGroup) RevTree(org.eclipse.jgit.revwalk.RevTree) StandardCharsets(java.nio.charset.StandardCharsets) PersonIdent(org.eclipse.jgit.lib.PersonIdent) GitException(hudson.plugins.git.GitException) List(java.util.List) Ref(org.eclipse.jgit.lib.Ref) PushResult(org.eclipse.jgit.transport.PushResult) DirCache(org.eclipse.jgit.dircache.DirCache) FS(org.eclipse.jgit.util.FS) JSchException(com.jcraft.jsch.JSchException) Pattern(java.util.regex.Pattern) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) TransportConfigCallback(org.eclipse.jgit.api.TransportConfigCallback) RevCommit(org.eclipse.jgit.revwalk.RevCommit) JSch(com.jcraft.jsch.JSch) StandardCredentials(com.cloudbees.plugins.credentials.common.StandardCredentials) CanonicalTreeParser(org.eclipse.jgit.treewalk.CanonicalTreeParser) DirCacheEntry(org.eclipse.jgit.dircache.DirCacheEntry) DirCacheBuilder(org.eclipse.jgit.dircache.DirCacheBuilder) Git(org.jenkinsci.plugins.gitclient.Git) FetchCommand(org.eclipse.jgit.api.FetchCommand) MessageFormat(java.text.MessageFormat) ArrayList(java.util.ArrayList) MergeCommand(org.eclipse.jgit.api.MergeCommand) ACL(hudson.security.ACL) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) SshSessionFactory(org.eclipse.jgit.transport.SshSessionFactory) EnvVars(hudson.EnvVars) Nonnull(javax.annotation.Nonnull) PushCommand(org.eclipse.jgit.api.PushCommand) Nullable(javax.annotation.Nullable) ConcurrentRefUpdateException(org.eclipse.jgit.api.errors.ConcurrentRefUpdateException) TaskListener(hudson.model.TaskListener) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk) Logger(org.slf4j.Logger) SmartCredentialsProvider(org.jenkinsci.plugins.gitclient.trilead.SmartCredentialsProvider) IOException(java.io.IOException) URIRequirementBuilder(com.cloudbees.plugins.credentials.domains.URIRequirementBuilder) ServiceException(io.jenkins.blueocean.commons.ServiceException) CheckoutCommand(org.eclipse.jgit.api.CheckoutCommand) ObjectId(org.eclipse.jgit.lib.ObjectId) TransportException(org.eclipse.jgit.api.errors.TransportException) JGitInternalException(org.eclipse.jgit.api.errors.JGitInternalException) RemoteRefUpdate(org.eclipse.jgit.transport.RemoteRefUpdate) CredentialsProvider(com.cloudbees.plugins.credentials.CredentialsProvider) MergeResult(org.eclipse.jgit.api.MergeResult) ErrorMessage(io.jenkins.blueocean.commons.ErrorMessage) ObjectReader(org.eclipse.jgit.lib.ObjectReader) Repository(org.eclipse.jgit.lib.Repository) JschConfigSessionFactory(org.eclipse.jgit.transport.JschConfigSessionFactory) InputStream(java.io.InputStream) KeyPair(com.jcraft.jsch.KeyPair) JschConfigSessionFactory(org.eclipse.jgit.transport.JschConfigSessionFactory) SshSessionFactory(org.eclipse.jgit.transport.SshSessionFactory) JSch(com.jcraft.jsch.JSch) FS(org.eclipse.jgit.util.FS) SshTransport(org.eclipse.jgit.transport.SshTransport)

Example 8 with JschConfigSessionFactory

use of org.eclipse.jgit.transport.JschConfigSessionFactory in project CzechIdMng by bcvsolutions.

the class AbstractReleaseManager method getTransportConfigCallback.

/**
 * Append credentials to git active operations
 *
 * @return
 */
protected TransportConfigCallback getTransportConfigCallback() {
    return new TransportConfigCallback() {

        @Override
        public void configure(Transport transport) {
            // 
            transport.setCredentialsProvider(getCredentialsProvider());
            // 
            if (transport instanceof SshTransport) {
                SshTransport sshTransport = (SshTransport) transport;
                // 
                sshTransport.setSshSessionFactory(new JschConfigSessionFactory() {

                    @Override
                    protected void configure(Host host, Session session) {
                        if (password != null) {
                            session.setPassword(password.asString());
                            // 
                            LOG.info("Ssh passphrase given, will be set for ssh public key ...");
                        }
                    }
                });
            } else {
                if (username == null || password == null) {
                    LOG.warn("No credentials given. Set git username and password, if repository authentication is needed.");
                } else {
                    LOG.info("Git credentials given, username [{}].", username);
                }
            }
        }
    };
}
Also used : TransportConfigCallback(org.eclipse.jgit.api.TransportConfigCallback) Host(org.eclipse.jgit.transport.OpenSshConfig.Host) JschConfigSessionFactory(org.eclipse.jgit.transport.JschConfigSessionFactory) Transport(org.eclipse.jgit.transport.Transport) SshTransport(org.eclipse.jgit.transport.SshTransport) SshTransport(org.eclipse.jgit.transport.SshTransport) Session(com.jcraft.jsch.Session)

Example 9 with JschConfigSessionFactory

use of org.eclipse.jgit.transport.JschConfigSessionFactory in project archi-modelrepository-plugin by archi-contribs.

the class CredentialsAuthenticator method getTransportConfigCallback.

/**
 * Factory method to get the default TransportConfigCallback for authentication for repoURL
 * npw can be null and is ignored if repoURL is SSH
 */
public static TransportConfigCallback getTransportConfigCallback(final String repoURL, final UsernamePassword npw) throws IOException {
    // SSH
    if (GraficoUtils.isSSH(repoURL)) {
        return new TransportConfigCallback() {

            @Override
            public void configure(Transport transport) {
                // Delete remote branches that we don't have
                transport.setRemoveDeletedRefs(true);
                if (transport instanceof SshTransport) {
                    ((SshTransport) transport).setSshSessionFactory(getSshSessionFactory());
                }
            }

            protected SshSessionFactory getSshSessionFactory() {
                return new JschConfigSessionFactory() {

                    @Override
                    protected void configure(OpenSshConfig.Host host, Session session) {
                        // $NON-NLS-1$ //$NON-NLS-2$
                        session.setConfig("StrictHostKeyChecking", "no");
                    }

                    @Override
                    protected JSch createDefaultJSch(FS fs) throws JSchException {
                        JSch jsch = super.createDefaultJSch(fs);
                        // TODO - we might not need to do this as it sets default locations for rsa_pub
                        jsch.removeAllIdentity();
                        File file = null;
                        char[] pw = null;
                        try {
                            file = sshIdentityProvider.getIdentityFile();
                            pw = sshIdentityProvider.getIdentityPassword();
                        } catch (IOException | GeneralSecurityException ex) {
                            throw new JSchException(ex.getMessage());
                        }
                        if (pw != null) {
                            jsch.addIdentity(file.getAbsolutePath(), new String(pw));
                        } else {
                            jsch.addIdentity(file.getAbsolutePath());
                        }
                        return jsch;
                    }
                };
            }
        };
    }
    // HTTP
    if (npw != null) {
        return new TransportConfigCallback() {

            @Override
            public void configure(Transport transport) {
                transport.setCredentialsProvider(new UsernamePasswordCredentialsProvider(npw.getUsername(), npw.getPassword()));
                // Delete remote branches that we don't have
                transport.setRemoveDeletedRefs(true);
            }
        };
    }
    // $NON-NLS-1$
    throw new IOException(Messages.CredentialsAuthenticator_2 + " " + repoURL);
}
Also used : JSchException(com.jcraft.jsch.JSchException) UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) JSch(com.jcraft.jsch.JSch) FS(org.eclipse.jgit.util.FS) TransportConfigCallback(org.eclipse.jgit.api.TransportConfigCallback) JschConfigSessionFactory(org.eclipse.jgit.transport.JschConfigSessionFactory) Transport(org.eclipse.jgit.transport.Transport) SshTransport(org.eclipse.jgit.transport.SshTransport) File(java.io.File) SshTransport(org.eclipse.jgit.transport.SshTransport) Session(com.jcraft.jsch.Session)

Example 10 with JschConfigSessionFactory

use of org.eclipse.jgit.transport.JschConfigSessionFactory in project fabric8 by fabric8io.

the class GitUtils method configureCommand.

/**
 * Configures the transport of the command to deal with things like SSH
 */
public static <C extends GitCommand> void configureCommand(TransportCommand<C, ?> command, CredentialsProvider credentialsProvider, final File sshPrivateKey, final File sshPublicKey) {
    LOG.info("Using " + credentialsProvider);
    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);
                }
            }
        });
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) UserInfo(com.jcraft.jsch.UserInfo) CredentialsProviderUserInfo(org.eclipse.jgit.transport.CredentialsProviderUserInfo) CredentialsProvider(org.eclipse.jgit.transport.CredentialsProvider) SshSessionFactory(org.eclipse.jgit.transport.SshSessionFactory) JSch(com.jcraft.jsch.JSch) FS(org.eclipse.jgit.util.FS) OpenSshConfig(org.eclipse.jgit.transport.OpenSshConfig) TransportConfigCallback(org.eclipse.jgit.api.TransportConfigCallback) CredentialsProviderUserInfo(org.eclipse.jgit.transport.CredentialsProviderUserInfo) JschConfigSessionFactory(org.eclipse.jgit.transport.JschConfigSessionFactory) SshTransport(org.eclipse.jgit.transport.SshTransport) Transport(org.eclipse.jgit.transport.Transport) SshTransport(org.eclipse.jgit.transport.SshTransport) Session(com.jcraft.jsch.Session) SSLSession(javax.net.ssl.SSLSession)

Aggregations

JschConfigSessionFactory (org.eclipse.jgit.transport.JschConfigSessionFactory)10 Session (com.jcraft.jsch.Session)8 JSch (com.jcraft.jsch.JSch)7 SshTransport (org.eclipse.jgit.transport.SshTransport)6 FS (org.eclipse.jgit.util.FS)6 JSchException (com.jcraft.jsch.JSchException)5 TransportConfigCallback (org.eclipse.jgit.api.TransportConfigCallback)5 SshSessionFactory (org.eclipse.jgit.transport.SshSessionFactory)4 Transport (org.eclipse.jgit.transport.Transport)4 IOException (java.io.IOException)3 OpenSshConfig (org.eclipse.jgit.transport.OpenSshConfig)3 UserInfo (com.jcraft.jsch.UserInfo)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 File (java.io.File)2 TransportException (org.eclipse.jgit.api.errors.TransportException)2 Host (org.eclipse.jgit.transport.OpenSshConfig.Host)2 UsernamePasswordCredentialsProvider (org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider)2 BasicSSHUserPrivateKey (com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey)1 CredentialsMatchers (com.cloudbees.plugins.credentials.CredentialsMatchers)1 CredentialsProvider (com.cloudbees.plugins.credentials.CredentialsProvider)1