org.apache.sshd.server.auth.password.PasswordAuthenticator Java Examples

The following examples show how to use org.apache.sshd.server.auth.password.PasswordAuthenticator. 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: SshTtyTestBase.java    From termd with Apache License 2.0 6 votes vote down vote up
@Override
protected void server(final Consumer<TtyConnection> onConnect) {
  if (sshd != null) {
    throw failure("Already a server");
  }
  try {
    sshd = createServer();
    sshd.setPort(5000);
    sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(new File("hostkey.ser").toPath()));
    sshd.setPasswordAuthenticator(new PasswordAuthenticator() {
      @Override
      public boolean authenticate(String username, String password, ServerSession session) throws PasswordChangeRequiredException {
        return true;
      }
    });
    sshd.setShellFactory(new Factory<Command>() {
      @Override
      public Command create() {
        return createConnection(onConnect);
      }
    });
    sshd.start();
  } catch (Exception e) {
    throw failure(e);
  }
}
 
Example #3
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 #4
Source File: AsyncAuthTestBase.java    From termd with Apache License 2.0 6 votes vote down vote up
@Test
public void testAsyncAuthFailed() throws Exception {
  startServer();
  authenticator = new PasswordAuthenticator() {
    @Override
    public boolean authenticate(String username, String password, ServerSession session) throws PasswordChangeRequiredException {
      final AsyncAuth auth = new AsyncAuth();
      new Thread() {
        @Override
        public void run() {
          try {
            Thread.sleep(200);
          } catch (InterruptedException ignore) {
          } finally {
            auth.setAuthed(false);
          }
        }
      }.start();
      throw auth;
    }
  };
  assertFalse(authenticate());
}
 
Example #5
Source File: AsyncAuthTestBase.java    From termd with Apache License 2.0 6 votes vote down vote up
@Test
public void testAsyncAuthSucceeded() throws Exception {
  startServer();
  authenticator = new PasswordAuthenticator() {
    @Override
    public boolean authenticate(String username, String password, ServerSession session) throws PasswordChangeRequiredException {
      final AsyncAuth auth = new AsyncAuth();
      new Thread() {
        @Override
        public void run() {
          try {
            Thread.sleep(200);
          } catch (InterruptedException ignore) {
          } finally {
            auth.setAuthed(true);
          }
        }
      }.start();
      throw auth;
    }
  };
  assertTrue(authenticate());
}
 
Example #6
Source File: SshShellConfiguration.java    From ssh-shell-spring-boot with Apache License 2.0 5 votes vote down vote up
public SshShellConfiguration(SshShellProperties properties,
                             SshShellCommandFactory shellCommandFactory,
                             PasswordAuthenticator passwordAuthenticator) {
    this.properties = properties;
    this.shellCommandFactory = shellCommandFactory;
    this.passwordAuthenticator = passwordAuthenticator;
}
 
Example #7
Source File: SshdServerConfiguration.java    From sshd-shell-spring-boot with Apache License 2.0 5 votes vote down vote up
private PasswordAuthenticator authProviderAuthenticator(Auth authProps) throws IllegalArgumentException {
    try {
        AuthenticationProvider authProvider = Objects.isNull(authProps.getAuthProviderBeanName())
                ? appContext.getBean(AuthenticationProvider.class)
                : appContext.getBean(authProps.getAuthProviderBeanName(), AuthenticationProvider.class);
        return new AuthProviderSshdPasswordAuthenticator(authProvider);
    } catch (BeansException ex) {
        throw new IllegalArgumentException("Expected a default or valid AuthenticationProvider bean", ex);
    }
}
 
Example #8
Source File: SshdServerConfiguration.java    From sshd-shell-spring-boot with Apache License 2.0 5 votes vote down vote up
private PasswordAuthenticator passwordAuthenticator(Shell props) {
    Auth authProps = props.getAuth();
    switch (authProps.getAuthType()) {
        case SIMPLE:
            return new SimpleSshdPasswordAuthenticator(props, new HashSet<>(Arrays.asList(systemCommandRoles)));
        case AUTH_PROVIDER:
            return authProviderAuthenticator(authProps);
        default:
            throw new IllegalArgumentException("Invalid/Unsupported auth type");
    }
}
 
