org.apache.sshd.client.SshClient Java Examples

The following examples show how to use org.apache.sshd.client.SshClient. 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: NetconfSessionMinaImpl.java    From onos with Apache License 2.0 8 votes vote down vote up
private void startClient() throws IOException {
    log.info("Creating NETCONF session to {}",
            deviceInfo.getDeviceId());

    client = SshClient.setUpDefaultClient();
    if (idleTimeout != NetconfControllerImpl.netconfIdleTimeout) {
        client.getProperties().putIfAbsent(FactoryManager.IDLE_TIMEOUT,
                TimeUnit.SECONDS.toMillis(idleTimeout));
        client.getProperties().putIfAbsent(FactoryManager.NIO2_READ_TIMEOUT,
                TimeUnit.SECONDS.toMillis(idleTimeout + 15L));
    }
    client.start();
    client.setKeyPairProvider(new SimpleGeneratorHostKeyProvider());
    startSession();

    disconnected = false;
}
 
Example #2
Source File: KeepAliveTest.java    From termd with Apache License 2.0 6 votes vote down vote up
@Test
public void testIdleClient() throws Exception {
    SshClient client = setupTestClient();
    client.start();

    try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
        session.addPasswordIdentity(getCurrentTestName());
        session.auth().verify(5L, TimeUnit.SECONDS);

        try (ClientChannel channel = session.createChannel(Channel.CHANNEL_SHELL)) {
            Collection<ClientChannelEvent> result =
                    channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), WAIT);
            assertTrue("Wrong channel state: " + result, result.containsAll(EnumSet.of(ClientChannelEvent.CLOSED)));
        }
    } finally {
        client.stop();
    }
}
 
Example #3
Source File: KeepAliveTest.java    From termd with Apache License 2.0 6 votes vote down vote up
@Test
public void testClientWithHeartBeat() throws Exception {
    SshClient client = setupTestClient();
    PropertyResolverUtils.updateProperty(client, ClientFactoryManager.HEARTBEAT_INTERVAL, HEARTBEAT);
    client.start();

    try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
        session.addPasswordIdentity(getCurrentTestName());
        session.auth().verify(5L, TimeUnit.SECONDS);

        try (ClientChannel channel = session.createChannel(Channel.CHANNEL_SHELL)) {
            Collection<ClientChannelEvent> result =
                    channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), WAIT);
            assertTrue("Wrong channel state: " + result, result.contains(ClientChannelEvent.TIMEOUT));
        }
    } finally {
        client.stop();
    }
}
 
Example #4
Source File: AuthenticationTest.java    From termd with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthPasswordOnly() throws Exception {
    try (SshClient client = setupTestClient()) {
        sshd.setPasswordAuthenticator(RejectAllPasswordAuthenticator.INSTANCE);

        client.start();
        try (ClientSession s = client.connect(null, TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
            Collection<ClientSession.ClientSessionEvent> result =
                    s.waitFor(EnumSet.of(ClientSession.ClientSessionEvent.CLOSED, ClientSession.ClientSessionEvent.WAIT_AUTH),
                    TimeUnit.SECONDS.toMillis(11L));
            assertFalse("Timeout while waiting for session", result.contains(ClientSession.ClientSessionEvent.TIMEOUT));

            String password = getCurrentTestName();
            try {
                assertAuthenticationResult(getCurrentTestName(), authPassword(s, getCurrentTestName(), password), false);
            } finally {
                s.removePasswordIdentity(password);
            }
        } finally {
            client.stop();
        }
    }
}
 
Example #5
Source File: KeyReExchangeTest.java    From termd with Apache License 2.0 6 votes vote down vote up
@Test
public void testSwitchToNoneCipher() throws Exception {
    setUp(0L, 0L, 0L);

    sshd.getCipherFactories().add(BuiltinCiphers.none);
    try (SshClient client = setupTestClient()) {
        client.getCipherFactories().add(BuiltinCiphers.none);
        client.start();

        try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
            session.addPasswordIdentity(getCurrentTestName());
            session.auth().verify(5L, TimeUnit.SECONDS);

            outputDebugMessage("Request switch to none cipher for %s", session);
            KeyExchangeFuture switchFuture = session.switchToNoneCipher();
            switchFuture.verify(5L, TimeUnit.SECONDS);
            try (ClientChannel channel = session.createSubsystemChannel(SftpConstants.SFTP_SUBSYSTEM_NAME)) {
                channel.open().verify(5L, TimeUnit.SECONDS);
            }
        } finally {
            client.stop();
        }
    }
}
 
