org.apache.sshd.common.util.buffer.Buffer Java Examples

The following examples show how to use org.apache.sshd.common.util.buffer.Buffer. 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: ClientUserAuthServiceOld.java    From termd with Apache License 2.0 6 votes vote down vote up
@Override
public void process(int cmd, Buffer buffer) throws Exception {
    if (this.authFuture.isSuccess()) {
        throw new IllegalStateException("UserAuth message delivered to authenticated client");
    } else if (this.authFuture.isDone()) {
        log.debug("Ignoring random message");
        // ignore for now; TODO: random packets
    } else if (cmd == SshConstants.SSH_MSG_USERAUTH_BANNER) {
        String welcome = buffer.getString();
        String lang = buffer.getString();
        log.debug("Welcome banner[{}]: {}", lang, welcome);
        UserInteraction ui = session.getUserInteraction();
        if ((ui != null) && ui.isInteractionAllowed(session)) {
            ui.welcome(session, welcome, lang);
        }
    } else {
        buffer.rpos(buffer.rpos() - 1);
        processUserAuth(buffer);
    }
}
 
Example #2
Source File: AsyncUserAuthService.java    From aesh-readline with Apache License 2.0 6 votes vote down vote up
private boolean asyncAuth(Buffer buffer, Exception e) {
    if (e instanceof AsyncAuth) {
        async = (AsyncAuth) e;
        async.setListener(authenticated -> {
            async = null;
            try {
                sendAuthenticationResult(buffer, authenticated);
            } catch (Exception e1) {
                // HANDLE THIS BETTER
                e1.printStackTrace();
            }
        });
        return true;
    }
    else {
        return false;
    }
}
 
Example #3
Source File: NettyIoSession.java    From aesh-readline with Apache License 2.0 6 votes vote down vote up
@Override
public IoWriteFuture write(Buffer buffer) {
    ByteBuf buf = Unpooled.buffer(buffer.available());
    buf.writeBytes(buffer.array(), buffer.rpos(), buffer.available());
    NettyIoWriteFuture msg = new NettyIoWriteFuture();
    ChannelPromise next = context.newPromise();
    prev.addListener(whatever -> {
        if (context != null) {
            context.writeAndFlush(buf, next);
        }
    });
    prev = next;
    next.addListener(fut -> {
        if (fut.isSuccess()) {
            msg.setValue(Boolean.TRUE);
        } else {
            msg.setValue(fut.cause());
        }
    });
    return msg;
}
 
Example #4
Source File: AsyncUserAuthService.java    From termd with Apache License 2.0 6 votes vote down vote up
private boolean asyncAuth(int cmd, Buffer buffer, Exception e) {
  if (e instanceof AsyncAuth) {
    async = (AsyncAuth) e;
    async.setListener(authenticated -> {
      async = null;
      try {
        if (authenticated) {
          handleAuthenticationSuccess(cmd, buffer);
        } else {
          handleAuthenticationFailure(cmd, buffer);
        }
      } catch (Exception e1) {
        // HANDLE THIS BETTER
        e1.printStackTrace();
      }
    });
    return true;
  } else {
    return false;
  }
}
 
Example #5
Source File: NettyIoSession.java    From termd with Apache License 2.0 6 votes vote down vote up
@Override
public IoWriteFuture write(Buffer buffer) {
  ByteBuf buf = Unpooled.buffer(buffer.available());
  buf.writeBytes(buffer.array(), buffer.rpos(), buffer.available());
  NettyIoWriteFuture msg = new NettyIoWriteFuture();
  ChannelPromise next = context.newPromise();
  prev.addListener(whatever -> {
    if (context != null) {
      context.writeAndFlush(buf, next);
    }
  });
  prev = next;
  next.addListener(fut -> {
    if (fut.isSuccess()) {
      msg.setValue(Boolean.TRUE);
    } else {
      msg.setValue(fut.cause());
    }
  });
  return msg;
}
 
Example #6
Source File: WindowAdjustTest.java    From termd with Apache License 2.0 6 votes vote down vote up
private void writeWithPendingDetection(final Buffer msg, final boolean wasPending) {
    try {
        asyncIn.write(msg).addListener(new SshFutureListener<IoWriteFuture>() {
            @SuppressWarnings("synthetic-access")
            @Override
            public void operationComplete(IoWriteFuture future) {
                if (future.isWritten()) {
                    if (wasPending) {
                        pending.remove();
                    }
                    writePendingIfAny();
                } else {
                    Throwable t = future.getException();
                    log.warn("Failed to write message", t);
                }
            }
        });
    } catch (final WritePendingException e) {
        if (!wasPending) {
            queueRequest(msg);
        }
    }
}
 
