org.apache.sshd.server.SshServer Java Examples

The following examples show how to use org.apache.sshd.server.SshServer. 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: AsyncAuthTestBase.java    From termd with Apache License 2.0 7 votes vote down vote up
public void startServer(Integer timeout) throws Exception {
  if (server != null) {
    throw failure("Server already started");
  }
  server = SshServer.setUpDefaultServer();
  if (timeout != null) {
    server.getProperties().put(FactoryManager.AUTH_TIMEOUT, timeout.toString());
  }
  server.setPort(5000);
  server.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(new File("hostkey.ser").toPath()));
  server.setPasswordAuthenticator(new PasswordAuthenticator() {
    @Override
    public boolean authenticate(String username, String password, ServerSession session) throws PasswordChangeRequiredException {
      return authenticator.authenticate(username, password, session);
    }
  });
  server.setShellFactory(new EchoShellFactory());
  server.setServiceFactories(Arrays.asList(ServerConnectionServiceFactory.INSTANCE, AsyncUserAuthServiceFactory.INSTANCE));
  server.start();
}
 
Example #2
Source File: SshProxyTest.java    From ssh-proxy with Apache License 2.0 6 votes vote down vote up
@Test(timeout = TEST_TIMEOUT_MILLIS)
public void testSingleHopWithLocalPort() throws Exception {
	SshServer sshServer = setUpSshServer();
	int sshServerPort = sshServer.getPort();

	String hostConfigName = "localhost-" + sshServerPort;
	appendToSshFile(CONFIG_FILENAME, "Host " + hostConfigName + "\n\tHostName localhost\n\tPort " + sshServerPort + "\n\n");

	try (DummyServerSocketThread dummyServerSocketThread = new DummyServerSocketThread(TRANSFER_CHARSET, TEST_TEXT);
		SshProxy sshProxy = new SshProxy()) {
		int port = sshProxy.connect(hostConfigName, "localhost", dummyServerSocketThread.getPort(), 2345);

		final String receivedText;
		try (Socket s = new Socket(SshProxy.LOCALHOST, port);
			 InputStream is = s.getInputStream()) {
			log.info("connected to port: {}", port);
			receivedText = readLine(is);
		}
		assertEquals(TEST_TEXT, receivedText);
	} finally {
		tryStop(sshServer);
	}
}
 
Example #3
Source File: SshProxyTest.java    From ssh-proxy with Apache License 2.0 6 votes vote down vote up
private void doTestTwoHops(String proxyConfiguration) throws Exception {
	SshServer firstSshServer = setUpSshServer();
	int firstServerPort = firstSshServer.getPort();

	SshServer secondSshServer = setUpSshServer();
	int secondServerPort = secondSshServer.getPort();

	appendToSshFile(CONFIG_FILENAME, "Host firsthop\n\tHostName localhost\n\tPort " + firstServerPort + "\n\n");
	appendToSshFile(CONFIG_FILENAME, "Host secondhop\n\tHostName localhost\n\tPort " + secondServerPort + "\n\t" + proxyConfiguration + "\n\n");

	try (DummyServerSocketThread dummyServerSocketThread = new DummyServerSocketThread(TRANSFER_CHARSET, TEST_TEXT);
		 SshProxy sshProxy = new SshProxy()) {
		int port = sshProxy.connect("secondhop", "localhost", dummyServerSocketThread.getPort());

		final String receivedText;
		try (Socket s = new Socket(SshProxy.LOCALHOST, port);
			 InputStream is = s.getInputStream()) {
			log.info("connected to port: {}", port);
			receivedText = readLine(is);
		}
		assertEquals(TEST_TEXT, receivedText);
	} finally {
		tryStop(firstSshServer);
		tryStop(secondSshServer);
	}
}
 
