org.apache.sshd.common.NamedFactory Java Examples

The following examples show how to use org.apache.sshd.common.NamedFactory. 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: EmbeddedSftpServer.java    From java-examples with MIT License 7 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    final PublicKey allowedKey = decodePublicKey();
    this.server.setPublickeyAuthenticator(new PublickeyAuthenticator() {

        @Override
        public boolean authenticate(String username, PublicKey key, ServerSession session) {
            return key.equals(allowedKey);
        }

    });
    this.server.setPort(this.port);
    this.server.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(Files.createTempFile("host_file", ".ser")));
    this.server.setSubsystemFactories(Collections.<NamedFactory<Command>>singletonList(new SftpSubsystemFactory()));
    server.setFileSystemFactory(new VirtualFileSystemFactory(Files.createTempDirectory("SFTP_TEMP")));
    server.setCommandFactory(new ScpCommandFactory());
}
 
Example #2
Source File: TestCipherFactories.java    From artifactory_ssh_proxy with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultFactories() throws SshdConfigurationException {
    // IF THIS TEST IS FAILING. Install the unlimited strength jce policy
    // files.
    // arcfour's aren't working on 7u45

    SshdSettingsInterface settings =
                    new SshdSettingsBuilder().setSshdPort(2222).setConfiguration(Utils.getConfigMock())
                                    .setArtifactoryUsername("a").setArtifactoryPassword("password")
                                    .setArtifactoryUrl("http://your:4080/artifactory")
                                    .setCommandFactories(Collections.<DelegatingCommandFactory>emptyList()).build();

    List<NamedFactory<Cipher>> ciphers = settings.getCiphers();

    Assert.assertTrue(ciphers.size() >= 4);

}
 
Example #3
Source File: SftpServer.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
private SshServer createSshServer( int port, String homeDir, String hostKeyPath ) {
  SshServer server = SshServer.setUpDefaultServer();
  server.setHost( "localhost" );
  server.setPort( port );
  server.setFileSystemFactory( new VirtualFileSystemFactory( homeDir ) );
  server.setSubsystemFactories( Collections.<NamedFactory<Command>>singletonList( new SftpSubsystem.Factory() ) );
  server.setCommandFactory( new ScpCommandFactory() );
  server.setKeyPairProvider( new SimpleGeneratorHostKeyProvider( hostKeyPath ) );
  server.setPasswordAuthenticator( this );
  return server;
}
 
Example #4
Source File: EmbeddedSftpServer.java    From java-examples with MIT License 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    final PublicKey allowedKey = decodePublicKey();
    this.server.setPublickeyAuthenticator(new PublickeyAuthenticator() {

        @Override
        public boolean authenticate(String username, PublicKey key, ServerSession session) {
            return key.equals(allowedKey);
        }

    });
    this.server.setPort(this.port);
    this.server.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(Files.createTempFile("host_file", ".ser")));
    this.server.setSubsystemFactories(Collections.<NamedFactory<Command>>singletonList(new SftpSubsystemFactory()));
    server.setFileSystemFactory(new VirtualFileSystemFactory(Files.createTempDirectory("SFTP_TEMP")));
    server.setCommandFactory(new ScpCommandFactory());
}
 
Example #5
Source File: SftpServerRunner.java    From product-ei with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    sshd.setPort(port);
    sshd.setSubsystemFactories(
            Arrays.<NamedFactory<Command>>asList(new SftpSubsystemFactory()));
    sshd.setCommandFactory(new ScpCommandFactory());
    sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider());
    sshd.setFileSystemFactory(new VirtualFileSystemFactory(Paths.get(path)));
    sshd.setPasswordAuthenticator(new PasswordAuthenticator() {
        @Override
        public boolean authenticate(final String username, final String password, final ServerSession session) {
            return StringUtils.equals(username, ftpUser) && StringUtils.equals(password, ftpPassword);
        }
    });
    try {
        LOGGER.info("Starting SFTP server on port {}", port);
        sshd.start();
    } catch (IOException e) {
        LOGGER.error("Error starting SFTP server", e);
    }
}
 