Example #6
Source File: WindowAdjustTest.java    From termd with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 6L * 60L * 1000L)
public void testTrafficHeavyLoad() throws Exception {
    try (SshClient client = setupTestClient()) {
        client.start();

        try (final ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
            session.addPasswordIdentity(getCurrentTestName());
            session.auth().verify(11L, TimeUnit.SECONDS);

            try (final ClientChannel channel = session.createShellChannel()) {
                channel.setOut(new VerifyingOutputStream(channel, END_FILE));
                channel.setErr(new NoCloseOutputStream(System.err));
                channel.open().verify(15L, TimeUnit.SECONDS);

                Collection<ClientChannelEvent> result =
                        channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.MINUTES.toMillis(2L));
                assertFalse("Timeout while waiting for channel closure", result.contains(ClientChannelEvent.TIMEOUT));
            }
        } finally {
            client.stop();
        }
    }
}
 
Example #7
Source File: AuthenticationTest.java    From termd with Apache License 2.0 6 votes vote down vote up
@Test
public void testPasswordIdentityProviderPropagation() throws Exception {
    try (SshClient client = setupTestClient()) {
        final List<String> passwords = Collections.singletonList(getCurrentTestName());
        final AtomicInteger loadCount = new AtomicInteger(0);
        PasswordIdentityProvider provider = new PasswordIdentityProvider() {
            @Override
            public Iterable<String> loadPasswords() {
                loadCount.incrementAndGet();
                outputDebugMessage("loadPasswords - count=%s", loadCount);
                return passwords;
            }
        };
        client.setPasswordIdentityProvider(provider);

        client.start();
        try (ClientSession s = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
            s.auth().verify(11L, TimeUnit.SECONDS);
            assertEquals("Mismatched load passwords count", 1, loadCount.get());
            assertSame("Mismatched passwords identity provider", provider, s.getPasswordIdentityProvider());
        } finally {
            client.stop();
        }
    }
}
 
Example #8
Source File: RuntimeClient.java    From tesb-studio-se with Apache License 2.0 6 votes vote down vote up
private static ClientSession connectWithRetries(SshClient client, ClientConfig config) throws Exception, InterruptedException {
    ClientSession session = null;
    int retries = 0;
    do {
        try {
            ConnectFuture future = client.connect(config.getUser(), config.getHost(), config.getPort());
            future.await();
            session = future.getSession();
        } catch (RuntimeSshException ex) {
            if (++retries < 10) {
                TimeUnit.SECONDS.sleep(2);
            } else {
                throw ex;
            }
        }
    } while (session == null);
    return session;
}
 
Example #9
Source File: WindowAdjustTest.java    From termd with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 6L * 60L * 1000L)
public void testTrafficHeavyLoad() throws Exception {
    try (SshClient client = setupTestClient()) {
        client.start();

        try (final ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
            session.addPasswordIdentity(getCurrentTestName());
            session.auth().verify(11L, TimeUnit.SECONDS);

            try (final ClientChannel channel = session.createShellChannel()) {
                channel.setOut(new VerifyingOutputStream(channel, END_FILE));
                channel.setErr(new NoCloseOutputStream(System.err));
                channel.open().verify(15L, TimeUnit.SECONDS);

                Collection<ClientChannelEvent> result =
                        channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.MINUTES.toMillis(2L));
                assertFalse("Timeout while waiting for channel closure", result.contains(ClientChannelEvent.TIMEOUT));
            }
        } finally {
            client.stop();
        }
    }
}
 
