Java Code Examples for com.jcraft.jsch.JSch#setConfig()

The following examples show how to use com.jcraft.jsch.JSch#setConfig() . 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: JSchHelper.java    From ssh-proxy with Apache License 2.0 6 votes vote down vote up
protected static void reconfigureServerHostKeyOrder(ServerHostKeySortOrder hostKeySortOrder) {
	List<HostKeyType> serverHostKeys = new ArrayList<>(getServerHostKeys());
	if (hostKeySortOrder == ServerHostKeySortOrder.PREFER_ECDSA) {
		serverHostKeys.sort(CMP_PREFER_ECDSA);
	} else if (hostKeySortOrder == ServerHostKeySortOrder.PREFER_RSA) {
		serverHostKeys.sort(CMP_PREFER_RSA);
	} else {
		throw new IllegalArgumentException("Unknown host key sort order: " + hostKeySortOrder);
	}

	if (!getServerHostKeys().equals(serverHostKeys)) {
		log.debug("changing server host key order to: {}", serverHostKeys);

		List<String> serverHostKeyNames = new ArrayList<>();
		for (HostKeyType serverHostKey : serverHostKeys) {
			serverHostKeyNames.add(serverHostKey.getTypeString());
		}

		String newHostKeyOrder = Utils.join(serverHostKeyNames, SERVER_HOST_KEY_SEPARATOR);
		JSch.setConfig(JSCH_CONFIG_KEY_SERVER_HOST_KEY, newHostKeyOrder);
	}
}
 
Example 2
Source File: JSchModule.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Provides
static JSch provideJSch(
    @Config("rdeSshIdentity") String identity,
    @Key("rdeSshClientPrivateKey") String privateKey,
    @Key("rdeSshClientPublicKey") String publicKey) {
  JSch jsch = new JSch();
  try {
    jsch.addIdentity(
        identity,
        privateKey.getBytes(UTF_8),
        publicKey.getBytes(UTF_8),
        null);
  } catch (JSchException e) {
    throw new RuntimeException(e);
  }
  // TODO(b/13028224): Implement known hosts checking.
  JSch.setConfig("StrictHostKeyChecking", "no");
  return jsch;
}
 
Example 3
Source File: Ssh.java    From BigDataScript with Apache License 2.0 6 votes vote down vote up
/**
 * Connect to a remote host and return a channel (session and jsch are set)
 */
Channel connect(String channleType, String sshCommand) throws Exception {
	JSch.setConfig("StrictHostKeyChecking", "no"); // Not recommended, but useful
	jsch = new JSch();

	// Some "reasonable" defaults
	if (Gpr.exists(defaultKnownHosts)) jsch.setKnownHosts(defaultKnownHosts);
	for (String identity : defaultKnownIdentity)
		if (Gpr.exists(identity)) jsch.addIdentity(identity);

	// Create session and connect
	if (debug) Gpr.debug("Create conection:\n\tuser: '" + host.getUserName() + "'\n\thost : '" + host.getHostName() + "'\n\tport : " + host.getPort());
	session = jsch.getSession(host.getUserName(), host.getHostName(), host.getPort());
	session.setUserInfo(new SshUserInfo());
	session.connect();

	// Create channel
	channel = session.openChannel(channleType);
	if ((sshCommand != null) && (channel instanceof ChannelExec)) ((ChannelExec) channel).setCommand(sshCommand);

	return channel;
}
 
