org.apache.sshd.server.session.ServerSession Java Examples

The following examples show how to use org.apache.sshd.server.session.ServerSession. 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: SshShellSecurityAuthenticationProviderTest.java    From ssh-shell-spring-boot with Apache License 2.0 6 votes vote down vote up
@Test
void authenticate() {
    ServerSession session = Mockito.mock(ServerSession.class);
    IoSession io = Mockito.mock(IoSession.class);
    Mockito.when(session.getIoSession()).thenReturn(io);
    Mockito.when(ctx.getBeansOfType(any())).thenReturn(Collections.singletonMap("sec", sec));
    ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(Object.class);
    Mockito.when(io.setAttribute(eq(AUTHENTICATION_ATTRIBUTE), captor.capture())).thenReturn(null);
    SshShellSecurityAuthenticationProvider provider = new SshShellSecurityAuthenticationProvider(ctx, null);
    provider.init();

    Mockito.when(sec.authenticate(any())).thenReturn(
            new UsernamePasswordAuthenticationToken("principal", "credentials",
                    Collections.singletonList(new SimpleGrantedAuthority("USER"))));
    assertTrue(provider.authenticate("user", "pass", session));
    SshAuthentication auth = (SshAuthentication) captor.getValue();
    assertEquals("principal", auth.getPrincipal());
    assertEquals("credentials", auth.getCredentials());
    assertEquals(1, auth.getAuthorities().size());
    assertNull(auth.getDetails());

    // fail auth
    Mockito.when(sec.authenticate(any())).thenThrow(new BadCredentialsException("[MOCK]"));
    assertFalse(provider.authenticate("user", "pass", session));
}
 
Example #3
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 #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: 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 #6
Source File: FixedSftpSubsystem.java    From sftp-fs with Apache License 2.0 6 votes vote down vote up
@Override
public Command create() {
    SftpSubsystem subsystem = new FixedSftpSubsystem(getExecutorService(), isShutdownOnExit(), getUnsupportedAttributePolicy(),
            getFileSystemAccessor(), getErrorStatusDataHandler());
    Collection<? extends SftpEventListener> listeners = getRegisteredListeners();
    if (GenericUtils.size(listeners) > 0) {
        for (SftpEventListener l : listeners) {
            subsystem.addSftpEventListener(l);
        }
    }
    subsystem.addSftpEventListener(new AbstractSftpEventListenerAdapter() {
        @Override
        public void open(ServerSession session, String remoteHandle, Handle localHandle) {
            if (localHandle instanceof DirectoryHandle) {
                DirectoryHandle directoryHandle = (DirectoryHandle) localHandle;
                directoryHandle.markDotSent();
                directoryHandle.markDotDotSent();
            }
        }
    });

    return subsystem;
}
 
Example #7
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 #8
Source File: TestSshRequestInfoBuilder.java    From artifactory_ssh_proxy with Apache License 2.0 6 votes vote down vote up
@Test
public void testObjectEqual() throws ArtifactNotFoundException, IOException, ArtifactMetaDataParseFailureException,
                ParseException {
    IoSession ioSession = Mockito.mock(IoSession.class);
    Mockito.when(ioSession.getRemoteAddress()).thenReturn(new InetSocketAddress("10.0.0.1", 9999));
    ServerSession session = Mockito.mock(ServerSession.class);
    Mockito.when(session.getUsername()).thenReturn("screwdrv");
    Mockito.when(session.getIoSession()).thenReturn(ioSession);

    SshRequestInfo request1 =
                    new SshRequestInfo.Builder(session).setStartTimestamp(1411455384909L)
                                    .setMethod(SshRequestStatus.CREATED.getReasonPhrase())
                                    .setStatus(SshRequestStatus.CREATED.getStatusCode()).setExitValue(0)
                                    .setRepoName("maven-local-release").setPath("/com/yahoo/sshd/util/Utils.java")
                                    .setSize(1024000L).build();

    SshRequestInfo request2 =
                    new SshRequestInfo.Builder(session).setStartTimestamp(1411455384909L)
                                    .setMethod(SshRequestStatus.OK.getReasonPhrase())
                                    .setStatus(SshRequestStatus.OK.getStatusCode()).setExitValue(0)
                                    .setRepoName("maven-local-release").setPath("/com/yahoo/sshd/util/Utils.java")
                                    .setSize(1024000L).build();

    Assert.assertFalse(request1.equals(request2));
}
 
