org.apache.sshd.client.session.ClientSession Java Examples

The following examples show how to use org.apache.sshd.client.session.ClientSession. 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: 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 #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: PortForwardingTest.java    From termd with Apache License 2.0 6 votes vote down vote up
@Test
public void testForwardingChannel() throws Exception {
    try (ClientSession session = createNativeSession()) {
        SshdSocketAddress local = new SshdSocketAddress("", 0);
        SshdSocketAddress remote = new SshdSocketAddress(TEST_LOCALHOST, echoPort);

        try (ChannelDirectTcpip channel = session.createDirectTcpipChannel(local, remote)) {
            channel.open().verify(9L, TimeUnit.SECONDS);

            String expected = getCurrentTestName();
            byte[] bytes = expected.getBytes(StandardCharsets.UTF_8);

            try (OutputStream output = channel.getInvertedIn();
                 InputStream input = channel.getInvertedOut()) {
                output.write(bytes);
                output.flush();

                byte[] buf = new byte[bytes.length + Long.SIZE];
                int n = input.read(buf);
                String res = new String(buf, 0, n);
                assertEquals("Mismatched data", expected, res);
            }
            channel.close(false);
        }
    }
}
 
Example #4
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 #5
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 #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: 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 #8
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 #9
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 #10
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 #11
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 #12
Source File: PortForwardingTest.java    From termd with Apache License 2.0 6 votes vote down vote up
@Test
public void testForwardingChannel() throws Exception {
    try (ClientSession session = createNativeSession()) {
        SshdSocketAddress local = new SshdSocketAddress("", 0);
        SshdSocketAddress remote = new SshdSocketAddress(TEST_LOCALHOST, echoPort);

        try (ChannelDirectTcpip channel = session.createDirectTcpipChannel(local, remote)) {
            channel.open().verify(9L, TimeUnit.SECONDS);

            String expected = getCurrentTestName();
            byte[] bytes = expected.getBytes(StandardCharsets.UTF_8);

            try (OutputStream output = channel.getInvertedIn();
                 InputStream input = channel.getInvertedOut()) {
                output.write(bytes);
                output.flush();

                byte[] buf = new byte[bytes.length + Long.SIZE];
                int n = input.read(buf);
                String res = new String(buf, 0, n);
                assertEquals("Mismatched data", expected, res);
            }
            channel.close(false);
        }
    }
}
 
Example #13
Source File: PortForwardingTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test
public void testLocalForwardingNativeReuse() throws Exception {
    try (ClientSession session = createNativeSession()) {
        SshdSocketAddress local = new SshdSocketAddress("", 0);
        SshdSocketAddress remote = new SshdSocketAddress(TEST_LOCALHOST, echoPort);
        SshdSocketAddress bound = session.startLocalPortForwarding(local, remote);

        session.stopLocalPortForwarding(bound);

        SshdSocketAddress bound2 = session.startLocalPortForwarding(local, remote);
        session.stopLocalPortForwarding(bound2);
    }
}
 
Example #14
Source File: ServerTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test
public void testFailAuthenticationWithFuture() throws Exception {
    final int maxAllowedAuths = 10;
    PropertyResolverUtils.updateProperty(sshd, ServerAuthenticationManager.MAX_AUTH_REQUESTS, maxAllowedAuths);

    sshd.start();

    client.setServiceFactories(Arrays.asList(
            new ClientUserAuthServiceOld.Factory(),
            ClientConnectionServiceFactory.INSTANCE
    ));
    client.start();
    try (ClientSession s = client.connect(getCurrentTestName(), TEST_LOCALHOST, sshd.getPort()).verify(7L, TimeUnit.SECONDS).getSession()) {
        int nbTrials = 0;
        AuthFuture authFuture;
        do {
            nbTrials++;
            assertTrue("Number of trials below max.", nbTrials < 100);
            authFuture = s.getService(ClientUserAuthServiceOld.class)
                    .auth(new org.apache.sshd.deprecated.UserAuthPassword(s, "ssh-connection", "buggy"));
            assertTrue("Authentication wait failed", authFuture.await(5L, TimeUnit.SECONDS));
            assertTrue("Authentication not done", authFuture.isDone());
            assertFalse("Authentication unexpectedly successful", authFuture.isSuccess());
        } while (authFuture.getException() == null);

        Throwable t = authFuture.getException();
        assertNotNull("Missing auth future exception", t);
        assertTrue("Number trials (" + nbTrials + ") below min.=" + maxAllowedAuths, nbTrials > maxAllowedAuths);
    } finally {
        client.stop();
    }
}
 