Example #6
Source File: AsyncUserAuthService.java    From aesh-readline with Apache License 2.0 5 votes vote down vote up
public AsyncUserAuthService(Session s) throws SshException {
    ValidateUtils.checkTrue(s instanceof ServerSession, "Server side service used on client side");
    if (s.isAuthenticated()) {
        throw new SshException("Session already authenticated");
    }

    this.session = (ServerSession) s;
    maxAuthRequests = session.getIntProperty(ServerFactoryManager.MAX_AUTH_REQUESTS, DEFAULT_MAX_AUTH_REQUESTS);

    ServerFactoryManager manager = getFactoryManager();
    userAuthFactories = new ArrayList<>(manager.getUserAuthFactories());
    // Get authentication methods
    authMethods = new ArrayList<>();

    String mths = FactoryManagerUtils.getString(manager, ServerFactoryManager.AUTH_METHODS);
    if (GenericUtils.isEmpty(mths)) {
        for (NamedFactory<UserAuth> uaf : manager.getUserAuthFactories()) {
            authMethods.add(new ArrayList<>(Collections.singletonList(uaf.getName())));
        }
    }
    else {
        for (String mthl : mths.split("\\s")) {
            authMethods.add(new ArrayList<>(Arrays.asList(mthl.split(","))));
        }
    }
    // Verify all required methods are supported
    for (List<String> l : authMethods) {
        for (String m : l) {
            NamedFactory<UserAuth> factory = NamedResource.Utils.findByName(m, String.CASE_INSENSITIVE_ORDER, userAuthFactories);
            if (factory == null) {
                throw new SshException("Configured method is not supported: " + m);
            }
        }
    }

    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("Authorized authentication methods: "+ NamedResource.Utils.getNames(userAuthFactories));
    }
}
 
Example #7
Source File: SshdProxySettings.java    From artifactory_ssh_proxy with Apache License 2.0 5 votes vote down vote up
@Override
public List<NamedFactory<Cipher>> getCiphers() {
    // FIXME: get list of approved ciphers
    // FIXME: load cipher list from config
    // FIXME: only allow approved ciphers
    // see org.apache.sshd.SshServer.setUpDefaultCiphers(SshServer)

    return createCipherFactoryList(Collections.<String>emptyList());
}
 
Example #8
Source File: SSHTestServer.java    From nifi with Apache License 2.0 5 votes vote down vote up
public void startServer() throws IOException {
    sshd = SshServer.setUpDefaultServer();
    sshd.setHost("localhost");

    sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider());

    //Accept all keys for authentication
    sshd.setPublickeyAuthenticator((s, publicKey, serverSession) -> true);

    //Allow username/password authentication using pre-defined credentials
    sshd.setPasswordAuthenticator((username, password, serverSession) ->  this.username.equals(username) && this.password.equals(password));

    //Setup Virtual File System (VFS)
    //Ensure VFS folder exists
    Path dir = Paths.get(getVirtualFileSystemPath());
    Files.createDirectories(dir);
    sshd.setFileSystemFactory(new VirtualFileSystemFactory(dir.toAbsolutePath()));

    //Add SFTP support
    List<NamedFactory<Command>> sftpCommandFactory = new ArrayList<>();
    sftpCommandFactory.add(new SftpSubsystemFactory());
    sshd.setSubsystemFactories(sftpCommandFactory);

    sshd.start();
}
 
Example #9
Source File: SftpServerRunner.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
SftpServer(int port, String path, String ftpUser, String ftpPassword) {

            sshd.setPort(port);
            sshd.setSubsystemFactories(
                    Arrays.<NamedFactory<Command>>asList(new SftpSubsystemFactory()));
            sshd.setCommandFactory(new ScpCommandFactory());
            sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider());
            sshd.setFileSystemFactory(new VirtualFileSystemFactory(Paths.get(path)));
            sshd.setPasswordAuthenticator((username, password, session) -> StringUtils.equals(username, ftpUser)
                                                                           && StringUtils.equals(password,
                                                                                                 ftpPassword));
        }
 