Example #9
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 #10
Source File: SshShellSecurityAuthenticationProvider.java    From ssh-shell-spring-boot with Apache License 2.0 6 votes vote down vote up
@Override
public boolean authenticate(String username, String pass,
                            ServerSession serverSession) throws PasswordChangeRequiredException {
    try {
        Authentication auth = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(username, pass));
        LOGGER.debug("User {} authenticated with authorities: {}", username, auth.getAuthorities());
        List<String> authorities =
                auth.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
        serverSession.getIoSession().setAttribute(AUTHENTICATION_ATTRIBUTE, new SshAuthentication(username,
                auth.getPrincipal(), auth.getDetails(), auth.getCredentials(), authorities));
        return auth.isAuthenticated();
    } catch (AuthenticationException e) {
        LOGGER.error("Unable to authenticate user [{}] : {}", username, e.getMessage());
        LOGGER.debug("Unable to authenticate user [{}]", username, e);
        return false;
    }
}
 
Example #11
Source File: ConfigPasswordAuthenticator.java    From Bukkit-SSHD with Apache License 2.0 6 votes vote down vote up
@Override
public boolean authenticate(String username, String password, ServerSession serverSession) {
    if (SshdPlugin.instance.getConfig().getString("credentials." + username).equals(password)) {
        failCounts.put(username, 0);
        return true;
    }
    SshdPlugin.instance.getLogger().info("Failed login for " + username + " using password authentication.");

    try {
        Thread.sleep(3000);
        if (failCounts.containsKey(username)) {
            failCounts.put(username, failCounts.get(username) + 1);
        } else {
            failCounts.put(username, 1);
        }
        if (failCounts.get(username) >= 3) {
            failCounts.put(username, 0);
            serverSession.close(true);
        }
    } catch (InterruptedException e) {
        // do nothing
    }
    return false;
}
 
Example #12
Source File: AntHarnessTest.java    From ExpectIt with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void startSshServer() throws IOException {
    sshServer = SshServer.setUpDefaultServer();
    ServerSocket serverSocket = new ServerSocket(0);
    sshPort = serverSocket.getLocalPort();
    serverSocket.close();
    sshServer.setPort(sshPort);
    sshServer.setPasswordAuthenticator(
            new PasswordAuthenticator() {
                @Override
                public boolean authenticate(
                        String username,
                        String password,
                        ServerSession session) {
                    return "ssh".equals(username) && "secret".equals(password);
                }
            });
    sshServer.setShellFactory(new SshEchoCommandFactory());
    sshServer.setKeyPairProvider(new SimpleGeneratorHostKeyProvider());
    sshServer.start();
}
 
Example #13
Source File: MultiUserAuthorizedKeysMap.java    From artifactory_ssh_proxy with Apache License 2.0 6 votes vote down vote up
public boolean authenticate(String username, PublicKey publicKey, ServerSession session) {
    // first we need to see if they have an entry.
    Map<PublicKey, AuthorizedKey> map = userToPkToAuthKeyMap.get(username);

    if (null == map) {
        LOGGER.error("Failed to authenticate unknown user {} from {}.", username, session.getIoSession()
                        .getRemoteAddress());
        return false;
    }

    AuthorizedKey ak = map.get(publicKey);
    if (null == ak) {
        LOGGER.error("Failed authentication of user {} from {} with unknown public key.", username, session
                        .getIoSession().getRemoteAddress());
        return false;
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Successful authentication of user {} from {} with public key {}.", new Object[] {username,
                        session.getIoSession().getRemoteAddress(), ak.getAlias()});
    }

    return true;
}
 