Example #15
Source File: PortForwardingTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test
public void testLocalForwardingNative() throws Exception {
    try (ClientSession session = createNativeSession()) {
        SshdSocketAddress local = new SshdSocketAddress("", 0);
        SshdSocketAddress remote = new SshdSocketAddress(TEST_LOCALHOST, echoPort);
        SshdSocketAddress bound = session.startLocalPortForwarding(local, remote);

        try (Socket s = new Socket(bound.getHostName(), bound.getPort());
             OutputStream output = s.getOutputStream();
             InputStream input = s.getInputStream()) {

            s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L));

            String expected = getCurrentTestName();
            byte[] bytes = expected.getBytes(StandardCharsets.UTF_8);

            output.write(bytes);
            output.flush();

            byte[] buf = new byte[bytes.length + Long.SIZE];
            int n = input.read(buf);
            String res = new String(buf, 0, n);
            assertEquals("Mismatched data", expected, res);
        } finally {
            session.stopLocalPortForwarding(bound);
        }
    }
}
 
Example #16
Source File: PortForwardingTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoteForwardingNative() throws Exception {
    try (ClientSession session = createNativeSession()) {
        SshdSocketAddress remote = new SshdSocketAddress("", 0);
        SshdSocketAddress local = new SshdSocketAddress(TEST_LOCALHOST, echoPort);
        SshdSocketAddress bound = session.startRemotePortForwarding(remote, local);

        try (Socket s = new Socket(bound.getHostName(), bound.getPort());
             OutputStream output = s.getOutputStream();
             InputStream input = s.getInputStream()) {

            s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L));

            String expected = getCurrentTestName();
            byte[] bytes = expected.getBytes(StandardCharsets.UTF_8);
            output.write(bytes);
            output.flush();

            byte[] buf = new byte[bytes.length + Long.SIZE];
            int n = input.read(buf);
            String res = new String(buf, 0, n);
            assertEquals("Mismatched data", expected, res);
        } finally {
            session.stopRemotePortForwarding(remote);
        }
    }
}
 
Example #17
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 #18
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 #19
Source File: SshSessionImpl.java    From java-11-examples with Apache License 2.0 5 votes vote down vote up
public SshSessionImpl(ClientSession session, ChannelSubsystem robotChannel, SshSessionListener listener, KeyMap keyMap) {
    this.session = session;
    this.robotChannel = robotChannel;
    this.listener = listener;
    this.keyMap = keyMap;
    this.executorService = Executors.newSingleThreadExecutor();
}
 
Example #20
Source File: ServerTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test
public void testFailAuthenticationWithWaitFor() throws Exception {
    final int maxAllowedAuths = 10;
    PropertyResolverUtils.updateProperty(sshd, ServerAuthenticationManager.MAX_AUTH_REQUESTS, maxAllowedAuths);

    sshd.start();
    client.setServiceFactories(Arrays.asList(
            new ClientUserAuthServiceOld.Factory(),
            ClientConnectionServiceFactory.INSTANCE
    ));
    client.start();

    try (ClientSession s = client.connect(getCurrentTestName(), TEST_LOCALHOST, sshd.getPort()).verify(7L, TimeUnit.SECONDS).getSession()) {
        int nbTrials = 0;
        Collection<ClientSession.ClientSessionEvent> res = Collections.emptySet();
        Collection<ClientSession.ClientSessionEvent> mask =
                EnumSet.of(ClientSession.ClientSessionEvent.CLOSED, ClientSession.ClientSessionEvent.WAIT_AUTH);
        while (!res.contains(ClientSession.ClientSessionEvent.CLOSED)) {
            nbTrials++;
            s.getService(ClientUserAuthServiceOld.class)
                    .auth(new org.apache.sshd.deprecated.UserAuthPassword(s, "ssh-connection", "buggy"));
            res = s.waitFor(mask, TimeUnit.SECONDS.toMillis(5L));
            assertFalse("Timeout signalled", res.contains(ClientSession.ClientSessionEvent.TIMEOUT));
        }
        assertTrue("Number trials (" + nbTrials + ") below min.=" + maxAllowedAuths, nbTrials > maxAllowedAuths);
    } finally {
        client.stop();
    }
}
 