Example #10
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 #11
Source File: ESBJAVA3470.java    From product-ei with Apache License 2.0 5 votes vote down vote up
/**
 * Starts a SFTP server on port 22
 * @param carbonHome
 */
private void setupSftpServer(String carbonHome) {
    SshServer sshd = SshServer.setUpDefaultServer();
    sshd.setPort(FTP_PORT);
    //sshd.setKeyPairProvider(new FileKeyPairProvider(new String[]{"/home/ravi/WORK/SUPPORT/JIRA/SKYTVNZDEV-26/SftpTest/dist/hostkey.ser"}));
    ClassLoader classLoader = getClass().getClassLoader();
    log.info("Using identity file: " + classLoader.getResource("sftp/id_rsa.pub").getFile());
    File file = new File(classLoader.getResource("sftp/id_rsa.pub").getFile());
    SFTPServer sftpServer = new SFTPServer();
    sshd.setKeyPairProvider(sftpServer.createTestHostKeyProvider(Paths.get(file.getAbsolutePath())));
    sshd.setKeyPairProvider(createTestHostKeyProvider(Paths.get(file.getAbsolutePath())));
    sshd.setUserAuthFactories(
            Arrays.<NamedFactory<UserAuth>>asList(new UserAuthPublicKeyFactory()));
    sshd.setFileSystemFactory(new VirtualFileSystemFactory(Paths.get(carbonHome)));
    sshd.setPublickeyAuthenticator(new PublickeyAuthenticator() {
        public boolean authenticate(String username, PublicKey key, ServerSession session) {
            return "sftpuser".equals(username);
        }
    });

    sshd.setCommandFactory(new ScpCommandFactory());

    sshd.setSubsystemFactories(
            Arrays.<NamedFactory<Command>>asList(new SftpSubsystemFactory()));

    try {
        sshd.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #12
Source File: SshServerBuilder.java    From java-11-examples with Apache License 2.0 5 votes vote down vote up
/**
 * Set {@link CommandProcessor} for ssh-client library processing.
 * @param commandProcessor implementation of {@link CommandProcessor} dedicated to ssh-client communication.
 * @param sshClientSessionListener provides instances of {@link SshClientSession} for pushing data to ssh-client.
 * @return
 */
public SshServerBuilder withSshClientProcessor(CommandProcessor commandProcessor,
                                               SshClientSessionListener sshClientSessionListener) {
    List<NamedFactory<Command>> namedFactories = new ArrayList<>();
    namedFactories.add(new SshClientNamedCommandFactory(keyMap, commandProcessor,
            sshClientSessionListener, sshClientSessionCounter));
    sshd.setSubsystemFactories(namedFactories);
    return this;
}
 
Example #13
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 #14
Source File: Server.java    From sftpserver with Apache License 2.0 5 votes vote down vote up
protected void setupCompress(final boolean enable) {
	// Compression is not enabled by default
	// You need download and compile:
	// http://www.jcraft.com/jzlib/
	if (enable) {
		sshd.setCompressionFactories(Arrays.<NamedFactory<Compression>>asList( //
				BuiltinCompressions.none, //
				BuiltinCompressions.zlib, //
				BuiltinCompressions.delayedZlib));
	} else {
		sshd.setCompressionFactories(Arrays.<NamedFactory<Compression>>asList( //
				BuiltinCompressions.none));
	}
}
 
Example #15
Source File: MockClientSession.java    From xenon with Apache License 2.0 4 votes vote down vote up
@Override
public void setMacFactories(List<NamedFactory<Mac>> macFactories) {
    throw new RuntimeException("Not implemented");

}
 
Example #16
Source File: LoadTest.java    From termd with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("checkstyle:nestedtrydepth")
protected void runClient(String msg) throws Exception {
    try (SshClient client = setupTestClient()) {
        PropertyResolverUtils.updateProperty(client, FactoryManager.MAX_PACKET_SIZE, 1024 * 16);
        PropertyResolverUtils.updateProperty(client, FactoryManager.WINDOW_SIZE, 1024 * 8);
        client.setKeyExchangeFactories(Arrays.asList(
                ClientBuilder.DH2KEX.transform(BuiltinDHFactories.dhg1)));
        client.setCipherFactories(Arrays.<NamedFactory<Cipher>>asList(BuiltinCiphers.blowfishcbc));
        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 (ByteArrayOutputStream out = new ByteArrayOutputStream();
                 ByteArrayOutputStream err = new ByteArrayOutputStream();
                 ClientChannel channel = session.createChannel(Channel.CHANNEL_SHELL)) {
                channel.setOut(out);
                channel.setErr(err);

                try {
                    channel.open().verify(9L, TimeUnit.SECONDS);
                    try (OutputStream pipedIn = channel.getInvertedIn()) {
                        msg += "\nexit\n";
                        pipedIn.write(msg.getBytes(StandardCharsets.UTF_8));
                        pipedIn.flush();
                    }

                    Collection<ClientChannelEvent> result =
                            channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(15L));
                    assertFalse("Timeout while waiting for channel closure", result.contains(ClientChannelEvent.TIMEOUT));
                } finally {
                    channel.close(false);
                }

                assertArrayEquals("Mismatched message data", msg.getBytes(StandardCharsets.UTF_8), out.toByteArray());
            }
        } finally {
            client.stop();
        }
    }
}
 
