Java Code Examples for org.apache.sshd.server.SshServer#setUpDefaultServer()

The following examples show how to use org.apache.sshd.server.SshServer#setUpDefaultServer() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 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: 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" };

}
 
Example 13
Source File: DefaultSshTtyTest.java    From aesh-readline with Apache License 2.0 4 votes vote down vote up
@Override
protected SshServer createServer() {
  return SshServer.setUpDefaultServer();
}
 
Example 14
Source File: NettySshTtyTest.java    From aesh-readline with Apache License 2.0 4 votes vote down vote up
@Override
protected SshServer createServer() {
  SshServer sshd = SshServer.setUpDefaultServer();
  sshd.setIoServiceFactoryFactory(new NettyIoServiceFactoryFactory(eventLoopGroup));
  return sshd;
}
 
Example 15
Source File: VertxSshTtyTest.java    From vertx-shell with Apache License 2.0 4 votes vote down vote up
@Override
protected SshServer createServer() {
  SshServer sshd = SshServer.setUpDefaultServer();
  sshd.setIoServiceFactoryFactory(new NettyIoServiceFactoryFactory(context.nettyEventLoop(), new VertxIoHandlerBridge(context)));
  return sshd;
}
 
Example 16
Source File: NettySshTtyTest.java    From termd with Apache License 2.0 4 votes vote down vote up
@Override
protected SshServer createServer() {
  SshServer sshd = SshServer.setUpDefaultServer();
  sshd.setIoServiceFactoryFactory(new NettyIoServiceFactoryFactory(eventLoopGroup));
  return sshd;
}
 
Example 17
Source File: SshServerBuilder.java    From java-11-examples with Apache License 2.0 4 votes vote down vote up
public SshServerBuilder() {
    this.sshd = SshServer.setUpDefaultServer();
    this.keyMap = KeyMapProvider.createDefaultKeyMap();
    this.sshClientSessionCounter = new SshClientSessionCounter();
}
 
Example 18
Source File: DefaultSshTtyTest.java    From termd with Apache License 2.0 4 votes vote down vote up
@Override
protected SshServer createServer() {
  return SshServer.setUpDefaultServer();
}
 
Example 19
Source File: NettySshTtyTest.java    From termd with Apache License 2.0 4 votes vote down vote up
@Override
protected SshServer createServer() {
  SshServer sshd = SshServer.setUpDefaultServer();
  sshd.setIoServiceFactoryFactory(new NettyIoServiceFactoryFactory(eventLoopGroup));
  return sshd;
}
 
Example 20
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()));
}