Example #21
Source File: ServerTest.java    From termd with Apache License 2.0 5 votes vote down vote up
private ClientSession createTestClientSession(SshServer server) throws Exception {
    ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, server.getPort()).verify(7L, TimeUnit.SECONDS).getSession();
    try {
        session.addPasswordIdentity(getCurrentTestName());
        session.auth().verify(5L, TimeUnit.SECONDS);

        ClientSession returnValue = session;
        session = null; // avoid 'finally' close
        return returnValue;
    } finally {
        if (session != null) {
            session.close();
        }
    }
}
 
Example #22
Source File: PortForwardingTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test
public void testLocalForwardingNativeBigPayload() throws Exception {
    try (ClientSession session = createNativeSession()) {
        String expected = getCurrentTestName();
        byte[] bytes = expected.getBytes(StandardCharsets.UTF_8);
        byte[] buf = new byte[bytes.length + Long.SIZE];

        SshdSocketAddress local = new SshdSocketAddress("", 0);
        SshdSocketAddress remote = new SshdSocketAddress(TEST_LOCALHOST, echoPort);
        SshdSocketAddress bound = session.startLocalPortForwarding(local, remote);
        try (Socket s = new Socket(bound.getHostName(), bound.getPort());
             OutputStream output = s.getOutputStream();
             InputStream input = s.getInputStream()) {

            s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L));

            for (int i = 0; i < 1000; i++) {
                output.write(bytes);
                output.flush();

                int n = input.read(buf);
                String res = new String(buf, 0, n);
                assertEquals("Mismatched data at iteration #" + i, expected, res);
            }
        } finally {
            session.stopLocalPortForwarding(bound);
        }
    }
}
 
Example #23
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 #24
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 #25
Source File: UserAuthPassword.java    From termd with Apache License 2.0 5 votes vote down vote up
@Override
public Result next(Buffer buffer) throws IOException {
    ClientSession session = getClientSession();
    String service = getService();
    if (buffer == null) {
        log.debug("Send SSH_MSG_USERAUTH_REQUEST for password");
        buffer = session.createBuffer(SshConstants.SSH_MSG_USERAUTH_REQUEST);
        buffer.putString(session.getUsername());
        buffer.putString(service);
        buffer.putString(UserAuthMethodFactory.PASSWORD);
        buffer.putBoolean(false);
        buffer.putString(password);
        session.writePacket(buffer);
        return Result.Continued;
    } else {
        int cmd = buffer.getUByte();
        if (cmd == SshConstants.SSH_MSG_USERAUTH_SUCCESS) {
            log.debug("Received SSH_MSG_USERAUTH_SUCCESS");
            return Result.Success;
        }
        if (cmd == SshConstants.SSH_MSG_USERAUTH_FAILURE) {
            String methods = buffer.getString();
            boolean partial = buffer.getBoolean();
            if (log.isDebugEnabled()) {
                log.debug("Received SSH_MSG_USERAUTH_FAILURE - partial={}, methods={}", partial, methods);
            }
            return Result.Failure;
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Received unkown packet {}", Integer.valueOf(cmd & 0xFF));
            }
            // TODO: check packets
            return Result.Continued;
        }
    }
}
 
Example #26
Source File: PortForwardingTest.java    From termd with Apache License 2.0 5 votes vote down vote up
protected ClientSession createNativeSession() throws Exception {
    client = setupTestClient();
    PropertyResolverUtils.updateProperty(client, FactoryManager.WINDOW_SIZE, 2048);
    PropertyResolverUtils.updateProperty(client, FactoryManager.MAX_PACKET_SIZE, 256);
    client.setTcpipForwardingFilter(AcceptAllForwardingFilter.INSTANCE);
    client.start();

    ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, sshPort).verify(7L, TimeUnit.SECONDS).getSession();
    session.addPasswordIdentity(getCurrentTestName());
    session.auth().verify(11L, TimeUnit.SECONDS);
    return session;
}
 
