org.eclipse.jgit.transport.OpenSshConfig Java Examples

The following examples show how to use org.eclipse.jgit.transport.OpenSshConfig. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: StudioNodeSyncGlobalRepoTask.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
private <T extends TransportCommand> void configureBasicAuthentication(
        ClusterMember remoteNode, T gitCommand, TextEncryptor encryptor, boolean sshProtocol) throws CryptoException {
    String password = encryptor.decrypt(remoteNode.getGitPassword());
    UsernamePasswordCredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider(
            remoteNode.getGitUsername(), password);

    if (sshProtocol) {
        gitCommand.setTransportConfigCallback(transport -> {
            SshTransport sshTransport = (SshTransport) transport;
            sshTransport.setSshSessionFactory(new StrictHostCheckingOffSshSessionFactory() {

                @Override
                protected void configure(OpenSshConfig.Host host, Session session) {
                    super.configure(host, session);
                    session.setPassword(password);
                }

            });
        });
    }

    gitCommand.setCredentialsProvider(credentialsProvider);
}
 
Example #2
Source File: SystemInfo.java    From app-runner with MIT License 6 votes vote down vote up
private static List<String> getPublicKeys() throws Exception {
    return new JschConfigSessionFactory() {
        @Override
        protected void configure(OpenSshConfig.Host hc, Session session) {
        }
        List<String> getPublicKeys() throws Exception {
            JSch jSch = createDefaultJSch(FS.DETECTED);
            List<String> keys = new ArrayList<>();
            for (Object o : jSch.getIdentityRepository().getIdentities()) {
                Identity i = (Identity) o;
                KeyPair keyPair = KeyPair.load(jSch, i.getName(), null);
                StringBuilder sb = new StringBuilder();
                try (StringBuilderWriter sbw = new StringBuilderWriter(sb);
                     OutputStream os = new WriterOutputStream(sbw, "UTF-8")) {
                    keyPair.writePublicKey(os, keyPair.getPublicKeyComment());
                } finally {
                    keyPair.dispose();
                }
                keys.add(sb.toString().trim());
            }
            return keys;
        }
    }.getPublicKeys();
}
 
Example #3
Source File: GitContentRepositoryHelper.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
private SshSessionFactory getSshSessionFactory(String remotePrivateKey, final Path tempKey) {
    try {

        Files.write(tempKey, remotePrivateKey.getBytes());
        SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
            @Override
            protected void configure(OpenSshConfig.Host hc, Session session) {
                Properties config = new Properties();
                config.put("StrictHostKeyChecking", "no");
                session.setConfig(config);
            }

            @Override
            protected JSch createDefaultJSch(FS fs) throws JSchException {
                JSch defaultJSch = super.createDefaultJSch(fs);
                defaultJSch.addIdentity(tempKey.toAbsolutePath().toString());
                return defaultJSch;
            }
        };
        return sshSessionFactory;
    } catch (IOException e) {
        logger.error("Failed to create private key for SSH connection.", e);
    }
    return null;
}
 
Example #4
Source File: GitContentRepository.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
private SshSessionFactory getSshSessionFactory(String privateKey, final Path tempKey)  {
    try {
        Files.write(tempKey, privateKey.getBytes());
        SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
            @Override
            protected void configure(OpenSshConfig.Host hc, Session session) {
                Properties config = new Properties();
                config.put("StrictHostKeyChecking", "no");
                session.setConfig(config);
            }

            @Override
            protected JSch createDefaultJSch(FS fs) throws JSchException {
                JSch defaultJSch = new JSch();
                defaultJSch.addIdentity(tempKey.toAbsolutePath().toString());
                return defaultJSch;
            }
        };
        return sshSessionFactory;
    } catch (IOException e) {
        logger.error("Failed to create private key for SSH connection.", e);
    }
    return null;
}
 
Example #5
Source File: GitRepositoryHelper.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
public SshSessionFactory getSshSessionFactory(String privateKey, final Path tempKey)  {
    try {
        Files.write(tempKey, privateKey.getBytes());
        SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
            @Override
            protected void configure(OpenSshConfig.Host hc, Session session) {
                Properties config = new Properties();
                config.put("StrictHostKeyChecking", "no");
                session.setConfig(config);
            }

            @Override
            protected JSch createDefaultJSch(FS fs) throws JSchException {
                JSch defaultJSch = new JSch();
                defaultJSch.addIdentity(tempKey.toAbsolutePath().toString());
                return defaultJSch;
            }
        };
        return sshSessionFactory;
    } catch (IOException e) {
        logger.error("Failed to create private key for SSH connection.", e);
    }
    return null;
}
 