Example 4
Source File: KeyReExchangeTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test
public void testReExchangeFromJschClient() throws Exception {
    Assume.assumeTrue("DH Group Exchange not supported", SecurityUtils.isDHGroupExchangeSupported());
    setUp(0L, 0L, 0L);

    JSch.setConfig("kex", BuiltinDHFactories.Constants.DIFFIE_HELLMAN_GROUP_EXCHANGE_SHA1);
    JSch sch = new JSch();
    com.jcraft.jsch.Session s = sch.getSession(getCurrentTestName(), TEST_LOCALHOST, port);
    try {
        s.setUserInfo(new SimpleUserInfo(getCurrentTestName()));
        s.connect();

        com.jcraft.jsch.Channel c = s.openChannel(Channel.CHANNEL_SHELL);
        c.connect();
        try (OutputStream os = c.getOutputStream();
             InputStream is = c.getInputStream()) {

            String expected = "this is my command\n";
            byte[] bytes = expected.getBytes(StandardCharsets.UTF_8);
            byte[] data = new byte[bytes.length + Long.SIZE];
            for (int i = 1; i <= 10; i++) {
                os.write(bytes);
                os.flush();

                int len = is.read(data);
                String str = new String(data, 0, len);
                assertEquals("Mismatched data at iteration " + i, expected, str);

                outputDebugMessage("Request re-key #%d", i);
                s.rekey();
            }
        } finally {
            c.disconnect();
        }
    } finally {
        s.disconnect();
    }
}
 
Example 5
Source File: ATest.java    From aws-ec2-ssh with MIT License 5 votes vote down vote up
protected final void probeSSH(final String host, final User user) {
    final Callable<Boolean> callable = () -> {
        final JSch jsch = new JSch();
        final Session session = jsch.getSession(user.userName, host);
        jsch.addIdentity(user.userName, user.sshPrivateKeyBlob, null, null);
        jsch.setConfig("StrictHostKeyChecking", "no"); // for testing this should be fine. adding the host key seems to be only possible via a file which is not very useful here
        session.connect(10000);
        session.disconnect();
        return true;
    };
    Assert.assertTrue(this.retry(callable));
}
 
Example 6
Source File: ATest.java    From aws-cf-templates with Apache License 2.0 5 votes vote down vote up
protected final void probeSSH(final String host, final User user) {
    final Callable<Boolean> callable = () -> {
        final JSch jsch = new JSch();
        final Session session = jsch.getSession(user.userName, host);
        jsch.addIdentity(user.userName, user.sshPrivateKeyBlob, null, null);
        jsch.setConfig("StrictHostKeyChecking", "no"); // for testing this should be fine. adding the host key seems to be only possible via a file which is not very useful here
        session.connect(10000);
        session.disconnect();
        return true;
    };
    Assert.assertTrue(this.retry(callable));
}
 
Example 7
Source File: ATest.java    From aws-cf-templates with Apache License 2.0 5 votes vote down vote up
protected final void probeSSH(final String host, final KeyPair key) {
    final Callable<Boolean> callable = () -> {
        final JSch jsch = new JSch();
        final Session session = jsch.getSession("ec2-user", host);
        jsch.addIdentity(key.getKeyName(), key.getKeyMaterial().getBytes(), null, null);
        jsch.setConfig("StrictHostKeyChecking", "no"); // for testing this should be fine. adding the host key seems to be only possible via a file which is not very useful here
        session.connect(10000);
        session.disconnect();
        return true;
    };
    Assert.assertTrue(this.retry(callable));
}
 
Example 8
Source File: ATest.java    From aws-cf-templates with Apache License 2.0 5 votes vote down vote up
protected final Session tunnelSSH(final String host, final KeyPair key, final Integer localPort, final String remoteHost, final Integer remotePort) throws JSchException {
    final JSch jsch = new JSch();
    final Session session = jsch.getSession("ec2-user", host);
    jsch.addIdentity(key.getKeyName(), key.getKeyMaterial().getBytes(), null, null);
    jsch.setConfig("StrictHostKeyChecking", "no"); // for testing this should be fine. adding the host key seems to be only possible via a file which is not very useful here
    session.setPortForwardingL(localPort, remoteHost, remotePort);
    session.connect(10000);
    return session;
}
 
Example 9
Source File: SshXpraConnector.java    From xpra-client with GNU General Public License v3.0 5 votes vote down vote up
public SshXpraConnector(XpraClient client, String host, String username, int port, UserInfo userInfo) {
	super(client);
	this.host = host;
	this.username = username;
	this.port = port;
	this.userInfo = userInfo;
	JSch.setConfig("compression_level", "0");
}
 