Example #17
Source File: MockClientSession.java    From xenon with Apache License 2.0 4 votes vote down vote up
@Override
public List<NamedFactory<Mac>> getMacFactories() {
    throw new RuntimeException("Not implemented");
}
 
Example #18
Source File: MockClientSession.java    From xenon with Apache License 2.0 4 votes vote down vote up
@Override
public void setCompressionFactories(List<NamedFactory<Compression>> compressionFactories) {
    throw new RuntimeException("Not implemented");

}
 
Example #19
Source File: MockClientSession.java    From xenon with Apache License 2.0 4 votes vote down vote up
@Override
public List<NamedFactory<Compression>> getCompressionFactories() {
    throw new RuntimeException("Not implemented");
}
 
Example #20
Source File: MockClientSession.java    From xenon with Apache License 2.0 4 votes vote down vote up
@Override
public void setCipherFactories(List<NamedFactory<Cipher>> cipherFactories) {
    throw new RuntimeException("Not implemented");

}
 
Example #21
Source File: MockClientSession.java    From xenon with Apache License 2.0 4 votes vote down vote up
@Override
public List<NamedFactory<Signature>> getSignatureFactories() {
    throw new RuntimeException("Not implemented");
}
 
Example #22
Source File: MockClientSession.java    From xenon with Apache License 2.0 4 votes vote down vote up
@Override
public List<NamedFactory<Cipher>> getCipherFactories() {
    throw new RuntimeException("Not implemented");
}
 
Example #23
Source File: MockClientSession.java    From xenon with Apache License 2.0 4 votes vote down vote up
@Override
public void setSignatureFactories(List<NamedFactory<Signature>> factories) {
    throw new RuntimeException("Not implemented");

}
 