Example #4
Source File: SshProxyTest.java    From ssh-proxy with Apache License 2.0 6 votes vote down vote up
@Test(timeout = TEST_TIMEOUT_MILLIS)
public void testSingleHop_EcDsaServer() throws Exception {
	SshServer sshServer = setUpSshServer(KeyUtils.EC_ALGORITHM);
	int sshServerPort = sshServer.getPort();

	String hostConfigName = "localhost-" + sshServerPort;
	appendToSshFile(CONFIG_FILENAME, "Host " + hostConfigName + "\n\tHostName localhost\n\tPort " + sshServerPort + "\n\n");

	try (DummyServerSocketThread dummyServerSocketThread = new DummyServerSocketThread(TRANSFER_CHARSET, TEST_TEXT);
		SshProxy sshProxy = new SshProxy()) {
		int port = sshProxy.connect(hostConfigName, "localhost", dummyServerSocketThread.getPort());

		final String receivedText;
		try (Socket s = new Socket(SshProxy.LOCALHOST, port);
			 InputStream is = s.getInputStream()) {
			log.info("connected to port: {}", port);
			receivedText = readLine(is);
		}
		assertEquals(TEST_TEXT, receivedText);
	} finally {
		tryStop(sshServer);
	}
}
 
Example #5
Source File: SshProxyTest.java    From ssh-proxy with Apache License 2.0 6 votes vote down vote up
@Test(timeout = TEST_TIMEOUT_MILLIS)
public void testSingleHop() throws Exception {
	SshServer sshServer = setUpSshServer();
	int sshServerPort = sshServer.getPort();

	String hostConfigName = "localhost-" + sshServerPort;
	appendToSshFile(CONFIG_FILENAME, "Host " + hostConfigName + "\n\tHostName localhost\n\tPort " + sshServerPort + "\n\n");

	try (DummyServerSocketThread dummyServerSocketThread = new DummyServerSocketThread(TRANSFER_CHARSET, TEST_TEXT);
		SshProxy sshProxy = new SshProxy()) {
		int port = sshProxy.connect(hostConfigName, "localhost", dummyServerSocketThread.getPort());

		final String receivedText;
		try (Socket s = new Socket(SshProxy.LOCALHOST, port);
			 InputStream is = s.getInputStream()) {
			log.info("connected to port: {}", port);
			receivedText = readLine(is);
		}
		assertEquals(TEST_TEXT, receivedText);
	} finally {
		tryStop(sshServer);
	}
}
 
Example #6
Source File: SshProxyTest.java    From ssh-proxy with Apache License 2.0 6 votes vote down vote up
private SshServer setUpSshServer(String algorithm) throws IOException {
	SshServer sshServer = SshServer.setUpDefaultServer();
	sshServer.setPort(0);
	AbstractGeneratorHostKeyProvider hostKeyProvider = SecurityUtils.createGeneratorHostKeyProvider(getServerKeyFile(algorithm));
	hostKeyProvider.setAlgorithm(algorithm);
	if (algorithm.equals(KeyUtils.EC_ALGORITHM)) {
		hostKeyProvider.setKeySize(256);
	}
	sshServer.setKeyPairProvider(hostKeyProvider);

	sshServer.setPublickeyAuthenticator(AcceptAllPublickeyAuthenticator.INSTANCE);
	sshServer.setForwardingFilter(AcceptAllForwardingFilter.INSTANCE);

	writeFingerprintToKnownHosts(algorithm);

	sshServer.start();

	int sshServerPort = sshServer.getPort();
	assertTrue(sshServerPort > 0);

	return sshServer;
}
 
Example #7
Source File: NettySshTtyBootstrap.java    From aesh-readline with Apache License 2.0 6 votes vote down vote up
public void start(Consumer<Connection> factory, Consumer<Throwable> doneHandler) {
    server = SshServer.setUpDefaultServer();
    server.setIoServiceFactoryFactory(new NettyIoServiceFactoryFactory(childGroup));
    server.setPort(port);
    server.setHost(host);
    server.setKeyPairProvider(keyPairProvider);
    server.setPasswordAuthenticator(passwordAuthenticator);
    if (publicKeyAuthenticator != null) {
        server.setPublickeyAuthenticator(publicKeyAuthenticator);
    }
    server.setShellFactory(() -> new TtyCommand(charset, factory));
    try {
        server.start();
    } catch (Exception e) {
        doneHandler.accept(e);
        return;
    }
    doneHandler.accept(null);
}
 
