org.apache.sshd.common.session.Session Java Examples

The following examples show how to use org.apache.sshd.common.session.Session. 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: ServiceLogger.java    From sftpserver with Apache License 2.0 5 votes vote down vote up
@Override
public void sessionDisconnect(final Session session, final int reason, final String msg, final String language,
		final boolean initiator) {
	if (log.isInfoEnabled()) {
		log.info("session disconnect(" + toHuman(session) + ") reason: " + reason + " msg: " + msg);
	}
}
 
Example #2
Source File: ClientUserAuthServiceOld.java    From termd with Apache License 2.0 5 votes vote down vote up
public ClientUserAuthServiceOld(Session s) {
    if (!(s instanceof ClientSessionImpl)) {
        throw new IllegalStateException("Client side service used on server side");
    }
    session = (ClientSessionImpl) s;
    lock = session.getLock();
    // Maintain the current auth status in the authFuture.
    authFuture = new DefaultAuthFuture(lock);
}
 
Example #3
Source File: KeyReExchangeTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test
public void testReExchangeFromJschClient() throws Exception {
    Assume.assumeTrue("DH Group Exchange not supported", SecurityUtils.isDHGroupExchangeSupported());
    setUp(0L, 0L, 0L);

    JSch.setConfig("kex", BuiltinDHFactories.Constants.DIFFIE_HELLMAN_GROUP_EXCHANGE_SHA1);
    JSch sch = new JSch();
    com.jcraft.jsch.Session s = sch.getSession(getCurrentTestName(), TEST_LOCALHOST, port);
    try {
        s.setUserInfo(new SimpleUserInfo(getCurrentTestName()));
        s.connect();

        com.jcraft.jsch.Channel c = s.openChannel(Channel.CHANNEL_SHELL);
        c.connect();
        try (OutputStream os = c.getOutputStream();
             InputStream is = c.getInputStream()) {

            String expected = "this is my command\n";
            byte[] bytes = expected.getBytes(StandardCharsets.UTF_8);
            byte[] data = new byte[bytes.length + Long.SIZE];
            for (int i = 1; i <= 10; i++) {
                os.write(bytes);
                os.flush();

                int len = is.read(data);
                String str = new String(data, 0, len);
                assertEquals("Mismatched data at iteration " + i, expected, str);

                outputDebugMessage("Request re-key #%d", i);
                s.rekey();
            }
        } finally {
            c.disconnect();
        }
    } finally {
        s.disconnect();
    }
}
 
Example #4
Source File: AsyncEchoShellFactory.java    From termd with Apache License 2.0 5 votes vote down vote up
@Override
public int data(final ChannelSession channel, byte[] buf, int start, int len) throws IOException {
    buffer.append(new String(buf, start, len));
    for (int i = 0; i < buffer.length(); i++) {
        if (buffer.charAt(i) == '\n') {
            final String s = buffer.substring(0, i + 1);
            final byte[] bytes = s.getBytes(StandardCharsets.UTF_8);
            out.write(new ByteArrayBuffer(bytes)).addListener(new SshFutureListener<IoWriteFuture>() {
                @Override
                public void operationComplete(IoWriteFuture future) {
                    Session session = channel.getSession();
                    if (future.isWritten()) {
                        try {
                            Window wLocal = channel.getLocalWindow();
                            wLocal.consumeAndCheck(bytes.length);
                        } catch (IOException e) {
                            session.exceptionCaught(e);
                        }
                    } else {
                        Throwable t = future.getException();
                        session.exceptionCaught(t);
                    }
                }
            });
            buffer = new StringBuilder(buffer.substring(i + 1));
            i = 0;
        }
    }
    return 0;
}
 
Example #5
Source File: NettySshTtyTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Override
protected TtyCommand createConnection(Consumer<TtyConnection> onConnect) {
  return new TtyCommand(charset, onConnect) {
    @Override
    public void execute(Runnable task) {
      Session session = this.session.getSession();
      NettyIoSession ioSession = (NettyIoSession) session.getIoSession();
      ioSession.execute(task);
    }
  };
}
 
Example #6
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 #7
Source File: NettySshTtyTest.java    From aesh-readline with Apache License 2.0 5 votes vote down vote up
@Override
protected TtyCommand createConnection(Consumer<Connection> onConnect) {
  return new TtyCommand(charset, onConnect) {
    @Override
    public void execute(Runnable task) {
      Session session = this.session.getSession();
      NettyIoSession ioSession = (NettyIoSession) session.getIoSession();
      ioSession.execute(task);
    }
  };
}
 
