org.apache.sshd.common.SshConstants Java Examples

The following examples show how to use org.apache.sshd.common.SshConstants. 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: 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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
Source File: AuthenticationTest.java    From termd with Apache License 2.0 4 votes vote down vote up
@Test   // see SSHD-624
public void testMismatchedUserAuthPkOkData() throws Exception {
    final AtomicInteger challengeCounter = new AtomicInteger(0);
    sshd.setUserAuthFactories(Collections.<NamedFactory<org.apache.sshd.server.auth.UserAuth>>singletonList(
            new org.apache.sshd.server.auth.pubkey.UserAuthPublicKeyFactory() {
                @Override
                public org.apache.sshd.server.auth.pubkey.UserAuthPublicKey create() {
                    return new org.apache.sshd.server.auth.pubkey.UserAuthPublicKey() {
                        @Override
                        protected void sendPublicKeyResponse(ServerSession session, String username, String alg, PublicKey key,
                                byte[] keyBlob, int offset, int blobLen, Buffer buffer) throws Exception {
                            int count = challengeCounter.incrementAndGet();
                            outputDebugMessage("sendPublicKeyChallenge(%s)[%s]: count=%d", session, alg, count);
                            if (count == 1) {
                                // send wrong key type
                                super.sendPublicKeyResponse(session, username, KeyPairProvider.SSH_DSS, key, keyBlob, offset, blobLen, buffer);
                            } else if (count == 2) {
                                // send another key
                                KeyPair otherPair = org.apache.sshd.util.test.Utils.generateKeyPair(KeyUtils.RSA_ALGORITHM, 1024);
                                PublicKey otherKey = otherPair.getPublic();
                                Buffer buf = session.createBuffer(SshConstants.SSH_MSG_USERAUTH_PK_OK, blobLen + alg.length() + Long.SIZE);
                                buf.putString(alg);
                                buf.putPublicKey(otherKey);
                                session.writePacket(buf);
                            } else {
                                super.sendPublicKeyResponse(session, username, alg, key, keyBlob, offset, blobLen, buffer);
                            }
                        }
                    };
                }

    }));

    try (SshClient client = setupTestClient()) {
        KeyPair clientIdentity = Utils.generateKeyPair(KeyUtils.RSA_ALGORITHM, 1024);
        client.start();

        try {
            for (int index = 1; index <= 4; index++) {
                try (ClientSession s = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
                    s.addPublicKeyIdentity(clientIdentity);
                    s.auth().verify(17L, TimeUnit.SECONDS);
                    assertEquals("Mismatched number of challenges", 3, challengeCounter.get());
                    break;
                } catch (SshException e) {   // expected
                    outputDebugMessage("%s on retry #%d: %s", e.getClass().getSimpleName(), index, e.getMessage());

                    Throwable t = e.getCause();
                    assertObjectInstanceOf("Unexpected failure cause at retry #" + index, InvalidKeySpecException.class, t);
                }
            }
        } finally {
            client.stop();
        }
    }
}
 
Example #13
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 #14
Source File: AuthenticationTest.java    From termd with Apache License 2.0 4 votes vote down vote up
@Test   // see SSHD-624
public void testMismatchedUserAuthPkOkData() throws Exception {
    final AtomicInteger challengeCounter = new AtomicInteger(0);
    sshd.setUserAuthFactories(Collections.<NamedFactory<org.apache.sshd.server.auth.UserAuth>>singletonList(
            new org.apache.sshd.server.auth.pubkey.UserAuthPublicKeyFactory() {
                @Override
                public org.apache.sshd.server.auth.pubkey.UserAuthPublicKey create() {
                    return new org.apache.sshd.server.auth.pubkey.UserAuthPublicKey() {
                        @Override
                        protected void sendPublicKeyResponse(ServerSession session, String username, String alg, PublicKey key,
                                byte[] keyBlob, int offset, int blobLen, Buffer buffer) throws Exception {
                            int count = challengeCounter.incrementAndGet();
                            outputDebugMessage("sendPublicKeyChallenge(%s)[%s]: count=%d", session, alg, count);
                            if (count == 1) {
                                // send wrong key type
                                super.sendPublicKeyResponse(session, username, KeyPairProvider.SSH_DSS, key, keyBlob, offset, blobLen, buffer);
                            } else if (count == 2) {
                                // send another key
                                KeyPair otherPair = org.apache.sshd.util.test.Utils.generateKeyPair(KeyUtils.RSA_ALGORITHM, 1024);
                                PublicKey otherKey = otherPair.getPublic();
                                Buffer buf = session.createBuffer(SshConstants.SSH_MSG_USERAUTH_PK_OK, blobLen + alg.length() + Long.SIZE);
                                buf.putString(alg);
                                buf.putPublicKey(otherKey);
                                session.writePacket(buf);
                            } else {
                                super.sendPublicKeyResponse(session, username, alg, key, keyBlob, offset, blobLen, buffer);
                            }
                        }
                    };
                }

    }));

    try (SshClient client = setupTestClient()) {
        KeyPair clientIdentity = Utils.generateKeyPair(KeyUtils.RSA_ALGORITHM, 1024);
        client.start();

        try {
            for (int index = 1; index <= 4; index++) {
                try (ClientSession s = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
                    s.addPublicKeyIdentity(clientIdentity);
                    s.auth().verify(17L, TimeUnit.SECONDS);
                    assertEquals("Mismatched number of challenges", 3, challengeCounter.get());
                    break;
                } catch (SshException e) {   // expected
                    outputDebugMessage("%s on retry #%d: %s", e.getClass().getSimpleName(), index, e.getMessage());

                    Throwable t = e.getCause();
                    assertObjectInstanceOf("Unexpected failure cause at retry #" + index, InvalidKeySpecException.class, t);
                }
            }
        } finally {
            client.stop();
        }
    }
}