org.apache.sshd.common.keyprovider.KeyPairProvider Java Examples
The following examples show how to use
org.apache.sshd.common.keyprovider.KeyPairProvider.
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: Utils.java From termd with Apache License 2.0 | 6 votes |
public static KeyPairProvider createTestHostKeyProvider(Class<?> anchor) { KeyPairProvider provider = KEYPAIR_PROVIDER_HOLDER.get(); if (provider != null) { return provider; } File targetFolder = ValidateUtils.checkNotNull(detectTargetFolder(anchor), "Failed to detect target folder"); File file = new File(targetFolder, "hostkey." + DEFAULT_TEST_HOST_KEY_PROVIDER_ALGORITHM.toLowerCase()); provider = createTestHostKeyProvider(file); KeyPairProvider prev = KEYPAIR_PROVIDER_HOLDER.getAndSet(provider); if (prev != null) { // check if somebody else beat us to it return prev; } else { return provider; } }
Example #2
Source File: Utils.java From termd with Apache License 2.0 | 6 votes |
public static KeyPairProvider createTestHostKeyProvider(Class<?> anchor) { KeyPairProvider provider = KEYPAIR_PROVIDER_HOLDER.get(); if (provider != null) { return provider; } File targetFolder = ValidateUtils.checkNotNull(detectTargetFolder(anchor), "Failed to detect target folder"); File file = new File(targetFolder, "hostkey." + DEFAULT_TEST_HOST_KEY_PROVIDER_ALGORITHM.toLowerCase()); provider = createTestHostKeyProvider(file); KeyPairProvider prev = KEYPAIR_PROVIDER_HOLDER.getAndSet(provider); if (prev != null) { // check if somebody else beat us to it return prev; } else { return provider; } }
Example #3
Source File: TestSshTunnel.java From datacollector with Apache License 2.0 | 5 votes |
private SshServer createSshd(PublickeyAuthenticator publickeyAuthenticator, java.security.KeyPair sshdKeyPair) { SshServer sshd = SshServer.setUpDefaultServer(); sshd.setHost("localhost"); sshd.setPort(randomPort()); KeyPairProvider keyPairProvider = KeyPairProvider.wrap(sshdKeyPair); sshd.setKeyPairProvider(keyPairProvider); sshd.setForwardingFilter(AcceptAllForwardingFilter.INSTANCE); sshd.setPublickeyAuthenticator(publickeyAuthenticator); return sshd; }
Example #4
Source File: AuthenticationTest.java From termd with Apache License 2.0 | 5 votes |
@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 #5
Source File: Utils.java From termd with Apache License 2.0 | 5 votes |
public static SshClient setupTestClient(Class<?> anchor) { SshClient client = SshClient.setUpDefaultClient(); client.setServerKeyVerifier(AcceptAllServerKeyVerifier.INSTANCE); client.setHostConfigEntryResolver(HostConfigEntryResolver.EMPTY); client.setKeyPairProvider(KeyPairProvider.EMPTY_KEYPAIR_PROVIDER); return client; }
Example #6
Source File: Utils.java From termd with Apache License 2.0 | 5 votes |
public static SshClient setupTestClient(Class<?> anchor) { SshClient client = SshClient.setUpDefaultClient(); client.setServerKeyVerifier(AcceptAllServerKeyVerifier.INSTANCE); client.setHostConfigEntryResolver(HostConfigEntryResolver.EMPTY); client.setKeyPairProvider(KeyPairProvider.EMPTY_KEYPAIR_PROVIDER); return client; }
Example #7
Source File: AuthenticationTest.java From termd with Apache License 2.0 | 5 votes |
@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 #8
Source File: KeyPairProviderBuilder.java From java-11-examples with Apache License 2.0 | 5 votes |
public KeyPairProvider build() throws UnrecoverableKeyException, CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException { KeyPair keyPair = Utils.loadKeyPair(is, keystorePassword, keyPairAlias, keyPairPassword); List<KeyPair> keyPairList = new ArrayList<>(); keyPairList.add(keyPair); return new KeyPairProviderImpl(keyPairList); }
Example #9
Source File: SshServerLauncher.java From onedev with MIT License | 5 votes |
@Inject public SshServerLauncher(KeyPairProvider keyPairProvider, ServerConfig serverConfig, SshAuthenticator authenticator, Set<SshCommandCreator> commandCreators) { this.keyPairProvider = keyPairProvider; this.serverConfig = serverConfig; this.authenticator = authenticator; this.commandCreators = commandCreators; }
Example #10
Source File: ServerApp.java From java-11-examples with Apache License 2.0 | 5 votes |
public void startApplication() throws IOException, UnrecoverableKeyException, CertificateException, NoSuchAlgorithmException, KeyStoreException { LOG.info("starting ssh server "); int port = 2222; String prompt = "CMD: "; SshClientSessionListenerImpl sshClientSessionListener = new SshClientSessionListenerImpl(); stringCommandProcessor = new StringCommandProcessorImpl(); sshClientCommandProcessor = new SshClientCommandProcessor(sshClientSessionListener); PasswordAuthenticator passwordAuthenticator = new PasswordAuthenticatorBuilder() .addCredentials("user", "secret") .build(); InputStream resourceAsStream = Main.class.getClassLoader().getResourceAsStream("server-keystore.jks"); KeyPairProvider keyPairProvider = new KeyPairProviderBuilder() .setIs(resourceAsStream) .setKeyPairAlias("serverkey") .setKeystorePassword("secret") .setKeyPairPassword("secret") .build(); KeyMap keyMap = KeyMapProvider.createDefaultKeyMap(); sshd = new SshServerBuilder() .setPort(port) .withKeyMap(keyMap) .withKeyPairProvider(keyPairProvider) .withPasswordAuthenticator(passwordAuthenticator) .withCommandFactory(stringCommandProcessor) .withShellFactory(prompt, stringCommandProcessor) .withSshClientProcessor(sshClientCommandProcessor, sshClientSessionListener) .build(); sshd.start(); LOG.info("Listening on port {}", port); }
Example #11
Source File: Utils.java From termd with Apache License 2.0 | 4 votes |
public static KeyPairProvider createTestHostKeyProvider(File file) { return createTestHostKeyProvider(ValidateUtils.checkNotNull(file, "No file").toPath()); }
Example #12
Source File: SSHServer.java From vertx-shell with Apache License 2.0 | 4 votes |
public SSHServer listen(Handler<AsyncResult<Void>> listenHandler) { if (!status.compareAndSet(STATUS_STOPPED, STATUS_STARTING)) { listenHandler.handle(Future.failedFuture("Invalid state:" + status.get())); return this; } if (options.getAuthOptions() != null) { authProvider = ShellAuth.load(vertx, options.getAuthOptions()); } Charset defaultCharset = Charset.forName(options.getDefaultCharset()); listenContext = (ContextInternal) vertx.getOrCreateContext(); vertx.executeBlocking(fut -> { try { KeyCertOptions ksOptions = options.getKeyPairOptions(); KeyStoreHelper ksHelper = KeyStoreHelper.create((VertxInternal) vertx, ksOptions); if (ksHelper == null) { throw new VertxException("No key pair store configured"); } KeyStore ks = ksHelper.store(); String kpPassword = ""; if (ksOptions instanceof JksOptions) { kpPassword = ((JksOptions) ksOptions).getPassword(); } else if (ksOptions instanceof PfxOptions) { kpPassword = ((PfxOptions) ksOptions).getPassword(); } List<KeyPair> keyPairs = new ArrayList<>(); for (Enumeration<String> it = ks.aliases(); it.hasMoreElements(); ) { String alias = it.nextElement(); Key key = ks.getKey(alias, kpPassword.toCharArray()); if (key instanceof PrivateKey) { Certificate cert = ks.getCertificate(alias); PublicKey publicKey = cert.getPublicKey(); keyPairs.add(new KeyPair(publicKey, (PrivateKey) key)); } } KeyPairProvider provider = new AbstractKeyPairProvider() { @Override public Iterable<KeyPair> loadKeys() { return keyPairs; } }; Buffer inputrc = Helper.loadResource(vertx.fileSystem(), options.getIntputrc()); if (inputrc == null) { throw new VertxException("Could not load inputrc from " + options.getIntputrc()); } Keymap keymap = new Keymap(new ByteArrayInputStream(inputrc.getBytes())); TermConnectionHandler connectionHandler = new TermConnectionHandler(vertx, keymap, termHandler); nativeServer = SshServer.setUpDefaultServer(); nativeServer.setShellFactory(() -> new TtyCommand(defaultCharset, connectionHandler::handle)); Handler<SSHExec> execHandler = this.execHandler; if (execHandler != null) { nativeServer.setCommandFactory(command -> new TtyCommand(defaultCharset, conn -> { execHandler.handle(new SSHExec(command, conn)); })); } nativeServer.setHost(options.getHost()); nativeServer.setPort(options.getPort()); nativeServer.setKeyPairProvider(provider); nativeServer.setIoServiceFactoryFactory(new NettyIoServiceFactoryFactory(listenContext.nettyEventLoop(), new VertxIoHandlerBridge(listenContext))); nativeServer.setServiceFactories(Arrays.asList(ServerConnectionServiceFactory.INSTANCE, AsyncUserAuthServiceFactory.INSTANCE)); // if (authProvider == null) { throw new VertxException("No authenticator"); } nativeServer.setPasswordAuthenticator((username, userpass, session) -> { AsyncAuth auth = new AsyncAuth(); listenContext.runOnContext(v -> { authProvider.authenticate(new JsonObject().put("username", username).put("password", userpass), ar -> { auth.setAuthed(ar.succeeded()); }); }); throw auth; }); // nativeServer.start(); status.set(STATUS_STARTED); fut.complete(); } catch (Exception e) { status.set(STATUS_STOPPED); fut.fail(e); } }, listenHandler); return this; }
Example #13
Source File: NettySshTtyBootstrap.java From termd with Apache License 2.0 | 4 votes |
public KeyPairProvider getKeyPairProvider() { return keyPairProvider; }
Example #14
Source File: NettySshTtyBootstrap.java From termd with Apache License 2.0 | 4 votes |
public NettySshTtyBootstrap setKeyPairProvider(KeyPairProvider keyPairProvider) { this.keyPairProvider = keyPairProvider; return this; }
Example #15
Source File: BaseTestSupport.java From termd with Apache License 2.0 | 4 votes |
protected KeyPairProvider createTestHostKeyProvider() { return Utils.createTestHostKeyProvider(getClass()); }
Example #16
Source File: SinglePublicKeyAuthTest.java From termd with Apache License 2.0 | 4 votes |
public SinglePublicKeyAuthTest() { SimpleGeneratorHostKeyProvider provider = new SimpleGeneratorHostKeyProvider(); provider.setAlgorithm(KeyUtils.RSA_ALGORITHM); pairRsaBad = provider.loadKey(KeyPairProvider.SSH_RSA); }
Example #17
Source File: Utils.java From termd with Apache License 2.0 | 4 votes |
public static KeyPairProvider createTestHostKeyProvider(Path path) { SimpleGeneratorHostKeyProvider keyProvider = new SimpleGeneratorHostKeyProvider(); keyProvider.setPath(ValidateUtils.checkNotNull(path, "No path")); keyProvider.setAlgorithm(DEFAULT_TEST_HOST_KEY_PROVIDER_ALGORITHM); return validateKeyPairProvider(keyProvider); }
Example #18
Source File: AuthenticationTest.java From termd with Apache License 2.0 | 4 votes |
@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 #19
Source File: ESBJAVA3470.java From micro-integrator with Apache License 2.0 | 4 votes |
public static KeyPairProvider createTestHostKeyProvider(Path path) { SimpleGeneratorHostKeyProvider keyProvider = new SimpleGeneratorHostKeyProvider(); keyProvider.setPath(ValidateUtils.checkNotNull(path, "No path")); keyProvider.setAlgorithm(DEFAULT_TEST_HOST_KEY_PROVIDER_ALGORITHM); return keyProvider; }
Example #20
Source File: NettySshTtyBootstrap.java From aesh-readline with Apache License 2.0 | 4 votes |
public NettySshTtyBootstrap setKeyPairProvider(KeyPairProvider keyPairProvider) { this.keyPairProvider = keyPairProvider; return this; }
Example #21
Source File: NettySshTtyBootstrap.java From aesh-readline with Apache License 2.0 | 4 votes |
public KeyPairProvider getKeyPairProvider() { return keyPairProvider; }
Example #22
Source File: ESBJAVA3470.java From product-ei with Apache License 2.0 | 4 votes |
public static KeyPairProvider createTestHostKeyProvider(Path path) { SimpleGeneratorHostKeyProvider keyProvider = new SimpleGeneratorHostKeyProvider(); keyProvider.setPath(ValidateUtils.checkNotNull(path, "No path")); keyProvider.setAlgorithm(DEFAULT_TEST_HOST_KEY_PROVIDER_ALGORITHM); return keyProvider; }
Example #23
Source File: SshServerBuilder.java From java-11-examples with Apache License 2.0 | 4 votes |
public SshServerBuilder withKeyPairProvider(KeyPairProvider keyPairProvider) { sshd.setKeyPairProvider(keyPairProvider); return this; }
Example #24
Source File: CoreModule.java From onedev with MIT License | 4 votes |
private void configureSsh() { bind(KeyPairProvider.class).to(DefaultKeyPairProvider.class); bind(SshAuthenticator.class).to(DefaultSshAuthenticator.class); bind(SshServerLauncher.class); }
Example #25
Source File: SinglePublicKeyAuthTest.java From termd with Apache License 2.0 | 4 votes |
public SinglePublicKeyAuthTest() { SimpleGeneratorHostKeyProvider provider = new SimpleGeneratorHostKeyProvider(); provider.setAlgorithm(KeyUtils.RSA_ALGORITHM); pairRsaBad = provider.loadKey(KeyPairProvider.SSH_RSA); }
Example #26
Source File: AuthenticationTest.java From termd with Apache License 2.0 | 4 votes |
@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 #27
Source File: Utils.java From termd with Apache License 2.0 | 4 votes |
public static KeyPairProvider createTestHostKeyProvider(Path path) { SimpleGeneratorHostKeyProvider keyProvider = new SimpleGeneratorHostKeyProvider(); keyProvider.setPath(ValidateUtils.checkNotNull(path, "No path")); keyProvider.setAlgorithm(DEFAULT_TEST_HOST_KEY_PROVIDER_ALGORITHM); return validateKeyPairProvider(keyProvider); }
Example #28
Source File: Utils.java From termd with Apache License 2.0 | 4 votes |
public static KeyPairProvider createTestHostKeyProvider(File file) { return createTestHostKeyProvider(ValidateUtils.checkNotNull(file, "No file").toPath()); }
Example #29
Source File: BaseTestSupport.java From termd with Apache License 2.0 | 4 votes |
protected KeyPairProvider createTestHostKeyProvider() { return Utils.createTestHostKeyProvider(getClass()); }
Example #30
Source File: NettySshTtyBootstrap.java From termd with Apache License 2.0 | 4 votes |
public NettySshTtyBootstrap setKeyPairProvider(KeyPairProvider keyPairProvider) { this.keyPairProvider = keyPairProvider; return this; }