Example #14
Source File: TestSshRequestInfoBuilder.java    From artifactory_ssh_proxy with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuildSshRequestInfoObj() throws ArtifactNotFoundException, IOException,
                ArtifactMetaDataParseFailureException, ParseException {
    IoSession ioSession = Mockito.mock(IoSession.class);
    Mockito.when(ioSession.getRemoteAddress()).thenReturn(new InetSocketAddress("10.0.0.1", 9999));
    ServerSession session = Mockito.mock(ServerSession.class);
    Mockito.when(session.getUsername()).thenReturn("screwdrv");
    Mockito.when(session.getIoSession()).thenReturn(ioSession);

    SshRequestInfo request =
                    new SshRequestInfo.Builder(session).setStartTimestamp(1411455384909L)
                                    .setMethod(SshRequestStatus.CREATED.getReasonPhrase())
                                    .setStatus(SshRequestStatus.CREATED.getStatusCode()).setExitValue(0)
                                    .setRepoName("maven-local-release").setPath("/com/yahoo/sshd/util/Utils.java")
                                    .setSize(1024000L).build();

    Assert.assertEquals(request.getStartTimestamp(), 1411455384909L);
    Assert.assertEquals(request.getRemoteAddr(), "10.0.0.1");
    Assert.assertEquals(request.getRepoName(), "maven-local-release");
    Assert.assertEquals(request.getRequestPath(), "/com/yahoo/sshd/util/Utils.java");
    Assert.assertEquals(request.getStatus(), 201);
    Assert.assertEquals(request.getExitValue(), 0);
    Assert.assertEquals(request.getMethod(), "PUT");
    Assert.assertEquals(request.getUserName(), "screwdrv");
}
 
Example #15
Source File: PublicKeyAuthenticator.java    From Bukkit-SSHD with Apache License 2.0 5 votes vote down vote up
@Override
public boolean authenticate(String username, PublicKey key, ServerSession session) {
    byte[] keyBytes = key.getEncoded();
    File keyFile = new File(authorizedKeysDir, username);

    if (keyFile.exists()) {
        try {

            FileReader fr = new FileReader(keyFile);
            PemDecoder pd = new PemDecoder(fr);
            PublicKey k = pd.getPemBytes();
            pd.close();

            if (k != null) {
                if (ArrayUtils.isEquals(key.getEncoded(), k.getEncoded())) {
                    return true;
                }
            } else {
                SshdPlugin.instance.getLogger().severe("Failed to parse PEM file. " + keyFile.getAbsolutePath());
            }
        } catch (Exception e) {
            SshdPlugin.instance.getLogger()
                    .severe("Failed to process public key " + keyFile.getAbsolutePath() + ". " + e.getMessage());
        }
    } else {
        SshdPlugin.instance.getLogger().warning("Could not locate public key for " + username +
                                                ". Make sure the user's key is named the same as their user name " +
                                                "without a file extension.");
    }

    return false;
}
 
Example #16
Source File: SinglePublicKeyAuthTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test
public void testPublicKeyAuthWithCache() throws Exception {
    final ConcurrentHashMap<String, AtomicInteger> count = new ConcurrentHashMap<String, AtomicInteger>();
    TestCachingPublicKeyAuthenticator auth = new TestCachingPublicKeyAuthenticator(new PublickeyAuthenticator() {
        @SuppressWarnings("synthetic-access")
        @Override
        public boolean authenticate(String username, PublicKey key, ServerSession session) {
            String fp = KeyUtils.getFingerPrint(key);
            count.putIfAbsent(fp, new AtomicInteger());
            count.get(fp).incrementAndGet();
            return key.equals(pairRsa.getPublic());
        }
    });
    delegate = auth;

    try (SshClient client = setupTestClient()) {
        client.start();

        try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
            session.addPublicKeyIdentity(pairRsaBad);
            session.addPublicKeyIdentity(pairRsa);
            session.auth().verify(5L, TimeUnit.SECONDS);

            assertEquals("Mismatched authentication invocations count", 2, count.size());

            String fpBad = KeyUtils.getFingerPrint(pairRsaBad.getPublic());
            String fpGood = KeyUtils.getFingerPrint(pairRsa.getPublic());
            assertTrue("Missing bad public key", count.containsKey(fpBad));
            assertTrue("Missing good public key", count.containsKey(fpGood));
            assertEquals("Mismatched bad key authentication attempts", 1, count.get(fpBad).get());
            assertEquals("Mismatched good key authentication attempts", 1, count.get(fpGood).get());
        } finally {
            client.stop();
        }
    }

    Thread.sleep(100L);
    assertTrue("Cache not empty", auth.getCache().isEmpty());
}
 
Example #17
Source File: SimpleSshdPasswordAuthenticator.java    From sshd-shell-spring-boot with Apache License 2.0 5 votes vote down vote up
@Override
public boolean authenticate(String username, String password, ServerSession session) throws
        PasswordChangeRequiredException {
    if (username.equals(props.getUsername()) && password.equals(props.getPassword())) {
        session.getIoSession().setAttribute(Constants.USER_ROLES, systemCommandRoles);
        session.getIoSession().setAttribute(Constants.USER, username);
        return true;
    }
    return false;
}
 