Example #8
Source File: SSHServer.java    From vertx-shell with Apache License 2.0 6 votes vote down vote up
public void close(Handler<AsyncResult<Void>> completionHandler) {
  if (!status.compareAndSet(STATUS_STARTED, STATUS_STOPPING)) {
    completionHandler.handle(Future.failedFuture("Invalid state:" + status.get()));
    return;
  }
  vertx.executeBlocking(fut-> {
    try {
      SshServer server = this.nativeServer;
      this.nativeServer = null;
      server.close();
      completionHandler.handle(Future.succeededFuture());
    } catch (Exception t) {
      completionHandler.handle(Future.failedFuture(t));
    } finally {
      status.set(STATUS_STOPPED);
    }
  }, completionHandler);
}
 
Example #9
Source File: SshServerLauncher.java    From onedev with MIT License 6 votes vote down vote up
@Listen
  public void on(SystemStarted event) {
      server = SshServer.setUpDefaultServer();

      server.setPort(serverConfig.getSshPort());
      server.setKeyPairProvider(keyPairProvider);
      server.setShellFactory(new DisableShellAccess());
      
      server.setPublickeyAuthenticator(new CachingPublicKeyAuthenticator(authenticator));
      server.setKeyboardInteractiveAuthenticator(null);
      
      server.setCommandFactory(command -> {
      	for (SshCommandCreator creator: commandCreators) {
      		Command sshCommand = creator.createCommand(command);
      		if (sshCommand != null)
      			return sshCommand;
      	}
          return new UnknownCommand(command);
      });

      try {
	server.start();
} catch (IOException e) {
	throw new RuntimeException(e);
}
  }
 
Example #10
Source File: SshShellConfiguration.java    From ssh-shell-spring-boot with Apache License 2.0 6 votes vote down vote up
/**
 * Construct ssh server thanks to ssh shell properties
 *
 * @return ssh server
 */
@Bean
public SshServer sshServer() {
    SshServer server = SshServer.setUpDefaultServer();
    server.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(properties.getHostKeyFile().toPath()));
    server.setHost(properties.getHost());
    server.setPasswordAuthenticator(passwordAuthenticator);
    server.setPublickeyAuthenticator(RejectAllPublickeyAuthenticator.INSTANCE);
    if (properties.getAuthorizedPublicKeysFile() != null) {
        if (properties.getAuthorizedPublicKeysFile().exists() && properties.getAuthorizedPublicKeysFile().canRead()) {
            server.setPublickeyAuthenticator(new SshShellPublicKeyAuthenticationProvider(properties.getAuthorizedPublicKeysFile()));
        } else {
            LOGGER.warn("Could not read authorized public keys file [{}], public key authentication is disabled.",
                    properties.getAuthorizedPublicKeysFile().getAbsolutePath());
        }
    }
    server.setPort(properties.getPort());
    server.setShellFactory(channelSession -> shellCommandFactory);
    server.setCommandFactory((channelSession, s) -> shellCommandFactory);
    return server;
}
 
Example #11
Source File: FakeSftpServerRule.java    From fake-sftp-server-rule with MIT License 6 votes vote down vote up
private SshServer startServer(
    FileSystem fileSystem
) throws IOException {
    SshServer server = SshServer.setUpDefaultServer();
    server.setPort(port);
    server.setKeyPairProvider(new SimpleGeneratorHostKeyProvider());
    server.setPasswordAuthenticator(this::authenticate);
    server.setSubsystemFactories(singletonList(new SftpSubsystemFactory()));
    /* When a channel is closed SshServer calls close() on the file system.
     * In order to use the file system for multiple channels/sessions we
     * have to use a file system wrapper whose close() does nothing.
     */
    server.setFileSystemFactory(session -> new DoNotClose(fileSystem));
    server.start();
    this.server = server;
    return server;
}
 
Example #12
Source File: NettySshTtyBootstrap.java    From termd with Apache License 2.0 6 votes vote down vote up
public void start(Consumer<TtyConnection> factory, Consumer<Throwable> doneHandler) {
  server = SshServer.setUpDefaultServer();
  server.setIoServiceFactoryFactory(new NettyIoServiceFactoryFactory(childGroup));
  server.setPort(port);
  server.setHost(host);
  server.setKeyPairProvider(keyPairProvider);
  server.setPasswordAuthenticator(passwordAuthenticator);
  server.setShellFactory(() -> new TtyCommand(charset, factory));
  try {
    server.start();
  } catch (Exception e) {
    doneHandler.accept(e);
    return;
  }
  doneHandler.accept(null);
}
 