Example #7
Source File: ClientUserAuthServiceOld.java    From termd with Apache License 2.0 6 votes vote down vote up
/**
 * execute one step in user authentication.
 *
 * @param buffer
 * @throws java.io.IOException
 */
private void processUserAuth(Buffer buffer) throws IOException {
    log.debug("processing {}", userAuth);
    Result result = userAuth.next(buffer);
    switch (result) {
        case Success:
            log.debug("succeeded with {}", userAuth);
            session.setAuthenticated();
            session.switchToNextService();
            // Will wake up anyone sitting in waitFor
            authFuture.setAuthed(true);
            break;
        case Failure:
            log.debug("failed with {}", userAuth);
            this.userAuth = null;
            // Will wake up anyone sitting in waitFor
            this.authFuture.setAuthed(false);
            break;
        case Continued:
            // Will wake up anyone sitting in waitFor
            log.debug("continuing with {}", userAuth);
            break;
        default:
            log.debug("ignored result={} for {}", result, userAuth);
    }
}
 
Example #8
Source File: ClientUserAuthServiceOld.java    From termd with Apache License 2.0 6 votes vote down vote up
/**
 * execute one step in user authentication.
 *
 * @param buffer
 * @throws java.io.IOException
 */
private void processUserAuth(Buffer buffer) throws IOException {
    log.debug("processing {}", userAuth);
    Result result = userAuth.next(buffer);
    switch (result) {
        case Success:
            log.debug("succeeded with {}", userAuth);
            session.setAuthenticated();
            session.switchToNextService();
            // Will wake up anyone sitting in waitFor
            authFuture.setAuthed(true);
            break;
        case Failure:
            log.debug("failed with {}", userAuth);
            this.userAuth = null;
            // Will wake up anyone sitting in waitFor
            this.authFuture.setAuthed(false);
            break;
        case Continued:
            // Will wake up anyone sitting in waitFor
            log.debug("continuing with {}", userAuth);
            break;
        default:
            log.debug("ignored result={} for {}", result, userAuth);
    }
}
 
Example #9
Source File: ClientUserAuthServiceOld.java    From termd with Apache License 2.0 6 votes vote down vote up
@Override
public void process(int cmd, Buffer buffer) throws Exception {
    if (this.authFuture.isSuccess()) {
        throw new IllegalStateException("UserAuth message delivered to authenticated client");
    } else if (this.authFuture.isDone()) {
        log.debug("Ignoring random message");
        // ignore for now; TODO: random packets
    } else if (cmd == SshConstants.SSH_MSG_USERAUTH_BANNER) {
        String welcome = buffer.getString();
        String lang = buffer.getString();
        log.debug("Welcome banner[{}]: {}", lang, welcome);
        UserInteraction ui = session.getUserInteraction();
        if ((ui != null) && ui.isInteractionAllowed(session)) {
            ui.welcome(session, welcome, lang);
        }
    } else {
        buffer.rpos(buffer.rpos() - 1);
        processUserAuth(buffer);
    }
}
 
Example #10
Source File: WindowAdjustTest.java    From termd with Apache License 2.0 6 votes vote down vote up
private void writeWithPendingDetection(final Buffer msg, final boolean wasPending) {
    try {
        asyncIn.write(msg).addListener(new SshFutureListener<IoWriteFuture>() {
            @SuppressWarnings("synthetic-access")
            @Override
            public void operationComplete(IoWriteFuture future) {
                if (future.isWritten()) {
                    if (wasPending) {
                        pending.remove();
                    }
                    writePendingIfAny();
                } else {
                    Throwable t = future.getException();
                    log.warn("Failed to write message", t);
                }
            }
        });
    } catch (final WritePendingException e) {
        if (!wasPending) {
            queueRequest(msg);
        }
    }
}
 