Example #18
Source File: AdminServer.java    From gameserver with Apache License 2.0 5 votes vote down vote up
@Override
public void startServer(String bindAddr, int port) {
	try {
		sshd = SshServer.setUpDefaultServer();
		sshd.setHost(bindAddr);
		sshd.setPort(port);
		
		SimpleGeneratorHostKeyProvider provider = new SimpleGeneratorHostKeyProvider("hostkey.ser", "RSA", 4096);
		sshd.setKeyPairProvider(provider);
		
		EnumSet<ProcessShellFactory.TtyOptions> options = EnumSet.allOf(ProcessShellFactory.TtyOptions.class);
		options.remove(ProcessShellFactory.TtyOptions.Echo);
		sshd.setShellFactory(new ProcessShellFactory(new String[] { "/bin/bash", "-i" }, options));
		
		sshd.setCommandFactory(commandFactory);
		
    sshd.setPasswordAuthenticator(new PasswordAuthenticator() {
      public boolean authenticate(String username, String password, ServerSession session) {
          return username != null && password.equals("VpWk5ujKA1c");
      }
	  });
    
		sshd.start();
		
		logger.info("AdminServer bind at " + bindAddr + ":" + port);
		
	} catch (Exception e) {
		logger.warn("Failed to start AdminServer", e);
	}
}
 
Example #19
Source File: SshShellUtilsTest.java    From ssh-shell-spring-boot with Apache License 2.0 5 votes vote down vote up
public static ChannelSession mockChannelSession(Long id) {
    ChannelSession session = mock(ChannelSession.class);
    ServerSession serverSession = mock(ServerSession.class);
    when(session.getSession()).thenReturn(serverSession);
    IoSession ioSession = mock(IoSession.class);
    when(serverSession.getIoSession()).thenReturn(ioSession);
    when(ioSession.getId()).thenReturn(id);
    return session;
}
 
Example #20
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 #21
Source File: SinglePublicKeyAuthTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    sshd = setupTestServer();
    PropertyResolverUtils.updateProperty(sshd, ServerFactoryManager.AUTH_METHODS, UserAuthPublicKeyFactory.NAME);
    sshd.setPublickeyAuthenticator(new PublickeyAuthenticator() {
        @SuppressWarnings("synthetic-access")
        @Override
        public boolean authenticate(String username, PublicKey key, ServerSession session) {
            return delegate.authenticate(username, key, session);
        }
    });
    sshd.start();
    port = sshd.getPort();
}
 
Example #22
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 #23
Source File: ServiceLogger.java    From sftpserver with Apache License 2.0 5 votes vote down vote up
@Override
public void removing(final ServerSession session, final Path path, final boolean isDirectory) throws IOException {
	if (!logRequest)
		return;
	if (log.isInfoEnabled()) {
		log.info("request removing(" + toHuman(session) + ")[" + (isDirectory ? "dir" : "file") + "] " + path);
	}
}
 
Example #24
Source File: AsyncUserAuthService.java    From termd with Apache License 2.0 5 votes vote down vote up
protected void handleAuthenticationFailure(int cmd, Buffer buffer) throws Exception {
  String username = (currentAuth == null) ? null : currentAuth.getUsername();
  ServerSession session = getServerSession();
  if (log.isDebugEnabled()) {
    log.debug("handleAuthenticationFailure({}@{}) {}",
        username, session, SshConstants.getCommandMessageName(cmd));
  }

  StringBuilder sb = new StringBuilder((authMethods.size() + 1) * Byte.SIZE);
  for (List<String> l : authMethods) {
    if (GenericUtils.size(l) > 0) {
      String m = l.get(0);
      if (!UserAuthNoneFactory.NAME.equals(m)) {
        if (sb.length() > 0) {
          sb.append(",");
        }
        sb.append(m);
      }
    }
  }

  String remaining = sb.toString();
  if (log.isDebugEnabled()) {
    log.debug("handleAuthenticationFailure({}@{}) remaining methods: {}", username, session, remaining);
  }

  buffer = session.createBuffer(SshConstants.SSH_MSG_USERAUTH_FAILURE, remaining.length() + Byte.SIZE);
  buffer.putString(remaining);
  buffer.putBoolean(false);   // no partial success ...
  session.writePacket(buffer);

  if (currentAuth != null) {
    try {
      currentAuth.destroy();
    } finally {
      currentAuth = null;
    }
  }
}
 
