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

The following examples show how to use org.apache.sshd.client.session.ClientSession. 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: 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 2
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 3
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 4
Source Project: termd   Source File: PortForwardingTest.java    License: 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 5
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 6
Source Project: termd   Source File: PortForwardingTest.java    License: 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 7
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 8
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 9
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 10
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 11
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 12
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 13
Source Project: termd   Source File: UserAuthPassword.java    License: 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 14
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 15
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 16
Source Project: termd   Source File: ServerTest.java    License: 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 17
Source Project: termd   Source File: ServerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthenticationTimeout() throws Exception {
    final long testAuthTimeout = TimeUnit.SECONDS.toMillis(5L);
    PropertyResolverUtils.updateProperty(sshd, FactoryManager.AUTH_TIMEOUT, testAuthTimeout);

    sshd.start();
    client.start();
    try (ClientSession s = client.connect(getCurrentTestName(), TEST_LOCALHOST, sshd.getPort()).verify(7L, TimeUnit.SECONDS).getSession()) {
        Collection<ClientSession.ClientSessionEvent> res = s.waitFor(EnumSet.of(ClientSession.ClientSessionEvent.CLOSED), 2L * testAuthTimeout);
        assertTrue("Session should be closed: " + res,
                   res.containsAll(EnumSet.of(ClientSession.ClientSessionEvent.CLOSED, ClientSession.ClientSessionEvent.WAIT_AUTH)));
    } finally {
        client.stop();
    }
}
 
Example 18
Source Project: termd   Source File: ServerTest.java    License: 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 19
Source Project: xenon   Source File: SshInteractiveProcess.java    License: Apache License 2.0 5 votes vote down vote up
SshInteractiveProcess(ClientSession session, JobDescription description, String jobIdentifier, long timeoutInMillis) throws XenonException {

        if (session == null) {
            throw new IllegalArgumentException("Session is null");
        }

        if (description == null) {
            throw new IllegalArgumentException("Job description is null");
        }

        if (jobIdentifier == null) {
            throw new IllegalArgumentException("Job identifier is null");
        }

        this.session = session;

        try {
            this.channel = session.createExecChannel(buildCommand(description));

            Map<String, String> environment = description.getEnvironment();

            for (Entry<String, String> entry : environment.entrySet()) {
                channel.setEnv(entry.getKey(), entry.getValue());
            }

            // TODO: Add agent FW
            // channel.setAgentForwarding(session.useAgentForwarding());

            channel.open().verify(timeoutInMillis);

            // set the streams first, then connect the channel.
            streams = new StreamsImplementation(jobIdentifier, channel.getInvertedOut(), channel.getInvertedIn(), channel.getInvertedErr());

        } catch (Exception e) {
            throw new XenonException(ADAPTOR_NAME, "Failed to start command", e);
        }
    }
 
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: onos   Source File: NetconfSessionMinaImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Deprecated
private void startSession() throws IOException {
    final ConnectFuture connectFuture;
    connectFuture = client.connect(deviceInfo.name(),
            deviceInfo.ip().toString(),
            deviceInfo.port())
            .verify(connectTimeout, TimeUnit.SECONDS);
    session = connectFuture.getSession();
    //Using the device ssh key if possible
    if (deviceInfo.getKey() != null) {
        try (PEMParser pemParser = new PEMParser(new CharArrayReader(deviceInfo.getKey()))) {
            JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME);
            try {
                KeyPair kp = converter.getKeyPair((PEMKeyPair) pemParser.readObject());
                session.addPublicKeyIdentity(kp);
            } catch (IOException e) {
                throw new NetconfException("Failed to authenticate session with device " +
                        deviceInfo + "check key to be a valid key", e);
            }
        }
    } else {
        session.addPasswordIdentity(deviceInfo.password());
    }
    session.auth().verify(connectTimeout, TimeUnit.SECONDS);
    Set<ClientSession.ClientSessionEvent> event = session.waitFor(
            ImmutableSet.of(ClientSession.ClientSessionEvent.WAIT_AUTH,
                    ClientSession.ClientSessionEvent.CLOSED,
                    ClientSession.ClientSessionEvent.AUTHED), 0);

    if (!event.contains(ClientSession.ClientSessionEvent.AUTHED)) {
        log.debug("Session closed {} {}", event, session.isClosed());
        throw new NetconfException("Failed to authenticate session with device " +
                deviceInfo + "check the user/pwd or key");
    }
    openChannel();
}
 
Example 22
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 23
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 24
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 25
Source Project: termd   Source File: PortForwardingTest.java    License: 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 26
Source Project: termd   Source File: PortForwardingTest.java    License: 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);
        }
    }
}
 
Example 27
Source Project: termd   Source File: PortForwardingTest.java    License: 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 28
Source Project: termd   Source File: PortForwardingTest.java    License: 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 Project: termd   Source File: PortForwardingTest.java    License: 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 30
Source Project: termd   Source File: PortForwardingTest.java    License: 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;
}