Example #11
Source File: AsyncUserAuthService.java    From termd with Apache License 2.0 6 votes vote down vote up
private boolean asyncAuth(final int cmd, final Buffer buffer, Exception e) {
  if (e instanceof AsyncAuth) {
    async = (AsyncAuth) e;
    async.setListener(new Consumer<Boolean>() {
      @Override
      public void accept(Boolean authenticated) {
        async = null;
        try {
          if (authenticated) {
            handleAuthenticationSuccess(cmd, buffer);
          } else {
            handleAuthenticationFailure(cmd, buffer);
          }
        } catch (Exception e1) {
          // HANDLE THIS BETTER
          e1.printStackTrace();
        }
      }
    });

    return true;
  } else {
    return false;
  }
}
 
Example #12
Source File: UserAuthPassword.java    From termd with Apache License 2.0 5 votes vote down vote up
@Override
public Result next(Buffer buffer) throws IOException {
    ClientSession session = getClientSession();
    String service = getService();
    if (buffer == null) {
        log.debug("Send SSH_MSG_USERAUTH_REQUEST for password");
        buffer = session.createBuffer(SshConstants.SSH_MSG_USERAUTH_REQUEST);
        buffer.putString(session.getUsername());
        buffer.putString(service);
        buffer.putString(UserAuthMethodFactory.PASSWORD);
        buffer.putBoolean(false);
        buffer.putString(password);
        session.writePacket(buffer);
        return Result.Continued;
    } else {
        int cmd = buffer.getUByte();
        if (cmd == SshConstants.SSH_MSG_USERAUTH_SUCCESS) {
            log.debug("Received SSH_MSG_USERAUTH_SUCCESS");
            return Result.Success;
        }
        if (cmd == SshConstants.SSH_MSG_USERAUTH_FAILURE) {
            String methods = buffer.getString();
            boolean partial = buffer.getBoolean();
            if (log.isDebugEnabled()) {
                log.debug("Received SSH_MSG_USERAUTH_FAILURE - partial={}, methods={}", partial, methods);
            }
            return Result.Failure;
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Received unkown packet {}", Integer.valueOf(cmd & 0xFF));
            }
            // TODO: check packets
            return Result.Continued;
        }
    }
}
 
Example #13
Source File: AsyncUserAuthService.java    From termd with Apache License 2.0 5 votes vote down vote up
protected void handleAuthenticationInProgress(int cmd, Buffer buffer) throws Exception {
  String username = (currentAuth == null) ? null : currentAuth.getUsername();
  if (log.isDebugEnabled()) {
    log.debug("handleAuthenticationInProgress({}@{}) {}",
        username, getServerSession(), SshConstants.getCommandMessageName(cmd));
  }
}
 
Example #14
Source File: UserAuthAgent.java    From termd with Apache License 2.0 5 votes vote down vote up
@Override
public Result next(Buffer buffer) throws IOException {
    if (buffer == null) {
        if (keys.hasNext()) {
            sendNextKey(keys.next().getFirst());
            return Result.Continued;
        } else {
            agent.close();
            return Result.Failure;
        }
    } else {
        int cmd = buffer.getUByte();
        if (cmd == SshConstants.SSH_MSG_USERAUTH_SUCCESS) {
            log.info("Received SSH_MSG_USERAUTH_SUCCESS");
            agent.close();
            return Result.Success;
        }
        if (cmd == SshConstants.SSH_MSG_USERAUTH_FAILURE) {
            String methods = buffer.getString();
            boolean partial = buffer.getBoolean();
            if (log.isDebugEnabled()) {
                log.debug("Received SSH_MSG_USERAUTH_FAILURE - partial={}, methods={}", partial, methods);
            }
            if (keys.hasNext()) {
                sendNextKey(keys.next().getFirst());
                return Result.Continued;
            } else {
                agent.close();
                return Result.Failure;
            }
        } else {
            // TODO: check packets
            log.info("Received unknown packet: {}", Integer.valueOf(cmd));
            return Result.Continued;
        }
    }
}
 
Example #15
Source File: WindowAdjustTest.java    From termd with Apache License 2.0 5 votes vote down vote up
public synchronized void write(final Object msg) {
    if ((asyncIn != null) && (!asyncIn.isClosed()) && (!asyncIn.isClosing())) {
        final Buffer byteBufferMsg = (Buffer) msg;
        if (!pending.isEmpty()) {
            queueRequest(byteBufferMsg);
            return;
        }

        writeWithPendingDetection(byteBufferMsg, false);
    }
}
 