Example #25
Source File: BogusPasswordAuthenticator.java    From termd with Apache License 2.0 5 votes vote down vote up
@Override
public boolean authenticate(String username, String password, ServerSession session) {
    boolean result = (username != null) && username.equals(password);
    if (log.isDebugEnabled()) {
        log.debug("authenticate({}) {} / {} - sucess = {}", session, username, password, Boolean.valueOf(result));
    }

    return result;
}
 
Example #26
Source File: Server.java    From sftpserver with Apache License 2.0 5 votes vote down vote up
public boolean checkUserPublicKey(final ServerSession session, final String user, final PublicKey key) {
	final String encodedKey = PublicKeyEntry.toString(key);
	final StringBuilder sb = new StringBuilder(40);
	boolean authOk = false;
	try {
		if (!isEnabledUser(user)) {
			sb.append("[user disabled]");
			return authOk;
		}
		for (int i = 1; i < 1024; i++) {
			final String value = getValue(user, PROP_KEY + i);
			if (value == null) {
				if (i == 1)
					sb.append("[no publickey]");
				break;
			} else {
				// Strip comment in keys
				// ssh-rsa AAAAB3NzaC1y...E7uQ== root@host
				final int s1 = value.indexOf(' ', 0);
				final int s2 = value.indexOf(' ', s1 + 1);
				final String ukey = (s2 > s1 ? value.substring(0, s2) : value);
				if (ukey.equals(encodedKey)) {
					if ((s1 > 0) && (s1 < s2)) {
						sb.append("[").append(value.substring(0, s1)).append("]");
					}
					authOk = true;
					break;
				}
			}
		}
	} finally {
		sb.append("[").append(authOk ? "OK" : "FAIL").append("]");
		if (authOk) {
			logger.authPublicKeyPostLogin(session, user, key, Level.INFO, sb.toString());
		} else {
			logger.authPublicKeyPostLogin(session, user, key, Level.ERROR, sb.toString());
		}
	}
	return authOk;
}
 
Example #27
Source File: Server.java    From sftpserver with Apache License 2.0 5 votes vote down vote up
@Override
public boolean authenticate(final String username, final String password, final ServerSession session) {
	logger.authPasswordPreLogin(session, username);
	if ((username != null) && (password != null)) {
		return db.checkUserPassword(session, username, password);
	}
	logger.authPasswordPostLogin(session, username, Level.ERROR, "[null data][FAIL]");
	return false;
}
 
Example #28
Source File: AuthProviderSshdPasswordAuthenticator.java    From sshd-shell-spring-boot with Apache License 2.0 5 votes vote down vote up
@Override
public boolean authenticate(String username, String password, ServerSession session) throws
        PasswordChangeRequiredException {
    try {
        Authentication auth = authProvider.authenticate(
                new UsernamePasswordAuthenticationToken(username, password));
        session.getIoSession().setAttribute(Constants.USER, username);
        session.getIoSession().setAttribute(Constants.USER_ROLES, auth.getAuthorities().stream()
                .map(ga -> ga.getAuthority()).collect(Collectors.toSet()));
        return true;
    } catch (AuthenticationException ex) {
        log.warn(ex.getMessage());
        return false;
    }
}
 
Example #29
Source File: ServiceLogger.java    From sftpserver with Apache License 2.0 5 votes vote down vote up
@Override
public void closing(final ServerSession session, final String remoteHandle, final Handle localHandle) {
	if (!logRequest)
		return;
	if (log.isInfoEnabled()) {
		final Path path = localHandle.getFile();
		log.info("request close(" + toHuman(session) + ")[" + remoteHandle + "][" //
				+ (Files.isDirectory(path) ? "dir" : "file") + "] " + path);
	}
}
 
Example #30
Source File: TestSshRequestLogListener.java    From artifactory_ssh_proxy with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("resource")
@Test
public void testRequestLogDoLog() {
    ServerSession session = Mockito.mock(ServerSession.class);
    SshRequestInfo requestInfo = Mockito.mock(SshRequestInfo.class);
    SshRequestLog requestLogger = Mockito.mock(SshRequestLog.class);

    SshRequestLogListener logListener = new SshRequestLogListener(requestLogger);
    logListener.handleRequest(requestInfo);
    logListener.sessionClosed(session);
    Mockito.verify(requestLogger).log(requestInfo);
}