Example #13
Source File: NettySshTtyBootstrap.java    From termd with Apache License 2.0 6 votes vote down vote up
public void start(final Consumer<TtyConnection> factory, Consumer<Throwable> doneHandler) {
  server = SshServer.setUpDefaultServer();
  server.setIoServiceFactoryFactory(new NettyIoServiceFactoryFactory(childGroup));
  server.setPort(port);
  server.setHost(host);
  server.setKeyPairProvider(keyPairProvider);
  server.setPasswordAuthenticator(passwordAuthenticator);
  server.setShellFactory(new Factory<Command>() {
    @Override
    public Command create() {
      return new TtyCommand(charset, factory);
    }
  });
  try {
    server.start();
  } catch (Exception e) {
    doneHandler.accept(e);
    return;
  }
  doneHandler.accept(null);
}
 
Example #14
Source File: SSHServer.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
public void start() throws ServiceException {
    sshServer = SshServer.setUpDefaultServer();
    sshServer.setPort(port);
    sshServer.setHost(bind);

    final String basePath = SystemInstance.get().getBase().getDirectory().getAbsolutePath();
    if (SecurityUtils.isBouncyCastleRegistered()) {
        sshServer.setKeyPairProvider(new BouncyCastleGeneratorHostKeyProvider(new File(basePath, KEY_NAME + ".pem").toPath()));
    } else {
        sshServer.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(new File(basePath, KEY_NAME + ".ser").toPath()));
    }

    final OpenEJBShellFactory sf = new OpenEJBShellFactory(bind, port);
    sshServer.setShellFactory(sf);

    final JaasPasswordAuthenticator authenticator = new OpenEJBJaasPasswordAuthenticator();
    authenticator.setDomain(domain);
    sshServer.setPasswordAuthenticator(authenticator);

    try {
        sshServer.start();
    } catch (IOException e) {
        // no-op
    }
}
 
Example #15
Source File: SshdServerConfiguration.java    From sshd-shell-spring-boot with Apache License 2.0 5 votes vote down vote up
@PostConstruct
void startServer() throws IOException {
    SshServer server = sshServer();
    server.start();
    properties.getShell().setPort(server.getPort()); // In case server port is 0, a random port is assigned.
    log.info("SSH server started on port {}", properties.getShell().getPort());
}
 
Example #16
Source File: SFTPCryptomatorInteroperabilityTest.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Before
public void startSerer() throws Exception {
    server = SshServer.setUpDefaultServer();
    server.setPort(PORT_NUMBER);
    server.setPasswordAuthenticator((username, password, session) -> true);
    server.setKeyPairProvider(new SimpleGeneratorHostKeyProvider());
    server.setSubsystemFactories(Collections.singletonList(new SftpSubsystemFactory()));
    final java.nio.file.Path tempDir = Files.createTempDirectory(String.format("%s-", this.getClass().getName()));
    final java.nio.file.Path vault = tempDir.resolve("vault");
    Files.createDirectory(vault);
    passphrase = new AlphanumericRandomStringService().random();
    cryptoFileSystem = CryptoFileSystemProvider.newFileSystem(vault, CryptoFileSystemProperties.cryptoFileSystemProperties().withPassphrase(passphrase).build());
    server.setFileSystemFactory(new VirtualFileSystemFactory(cryptoFileSystem.getPathToVault().getParent().toAbsolutePath()));
    server.start();
}
 
Example #17
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 #18
Source File: SshdServerConfiguration.java    From sshd-shell-spring-boot with Apache License 2.0 5 votes vote down vote up
@Bean
SshServer sshServer() {
    Shell props = properties.getShell();
    if (Objects.isNull(props.getPassword())) {
        props.setPassword(UUID.randomUUID().toString());
        log.info("********** User password not set. Use following password to login: {} **********",
                props.getPassword());
    }
    return buildServer(props);
}
 