Example #16
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 #17
Source File: AsyncUserAuthService.java    From termd with Apache License 2.0 5 votes vote down vote up
protected void handleAuthenticationInProgress(int cmd, Buffer buffer) throws Exception {
  String username = (currentAuth == null) ? null : currentAuth.getUsername();
  if (log.isDebugEnabled()) {
    log.debug("handleAuthenticationInProgress({}@{}) {}",
        username, getServerSession(), SshConstants.getCommandMessageName(cmd));
  }
}
 
Example #18
Source File: WindowAdjustTest.java    From termd with Apache License 2.0 5 votes vote down vote up
private synchronized void writePendingIfAny() {
    if (pending.peek() == null) {
        return;
    }

    final Buffer msg = pending.peek();
    writeWithPendingDetection(msg, true);
}
 
Example #19
Source File: WindowAdjustTest.java    From termd with Apache License 2.0 5 votes vote down vote up
private synchronized void writePendingIfAny() {
    if (pending.peek() == null) {
        return;
    }

    final Buffer msg = pending.peek();
    writeWithPendingDetection(msg, true);
}
 
Example #20
Source File: WindowAdjustTest.java    From termd with Apache License 2.0 5 votes vote down vote up
public synchronized void write(final Object msg) {
    if ((asyncIn != null) && (!asyncIn.isClosed()) && (!asyncIn.isClosing())) {
        final Buffer byteBufferMsg = (Buffer) msg;
        if (!pending.isEmpty()) {
            queueRequest(byteBufferMsg);
            return;
        }

        writeWithPendingDetection(byteBufferMsg, false);
    }
}
 
Example #21
Source File: UserAuthPassword.java    From termd with Apache License 2.0 5 votes vote down vote up
@Override
public Result next(Buffer buffer) throws IOException {
    ClientSession session = getClientSession();
    String service = getService();
    if (buffer == null) {
        log.debug("Send SSH_MSG_USERAUTH_REQUEST for password");
        buffer = session.createBuffer(SshConstants.SSH_MSG_USERAUTH_REQUEST);
        buffer.putString(session.getUsername());
        buffer.putString(service);
        buffer.putString(UserAuthMethodFactory.PASSWORD);
        buffer.putBoolean(false);
        buffer.putString(password);
        session.writePacket(buffer);
        return Result.Continued;
    } else {
        int cmd = buffer.getUByte();
        if (cmd == SshConstants.SSH_MSG_USERAUTH_SUCCESS) {
            log.debug("Received SSH_MSG_USERAUTH_SUCCESS");
            return Result.Success;
        }
        if (cmd == SshConstants.SSH_MSG_USERAUTH_FAILURE) {
            String methods = buffer.getString();
            boolean partial = buffer.getBoolean();
            if (log.isDebugEnabled()) {
                log.debug("Received SSH_MSG_USERAUTH_FAILURE - partial={}, methods={}", partial, methods);
            }
            return Result.Failure;
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Received unkown packet {}", Integer.valueOf(cmd & 0xFF));
            }
            // TODO: check packets
            return Result.Continued;
        }
    }
}
 
Example #22
Source File: UserAuthAgent.java    From termd with Apache License 2.0 5 votes vote down vote up
@Override
public Result next(Buffer buffer) throws IOException {
    if (buffer == null) {
        if (keys.hasNext()) {
            sendNextKey(keys.next().getFirst());
            return Result.Continued;
        } else {
            agent.close();
            return Result.Failure;
        }
    } else {
        int cmd = buffer.getUByte();
        if (cmd == SshConstants.SSH_MSG_USERAUTH_SUCCESS) {
            log.info("Received SSH_MSG_USERAUTH_SUCCESS");
            agent.close();
            return Result.Success;
        }
        if (cmd == SshConstants.SSH_MSG_USERAUTH_FAILURE) {
            String methods = buffer.getString();
            boolean partial = buffer.getBoolean();
            if (log.isDebugEnabled()) {
                log.debug("Received SSH_MSG_USERAUTH_FAILURE - partial={}, methods={}", partial, methods);
            }
            if (keys.hasNext()) {
                sendNextKey(keys.next().getFirst());
                return Result.Continued;
            } else {
                agent.close();
                return Result.Failure;
            }
        } else {
            // TODO: check packets
            log.info("Received unknown packet: {}", Integer.valueOf(cmd));
            return Result.Continued;
        }
    }
}
 