Example #6
Source File: TestSshGit.java    From Jpom with MIT License 5 votes vote down vote up
public static void main(String[] args) throws GitAPIException {
    Git.cloneRepository()
            .setURI("[email protected]:jiangzeyin/test.git")
            .setDirectory(new File("D:\\test\\gitssh"))
            .setTransportConfigCallback(new TransportConfigCallback() {
                @Override
                public void configure(Transport transport) {
                    SshTransport sshTransport = (SshTransport) transport;
                    sshTransport.setSshSessionFactory(new JschConfigSessionFactory() {
                        @Override
                        protected void configure(OpenSshConfig.Host hc, Session session) {
                            session.setConfig("StrictHostKeyChecking", "no");
                            session.setPassword("");
                        }

                        @Override
                        protected JSch createDefaultJSch(FS fs) throws JSchException {
                            JSch defaultJSch = super.createDefaultJSch(fs);

                            defaultJSch.addIdentity("C:\\Users\\Colorful\\.ssh\\id_rsa.pub");
                            return defaultJSch;
                        }

                    });
                }
            })
            .call();
}
 
Example #7
Source File: JGitSshSessionFactory.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean setupJSch (FS fs, String host, CredentialItem.StringType identityFile, URIish uri, boolean preferAgent) throws TransportException {
    boolean agentUsed;
    if (sshConfig == null) {
        sshConfig = OpenSshConfig.get(fs);
    }
    final OpenSshConfig.Host hc = sshConfig.lookup(host);
    try {
        JSch jsch = getJSch(hc, fs);
        agentUsed = setupJSchIdentityRepository(jsch, identityFile.getValue(), preferAgent);
    } catch (JSchException ex) {
        throw new TransportException(uri, ex.getMessage(), ex);
    }
    return agentUsed;
}
 
Example #8
Source File: GitMonitoringService.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
private SshSessionFactory getSshSessionFactory() {
  JschConfigSessionFactory sessionFactory = new JschConfigSessionFactory() {
    @Override
    protected void configure(OpenSshConfig.Host hc, Session session) {
      if (!GitMonitoringService.this.strictHostKeyCheckingEnabled) {
        session.setConfig("StrictHostKeyChecking", "no");
      }
    }

    @Override
    protected JSch createDefaultJSch(FS fs) throws JSchException {
      if (GitMonitoringService.this.isJschLoggerEnabled) {
        JSch.setLogger(new JschLogger());
      }
      JSch defaultJSch = super.createDefaultJSch(fs);
      defaultJSch.getIdentityRepository().removeAll();
      if (GitMonitoringService.this.privateKeyPath != null) {
        defaultJSch.addIdentity(GitMonitoringService.this.privateKeyPath, GitMonitoringService.this.passphrase);
      } else {
        defaultJSch.addIdentity("gaas-git", GitMonitoringService.this.privateKey, null,
            GitMonitoringService.this.passphrase.getBytes(Charset.forName("UTF-8")));
      }
      if (!Strings.isNullOrEmpty(GitMonitoringService.this.knownHosts)) {
        defaultJSch.setKnownHosts(new ByteArrayInputStream(GitMonitoringService.this.knownHosts.getBytes(Charset.forName("UTF-8"))));
      } else if (!Strings.isNullOrEmpty(GitMonitoringService.this.knownHostsFile)) {
        defaultJSch.setKnownHosts(GitMonitoringService.this.knownHostsFile);
      }
      return defaultJSch;
    }
  };
  return sessionFactory;
}
 
Example #9
Source File: FileBasedSshTransportConfigCallback.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(Transport transport) {
	SshSessionFactory.setInstance(new JschConfigSessionFactory() {
		@Override
		protected void configure(OpenSshConfig.Host hc, Session session) {
			session.setConfig("StrictHostKeyChecking",
					FileBasedSshTransportConfigCallback.this.sshUriProperties
							.isStrictHostKeyChecking() ? "yes" : "no");
		}
	});
}
 