Example #19
Source File: SftpTestResource.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, String> start() {
    try {
        final int port = AvailablePortFinder.getNextAvailable();

        sftpHome = Files.createTempDirectory("sftp-");
        sshHome = sftpHome.resolve("admin/.ssh");

        Files.createDirectories(sshHome);

        byte[] knownHostsBytes = String.format(KNOWN_HOSTS, port).getBytes(StandardCharsets.UTF_8);
        Files.write(sshHome.resolve(".known_hosts"), knownHostsBytes);

        VirtualFileSystemFactory factory = new VirtualFileSystemFactory();
        factory.setUserHomeDir("admin", sftpHome.resolve("admin").toAbsolutePath());

        sshServer = SshServer.setUpDefaultServer();
        sshServer.setPort(port);
        sshServer.setKeyPairProvider(new ClassLoadableResourceKeyPairProvider("hostkey.pem"));
        sshServer.setSubsystemFactories(Collections.singletonList(new SftpSubsystemFactory()));
        sshServer.setCommandFactory(new ScpCommandFactory());
        sshServer.setPasswordAuthenticator((username, password, session) -> true);
        sshServer.setPublickeyAuthenticator((username, key, session) -> true);
        sshServer.setFileSystemFactory(factory);
        sshServer.start();

        return CollectionHelper.mapOf("camel.sftp.test-port", Integer.toString(port));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #20
Source File: SshdPlugin.java    From Bukkit-SSHD with Apache License 2.0 5 votes vote down vote up
@Override
public void onEnable() {
    instance = this;

    sshd = SshServer.setUpDefaultServer();
    sshd.setPort(getConfig().getInt("port", 22));
    String host = getConfig().getString("listenAddress", "all");
    sshd.setHost(host.equals("all") ? null : host);

    File hostKey = new File(getDataFolder(), "hostkey");
    File authorizedKeys = new File(getDataFolder(), "authorized_keys");

    sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(hostKey));
    sshd.setShellFactory(new ConsoleShellFactory());
    sshd.setPasswordAuthenticator(new ConfigPasswordAuthenticator());
    sshd.setPublickeyAuthenticator(new PublicKeyAuthenticator(authorizedKeys));

    if (getConfig().getBoolean("enableSFTP")) {
        sshd.setSubsystemFactories(Collections.singletonList(new SftpSubsystemFactory()));
        sshd.setFileSystemFactory(new VirtualFileSystemFactory(
                FileSystems.getDefault().getPath(
                        getDataFolder().getAbsolutePath()
                ).getParent().getParent()
        ));
    }

    sshd.setCommandFactory(new ConsoleCommandFactory());
    try {
        sshd.start();
    } catch (IOException e) {
        getLogger().log(Level.SEVERE, "Failed to start SSH server! ", e);
    }
}
 
Example #21
Source File: ESBJAVA3470.java    From micro-integrator 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());
    sshd.setKeyPairProvider(createTestHostKeyProvider(Paths.get(file.getAbsolutePath())));
    sshd.setUserAuthFactories(Arrays.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.asList(new SftpSubsystemFactory()));
    SftpServerRunner sftpServerRunner = new SftpServerRunner(sshd);

    try {
        sftpServerRunner.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #22
Source File: SshProxyTest.java    From ssh-proxy with Apache License 2.0 5 votes vote down vote up
@Test(timeout = TEST_TIMEOUT_MILLIS)
public void testSingleHop_ConnectionRefused() throws Exception {
	SshServer sshServer = setUpSshServer();
	sshServer.stop();
	try (SshProxy sshProxy = new SshProxy()) {
		sshProxy.connect("localhost", "targethost", 1234);
		fail("SshProxyRuntimeException expected");
	} catch (SshProxyRuntimeException e) {
		log.debug("Expected exception", e);
		assertEquals("Failed to create SSH tunnel to targethost via localhost", e.getMessage());
		assertEquals("Failed to connect to targethost via localhost", e.getCause().getMessage());
	}
}
 
Example #23
Source File: SshProxyTest.java    From ssh-proxy with Apache License 2.0 5 votes vote down vote up
private void tryStop(SshServer sshServer) {
	try {
		log.debug("stopping SSH server");
		sshServer.stop();
	} catch (IOException e) {
		log.error("Failed to stop SSH server", e);
	}
}
 
Example #24
Source File: AsyncAuthTestBase.java    From aesh-readline with Apache License 2.0 5 votes vote down vote up
public void startServer(Integer timeout) throws Exception {
  if (server != null) {
    throw failure("Server already started");
  }
  server = SshServer.setUpDefaultServer();
  if (timeout != null) {
    server.setProperties(Collections.singletonMap(FactoryManager.AUTH_TIMEOUT, timeout.toString()));
  }
  server.setPort(5000);
  server.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(new File("hostkey.ser").toPath()));
  server.setPasswordAuthenticator((username, password, sess) -> authenticator.authenticate(username, password, sess));
  server.setShellFactory(new EchoShellFactory());
  server.setServiceFactories(Arrays.asList(ServerConnectionServiceFactory.INSTANCE, AsyncUserAuthServiceFactory.INSTANCE));
  server.start();
}
 