Example #23
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 #24
Source File: UserAuthKeyboardInteractive.java    From termd with Apache License 2.0 4 votes vote down vote up
@Override
public Result next(Buffer buffer) throws IOException {
    ClientSession session = getClientSession();
    String service = getService();
    if (buffer == null) {
        log.debug("Send SSH_MSG_USERAUTH_REQUEST for password");
        buffer = session.createBuffer(SshConstants.SSH_MSG_USERAUTH_REQUEST);
        buffer.putString(session.getUsername());
        buffer.putString(service);
        buffer.putString("keyboard-interactive");
        buffer.putString("");
        buffer.putString("");
        session.writePacket(buffer);
        return Result.Continued;
    } else {
        int cmd = buffer.getUByte();
        switch (cmd) {
            case SshConstants.SSH_MSG_USERAUTH_INFO_REQUEST: {
                String name = buffer.getString();
                String instruction = buffer.getString();
                String language_tag = buffer.getString();
                if (log.isDebugEnabled()) {
                    log.debug("next({}) Received SSH_MSG_USERAUTH_INFO_REQUEST - name={}, instruction={}, lang={}",
                             session, name, instruction, language_tag);
                }
                int num = buffer.getInt();
                String[] prompt = new String[num];
                boolean[] echo = new boolean[num];
                for (int i = 0; i < num; i++) {
                    prompt[i] = buffer.getString();
                    echo[i] = buffer.getBoolean();
                }
                log.debug("Promt: {}", Arrays.toString(prompt));
                log.debug("Echo: {}", echo);

                String[] rep = null;
                if (num == 0) {
                    rep = new String[0];
                } else if (num == 1 && password != null && !echo[0] && prompt[0].toLowerCase().startsWith("password:")) {
                    rep = new String[]{password};
                } else {
                    UserInteraction ui = session.getUserInteraction();
                    if ((ui != null) && ui.isInteractionAllowed(session)) {
                        rep = ui.interactive(session, name, instruction, language_tag, prompt, echo);
                    }
                }
                if (rep == null) {
                    return Result.Failure;
                }

                buffer = session.createBuffer(SshConstants.SSH_MSG_USERAUTH_INFO_RESPONSE);
                buffer.putInt(rep.length);
                for (String r : rep) {
                    buffer.putString(r);
                }
                session.writePacket(buffer);
                return Result.Continued;
            }
            case SshConstants.SSH_MSG_USERAUTH_SUCCESS:
                log.debug("Received SSH_MSG_USERAUTH_SUCCESS");
                return Result.Success;
            case SshConstants.SSH_MSG_USERAUTH_FAILURE:
                {
                    String methods = buffer.getString();
                    boolean partial = buffer.getBoolean();
                    if (log.isDebugEnabled()) {
                        log.debug("Received SSH_MSG_USERAUTH_FAILURE - partial={}, methods={}", partial, methods);
                    }
                    return Result.Failure;
                }
            default:
                log.debug("Received unknown packet {}", Integer.valueOf(cmd));
                return Result.Continued;
        }
    }
}
 
Example #25
Source File: MockClientSession.java    From xenon with Apache License 2.0 4 votes vote down vote up
@Override
public void startService(String name, Buffer buffer) throws Exception {
    // TODO Auto-generated method stub

}
 
Example #26
Source File: MockClientSession.java    From xenon with Apache License 2.0 4 votes vote down vote up
@Override
public IoWriteFuture writePacket(Buffer buffer, long timeout, TimeUnit unit) throws IOException {
    throw new RuntimeException("Not implemented");
}
 
Example #27
Source File: MockClientSession.java    From xenon with Apache License 2.0 4 votes vote down vote up
@Override
public IoWriteFuture writePacket(Buffer buffer) throws IOException {
    throw new RuntimeException("Not implemented");
}
 
Example #28
Source File: MockClientSession.java    From xenon with Apache License 2.0 4 votes vote down vote up
@Override
public Buffer prepareBuffer(byte cmd, Buffer buffer) {
    throw new RuntimeException("Not implemented");
}
 
Example #29
Source File: MockClientSession.java    From xenon with Apache License 2.0 4 votes vote down vote up
@Override
public Buffer createBuffer(byte cmd, int estimatedSize) {
    throw new RuntimeException("Not implemented");
}
 
Example #30
Source File: MockClientSession.java    From xenon with Apache License 2.0 4 votes vote down vote up
@Override
public Buffer createBuffer(byte cmd) {
    throw new RuntimeException("Not implemented");
}