Example 10
Source File: KeyReExchangeTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test
public void testReExchangeFromJschClient() throws Exception {
    Assume.assumeTrue("DH Group Exchange not supported", SecurityUtils.isDHGroupExchangeSupported());
    setUp(0L, 0L, 0L);

    JSch.setConfig("kex", BuiltinDHFactories.Constants.DIFFIE_HELLMAN_GROUP_EXCHANGE_SHA1);
    JSch sch = new JSch();
    com.jcraft.jsch.Session s = sch.getSession(getCurrentTestName(), TEST_LOCALHOST, port);
    try {
        s.setUserInfo(new SimpleUserInfo(getCurrentTestName()));
        s.connect();

        com.jcraft.jsch.Channel c = s.openChannel(Channel.CHANNEL_SHELL);
        c.connect();
        try (OutputStream os = c.getOutputStream();
             InputStream is = c.getInputStream()) {

            String expected = "this is my command\n";
            byte[] bytes = expected.getBytes(StandardCharsets.UTF_8);
            byte[] data = new byte[bytes.length + Long.SIZE];
            for (int i = 1; i <= 10; i++) {
                os.write(bytes);
                os.flush();

                int len = is.read(data);
                String str = new String(data, 0, len);
                assertEquals("Mismatched data at iteration " + i, expected, str);

                outputDebugMessage("Request re-key #%d", i);
                s.rekey();
            }
        } finally {
            c.disconnect();
        }
    } finally {
        s.disconnect();
    }
}
 
Example 11
Source File: JSchHelper.java    From ssh-proxy with Apache License 2.0 4 votes vote down vote up
protected static void reconfigurePreferredAuthentications() {
	JSch.setConfig(JSCH_CONFIG_KEY_PREFERRED_AUTHENTICATIONS, "publickey");
}
 
Example 12
Source File: GitConfigStore.java    From vertx-config with Apache License 2.0 4 votes vote down vote up
public GitConfigStore(Vertx vertx, JsonObject configuration) {
  this.vertx = vertx;

  String path = Objects.requireNonNull(configuration.getString("path"),
    "The `path` configuration is required.");
  this.path = new File(path);
  if (this.path.isFile()) {
    throw new IllegalArgumentException("The `path` must not be a file");
  }

  JsonArray filesets = Objects.requireNonNull(configuration
      .getJsonArray("filesets"),
    "The `filesets` element is required.");

  for (Object o : filesets) {
    JsonObject json = (JsonObject) o;
    FileSet set = new FileSet(vertx, this.path, json);
    this.filesets.add(set);
  }

  // Git repository
  url = Objects.requireNonNull(configuration.getString("url"),
    "The `url` configuration (Git repository location) is required.");
  branch = configuration.getString("branch", "master");
  remote = configuration.getString("remote", "origin");

  if (Objects.nonNull(configuration.getString("user")) &&
      Objects.nonNull(configuration.getString("password"))) {
    credentialProvider = new UsernamePasswordCredentialsProvider(
      configuration.getString("user"), configuration.getString("password"));
  } else {
    credentialProvider = null;
  }
  if(Objects.nonNull(configuration.getString("idRsaKeyPath"))){
    SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
      @Override
      protected void configure(OpenSshConfig.Host host, Session session ) {
      }
      @Override
      protected JSch createDefaultJSch(FS fs ) throws JSchException {
        JSch defaultJSch = super.createDefaultJSch( fs );
        defaultJSch.setConfig("StrictHostKeyChecking", "no");
        defaultJSch.addIdentity(configuration.getString("idRsaKeyPath"));
        return defaultJSch;
      }
    };
    transportConfigCallback = new TransportConfigCallback() {
      @Override
      public void configure( Transport transport ) {
        SshTransport sshTransport = ( SshTransport )transport;
        sshTransport.setSshSessionFactory( sshSessionFactory );
      }
    };
  }else {
    transportConfigCallback = null;
  }

  try {
    git = initializeGit();
  } catch (Exception e) {
    throw new VertxException("Unable to initialize the Git repository", e);
  }
}