Example #24
Source File: NetconfSessionMinaImplTest.java    From onos with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    int portNumber = TestTools.findAvailablePort(50830);
    sshServerNetconf = SshServer.setUpDefaultServer();
    sshServerNetconf.setPasswordAuthenticator(
            new PasswordAuthenticator() {
                @Override
                public boolean authenticate(
                        String username,
                        String password,
                        ServerSession session) {
                    return TEST_USERNAME.equals(username) && TEST_PASSWORD.equals(password);
                }
            });

    TestUtils.setField(NetconfSessionMinaImpl.class, "directory", TEST_DIRECTORY);

    sshServerNetconf.setPort(portNumber);
    SimpleGeneratorHostKeyProvider provider = new SimpleGeneratorHostKeyProvider();
    provider.setFile(new File(TEST_SERFILE));
    sshServerNetconf.setKeyPairProvider(provider);
    sshServerNetconf.setSubsystemFactories(
            Arrays.<NamedFactory<Command>>asList(new NetconfSshdTestSubsystem.Factory()));
    sshServerNetconf.open();
    log.info("SSH Server opened on port {}", portNumber);

    NetconfDeviceInfo deviceInfo = new NetconfDeviceInfo(
            TEST_USERNAME, TEST_PASSWORD, Ip4Address.valueOf(TEST_HOSTNAME), portNumber);
    deviceInfo.setConnectTimeoutSec(OptionalInt.of(30));
    deviceInfo.setReplyTimeoutSec(OptionalInt.of(30));

    session1 = new NetconfSessionMinaImpl(deviceInfo, ImmutableList.of("urn:ietf:params:netconf:base:1.0"));
    log.info("Started NETCONF Session {} with test SSHD server in Unit Test", session1.getSessionId());
    assertTrue("Incorrect sessionId", !session1.getSessionId().equalsIgnoreCase("-1"));
    assertTrue("Incorrect sessionId", !session1.getSessionId().equalsIgnoreCase("0"));
    assertThat(session1.getDeviceCapabilitiesSet(), containsInAnyOrder(DEFAULT_CAPABILITIES.toArray()));

    session2 = new NetconfSessionMinaImpl(deviceInfo, ImmutableList.of("urn:ietf:params:netconf:base:1.0"));
    log.info("Started NETCONF Session {} with test SSHD server in Unit Test", session2.getSessionId());
    assertTrue("Incorrect sessionId", !session2.getSessionId().equalsIgnoreCase("-1"));
    assertTrue("Incorrect sessionId", !session2.getSessionId().equalsIgnoreCase("0"));
    assertThat(session2.getDeviceCapabilitiesSet(), containsInAnyOrder(DEFAULT_CAPABILITIES.toArray()));

    session3 = new NetconfSessionMinaImpl(deviceInfo);
    log.info("Started NETCONF Session {} with test SSHD server in Unit Test", session3.getSessionId());
    assertTrue("Incorrect sessionId", !session3.getSessionId().equalsIgnoreCase("-1"));
    assertTrue("Incorrect sessionId", !session3.getSessionId().equalsIgnoreCase("0"));
    assertThat(session3.getDeviceCapabilitiesSet(), containsInAnyOrder(DEFAULT_CAPABILITIES_1_1.toArray()));

    session4 = new NetconfSessionMinaImpl(deviceInfo);
    log.info("Started NETCONF Session {} with test SSHD server in Unit Test", session4.getSessionId());
    assertTrue("Incorrect sessionId", !session4.getSessionId().equalsIgnoreCase("-1"));
    assertTrue("Incorrect sessionId", !session4.getSessionId().equalsIgnoreCase("0"));
    assertThat(session4.getDeviceCapabilitiesSet(), containsInAnyOrder(DEFAULT_CAPABILITIES_1_1.toArray()));
}
 
Example #25
Source File: TestCiphers.java    From artifactory_ssh_proxy with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    List<NamedFactory<Cipher>> list = SshdProxySettings.createCipherFactoryList(Collections.<String>emptyList());
    System.err.println("length: " + list.size());
}
 
Example #26
Source File: SshdProxySettings.java    From artifactory_ssh_proxy with Apache License 2.0 4 votes vote down vote up
/**
 * create a list of factories from a list of cipher names
 */