Example #10
Source File: KeepAliveTest.java    From termd with Apache License 2.0 6 votes vote down vote up
@Test
public void testIdleClient() throws Exception {
    SshClient client = setupTestClient();
    client.start();

    try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
        session.addPasswordIdentity(getCurrentTestName());
        session.auth().verify(5L, TimeUnit.SECONDS);

        try (ClientChannel channel = session.createChannel(Channel.CHANNEL_SHELL)) {
            Collection<ClientChannelEvent> result =
                    channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), WAIT);
            assertTrue("Wrong channel state: " + result, result.containsAll(EnumSet.of(ClientChannelEvent.CLOSED)));
        }
    } finally {
        client.stop();
    }
}
 
Example #11
Source File: KeepAliveTest.java    From termd with Apache License 2.0 6 votes vote down vote up
@Test
public void testClientWithHeartBeat() throws Exception {
    SshClient client = setupTestClient();
    PropertyResolverUtils.updateProperty(client, ClientFactoryManager.HEARTBEAT_INTERVAL, HEARTBEAT);
    client.start();

    try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
        session.addPasswordIdentity(getCurrentTestName());
        session.auth().verify(5L, TimeUnit.SECONDS);

        try (ClientChannel channel = session.createChannel(Channel.CHANNEL_SHELL)) {
            Collection<ClientChannelEvent> result =
                    channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), WAIT);
            assertTrue("Wrong channel state: " + result, result.contains(ClientChannelEvent.TIMEOUT));
        }
    } finally {
        client.stop();
    }
}
 
Example #12
Source File: KeyReExchangeTest.java    From termd with Apache License 2.0 6 votes vote down vote up
@Test
public void testSwitchToNoneCipher() throws Exception {
    setUp(0L, 0L, 0L);

    sshd.getCipherFactories().add(BuiltinCiphers.none);
    try (SshClient client = setupTestClient()) {
        client.getCipherFactories().add(BuiltinCiphers.none);
        client.start();

        try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
            session.addPasswordIdentity(getCurrentTestName());
            session.auth().verify(5L, TimeUnit.SECONDS);

            outputDebugMessage("Request switch to none cipher for %s", session);
            KeyExchangeFuture switchFuture = session.switchToNoneCipher();
            switchFuture.verify(5L, TimeUnit.SECONDS);
            try (ClientChannel channel = session.createSubsystemChannel(SftpConstants.SFTP_SUBSYSTEM_NAME)) {
                channel.open().verify(5L, TimeUnit.SECONDS);
            }
        } finally {
            client.stop();
        }
    }
}
 