Example #25
Source File: TestSshTunnel.java    From datacollector with Apache License 2.0 5 votes vote down vote up
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 #26
Source File: TestSshTunnel.java    From datacollector with Apache License 2.0 5 votes vote down vote up
public void runSshd(PublickeyAuthenticator authenticator, SshCommand command) throws Exception {
  SshServer sshd = createSshd(authenticator, sshdKeyPair);
  try {
    sshd.start();
    command.run(sshd.getHost(), sshd.getPort(), sshdFingerprint, () -> {
      try {
        sshd.stop();
      } catch (Exception ex) {
        throw new RuntimeException("Stopping SSHD: " + ex, ex);
      }
    });
  } finally {
    sshd.stop();
  }
}
 
Example #27
Source File: Utils.java    From termd with Apache License 2.0 5 votes vote down vote up
public static SshServer setupTestServer(Class<?> anchor) {
    SshServer sshd = SshServer.setUpDefaultServer();
    sshd.setKeyPairProvider(createTestHostKeyProvider(anchor));
    sshd.setPasswordAuthenticator(BogusPasswordAuthenticator.INSTANCE);
    sshd.setPublickeyAuthenticator(AcceptAllPublickeyAuthenticator.INSTANCE);
    sshd.setShellFactory(EchoShellFactory.INSTANCE);
    sshd.setCommandFactory(UnknownCommandFactory.INSTANCE);
    return sshd;
}
 
Example #28
Source File: AsyncAuthTestBase.java    From termd with Apache License 2.0 5 votes vote down vote up
public void startServer(Integer timeout) throws Exception {
  if (server != null) {
    throw failure("Server already started");
  }
  server = SshServer.setUpDefaultServer();
  if (timeout != null) {
    server.getProperties().put(FactoryManager.AUTH_TIMEOUT, timeout.toString());
  }
  server.setPort(5000);
  server.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(new File("hostkey.ser").toPath()));
  server.setPasswordAuthenticator((username, password, sess) -> authenticator.authenticate(username, password, sess));
  server.setShellFactory(new EchoShellFactory());
  server.setServiceFactories(Arrays.asList(ServerConnectionServiceFactory.INSTANCE, AsyncUserAuthServiceFactory.INSTANCE));
  server.start();
}
 
Example #29
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 #30
Source File: EmbeddedSSHServer.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
public EmbeddedSSHServer(Path homeDir, int port) {
    this.sshServer = SshServer.setUpDefaultServer();
    this.sshServer.setPort(port);
    this.sshServer.setCommandFactory(new EchoCommandFactory());
    this.sshServer.setKeyPairProvider(new SimpleGeneratorHostKeyProvider());
    this.sshServer.setPasswordAuthenticator((username, password, serverSession) -> username.equals("admin") && password.equals("admin"));
    this.sshServer.setPublickeyAuthenticator((s, publicKey, serverSession) -> true);
    this.homeDir = homeDir;

    if (EnvironmentUtils.isWindows()) {
        sshServer.setShellFactory(new ProcessShellFactory(new String[] { "cmd.exe " }));
    } else {
        sshServer.setShellFactory(new ProcessShellFactory(new String[] { "/bin/sh", "-i", "-s" }));
    }
}