Example #27
Source File: PortForwardingTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test
public void testLocalForwardingNativeBigPayload() throws Exception {
    try (ClientSession session = createNativeSession()) {
        String expected = getCurrentTestName();
        byte[] bytes = expected.getBytes(StandardCharsets.UTF_8);
        byte[] buf = new byte[bytes.length + Long.SIZE];

        SshdSocketAddress local = new SshdSocketAddress("", 0);
        SshdSocketAddress remote = new SshdSocketAddress(TEST_LOCALHOST, echoPort);
        SshdSocketAddress bound = session.startLocalPortForwarding(local, remote);
        try (Socket s = new Socket(bound.getHostName(), bound.getPort());
             OutputStream output = s.getOutputStream();
             InputStream input = s.getInputStream()) {

            s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L));

            for (int i = 0; i < 1000; i++) {
                output.write(bytes);
                output.flush();

                int n = input.read(buf);
                String res = new String(buf, 0, n);
                assertEquals("Mismatched data at iteration #" + i, expected, res);
            }
        } finally {
            session.stopLocalPortForwarding(bound);
        }
    }
}
 
Example #28
Source File: PortForwardingTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test
public void testLocalForwardingNativeReuse() throws Exception {
    try (ClientSession session = createNativeSession()) {
        SshdSocketAddress local = new SshdSocketAddress("", 0);
        SshdSocketAddress remote = new SshdSocketAddress(TEST_LOCALHOST, echoPort);
        SshdSocketAddress bound = session.startLocalPortForwarding(local, remote);

        session.stopLocalPortForwarding(bound);

        SshdSocketAddress bound2 = session.startLocalPortForwarding(local, remote);
        session.stopLocalPortForwarding(bound2);
    }
}
 
Example #29
Source File: PortForwardingTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test
public void testLocalForwardingNative() throws Exception {
    try (ClientSession session = createNativeSession()) {
        SshdSocketAddress local = new SshdSocketAddress("", 0);
        SshdSocketAddress remote = new SshdSocketAddress(TEST_LOCALHOST, echoPort);
        SshdSocketAddress bound = session.startLocalPortForwarding(local, remote);

        try (Socket s = new Socket(bound.getHostName(), bound.getPort());
             OutputStream output = s.getOutputStream();
             InputStream input = s.getInputStream()) {

            s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L));

            String expected = getCurrentTestName();
            byte[] bytes = expected.getBytes(StandardCharsets.UTF_8);

            output.write(bytes);
            output.flush();

            byte[] buf = new byte[bytes.length + Long.SIZE];
            int n = input.read(buf);
            String res = new String(buf, 0, n);
            assertEquals("Mismatched data", expected, res);
        } finally {
            session.stopLocalPortForwarding(bound);
        }
    }
}
 
Example #30
Source File: PortForwardingTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoteForwardingNativeBigPayload() throws Exception {
    try (ClientSession session = createNativeSession()) {
        SshdSocketAddress remote = new SshdSocketAddress("", 0);
        SshdSocketAddress local = new SshdSocketAddress(TEST_LOCALHOST, echoPort);
        SshdSocketAddress bound = session.startRemotePortForwarding(remote, local);

        try (Socket s = new Socket(bound.getHostName(), bound.getPort());
             OutputStream output = s.getOutputStream();
             InputStream input = s.getInputStream()) {

            s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L));

            String expected = getCurrentTestName();
            byte[] bytes = expected.getBytes(StandardCharsets.UTF_8);
            byte[] buf = new byte[bytes.length + Long.SIZE];

            for (int i = 0; i < 1000; i++) {
                output.write(bytes);
                output.flush();

                int n = input.read(buf);
                String res = new String(buf, 0, n);
                assertEquals("Mismatched data at iteration #" + i, expected, res);
            }
        } finally {
            session.stopRemotePortForwarding(remote);
        }
    }
}