Example #13
Source File: AuthenticationTest.java    From termd with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthPasswordOnly() throws Exception {
    try (SshClient client = setupTestClient()) {
        sshd.setPasswordAuthenticator(RejectAllPasswordAuthenticator.INSTANCE);

        client.start();
        try (ClientSession s = client.connect(null, TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
            Collection<ClientSession.ClientSessionEvent> result =
                    s.waitFor(EnumSet.of(ClientSession.ClientSessionEvent.CLOSED, ClientSession.ClientSessionEvent.WAIT_AUTH),
                    TimeUnit.SECONDS.toMillis(11L));
            assertFalse("Timeout while waiting for session", result.contains(ClientSession.ClientSessionEvent.TIMEOUT));

            String password = getCurrentTestName();
            try {
                assertAuthenticationResult(getCurrentTestName(), authPassword(s, getCurrentTestName(), password), false);
            } finally {
                s.removePasswordIdentity(password);
            }
        } finally {
            client.stop();
        }
    }
}
 
Example #14
Source File: AuthenticationTest.java    From termd with Apache License 2.0 6 votes vote down vote up
@Test
public void testPasswordIdentityProviderPropagation() throws Exception {
    try (SshClient client = setupTestClient()) {
        final List<String> passwords = Collections.singletonList(getCurrentTestName());
        final AtomicInteger loadCount = new AtomicInteger(0);
        PasswordIdentityProvider provider = new PasswordIdentityProvider() {
            @Override
            public Iterable<String> loadPasswords() {
                loadCount.incrementAndGet();
                outputDebugMessage("loadPasswords - count=%s", loadCount);
                return passwords;
            }
        };
        client.setPasswordIdentityProvider(provider);

        client.start();
        try (ClientSession s = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
            s.auth().verify(11L, TimeUnit.SECONDS);
            assertEquals("Mismatched load passwords count", 1, loadCount.get());
            assertSame("Mismatched passwords identity provider", provider, s.getPasswordIdentityProvider());
        } finally {
            client.stop();
        }
    }
}
 
Example #15
Source File: FuseUtils.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private static ClientSession openSshChannel(String username, String password) throws IOException {
    SshClient client = SshClient.setUpDefaultClient();
    client.start();
    ConnectFuture future = client.connect(username, "localhost", 8101);
    future.await();
    ClientSession session = future.getSession();

    Set<ClientSession.ClientSessionEvent> ret = EnumSet.of(ClientSession.ClientSessionEvent.WAIT_AUTH);
    while (ret.contains(ClientSession.ClientSessionEvent.WAIT_AUTH)) {
        session.addPasswordIdentity(password);
        session.auth().verify();
        ret = session.waitFor(EnumSet.of(ClientSession.ClientSessionEvent.WAIT_AUTH, ClientSession.ClientSessionEvent.CLOSED, ClientSession.ClientSessionEvent.AUTHED), 0);
    }
    if (ret.contains(ClientSession.ClientSessionEvent.CLOSED)) {
        throw new RuntimeException("Could not open SSH channel");
    }

    return session;
}
 
Example #16
Source File: SshInteractiveProcessITest.java    From xenon with Apache License 2.0 5 votes vote down vote up
@Test
public void test_exitStatusBeforeFinish() throws Exception {
    SshClient client = SSHUtil.createSSHClient(false, false, false, false, false);
    SSHConnection conn = SSHUtil.connect("test", client, getLocation(), getCorrectCredential(), 0, 10 * 1000);

    JobDescription desc = new JobDescription();
    desc.setExecutable("/bin/sleep");
    desc.addArgument("5");

    String id = "TESTID";

    SshInteractiveProcess p = new SshInteractiveProcess(conn.getSession(), desc, id, 10000L);

    // Not done yet, so exit returns -1
    assertEquals(-1, p.getExitStatus());

    Streams s = p.getStreams();

    assertNotNull(s.getStdin());
    assertNotNull(s.getStdout());
    assertNotNull(s.getStderr());

    s.getStdin().close();

    OutputReader stdout = new OutputReader(s.getStdout());
    OutputReader stderr = new OutputReader(s.getStderr());

    stderr.waitUntilFinished();
    stdout.waitUntilFinished();

    String output = stdout.getResultAsString();
    String error = stderr.getResultAsString();

    assertTrue(error.isEmpty());
    assertTrue(output.isEmpty());

    // Done yet, so exit returns 0
    assertEquals(0, p.getExitStatus());
}
 
Example #17
Source File: SshSchedulerAdaptor.java    From xenon with Apache License 2.0 5 votes vote down vote up
@Override
public Scheduler createScheduler(String location, Credential credential, Map<String, String> properties) throws XenonException {

    LOGGER.debug("new SSH scheduler location = {} credential = {} properties = {}", location, credential, properties);

    XenonProperties xp = new XenonProperties(VALID_PROPERTIES, properties);

    boolean loadKnownHosts = xp.getBooleanProperty(LOAD_STANDARD_KNOWN_HOSTS);
    boolean loadSSHConfig = xp.getBooleanProperty(LOAD_SSH_CONFIG);
    boolean strictHostCheck = xp.getBooleanProperty(STRICT_HOST_KEY_CHECKING);
    boolean useSSHAgent = xp.getBooleanProperty(AGENT);
    boolean useAgentForwarding = xp.getBooleanProperty(AGENT_FORWARDING);

    SshClient client = SSHUtil.createSSHClient(loadKnownHosts, loadSSHConfig, strictHostCheck, useSSHAgent, useAgentForwarding);

    long timeout = xp.getLongProperty(TIMEOUT);

    SSHConnection connection = SSHUtil.connect(ADAPTOR_NAME, client, location, credential, 0, timeout);

    // We must convert the relevant SSH properties to SFTP here.
    Map<String, String> sftpProperties = SSHUtil.translateProperties(properties, SshSchedulerAdaptor.PREFIX,
            FileSystem.getAdaptorDescription("sftp").getSupportedProperties(), SftpFileAdaptor.PREFIX);

    // Create a file system that point to the same location as the
    // scheduler.
    FileSystem fs = FileSystem.create("sftp", location, credential, sftpProperties);

    long pollingDelay = xp.getLongProperty(POLLING_DELAY);
    int multiQThreads = xp.getIntegerProperty(MULTIQ_MAX_CONCURRENT);

    return new JobQueueScheduler(getNewUniqueID(), ADAPTOR_NAME, location, credential, new SshInteractiveProcessFactory(connection), fs,
            fs.getWorkingDirectory(), multiQThreads, pollingDelay, timeout, xp);
}
 
Example #18
Source File: SshInteractiveProcessITest.java    From xenon with Apache License 2.0 5 votes vote down vote up
@Test
public void test_run_hostname() throws Exception {
    SshClient client = SSHUtil.createSSHClient(false, false, false, false, false);
    SSHConnection conn = SSHUtil.connect("test", client, getLocation(), getCorrectCredential(), 0, 10 * 1000);

    JobDescription desc = new JobDescription();
    desc.setExecutable("/bin/hostname");

    String id = "TESTID";

    SshInteractiveProcess p = new SshInteractiveProcess(conn.getSession(), desc, id, 10000L);

    Streams s = p.getStreams();

    assertNotNull(s.getStdin());
    assertNotNull(s.getStdout());
    assertNotNull(s.getStderr());

    // No input, so close stdin
    s.getStdin().close();

    OutputReader stdout = new OutputReader(s.getStdout());
    OutputReader stderr = new OutputReader(s.getStderr());

    stderr.waitUntilFinished();
    stdout.waitUntilFinished();

    String output = stdout.getResultAsString();
    String error = stderr.getResultAsString();

    assertTrue(error.isEmpty());
    assertFalse(output.isEmpty());
    assertEquals(0, p.getExitStatus());
}
 
Example #19
Source File: SshInteractiveProcessITest.java    From xenon with Apache License 2.0 5 votes vote down vote up
@Test
public void test_run_cat() throws Exception {
    SshClient client = SSHUtil.createSSHClient(false, false, false, false, false);
    SSHConnection conn = SSHUtil.connect("test", client, getLocation(), getCorrectCredential(), 0, 10 * 1000);

    JobDescription desc = new JobDescription();
    desc.setExecutable("/bin/cat");

    String id = "TESTID";

    SshInteractiveProcess p = new SshInteractiveProcess(conn.getSession(), desc, id, 10000L);

    Streams s = p.getStreams();

    assertNotNull(s.getStdin());
    assertNotNull(s.getStdout());
    assertNotNull(s.getStderr());

    String message = "Hello World!";

    InputWriter stdin = new InputWriter(message, s.getStdin());
    OutputReader stdout = new OutputReader(s.getStdout());
    OutputReader stderr = new OutputReader(s.getStderr());

    stdin.waitUntilFinished();
    stderr.waitUntilFinished();
    stdout.waitUntilFinished();

    String output = stdout.getResultAsString();
    String error = stderr.getResultAsString();

    assertTrue(error.isEmpty());
    assertEquals(message, output);
    assertEquals(0, p.getExitStatus());
}
 
Example #20
Source File: SshTunnelDockerTest.java    From xenon with Apache License 2.0 5 votes vote down vote up
@Test
public void test_tunnel_one_hop() throws Exception {
    SshClient client = SSHUtil.createSSHClient(false, false, false, false, false);

    String location = "ssh2 via:" + getLocation();

    CredentialMap map = new CredentialMap();
    map.put("ssh2", new PasswordCredential("xenon2", "javagat2".toCharArray()));
    map.put(getLocation(), new PasswordCredential("xenon", "javagat".toCharArray()));

    SSHConnection session = SSHUtil.connect("test", client, location, map, 0, 10 * 1000);
    session.close();
}
 
Example #21
Source File: SshTunnelDockerTest.java    From xenon with Apache License 2.0 5 votes vote down vote up
@Test
public void test_tunnel_two_hop() throws Exception {
    SshClient client = SSHUtil.createSSHClient(false, false, false, false, false);

    String location = "ssh3 via:ssh2 via:" + getLocation();

    CredentialMap map = new CredentialMap();
    map.put("ssh3", new PasswordCredential("xenon", "javagat".toCharArray()));
    map.put("ssh2", new PasswordCredential("xenon2", "javagat2".toCharArray()));
    map.put(getLocation(), new PasswordCredential("xenon", "javagat".toCharArray()));

    SSHConnection session = SSHUtil.connect("test", client, location, map, 0, 10 * 1000);
    session.close();
}
 
Example #22
Source File: SSHServerTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 10000L)
public void call() throws Exception {
    final SshClient client = SshClient.setUpDefaultClient();
    client.start();
    try {
        final ClientSession session = client.connect("jonathan", "localhost", 4222).verify().getSession();
        session.addPasswordIdentity("secret");
        session.auth().verify(FactoryManager.DEFAULT_AUTH_TIMEOUT);

        final ClientChannel channel = session.createChannel("shell");
        ByteArrayOutputStream sent = new ByteArrayOutputStream();
        PipedOutputStream pipedIn = new TeePipedOutputStream(sent);
        channel.setIn(new PipedInputStream(pipedIn));
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayOutputStream err = new ByteArrayOutputStream();
        channel.setOut(out);
        channel.setErr(err);
        channel.open();

        pipedIn.write("properties\r\n".getBytes());
        pipedIn.flush();

        pipedIn.write("exit\r\n".getBytes());
        pipedIn.flush();

        channel.waitFor(Collections.singleton(ClientChannelEvent.CLOSED), 0);
        channel.close(false);
        client.stop();

        assertTrue(new String(sent.toByteArray()).contains("properties\r\nexit\r\n"));
        assertTrue(new String(out.toByteArray()).contains("ServerService(id=ssh)"));
    } catch (Exception e) {
        e.printStackTrace();
        fail();
    }
}
 