@SuppressWarnings("unchecked")
public static List<NamedFactory<Cipher>> createCipherFactoryList(List<String> cipherNames) {

    final NamedFactory<Cipher>[] cipherArray = new NamedFactory[] { //
                    //
                                    new AES128CTR.Factory(), //
                                    new AES256CTR.Factory(), //
                                    new ARCFOUR128.Factory(), //
                                    new ARCFOUR256.Factory(), //
                                    new AES128CBC.Factory(), //
                                    new TripleDESCBC.Factory(), //
                                    new BlowfishCBC.Factory(), //
                                    new AES192CBC.Factory(), //
                                    new AES256CBC.Factory(), //
                    };

    // first get all of the ciphers we know about in a set
    final Map<String, NamedFactory<Cipher>> nameMap = new HashMap<>();

    final boolean useDefaults;
    if (cipherNames.size() <= 0) {
        useDefaults = true;
        cipherNames = new ArrayList<>(cipherArray.length);
    } else {
        useDefaults = false;

    }

    for (NamedFactory<Cipher> cipherFactory : cipherArray) {
        nameMap.put(cipherFactory.getName(), cipherFactory);
        if (useDefaults) {
            cipherNames.add(cipherFactory.getName());
        }
    }

    final List<NamedFactory<Cipher>> available = new ArrayList<>(cipherArray.length);

    for (String cipherName : cipherNames) {
        final NamedFactory<Cipher> factory = nameMap.get(cipherName);
        if (null == factory) {
            continue;
        }


        try {
            final Cipher c = factory.create();
            final byte[] key = new byte[c.getBlockSize()];
            final byte[] iv = new byte[c.getIVSize()];
            c.init(Cipher.Mode.Encrypt, key, iv);
            available.add(factory);
        } catch (Exception e) {
            LOGGER.info("Failed to load cipher " + cipherName
                            + " ensure you have the unlimited strength JCE installed");
        }
    }

    return available;
}
 
Example #27
Source File: AuthenticationTest.java    From termd with Apache License 2.0 4 votes vote down vote up
@Test   // see SSHD-624
public void testMismatchedUserAuthPkOkData() throws Exception {
    final AtomicInteger challengeCounter = new AtomicInteger(0);
    sshd.setUserAuthFactories(Collections.<NamedFactory<org.apache.sshd.server.auth.UserAuth>>singletonList(
            new org.apache.sshd.server.auth.pubkey.UserAuthPublicKeyFactory() {
                @Override
                public org.apache.sshd.server.auth.pubkey.UserAuthPublicKey create() {
                    return new org.apache.sshd.server.auth.pubkey.UserAuthPublicKey() {
                        @Override
                        protected void sendPublicKeyResponse(ServerSession session, String username, String alg, PublicKey key,
                                byte[] keyBlob, int offset, int blobLen, Buffer buffer) throws Exception {
                            int count = challengeCounter.incrementAndGet();
                            outputDebugMessage("sendPublicKeyChallenge(%s)[%s]: count=%d", session, alg, count);
                            if (count == 1) {
                                // send wrong key type
                                super.sendPublicKeyResponse(session, username, KeyPairProvider.SSH_DSS, key, keyBlob, offset, blobLen, buffer);
                            } else if (count == 2) {
                                // send another key
                                KeyPair otherPair = org.apache.sshd.util.test.Utils.generateKeyPair(KeyUtils.RSA_ALGORITHM, 1024);
                                PublicKey otherKey = otherPair.getPublic();
                                Buffer buf = session.createBuffer(SshConstants.SSH_MSG_USERAUTH_PK_OK, blobLen + alg.length() + Long.SIZE);
                                buf.putString(alg);
                                buf.putPublicKey(otherKey);
                                session.writePacket(buf);
                            } else {
                                super.sendPublicKeyResponse(session, username, alg, key, keyBlob, offset, blobLen, buffer);
                            }
                        }
                    };
                }

    }));

    try (SshClient client = setupTestClient()) {
        KeyPair clientIdentity = Utils.generateKeyPair(KeyUtils.RSA_ALGORITHM, 1024);
        client.start();

        try {
            for (int index = 1; index <= 4; index++) {
                try (ClientSession s = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
                    s.addPublicKeyIdentity(clientIdentity);
                    s.auth().verify(17L, TimeUnit.SECONDS);
                    assertEquals("Mismatched number of challenges", 3, challengeCounter.get());
                    break;
                } catch (SshException e) {   // expected
                    outputDebugMessage("%s on retry #%d: %s", e.getClass().getSimpleName(), index, e.getMessage());

                    Throwable t = e.getCause();
                    assertObjectInstanceOf("Unexpected failure cause at retry #" + index, InvalidKeySpecException.class, t);
                }
            }
        } finally {
            client.stop();
        }
    }
}
 