Example #8
Source File: NettySshTtyTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Override
protected TtyCommand createConnection(Consumer<TtyConnection> onConnect) {
  return new TtyCommand(charset, onConnect) {
    @Override
    public void execute(Runnable task) {
      Session session = this.session.getSession();
      NettyIoSession ioSession = (NettyIoSession) session.getIoSession();
      ioSession.execute(task);
    }
  };
}
 
Example #9
Source File: AsyncEchoShellFactory.java    From termd with Apache License 2.0 5 votes vote down vote up
@Override
public int data(final ChannelSession channel, byte[] buf, int start, int len) throws IOException {
    buffer.append(new String(buf, start, len));
    for (int i = 0; i < buffer.length(); i++) {
        if (buffer.charAt(i) == '\n') {
            final String s = buffer.substring(0, i + 1);
            final byte[] bytes = s.getBytes(StandardCharsets.UTF_8);
            out.write(new ByteArrayBuffer(bytes)).addListener(new SshFutureListener<IoWriteFuture>() {
                @Override
                public void operationComplete(IoWriteFuture future) {
                    Session session = channel.getSession();
                    if (future.isWritten()) {
                        try {
                            Window wLocal = channel.getLocalWindow();
                            wLocal.consumeAndCheck(bytes.length);
                        } catch (IOException e) {
                            session.exceptionCaught(e);
                        }
                    } else {
                        Throwable t = future.getException();
                        session.exceptionCaught(t);
                    }
                }
            });
            buffer = new StringBuilder(buffer.substring(i + 1));
            i = 0;
        }
    }
    return 0;
}
 
Example #10
Source File: ClientUserAuthServiceOld.java    From termd with Apache License 2.0 5 votes vote down vote up
public ClientUserAuthServiceOld(Session s) {
    if (!(s instanceof ClientSessionImpl)) {
        throw new IllegalStateException("Client side service used on server side");
    }
    session = (ClientSessionImpl) s;
    lock = session.getLock();
    // Maintain the current auth status in the authFuture.
    authFuture = new DefaultAuthFuture(lock);
}
 
Example #11
Source File: KeyReExchangeTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test
public void testReExchangeFromJschClient() throws Exception {
    Assume.assumeTrue("DH Group Exchange not supported", SecurityUtils.isDHGroupExchangeSupported());
    setUp(0L, 0L, 0L);

    JSch.setConfig("kex", BuiltinDHFactories.Constants.DIFFIE_HELLMAN_GROUP_EXCHANGE_SHA1);
    JSch sch = new JSch();
    com.jcraft.jsch.Session s = sch.getSession(getCurrentTestName(), TEST_LOCALHOST, port);
    try {
        s.setUserInfo(new SimpleUserInfo(getCurrentTestName()));
        s.connect();

        com.jcraft.jsch.Channel c = s.openChannel(Channel.CHANNEL_SHELL);
        c.connect();
        try (OutputStream os = c.getOutputStream();
             InputStream is = c.getInputStream()) {

            String expected = "this is my command\n";
            byte[] bytes = expected.getBytes(StandardCharsets.UTF_8);
            byte[] data = new byte[bytes.length + Long.SIZE];
            for (int i = 1; i <= 10; i++) {
                os.write(bytes);
                os.flush();

                int len = is.read(data);
                String str = new String(data, 0, len);
                assertEquals("Mismatched data at iteration " + i, expected, str);

                outputDebugMessage("Request re-key #%d", i);
                s.rekey();
            }
        } finally {
            c.disconnect();
        }
    } finally {
        s.disconnect();
    }
}
 
Example #12
Source File: AsyncUserAuthService.java    From termd with Apache License 2.0 4 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");
  }

  serverSession = (ServerSession) s;
  maxAuthRequests = PropertyResolverUtils.getIntProperty(s, ServerAuthenticationManager.MAX_AUTH_REQUESTS, ServerAuthenticationManager.DEFAULT_MAX_AUTH_REQUESTS);

  List<NamedFactory<UserAuth>> factories = ValidateUtils.checkNotNullAndNotEmpty(
      serverSession.getUserAuthFactories(), "No user auth factories for %s", s);
  userAuthFactories = new ArrayList<>(factories);
  // Get authentication methods
  authMethods = new ArrayList<>();

  String mths = PropertyResolverUtils.getString(s, ServerFactoryManager.AUTH_METHODS);
  if (GenericUtils.isEmpty(mths)) {
    for (NamedFactory<UserAuth> uaf : factories) {
      authMethods.add(new ArrayList<>(Collections.singletonList(uaf.getName())));
    }
  } else {
    if (log.isDebugEnabled()) {
      log.debug("ServerUserAuthService({}) using configured methods={}", s, mths);
    }
    for (String mthl : mths.split("\\s")) {
      authMethods.add(new ArrayList<>(Arrays.asList(GenericUtils.split(mthl, ','))));
    }
  }
  // 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 (log.isDebugEnabled()) {
    log.debug("ServerUserAuthService({}) authorized authentication methods: {}",
        s, NamedResource.Utils.getNames(userAuthFactories));
  }
}
 