Example #23
Source File: SshTunnelDockerTest.java    From xenon with Apache License 2.0 5 votes vote down vote up
@Test
public void test_no_tunnel() throws Exception {
    SshClient client = SSHUtil.createSSHClient(false, false, false, false, false);

    SSHConnection session = SSHUtil.connect("test", client, getLocation(), new PasswordCredential("xenon", "javagat".toCharArray()), 0, 10 * 1000);
    session.close();
}
 
Example #24
Source File: SinglePublicKeyAuthTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test
public void testPublicKeyAuthWithCache() throws Exception {
    final ConcurrentHashMap<String, AtomicInteger> count = new ConcurrentHashMap<String, AtomicInteger>();
    TestCachingPublicKeyAuthenticator auth = new TestCachingPublicKeyAuthenticator(new PublickeyAuthenticator() {
        @SuppressWarnings("synthetic-access")
        @Override
        public boolean authenticate(String username, PublicKey key, ServerSession session) {
            String fp = KeyUtils.getFingerPrint(key);
            count.putIfAbsent(fp, new AtomicInteger());
            count.get(fp).incrementAndGet();
            return key.equals(pairRsa.getPublic());
        }
    });
    delegate = auth;

    try (SshClient client = setupTestClient()) {
        client.start();

        try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
            session.addPublicKeyIdentity(pairRsaBad);
            session.addPublicKeyIdentity(pairRsa);
            session.auth().verify(5L, TimeUnit.SECONDS);

            assertEquals("Mismatched authentication invocations count", 2, count.size());

            String fpBad = KeyUtils.getFingerPrint(pairRsaBad.getPublic());
            String fpGood = KeyUtils.getFingerPrint(pairRsa.getPublic());
            assertTrue("Missing bad public key", count.containsKey(fpBad));
            assertTrue("Missing good public key", count.containsKey(fpGood));
            assertEquals("Mismatched bad key authentication attempts", 1, count.get(fpBad).get());
            assertEquals("Mismatched good key authentication attempts", 1, count.get(fpGood).get());
        } finally {
            client.stop();
        }
    }

    Thread.sleep(100L);
    assertTrue("Cache not empty", auth.getCache().isEmpty());
}
 