Example #28
Source File: KeyReExchangeTest.java    From termd with Apache License 2.0 4 votes vote down vote up
@Test   // see SSHD-558
public void testKexFutureExceptionPropagation() throws Exception {
    setUp(0L, 0L, 0L);
    sshd.getCipherFactories().add(BuiltinCiphers.none);

    try (SshClient client = setupTestClient()) {
        client.getCipherFactories().add(BuiltinCiphers.none);
        // replace the original KEX factories with wrapped ones that we can fail intentionally
        List<NamedFactory<KeyExchange>> kexFactories = new ArrayList<>();
        final AtomicBoolean successfulInit = new AtomicBoolean(true);
        final AtomicBoolean successfulNext = new AtomicBoolean(true);
        final ClassLoader loader = getClass().getClassLoader();
        final Class<?>[] interfaces = {KeyExchange.class};
        for (final NamedFactory<KeyExchange> factory : client.getKeyExchangeFactories()) {
            kexFactories.add(new NamedFactory<KeyExchange>() {
                @Override
                public String getName() {
                    return factory.getName();
                }

                @Override
                public KeyExchange create() {
                    final KeyExchange proxiedInstance = factory.create();
                    return (KeyExchange) Proxy.newProxyInstance(loader, interfaces, new InvocationHandler() {
                        @Override
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                            String name = method.getName();
                            if ("init".equals(name) && (!successfulInit.get())) {
                                throw new UnsupportedOperationException("Intentionally failing 'init'");
                            } else if ("next".equals(name) && (!successfulNext.get())) {
                                throw new UnsupportedOperationException("Intentionally failing 'next'");
                            } else {
                                return method.invoke(proxiedInstance, args);
                            }
                        }
                    });
                }
            });
        }
        client.setKeyExchangeFactories(kexFactories);
        client.start();

        try {
            try {
                testKexFutureExceptionPropagation("init", successfulInit, client);
            } finally {
                successfulInit.set(true);
            }

            try {
                testKexFutureExceptionPropagation("next", successfulNext, client);
            } finally {
                successfulNext.set(true);
            }
        } finally {
            client.stop();
        }
    }
}
 
Example #29
Source File: AsyncUserAuthService.java    From termd with Apache License 2.0 4 votes vote down vote up
public AsyncUserAuthService(Session s) throws SshException {
  ValidateUtils.checkTrue(s instanceof ServerSession, "Server side service used on client side");
  if (s.isAuthenticated()) {
    throw new SshException("Session already authenticated");
  }

  serverSession = (ServerSession) s;
  maxAuthRequests = PropertyResolverUtils.getIntProperty(s, ServerAuthenticationManager.MAX_AUTH_REQUESTS, ServerAuthenticationManager.DEFAULT_MAX_AUTH_REQUESTS);

  List<NamedFactory<UserAuth>> factories = ValidateUtils.checkNotNullAndNotEmpty(
      serverSession.getUserAuthFactories(), "No user auth factories for %s", s);
  userAuthFactories = new ArrayList<>(factories);
  // Get authentication methods
  authMethods = new ArrayList<>();

  String mths = PropertyResolverUtils.getString(s, ServerFactoryManager.AUTH_METHODS);
  if (GenericUtils.isEmpty(mths)) {
    for (NamedFactory<UserAuth> uaf : factories) {
      authMethods.add(new ArrayList<>(Collections.singletonList(uaf.getName())));
    }
  } else {
    if (log.isDebugEnabled()) {
      log.debug("ServerUserAuthService({}) using configured methods={}", s, mths);
    }
    for (String mthl : mths.split("\\s")) {
      authMethods.add(new ArrayList<>(Arrays.asList(GenericUtils.split(mthl, ','))));
    }
  }
  // Verify all required methods are supported
  for (List<String> l : authMethods) {
    for (String m : l) {
      NamedFactory<UserAuth> factory = NamedResource.Utils.findByName(m, String.CASE_INSENSITIVE_ORDER, userAuthFactories);
      if (factory == null) {
        throw new SshException("Configured method is not supported: " + m);
      }
    }
  }

  if (log.isDebugEnabled()) {
    log.debug("ServerUserAuthService({}) authorized authentication methods: {}",
        s, NamedResource.Utils.getNames(userAuthFactories));
  }
}
 
