Java Code Examples for org.apache.sshd.client.SshClient

The following examples show how to use org.apache.sshd.client.SshClient. These examples are extracted from open source projects. 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 Project: onos   Source File: NetconfSessionMinaImpl.java    License: 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 Project: termd   Source File: WindowAdjustTest.java    License: 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 3
Source Project: termd   Source File: KeepAliveTest.java    License: 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 4
Source Project: termd   Source File: KeepAliveTest.java    License: 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 5
Source Project: termd   Source File: KeyReExchangeTest.java    License: 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 Project: termd   Source File: AuthenticationTest.java    License: 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 7
Source Project: termd   Source File: AuthenticationTest.java    License: 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 Project: tesb-studio-se   Source File: RuntimeClient.java    License: 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 Project: termd   Source File: WindowAdjustTest.java    License: 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 Project: termd   Source File: KeepAliveTest.java    License: 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 Project: termd   Source File: KeepAliveTest.java    License: 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 Project: termd   Source File: KeyReExchangeTest.java    License: 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 Project: termd   Source File: AuthenticationTest.java    License: 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 Project: termd   Source File: AuthenticationTest.java    License: 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 Project: keycloak   Source File: FuseUtils.java    License: 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 Project: termd   Source File: KeepAliveTest.java    License: 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 17
Source Project: termd   Source File: KeyReExchangeTest.java    License: Apache License 2.0 5 votes vote down vote up
private void testKexFutureExceptionPropagation(String failureType, AtomicBoolean successFlag, SshClient client) throws Exception {
    try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
        session.addPasswordIdentity(getCurrentTestName());
        session.auth().verify(5L, TimeUnit.SECONDS);

        successFlag.set(false);
        KeyExchangeFuture kexFuture = session.switchToNoneCipher();
        assertTrue(failureType + ": failed to complete KEX on time", kexFuture.await(7L, TimeUnit.SECONDS));
        assertNotNull(failureType + ": unexpected success", kexFuture.getException());
    }
}
 
Example 18
Source Project: termd   Source File: Utils.java    License: 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;
}
 
Example 19
Source Project: termd   Source File: AuthenticationTest.java    License: 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 20
Source Project: termd   Source File: AuthenticationTest.java    License: 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 21
Source Project: termd   Source File: AuthenticationTest.java    License: 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 22
Source Project: termd   Source File: AuthenticationTest.java    License: 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 23
Source Project: termd   Source File: SinglePublicKeyAuthTest.java    License: 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 24
Source Project: java-11-examples   Source File: ClientImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void start() {
    this.client = SshClient.setUpDefaultClient();
    if (serverKeyVerifier != null) {
        client.setServerKeyVerifier(serverKeyVerifier);
    }
    this.client.start();
}
 
Example 25
Source Project: java-11-examples   Source File: SshClientSessionImpl.java    License: Apache License 2.0 5 votes vote down vote up
public void connect() throws IOException {
    client = SshClient.setUpDefaultClient();
    client.start();
    session = client.connect(userCredentials.getUserName(),
            hostData.getHostName(), hostData.getPort()).verify().getSession();
    session.addPasswordIdentity(userCredentials.getPassword());
    session.auth().await();
}
 
Example 26
Source Project: anx   Source File: NetconfSSHClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a new NETCONF connection to the given server
 *
 * The connection will not be established immediately, but instead upon creating the first session.
 *
 * @param hostname
 * @param port
 * @param username
 */
public NetconfSSHClient(String hostname, int port, String username) {
    this.hostname = hostname;
    this.port = port;
    this.username = username;

    client = SshClient.setUpDefaultClient();
    client.setSessionHeartbeat(HeartbeatType.IGNORE, TimeUnit.MILLISECONDS, 5000);
    client.start();
}
 
Example 27
Source Project: termd   Source File: KeepAliveTest.java    License: 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 28
Source Project: termd   Source File: KeyReExchangeTest.java    License: Apache License 2.0 5 votes vote down vote up
private void testKexFutureExceptionPropagation(String failureType, AtomicBoolean successFlag, SshClient client) throws Exception {
    try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
        session.addPasswordIdentity(getCurrentTestName());
        session.auth().verify(5L, TimeUnit.SECONDS);

        successFlag.set(false);
        KeyExchangeFuture kexFuture = session.switchToNoneCipher();
        assertTrue(failureType + ": failed to complete KEX on time", kexFuture.await(7L, TimeUnit.SECONDS));
        assertNotNull(failureType + ": unexpected success", kexFuture.getException());
    }
}
 
Example 29
Source Project: termd   Source File: Utils.java    License: 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;
}
 
Example 30
Source Project: termd   Source File: AuthenticationTest.java    License: 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);
        }
    }
}