Example #25
Source File: KeepAliveTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test
public void testShellClosedOnClientTimeout() throws Exception {
    TestEchoShell.latch = new CountDownLatch(1);

    SshClient client = setupTestClient();
    client.start();

    try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
        session.addPasswordIdentity(getCurrentTestName());
        session.auth().verify(5L, TimeUnit.SECONDS);

        try (ClientChannel channel = session.createChannel(Channel.CHANNEL_SHELL);
             ByteArrayOutputStream out = new ByteArrayOutputStream();
             ByteArrayOutputStream err = new ByteArrayOutputStream()) {

            channel.setOut(out);
            channel.setErr(err);
            channel.open().verify(9L, TimeUnit.SECONDS);

            assertTrue("Latch time out", TestEchoShell.latch.await(10L, TimeUnit.SECONDS));
            Collection<ClientChannelEvent> result =
                    channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), WAIT);
            assertTrue("Wrong channel state: " + result,
                       result.containsAll(
                           EnumSet.of(ClientChannelEvent.CLOSED, ClientChannelEvent.OPENED)));
        }
    } finally {
        TestEchoShell.latch = null;
        client.stop();
    }
}
 
Example #26
Source File: AuthenticationTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthKeyPassword() throws Exception {
    try (SshClient client = setupTestClient()) {
        sshd.setPublickeyAuthenticator(RejectAllPublickeyAuthenticator.INSTANCE);
        sshd.setKeyboardInteractiveAuthenticator(KeyboardInteractiveAuthenticator.NONE);

        client.start();

        try (ClientSession s = client.connect(null, TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
            Collection<ClientSession.ClientSessionEvent> result =
                    s.waitFor(EnumSet.of(ClientSession.ClientSessionEvent.CLOSED, ClientSession.ClientSessionEvent.WAIT_AUTH),
                    TimeUnit.SECONDS.toMillis(11L));
            assertFalse("Timeout while waiting for session", result.contains(ClientSession.ClientSessionEvent.TIMEOUT));

            KeyPair pair = createTestHostKeyProvider().loadKey(KeyPairProvider.SSH_RSA);
            try {
                assertAuthenticationResult(UserAuthMethodFactory.PUBLIC_KEY, authPublicKey(s, getCurrentTestName(), pair), false);
            } finally {
                s.removePublicKeyIdentity(pair);
            }

            String password = getCurrentTestName();
            try {
                assertAuthenticationResult(UserAuthMethodFactory.PASSWORD, authPassword(s, getCurrentTestName(), password), true);
            } finally {
                s.removePasswordIdentity(password);
            }
        } finally {
            client.stop();
        }
    }
}
 
Example #27
Source File: AuthenticationTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test
public void testChangeUser() throws Exception {
    try (SshClient client = setupTestClient()) {
        client.start();

        try (ClientSession s = client.connect(null, TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
            Collection<ClientSession.ClientSessionEvent> mask =
                    EnumSet.of(ClientSession.ClientSessionEvent.CLOSED, ClientSession.ClientSessionEvent.WAIT_AUTH);
            Collection<ClientSession.ClientSessionEvent> result = s.waitFor(mask, TimeUnit.SECONDS.toMillis(11L));
            assertFalse("Timeout while waiting on session events", result.contains(ClientSession.ClientSessionEvent.TIMEOUT));

            String password = "the-password";
            for (String username : new String[]{"user1", "user2"}) {
                try {
                    assertAuthenticationResult(username, authPassword(s, username, password), false);
                } finally {
                    s.removePasswordIdentity(password);
                }
            }

            // Note that WAIT_AUTH flag should be false, but since the internal
            // authentication future is not updated, it's still returned
            result = s.waitFor(EnumSet.of(ClientSession.ClientSessionEvent.CLOSED), TimeUnit.SECONDS.toMillis(3L));
            assertTrue("Mismatched client session close mask: " + result, result.containsAll(mask));
        } finally {
            client.stop();
        }
    }
}
 
Example #28
Source File: AuthenticationTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test
public void testWrongPassword() throws Exception {
    try (SshClient client = setupTestClient()) {
        client.start();
        try (ClientSession s = client.connect("user", TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
            s.addPasswordIdentity("bad password");
            assertAuthenticationResult(getCurrentTestName(), s.auth(), false);
        }
    }
}
 
Example #29
Source File: AuthenticationTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test   // see SSHD-620
public void testHostBasedAuthentication() throws Exception {
    final String hostClienUser = getClass().getSimpleName();
    final String hostClientName = SshdSocketAddress.toAddressString(SshdSocketAddress.getFirstExternalNetwork4Address());
    final KeyPair hostClientKey = Utils.generateKeyPair(KeyUtils.RSA_ALGORITHM, 1024);
    final AtomicInteger invocationCount = new AtomicInteger(0);
    sshd.setHostBasedAuthenticator(new HostBasedAuthenticator() {
        @Override
        public boolean authenticate(ServerSession session, String username,
                PublicKey clientHostKey, String clientHostName, String clientUsername, List<X509Certificate> certificates) {
            invocationCount.incrementAndGet();
            return hostClienUser.equals(clientUsername)
                && hostClientName.equals(clientHostName)
                && KeyUtils.compareKeys(hostClientKey.getPublic(), clientHostKey);
        }
    });
    sshd.setPasswordAuthenticator(RejectAllPasswordAuthenticator.INSTANCE);
    sshd.setKeyboardInteractiveAuthenticator(KeyboardInteractiveAuthenticator.NONE);
    sshd.setPublickeyAuthenticator(RejectAllPublickeyAuthenticator.INSTANCE);
    sshd.setUserAuthFactories(
            Collections.<NamedFactory<org.apache.sshd.server.auth.UserAuth>>singletonList(
                    org.apache.sshd.server.auth.hostbased.UserAuthHostBasedFactory.INSTANCE));

    try (SshClient client = setupTestClient()) {
        org.apache.sshd.client.auth.hostbased.UserAuthHostBasedFactory factory =
                new org.apache.sshd.client.auth.hostbased.UserAuthHostBasedFactory();
        // TODO factory.setClientHostname(CLIENT_HOSTNAME);
        factory.setClientUsername(hostClienUser);
        factory.setClientHostKeys(HostKeyIdentityProvider.Utils.wrap(hostClientKey));

        client.setUserAuthFactories(Collections.<NamedFactory<org.apache.sshd.client.auth.UserAuth>>singletonList(factory));
        client.start();
        try (ClientSession s = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
            s.auth().verify(11L, TimeUnit.SECONDS);
            assertEquals("Mismatched authenticator invocation count", 1, invocationCount.get());
        } finally {
            client.stop();
        }
    }
}
 
Example #30
Source File: Utils.java    From termd with Apache License 2.0 5 votes vote down vote up
public static SshClient setupTestClient(Class<?> anchor) {
    SshClient client = SshClient.setUpDefaultClient();
    client.setServerKeyVerifier(AcceptAllServerKeyVerifier.INSTANCE);
    client.setHostConfigEntryResolver(HostConfigEntryResolver.EMPTY);
    client.setKeyPairProvider(KeyPairProvider.EMPTY_KEYPAIR_PROVIDER);
    return client;
}