Example #13
Source File: ServiceLogger.java    From sftpserver with Apache License 2.0 4 votes vote down vote up
@Override
public void sessionClosed(final Session session) {
	if (log.isInfoEnabled()) {
		log.info("session closed(" + toHuman(session) + ")");
	}
}
 
Example #14
Source File: ServiceLogger.java    From sftpserver with Apache License 2.0 4 votes vote down vote up
@Override
public void sessionCreated(final Session session) {
	if (log.isInfoEnabled()) {
		log.info("session created(" + toHuman(session) + ")");
	}
}
 
Example #15
Source File: ServiceLogger.java    From sftpserver with Apache License 2.0 4 votes vote down vote up
private static final String toHuman(final Session session) {
	return toHuman(session, session.getUsername());
}
 
Example #16
Source File: ServiceLogger.java    From sftpserver with Apache License 2.0 4 votes vote down vote up
private static final String toHuman(final Session session, final String username) {
	final IoSession networkSession = session.getIoSession();
	final SocketAddress peerAddress = (networkSession == null) ? null : networkSession.getRemoteAddress();
	return (username == null ? "<unknown>" : username) + "@" + addrToHuman(peerAddress);
}
 
Example #17
Source File: ClientUserAuthServiceOld.java    From termd with Apache License 2.0 4 votes vote down vote up
@Override
public Service create(Session session) throws IOException {
    return new ClientUserAuthServiceOld(session);
}
 
Example #18
Source File: AsyncUserAuthServiceFactory.java    From termd with Apache License 2.0 4 votes vote down vote up
@Override
public Service create(Session session) throws IOException {
  return new AsyncUserAuthService(session);
}
 
Example #19
Source File: AsyncUserAuthService.java    From termd with Apache License 2.0 4 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");
  }

  serverSession = (ServerSession) s;
  maxAuthRequests = PropertyResolverUtils.getIntProperty(s, ServerAuthenticationManager.MAX_AUTH_REQUESTS, ServerAuthenticationManager.DEFAULT_MAX_AUTH_REQUESTS);

  List<NamedFactory<UserAuth>> factories = ValidateUtils.checkNotNullAndNotEmpty(
      serverSession.getUserAuthFactories(), "No user auth factories for %s", s);
  userAuthFactories = new ArrayList<NamedFactory<UserAuth>>(factories);
  // Get authentication methods
  authMethods = new ArrayList<List<String>>();

  String mths = PropertyResolverUtils.getString(s, ServerFactoryManager.AUTH_METHODS);
  if (GenericUtils.isEmpty(mths)) {
    for (NamedFactory<UserAuth> uaf : factories) {
      authMethods.add(new ArrayList<String>(Collections.singletonList(uaf.getName())));
    }
  } else {
    if (log.isDebugEnabled()) {
      log.debug("ServerUserAuthService({}) using configured methods={}", s, mths);
    }
    for (String mthl : mths.split("\\s")) {
      authMethods.add(new ArrayList<String>(Arrays.asList(GenericUtils.split(mthl, ','))));
    }
  }
  // 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 (log.isDebugEnabled()) {
    log.debug("ServerUserAuthService({}) authorized authentication methods: {}",
        s, NamedResource.Utils.getNames(userAuthFactories));
  }
}
 
Example #20
Source File: AsyncUserAuthServiceFactory.java    From aesh-readline with Apache License 2.0 4 votes vote down vote up
@Override
public Service create(Session session) throws IOException {
  return new AsyncUserAuthService(session);
}
 
Example #21
Source File: SshdNativeFileSystemFactory.java    From sshd-shell-spring-boot with Apache License 2.0 4 votes vote down vote up
@Override
public FileSystem createFileSystem(Session session) throws IOException {
    Path sessionUserDir = Paths.get(baseDir, session.getUsername());
    processForSessionUserDirectory(sessionUserDir);
    return new RootedFileSystem(new RootedFileSystemProvider(), sessionUserDir, null);
}
 
Example #22
Source File: ClientUserAuthServiceOld.java    From termd with Apache License 2.0 4 votes vote down vote up
@Override
public Service create(Session session) throws IOException {
    return new ClientUserAuthServiceOld(session);
}
 
Example #23
Source File: AsyncUserAuthServiceFactory.java    From termd with Apache License 2.0 4 votes vote down vote up
@Override
public Service create(Session session) throws IOException {
  return new AsyncUserAuthService(session);
}