Example #9
Source File: ServerApp.java    From java-11-examples with Apache License 2.0 5 votes vote down vote up
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 #10
Source File: NettySshTtyBootstrap.java    From termd with Apache License 2.0 5 votes vote down vote up
public NettySshTtyBootstrap() {
  this.host = "localhost";
  this.port = 5000;
  this.charset = UTF_8;
  this.parentGroup = new NioEventLoopGroup(1);
  this.childGroup = new NioEventLoopGroup();
  this.keyPairProvider = new SimpleGeneratorHostKeyProvider(new File("hostkey.ser").toPath());
  this.passwordAuthenticator = new PasswordAuthenticator() {
    @Override
    public boolean authenticate(String username, String password, ServerSession session) throws PasswordChangeRequiredException {
      return true;
    }
  };
}
 
Example #11
Source File: AsyncAuthTestBase.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test
public void testAsyncAuthSucceededAfterTimeout() throws Exception {
  startServer(500);
  authenticator = new PasswordAuthenticator() {
    @Override
    public boolean authenticate(String username, String password, ServerSession session) throws PasswordChangeRequiredException {
      final AsyncAuth auth = new AsyncAuth();
      new Thread() {
        @Override
        public void run() {
          try {
            Thread.sleep(1000);
          } catch (InterruptedException ignore) {
          } finally {
            auth.setAuthed(true);
          }
        }
      }.start();
      throw auth;
    }
  };
  try {
    authenticate();
  } catch (JSchException e) {
    assertTrue("Unexpected failure " + e.getMessage(), e.getMessage().startsWith("SSH_MSG_DISCONNECT"));
  }
}
 
Example #12
Source File: AsyncAuthTestBase.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test
public void testAsyncAuthTimeout() throws Exception {
  startServer(500);
  authenticator = new PasswordAuthenticator() {
    @Override
    public boolean authenticate(String username, String password, ServerSession session) throws PasswordChangeRequiredException {
      throw new AsyncAuth();
    }
  };
  try {
    authenticate();
  } catch (JSchException e) {
    assertTrue("Unexpected failure " + e.getMessage(), e.getMessage().startsWith("SSH_MSG_DISCONNECT"));
  }
}
 
Example #13
Source File: AsyncAuthTestBase.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test
public void testSyncAuthSucceeded() throws Exception {
  startServer();
  authenticator = new PasswordAuthenticator() {
    @Override
    public boolean authenticate(String username, String password, ServerSession session) throws PasswordChangeRequiredException {
      return true;
    }
  };
  assertTrue(authenticate());
}
 
Example #14
Source File: AsyncAuthTestBase.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test
public void testSyncAuthFailed() throws Exception {
  startServer();
  authenticator = new PasswordAuthenticator() {
    @Override
    public boolean authenticate(String username, String password, ServerSession session) throws PasswordChangeRequiredException {
      return false;
    }
  };
  assertFalse(authenticate());
}
 
Example #15
Source File: SshServerBuilder.java    From java-11-examples with Apache License 2.0 4 votes vote down vote up
public SshServerBuilder withPasswordAuthenticator(PasswordAuthenticator passwordAuthenticator) {
    sshd.setPasswordAuthenticator(passwordAuthenticator);
    return this;
}
 
Example #16
Source File: PasswordAuthenticatorBuilder.java    From java-11-examples with Apache License 2.0 4 votes vote down vote up
public PasswordAuthenticator build() {
    return new PasswordAuthenticatorImpl(credentials);
}
 
Example #17
Source File: NettySshTtyBootstrap.java    From aesh-readline with Apache License 2.0 4 votes vote down vote up
public NettySshTtyBootstrap setPasswordAuthenticator(PasswordAuthenticator passwordAuthenticator) {
    this.passwordAuthenticator = passwordAuthenticator;
    return this;
}
 
Example #18
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 #19
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()));
}