Example #10
Source File: TransportConfigurationIntegrationTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void strictHostKeyCheckShouldCheck() throws Exception {
	String uri = "git+ssh://git@somegitserver/somegitrepo";
	SshSessionFactory.setInstance(null);
	this.jGitEnvironmentRepository.setUri(uri);
	this.jGitEnvironmentRepository.setBasedir(new File("./mybasedir"));
	assertThat(this.jGitEnvironmentRepository.isStrictHostKeyChecking())
			.isTrue();
	this.jGitEnvironmentRepository.setCloneOnStart(true);
	try {
		// this will throw but we don't care about connecting.
		this.jGitEnvironmentRepository.afterPropertiesSet();
	}
	catch (Exception e) {
		final OpenSshConfig.Host hc = OpenSshConfig.get(FS.detect())
				.lookup("github.com");
		JschConfigSessionFactory factory = (JschConfigSessionFactory) SshSessionFactory
				.getInstance();
		// There's no public method that can be used to inspect the ssh
		// configuration, so we'll reflect
		// the configure method to allow us to check that the config
		// property is set as expected.
		Method configure = factory.getClass().getDeclaredMethod("configure",
				OpenSshConfig.Host.class, Session.class);
		configure.setAccessible(true);
		Session session = mock(Session.class);
		ArgumentCaptor<String> keyCaptor = ArgumentCaptor
				.forClass(String.class);
		ArgumentCaptor<String> valueCaptor = ArgumentCaptor
				.forClass(String.class);
		configure.invoke(factory, hc, session);
		verify(session).setConfig(keyCaptor.capture(), valueCaptor.capture());
		configure.setAccessible(false);
		assertThat("yes".equals(valueCaptor.getValue())).isTrue();
	}
}
 
Example #11
Source File: TransportConfigurationIntegrationTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void strictHostKeyCheckShouldCheck() throws Exception {
	String uri = "git+ssh://git@somegitserver/somegitrepo";
	SshSessionFactory.setInstance(null);
	this.jGitEnvironmentRepository.setUri(uri);
	this.jGitEnvironmentRepository.setBasedir(new File("./mybasedir"));
	assertThat(this.jGitEnvironmentRepository.isStrictHostKeyChecking())
			.isTrue();
	this.jGitEnvironmentRepository.setCloneOnStart(true);
	try {
		// this will throw but we don't care about connecting.
		this.jGitEnvironmentRepository.afterPropertiesSet();
	}
	catch (Exception e) {
		final OpenSshConfig.Host hc = OpenSshConfig.get(FS.detect())
				.lookup("github.com");
		JschConfigSessionFactory factory = (JschConfigSessionFactory) SshSessionFactory
				.getInstance();
		// There's no public method that can be used to inspect the ssh
		// configuration, so we'll reflect
		// the configure method to allow us to check that the config
		// property is set as expected.
		Method configure = factory.getClass().getDeclaredMethod("configure",
				OpenSshConfig.Host.class, Session.class);
		configure.setAccessible(true);
		Session session = mock(Session.class);
		ArgumentCaptor<String> keyCaptor = ArgumentCaptor
				.forClass(String.class);
		ArgumentCaptor<String> valueCaptor = ArgumentCaptor
				.forClass(String.class);
		configure.invoke(factory, hc, session);
		verify(session).setConfig(keyCaptor.capture(), valueCaptor.capture());
		configure.setAccessible(false);
		assertThat("yes".equals(valueCaptor.getValue())).isTrue();
	}
}
 
Example #12
Source File: JGitConfigSessionFactory.java    From mOrgAnd with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void configure(OpenSshConfig.Host host, Session session) {
    session.setConfig("StrictHostKeyChecking", "no"); // TODO Find out how to enable strict host checking

    // TODO Delete me
    // String knownHostsLocation = "/sdcard/morg/known_hosts";
    // jSch.setKnownHosts(knownHostsLocation);

    CredentialsProvider provider = new JGitCredentialsProvider(username, password);
    session.setUserInfo(new CredentialsProviderUserInfo(session, provider));
}
 
Example #13
Source File: JGitConfigSessionFactory.java    From mOrgAnd with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected JSch getJSch(OpenSshConfig.Host hc, FS fs) throws JSchException {
    JSch jSch = super.getJSch(hc, fs);
    jSch.removeAllIdentity();
    if (!keyLocation.isEmpty())
        jSch.addIdentity(keyLocation, password);
    return jSch;
}
 
Example #14
Source File: StudioNodeSyncGlobalRepoTask.java    From studio with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected void configure(OpenSshConfig.Host hc, Session session) {
    Properties config = new Properties();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
}
 
Example #15
Source File: CustomJschConfigSessionFactory.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
@Override
protected void configure(OpenSshConfig.Host host, Session session) {
    java.util.Properties config = new java.util.Properties();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
}
 
Example #16
Source File: SshAgentSessionFactory.java    From multi-module-maven-release-plugin with MIT License 4 votes vote down vote up
@Override
protected void configure(final OpenSshConfig.Host host, final Session sn) {
}
 
Example #17
Source File: GitRepo.java    From spring-cloud-release-tools with Apache License 2.0 4 votes vote down vote up
@Override
protected void configure(OpenSshConfig.Host host, Session session) {
}
 
Example #18
Source File: GitClient.java    From flow-platform-x with Apache License 2.0 4 votes vote down vote up
@Override
protected void configure(OpenSshConfig.Host host, Session session) {
    session.setConfig("StrictHostKeyChecking", "no");
}