Example #30
Source File: TestSSHInfrastructureV2.java    From scheduling with GNU Affero General Public License v3.0 4 votes vote down vote up
@BeforeClass
public static void startSSHServer() throws Exception {
    // Disable bouncy castle to avoid versions conflict
    System.setProperty("org.apache.sshd.registerBouncyCastle", "false");

    sshd = SshServer.setUpDefaultServer();

    SimpleGeneratorHostKeyProvider keyProvider = new SimpleGeneratorHostKeyProvider();
    keyProvider.setAlgorithm("RSA");
    sshd.setKeyPairProvider(keyProvider);

    List<NamedFactory<UserAuth>> userAuthFactories = new ArrayList<>(1);
    userAuthFactories.add(new UserAuthPasswordFactory());
    sshd.setUserAuthFactories(userAuthFactories);

    sshd.setPasswordAuthenticator(new PasswordAuthenticator() {
        @Override
        public boolean authenticate(String username, String password, ServerSession session) {
            return username != null && username.equals(password);
        }
    });

    CommandFactory cf = new CommandFactory() {
        @Override
        public Command createCommand(String command) {
            String[] splitCommand;
            if (OsUtils.isUNIX()) {
                splitCommand = SSHInfrastructureHelper.splitCommand(command);
            } else if (OsUtils.isWin32()) {
                splitCommand = SSHInfrastructureHelper.splitCommandWithoutRemovingQuotes(command);
            } else {
                throw new IllegalStateException("Operating system is not recognized");
            }
            StringBuilder rebuiltCommand = new StringBuilder();
            for (String commandPiece : splitCommand) {
                rebuiltCommand.append(commandPiece).append(" ");
            }
            rebuiltCommand.trimToSize();

            if (OsUtils.isUNIX()) {
                return new ProcessShellFactory(new String[] { "/bin/sh", "-c",
                                                              rebuiltCommand.toString() }).create();
            } else {
                return new ProcessShellFactory(new String[] { "cmd.exe", "/C",
                                                              rebuiltCommand.toString() }).create();
            }
        }
    };

    sshd.setCommandFactory(cf);

    sshd.start();

    port = sshd.getPort();

    javaExePath = System.getProperty("java.home") + File.separator + "bin" + File.separator +
                  (OsUtils.isWin32() ? "java.exe" : "java");
    javaExePath = "\"" + javaExePath + "\"";

    infraParams = new Object[] { ("localhost " + NB_NODES + "\n").getBytes(), //hosts
                                 60000, //timeout
                                 0, //attempts
                                 10, //wait between failures
                                 port, //ssh server port
                                 "toto", //ssh username
                                 "toto", //ssh password
                                 new byte[0], // optional ssh private key
                                 new byte[0], // optional ssh options file
                                 javaExePath, //java path on the remote machines
                                 PAResourceManagerProperties.RM_HOME.getValueAsString(), //Scheduling path on remote machines
                                 OperatingSystem.getOperatingSystem(), "" }; // extra java options

    policyParameters = new Object[] { AccessType.ALL.toString(), AccessType.ALL.toString(), "20000" };

}