Search in sources :

Example 1 with DIGESTMD5BindRequest

use of com.unboundid.ldap.sdk.DIGESTMD5BindRequest in project ldapsdk by pingidentity.

the class SASLUtils method createDIGESTMD5BindRequest.

/**
 * Creates a SASL DIGEST-MD5 bind request using the provided password and set
 * of options.
 *
 * @param  password           The password to use for the bind request.
 * @param  promptForPassword  Indicates whether to interactively prompt for
 *                            the password if one is needed but none was
 *                            provided.
 * @param  tool               The command-line tool whose input and output
 *                            streams should be used when prompting for the
 *                            bind password.  It may be {@code null} only if
 *                            {@code promptForPassword} is {@code false}.
 * @param  options            The set of SASL options for the bind request.
 * @param  controls           The set of controls to include in the request.
 *
 * @return  The SASL DIGEST-MD5 bind request that was created.
 *
 * @throws  LDAPException  If a problem is encountered while trying to create
 *                         the SASL bind request.
 */
@NotNull()
private static DIGESTMD5BindRequest createDIGESTMD5BindRequest(@Nullable() final byte[] password, final boolean promptForPassword, @Nullable final CommandLineTool tool, @NotNull final Map<String, String> options, @Nullable final Control[] controls) throws LDAPException {
    final byte[] pw;
    if (password == null) {
        if (promptForPassword) {
            tool.getOriginalOut().print(INFO_LDAP_TOOL_ENTER_BIND_PASSWORD.get());
            pw = PasswordReader.readPassword();
            tool.getOriginalOut().println();
        } else {
            throw new LDAPException(ResultCode.PARAM_ERROR, ERR_SASL_OPTION_MECH_REQUIRES_PASSWORD.get(DIGESTMD5BindRequest.DIGESTMD5_MECHANISM_NAME));
        }
    } else {
        pw = password;
    }
    // The authID option is required.
    final String authID = options.remove(StaticUtils.toLowerCase(SASL_OPTION_AUTH_ID));
    if (authID == null) {
        throw new LDAPException(ResultCode.PARAM_ERROR, ERR_SASL_MISSING_REQUIRED_OPTION.get(SASL_OPTION_AUTH_ID, DIGESTMD5BindRequest.DIGESTMD5_MECHANISM_NAME));
    }
    final DIGESTMD5BindRequestProperties properties = new DIGESTMD5BindRequestProperties(authID, pw);
    // The authzID option is optional.
    properties.setAuthorizationID(options.remove(StaticUtils.toLowerCase(SASL_OPTION_AUTHZ_ID)));
    // The realm option is optional.
    properties.setRealm(options.remove(StaticUtils.toLowerCase(SASL_OPTION_REALM)));
    // The QoP option is optional, and may contain multiple values that need to
    // be parsed.
    final String qopString = options.remove(StaticUtils.toLowerCase(SASL_OPTION_QOP));
    if (qopString != null) {
        properties.setAllowedQoP(SASLQualityOfProtection.decodeQoPList(qopString));
    }
    // Ensure no unsupported options were provided.
    ensureNoUnsupportedOptions(options, DIGESTMD5BindRequest.DIGESTMD5_MECHANISM_NAME);
    return new DIGESTMD5BindRequest(properties, controls);
}
Also used : DIGESTMD5BindRequestProperties(com.unboundid.ldap.sdk.DIGESTMD5BindRequestProperties) LDAPException(com.unboundid.ldap.sdk.LDAPException) DIGESTMD5BindRequest(com.unboundid.ldap.sdk.DIGESTMD5BindRequest)

Example 2 with DIGESTMD5BindRequest

use of com.unboundid.ldap.sdk.DIGESTMD5BindRequest in project ldapsdk by pingidentity.

the class CommandLineToolInteractiveModeProcessor method promptForLDAPArguments.

/**
 * Interactively prompts for the arguments used to connect and optionally
 * authenticate to the directory server.
 *
 * @param  argList  The list to which the string representations of all LDAP
 *                  arguments should be added.
 * @param  test     Indicates whether to attempt to use the arguments to
 *                  establish an LDAP connection.
 *
 * @throws  LDAPException  If a problem is encountered while interacting with
 *                         the user, or if the user wants to quit.
 */
private void promptForLDAPArguments(@NotNull final List<String> argList, final boolean test) throws LDAPException {
    final LDAPCommandLineTool ldapTool = (LDAPCommandLineTool) tool;
    argList.clear();
    // Get the address of the directory server.
    final String defaultHostname;
    final StringArgument hostnameArgument = parser.getStringArgument("hostname");
    if (hostnameArgument.isPresent()) {
        defaultHostname = hostnameArgument.getValue();
    } else {
        defaultHostname = "localhost";
    }
    ArgumentHelper.reset(hostnameArgument);
    final String hostname = promptForString(INFO_INTERACTIVE_LDAP_PROMPT_HOST.get(), defaultHostname, true);
    ArgumentHelper.addValueSuppressException(hostnameArgument, hostname);
    argList.add("--hostname");
    argList.add(hostname);
    // If this tool is running with access to Directory Server data, and if the
    // selected hostname is "localhost" or a loopback address, then try to load
    // information about the server's connection handlers.
    List<LDAPConnectionHandlerConfiguration> serverListenerConfigs = null;
    final File dsInstanceRoot = InternalSDKHelper.getPingIdentityServerRoot();
    if (dsInstanceRoot != null) {
        final File configFile = StaticUtils.constructPath(dsInstanceRoot, "config", "config.ldif");
        if (configFile.exists() && configFile.isFile()) {
            try {
                serverListenerConfigs = LDAPConnectionHandlerConfiguration.readConfiguration(configFile, true);
            } catch (final Exception e) {
                Debug.debugException(e);
            }
        }
    }
    // Determine the type of connection security to use.
    final BooleanArgument useSSLArgument = parser.getBooleanArgument("useSSL");
    final BooleanArgument useStartTLSArgument = parser.getBooleanArgument("useStartTLS");
    final String defaultSecurityChoice;
    if (useSSLArgument.isPresent()) {
        defaultSecurityChoice = "1";
    } else if (useStartTLSArgument.isPresent()) {
        defaultSecurityChoice = "3";
    } else if ((serverListenerConfigs != null) && (!serverListenerConfigs.isEmpty())) {
        final LDAPConnectionHandlerConfiguration cfg = serverListenerConfigs.get(0);
        if (cfg.usesSSL()) {
            defaultSecurityChoice = "1";
        } else if (cfg.supportsStartTLS()) {
            defaultSecurityChoice = "3";
        } else {
            defaultSecurityChoice = "5";
        }
    } else {
        defaultSecurityChoice = "1";
    }
    ArgumentHelper.reset(useSSLArgument);
    ArgumentHelper.reset(useStartTLSArgument);
    final boolean useSSL;
    final boolean useStartTLS;
    final boolean defaultTrust;
    final int securityType = getNumberedMenuChoice(INFO_INTERACTIVE_LDAP_SECURITY_PROMPT.get(), false, defaultSecurityChoice, INFO_INTERACTIVE_LDAP_SECURITY_OPTION_SSL_DEFAULT.get(), INFO_INTERACTIVE_LDAP_SECURITY_OPTION_SSL_MANUAL.get(), INFO_INTERACTIVE_LDAP_SECURITY_OPTION_START_TLS_DEFAULT.get(), INFO_INTERACTIVE_LDAP_SECURITY_OPTION_START_TLS_MANUAL.get(), INFO_INTERACTIVE_LDAP_SECURITY_OPTION_NONE.get());
    switch(securityType) {
        case 0:
            useSSL = true;
            useStartTLS = false;
            defaultTrust = true;
            argList.add("--useSSL");
            ArgumentHelper.incrementOccurrencesSuppressException(useSSLArgument);
            break;
        case 1:
            useSSL = true;
            useStartTLS = false;
            defaultTrust = false;
            argList.add("--useSSL");
            ArgumentHelper.incrementOccurrencesSuppressException(useSSLArgument);
            break;
        case 2:
            useSSL = false;
            useStartTLS = true;
            defaultTrust = true;
            argList.add("--useStartTLS");
            ArgumentHelper.incrementOccurrencesSuppressException(useStartTLSArgument);
            break;
        case 3:
            useSSL = false;
            useStartTLS = true;
            defaultTrust = false;
            argList.add("--useStartTLS");
            ArgumentHelper.incrementOccurrencesSuppressException(useStartTLSArgument);
            break;
        case 4:
        default:
            useSSL = false;
            useStartTLS = false;
            defaultTrust = false;
            break;
    }
    // If we are to use security without default trust configuration, then
    // prompt for the appropriate settings.
    BindRequest bindRequest = null;
    boolean trustAll = false;
    byte[] keyStorePIN = null;
    byte[] trustStorePIN = null;
    File keyStorePath = null;
    File trustStorePath = null;
    String certificateNickname = null;
    String keyStoreFormat = null;
    String trustStoreFormat = null;
    final StringArgument keyStorePasswordArgument = parser.getStringArgument("keyStorePassword");
    final StringArgument trustStorePasswordArgument = parser.getStringArgument("trustStorePassword");
    final StringArgument saslOptionArgument = parser.getStringArgument("saslOption");
    if (!defaultTrust) {
        // If the user wants to connect securely, then get the appropriate set of
        // arguments pertaining to key and trust managers.
        ArgumentHelper.reset(keyStorePasswordArgument);
        ArgumentHelper.reset(trustStorePasswordArgument);
        ArgumentHelper.reset(parser.getNamedArgument("keyStorePasswordFile"));
        ArgumentHelper.reset(parser.getNamedArgument("promptForKeyStorePassword"));
        ArgumentHelper.reset(parser.getNamedArgument("trustStorePasswordFile"));
        ArgumentHelper.reset(parser.getNamedArgument("promptForTrustStorePassword"));
        if (useSSL || useStartTLS) {
            final StringArgument keyStorePathArgument = parser.getStringArgument("keyStorePath");
            final StringArgument keyStoreFormatArgument = parser.getStringArgument("keyStoreFormat");
            // Determine if a client certificate should be presented.
            final String defaultStoreTypeChoice;
            if (keyStoreFormatArgument.isPresent()) {
                final String format = keyStoreFormatArgument.getValue();
                if (format.equalsIgnoreCase(CryptoHelper.KEY_STORE_TYPE_PKCS_12)) {
                    defaultStoreTypeChoice = "3";
                } else {
                    defaultStoreTypeChoice = "2";
                }
            } else if (keyStorePathArgument.isPresent()) {
                defaultStoreTypeChoice = "2";
            } else {
                defaultStoreTypeChoice = "1";
            }
            final String defaultKeyStorePath;
            if (keyStorePathArgument.isPresent()) {
                defaultKeyStorePath = keyStorePathArgument.getValue();
            } else {
                defaultKeyStorePath = null;
            }
            final String defaultCertNickname;
            final StringArgument certNicknameArgument = parser.getStringArgument("certNickname");
            if (certNicknameArgument.isPresent()) {
                defaultCertNickname = certNicknameArgument.getValue();
            } else {
                defaultCertNickname = null;
            }
            ArgumentHelper.reset(keyStorePathArgument);
            ArgumentHelper.reset(keyStoreFormatArgument);
            ArgumentHelper.reset(certNicknameArgument);
            final int keystoreType = getNumberedMenuChoice(INFO_INTERACTIVE_LDAP_CLIENT_CERT_PROMPT.get(), false, defaultStoreTypeChoice, INFO_INTERACTIVE_LDAP_CLIENT_CERT_OPTION_NO.get(), INFO_INTERACTIVE_LDAP_CLIENT_CERT_OPTION_JKS.get(), INFO_INTERACTIVE_LDAP_CLIENT_CERT_OPTION_PKCS12.get());
            ArgumentHelper.reset(keyStoreFormatArgument);
            switch(keystoreType) {
                case 1:
                    keyStoreFormat = CryptoHelper.KEY_STORE_TYPE_JKS;
                    break;
                case 2:
                    keyStoreFormat = CryptoHelper.KEY_STORE_TYPE_PKCS_12;
                    break;
                case 0:
                default:
                    break;
            }
            if (keyStoreFormat != null) {
                ArgumentHelper.addValueSuppressException(keyStoreFormatArgument, keyStoreFormat);
                // Get the path to the keystore file.
                keyStorePath = promptForPath(INFO_INTERACTIVE_LDAP_KEYSTORE_PATH_PROMPT.get(), defaultKeyStorePath, true, true, true, true, false);
                argList.add("--keyStorePath");
                argList.add(keyStorePath.getAbsolutePath());
                ArgumentHelper.addValueSuppressException(keyStorePathArgument, keyStorePath.getAbsolutePath());
                // Get the PIN needed to access the keystore.
                keyStorePIN = promptForPassword(INFO_INTERACTIVE_LDAP_KEYSTORE_PIN_PROMPT.get(), null, false);
                if (keyStorePIN != null) {
                    argList.add("--keyStorePassword");
                    argList.add("***REDACTED***");
                    ArgumentHelper.addValueSuppressException(keyStorePasswordArgument, StaticUtils.toUTF8String(keyStorePIN));
                }
                argList.add("--keyStoreFormat");
                argList.add(keyStoreFormat);
                certificateNickname = promptForString(INFO_INTERACTIVE_LDAP_CERT_NICKNAME_PROMPT.get(), defaultCertNickname, false);
                if (certificateNickname != null) {
                    argList.add("--certNickname");
                    argList.add(certificateNickname);
                    ArgumentHelper.addValueSuppressException(certNicknameArgument, certificateNickname);
                }
                if (ldapTool.supportsAuthentication() && promptForYesNo(INFO_INTERACTIVE_LDAP_CERT_AUTH_PROMPT.get(), false, true)) {
                    bindRequest = new EXTERNALBindRequest();
                    argList.add("--saslOption");
                    argList.add("mech=EXTERNAL");
                    ArgumentHelper.reset(saslOptionArgument);
                    ArgumentHelper.addValueSuppressException(saslOptionArgument, "mech=EXTERNAL");
                }
            }
            // Determine how to trust the server certificate.
            final BooleanArgument trustAllArgument = parser.getBooleanArgument("trustAll");
            final StringArgument trustStorePathArgument = parser.getStringArgument("trustStorePath");
            final StringArgument trustStoreFormatArgument = parser.getStringArgument("trustStoreFormat");
            final String defaultTrustTypeChoice;
            if (trustAllArgument.isPresent()) {
                defaultTrustTypeChoice = "4";
            } else if (trustStoreFormatArgument.isPresent()) {
                final String format = trustStoreFormatArgument.getValue();
                if (format.equalsIgnoreCase(CryptoHelper.KEY_STORE_TYPE_PKCS_12)) {
                    defaultTrustTypeChoice = "3";
                } else {
                    defaultTrustTypeChoice = "2";
                }
            } else if (trustStorePathArgument.isPresent()) {
                defaultTrustTypeChoice = "2";
            } else {
                defaultTrustTypeChoice = "1";
            }
            final String defaultTrustStorePath;
            if (trustStorePathArgument.isPresent()) {
                defaultTrustStorePath = trustStorePathArgument.getValue();
            } else {
                defaultTrustStorePath = null;
            }
            ArgumentHelper.reset(trustAllArgument);
            ArgumentHelper.reset(trustStorePathArgument);
            ArgumentHelper.reset(trustStoreFormatArgument);
            final int trustType = getNumberedMenuChoice(INFO_INTERACTIVE_LDAP_TRUST_PROMPT.get(), false, defaultTrustTypeChoice, INFO_INTERACTIVE_LDAP_TRUST_OPTION_PROMPT.get(), INFO_INTERACTIVE_LDAP_TRUST_OPTION_JKS.get(), INFO_INTERACTIVE_LDAP_TRUST_OPTION_PKCS12.get(), INFO_INTERACTIVE_LDAP_TRUST_OPTION_BLIND.get());
            switch(trustType) {
                case 1:
                    trustStoreFormat = CryptoHelper.KEY_STORE_TYPE_JKS;
                    break;
                case 2:
                    trustStoreFormat = CryptoHelper.KEY_STORE_TYPE_PKCS_12;
                    break;
                case 3:
                    trustAll = true;
                    argList.add("--trustAll");
                    ArgumentHelper.incrementOccurrencesSuppressException(trustAllArgument);
                    break;
                case 0:
                default:
                    // We will interactively prompt the user about whether to trust the
                    // certificate in the test section below.  However, to avoid
                    // prompting the user twice, we will configure the tool behind the
                    // scenes to trust all certificates.
                    ArgumentHelper.incrementOccurrencesSuppressException(trustAllArgument);
                    break;
            }
            if (trustStoreFormat != null) {
                ArgumentHelper.addValueSuppressException(trustStoreFormatArgument, trustStoreFormat);
                // Get the path to the truststore file.
                trustStorePath = promptForPath(INFO_INTERACTIVE_LDAP_TRUSTSTORE_PATH_PROMPT.get(), defaultTrustStorePath, true, true, true, true, false);
                argList.add("--trustStorePath");
                argList.add(trustStorePath.getAbsolutePath());
                ArgumentHelper.addValueSuppressException(trustStorePathArgument, trustStorePath.getAbsolutePath());
                // Get the PIN needed to access the truststore.
                trustStorePIN = promptForPassword(INFO_INTERACTIVE_LDAP_TRUSTSTORE_PIN_PROMPT.get(), null, false);
                if (trustStorePIN != null) {
                    argList.add("--trustStorePassword");
                    argList.add("***REDACTED***");
                    ArgumentHelper.addValueSuppressException(trustStorePasswordArgument, StaticUtils.toUTF8String(trustStorePIN));
                }
                argList.add("--trustStoreFormat");
                argList.add(trustStoreFormat);
            }
        } else {
            ArgumentHelper.reset(parser.getNamedArgument("keyStorePath"));
            ArgumentHelper.reset(parser.getNamedArgument("keyStoreFormat"));
            ArgumentHelper.reset(parser.getNamedArgument("trustStorePath"));
            ArgumentHelper.reset(parser.getNamedArgument("trustStoreFormat"));
            ArgumentHelper.reset(parser.getNamedArgument("certNickname"));
        }
    }
    // Get the port of the directory server.
    int defaultPort;
    final IntegerArgument portArgument = parser.getIntegerArgument("port");
    if (portArgument.getNumOccurrences() > 0) {
        // Note -- We're using getNumOccurrences here because isPresent also
        // returns true if there is a default value, and that could be wrong in
        // this case because the default value doesn't know about SSL.
        defaultPort = portArgument.getValue();
    } else if (useSSL) {
        defaultPort = 636;
        if (serverListenerConfigs != null) {
            for (final LDAPConnectionHandlerConfiguration cfg : serverListenerConfigs) {
                if (cfg.usesSSL()) {
                    defaultPort = cfg.getPort();
                    break;
                }
            }
        }
    } else if (useStartTLS) {
        defaultPort = 389;
        if (serverListenerConfigs != null) {
            for (final LDAPConnectionHandlerConfiguration cfg : serverListenerConfigs) {
                if (cfg.supportsStartTLS()) {
                    defaultPort = cfg.getPort();
                    break;
                }
            }
        }
    } else {
        defaultPort = 389;
        if (serverListenerConfigs != null) {
            for (final LDAPConnectionHandlerConfiguration cfg : serverListenerConfigs) {
                if (!cfg.usesSSL()) {
                    defaultPort = cfg.getPort();
                    break;
                }
            }
        }
    }
    ArgumentHelper.reset(portArgument);
    final int port = promptForInteger(INFO_INTERACTIVE_LDAP_PROMPT_PORT.get(), defaultPort, 1, 65_535, true);
    argList.add("--port");
    argList.add(String.valueOf(port));
    ArgumentHelper.addValueSuppressException(portArgument, String.valueOf(port));
    // Determine how to authenticate to the directory server.
    if (ldapTool.supportsAuthentication()) {
        final DNArgument bindDNArgument = parser.getDNArgument("bindDN");
        final StringArgument bindPasswordArgument = parser.getStringArgument("bindPassword");
        ArgumentHelper.reset(bindPasswordArgument);
        ArgumentHelper.reset(parser.getNamedArgument("bindPasswordFile"));
        ArgumentHelper.reset(parser.getNamedArgument("promptForBindPassword"));
        if (bindRequest == null) {
            final String defaultAuthTypeChoice;
            final String defaultBindDN;
            if (saslOptionArgument.isPresent()) {
                defaultAuthTypeChoice = "2";
                defaultBindDN = null;
            } else {
                defaultAuthTypeChoice = "1";
                if (bindDNArgument.isPresent()) {
                    defaultBindDN = bindDNArgument.getStringValue();
                } else {
                    defaultBindDN = null;
                }
            }
            ArgumentHelper.reset(bindDNArgument);
            boolean useSimpleAuth = false;
            boolean useSASLAuth = false;
            final int authMethod = getNumberedMenuChoice(INFO_INTERACTIVE_LDAP_AUTH_PROMPT.get(), false, defaultAuthTypeChoice, INFO_INTERACTIVE_LDAP_AUTH_OPTION_SIMPLE.get(), INFO_INTERACTIVE_LDAP_AUTH_OPTION_SASL.get(), INFO_INTERACTIVE_LDAP_AUTH_OPTION_NONE.get());
            switch(authMethod) {
                case 0:
                    useSimpleAuth = true;
                    break;
                case 1:
                    useSASLAuth = true;
                    break;
                case 2:
                default:
                    break;
            }
            if (useSimpleAuth) {
                ArgumentHelper.reset(saslOptionArgument);
                final DN bindDN = promptForDN(INFO_INTERACTIVE_LDAP_AUTH_BIND_DN_PROMPT.get(), defaultBindDN, true);
                if (bindDN.isNullDN()) {
                    bindRequest = new SimpleBindRequest();
                    argList.add("--bindDN");
                    argList.add("");
                    argList.add("--bindPassword");
                    argList.add("");
                    ArgumentHelper.addValueSuppressException(bindDNArgument, "");
                    ArgumentHelper.addValueSuppressException(bindPasswordArgument, "");
                } else {
                    final byte[] bindPassword = promptForPassword(INFO_INTERACTIVE_LDAP_AUTH_PW_PROMPT.get(), null, true);
                    bindRequest = new SimpleBindRequest(bindDN, bindPassword);
                    argList.add("--bindDN");
                    argList.add(bindDN.toString());
                    argList.add("--bindPassword");
                    argList.add("***REDACTED***");
                    ArgumentHelper.addValueSuppressException(bindDNArgument, bindDN.toString());
                    ArgumentHelper.addValueSuppressException(bindPasswordArgument, StaticUtils.toUTF8String(bindPassword));
                }
            } else if (useSASLAuth) {
                String defaultMechChoice = null;
                String defaultAuthID = null;
                String defaultAuthzID = null;
                String defaultRealm = null;
                if (saslOptionArgument.isPresent()) {
                    for (final String saslOption : saslOptionArgument.getValues()) {
                        final String lowerOption = StaticUtils.toLowerCase(saslOption);
                        if (lowerOption.equals("mech=cram-md5")) {
                            defaultMechChoice = "1";
                        } else if (lowerOption.equals("mech=digest-md5")) {
                            defaultMechChoice = "2";
                        } else if (lowerOption.equals("mech=plain")) {
                            defaultMechChoice = "3";
                        } else if (lowerOption.startsWith("authid=")) {
                            defaultAuthID = saslOption.substring(7);
                        } else if (lowerOption.startsWith("authzid=")) {
                            defaultAuthzID = saslOption.substring(8);
                        } else if (lowerOption.startsWith("realm=")) {
                            defaultRealm = saslOption.substring(6);
                        }
                    }
                }
                ArgumentHelper.reset(saslOptionArgument);
                final int mech = getNumberedMenuChoice(INFO_INTERACTIVE_LDAP_AUTH_SASL_PROMPT.get(), false, defaultMechChoice, INFO_INTERACTIVE_LDAP_SASL_OPTION_CRAM_MD5.get(), INFO_INTERACTIVE_LDAP_SASL_OPTION_DIGEST_MD5.get(), INFO_INTERACTIVE_LDAP_SASL_OPTION_PLAIN.get());
                switch(mech) {
                    case 0:
                        String authID = promptForString(INFO_INTERACTIVE_LDAP_AUTH_AUTHID_PROMPT.get(), defaultAuthID, true);
                        byte[] pw = promptForPassword(INFO_INTERACTIVE_LDAP_AUTH_PW_PROMPT.get(), null, true);
                        bindRequest = new CRAMMD5BindRequest(authID, pw);
                        argList.add("--saslOption");
                        argList.add("mech=CRAM-MD5");
                        argList.add("--saslOption");
                        argList.add("authID=" + authID);
                        argList.add("--bindPassword");
                        argList.add("***REDACTED***");
                        ArgumentHelper.addValueSuppressException(saslOptionArgument, "mech=CRAM-MD5");
                        ArgumentHelper.addValueSuppressException(saslOptionArgument, "authID=" + authID);
                        ArgumentHelper.addValueSuppressException(bindPasswordArgument, StaticUtils.toUTF8String(pw));
                        break;
                    case 1:
                        authID = promptForString(INFO_INTERACTIVE_LDAP_AUTH_AUTHID_PROMPT.get(), defaultAuthID, true);
                        String authzID = promptForString(INFO_INTERACTIVE_LDAP_AUTH_AUTHZID_PROMPT.get(), defaultAuthzID, false);
                        final String realm = promptForString(INFO_INTERACTIVE_LDAP_AUTH_REALM_PROMPT.get(), defaultRealm, false);
                        pw = promptForPassword(INFO_INTERACTIVE_LDAP_AUTH_PW_PROMPT.get(), null, true);
                        bindRequest = new DIGESTMD5BindRequest(authID, authzID, pw, realm);
                        argList.add("--saslOption");
                        argList.add("mech=DIGEST-MD5");
                        argList.add("--saslOption");
                        argList.add("authID=" + authID);
                        ArgumentHelper.addValueSuppressException(saslOptionArgument, "mech=DIGEST-MD5");
                        ArgumentHelper.addValueSuppressException(saslOptionArgument, "authID=" + authID);
                        if (authzID != null) {
                            argList.add("--saslOption");
                            argList.add("authzID=" + authzID);
                            ArgumentHelper.addValueSuppressException(saslOptionArgument, "authzID=" + authzID);
                        }
                        if (realm != null) {
                            argList.add("--saslOption");
                            argList.add("realm=" + realm);
                            ArgumentHelper.addValueSuppressException(saslOptionArgument, "realm=" + realm);
                        }
                        argList.add("--bindPassword");
                        argList.add("***REDACTED***");
                        ArgumentHelper.addValueSuppressException(bindPasswordArgument, StaticUtils.toUTF8String(pw));
                        break;
                    case 2:
                        authID = promptForString(INFO_INTERACTIVE_LDAP_AUTH_AUTHID_PROMPT.get(), defaultAuthID, true);
                        authzID = promptForString(INFO_INTERACTIVE_LDAP_AUTH_AUTHZID_PROMPT.get(), defaultAuthzID, false);
                        pw = promptForPassword(INFO_INTERACTIVE_LDAP_AUTH_PW_PROMPT.get(), null, true);
                        bindRequest = new PLAINBindRequest(authID, authzID, pw);
                        argList.add("--saslOption");
                        argList.add("mech=PLAIN");
                        argList.add("--saslOption");
                        argList.add("authID=" + authID);
                        ArgumentHelper.addValueSuppressException(saslOptionArgument, "mech=PLAIN");
                        ArgumentHelper.addValueSuppressException(saslOptionArgument, "authID=" + authID);
                        if (authzID != null) {
                            argList.add("--saslOption");
                            argList.add("authzID=" + authzID);
                            ArgumentHelper.addValueSuppressException(saslOptionArgument, "authzID=" + authzID);
                        }
                        argList.add("--bindPassword");
                        argList.add("***REDACTED***");
                        ArgumentHelper.addValueSuppressException(bindPasswordArgument, StaticUtils.toUTF8String(pw));
                        break;
                }
            }
        } else {
            ArgumentHelper.reset(bindDNArgument);
        }
    }
    if (test) {
        // Perform the necessary initialization for SSL/TLS communication.
        final SSLUtil sslUtil;
        if (useSSL || useStartTLS) {
            final KeyManager keyManager;
            if (keyStorePath == null) {
                keyManager = null;
            } else {
                final char[] pinChars;
                if (keyStorePIN == null) {
                    pinChars = null;
                } else {
                    final String pinString = StaticUtils.toUTF8String(keyStorePIN);
                    pinChars = pinString.toCharArray();
                }
                try {
                    keyManager = new KeyStoreKeyManager(keyStorePath, pinChars, keyStoreFormat, certificateNickname, true);
                } catch (final Exception e) {
                    Debug.debugException(e);
                    tool.wrapErr(0, wrapColumn, ERR_INTERACTIVE_LDAP_CANNOT_CREATE_KEY_MANAGER.get(StaticUtils.getExceptionMessage(e)));
                    if (promptForYesNo(INFO_INTERACTIVE_LDAP_RETRY_PROMPT.get(), true, true)) {
                        promptForLDAPArguments(argList, test);
                        return;
                    } else {
                        throw new LDAPException(ResultCode.LOCAL_ERROR, "", e);
                    }
                }
            }
            final TrustManager trustManager;
            if (trustAll) {
                trustManager = new TrustAllTrustManager();
            } else if (trustStorePath == null) {
                trustManager = InternalSDKHelper.getPreferredPromptTrustManagerChain(null);
            } else {
                final char[] pinChars;
                if (trustStorePIN == null) {
                    pinChars = null;
                } else {
                    final String pinString = StaticUtils.toUTF8String(trustStorePIN);
                    pinChars = pinString.toCharArray();
                }
                try {
                    trustManager = new TrustStoreTrustManager(trustStorePath, pinChars, trustStoreFormat, true);
                } catch (final Exception e) {
                    Debug.debugException(e);
                    tool.wrapErr(0, wrapColumn, ERR_INTERACTIVE_LDAP_CANNOT_CREATE_TRUST_MANAGER.get(StaticUtils.getExceptionMessage(e)));
                    if (promptForYesNo(INFO_INTERACTIVE_LDAP_RETRY_PROMPT.get(), true, true)) {
                        promptForLDAPArguments(argList, test);
                        return;
                    } else {
                        throw new LDAPException(ResultCode.LOCAL_ERROR, "", e);
                    }
                }
            }
            sslUtil = new SSLUtil(keyManager, trustManager);
        } else {
            sslUtil = null;
        }
        // Create and establish the connection.
        final LDAPConnection conn;
        if (useSSL) {
            try {
                conn = new LDAPConnection(sslUtil.createSSLSocketFactory());
            } catch (final Exception e) {
                Debug.debugException(e);
                tool.wrapErr(0, wrapColumn, ERR_INTERACTIVE_LDAP_CANNOT_CREATE_SOCKET_FACTORY.get(StaticUtils.getExceptionMessage(e)), e);
                if (promptForYesNo(INFO_INTERACTIVE_LDAP_RETRY_PROMPT.get(), true, true)) {
                    promptForLDAPArguments(argList, test);
                    return;
                } else {
                    throw new LDAPException(ResultCode.LOCAL_ERROR, "", e);
                }
            }
        } else {
            conn = new LDAPConnection();
        }
        try {
            try {
                conn.connect(hostname, port);
            } catch (final LDAPException le) {
                Debug.debugException(le);
                tool.wrapErr(0, wrapColumn, ERR_INTERACTIVE_LDAP_CANNOT_CONNECT.get(hostname, port, le.getResultString()));
                if (promptForYesNo(INFO_INTERACTIVE_LDAP_RETRY_PROMPT.get(), true, true)) {
                    promptForLDAPArguments(argList, test);
                    return;
                } else {
                    throw new LDAPException(le.getResultCode(), "", le);
                }
            }
            // If we should use StartTLS to secure the connection, then do so now.
            if (useStartTLS) {
                try {
                    final ExtendedResult startTLSResult = conn.processExtendedOperation(new StartTLSExtendedRequest(sslUtil.createSSLContext()));
                    if (startTLSResult.getResultCode() != ResultCode.SUCCESS) {
                        throw new LDAPException(startTLSResult);
                    }
                } catch (final Exception e) {
                    Debug.debugException(e);
                    final String msg;
                    if (e instanceof LDAPException) {
                        msg = ((LDAPException) e).getResultString();
                    } else {
                        msg = StaticUtils.getExceptionMessage(e);
                    }
                    tool.wrapErr(0, wrapColumn, ERR_INTERACTIVE_LDAP_CANNOT_PERFORM_STARTTLS.get(msg));
                    if (promptForYesNo(INFO_INTERACTIVE_LDAP_RETRY_PROMPT.get(), true, true)) {
                        promptForLDAPArguments(argList, test);
                        return;
                    } else {
                        throw new LDAPException(ResultCode.LOCAL_ERROR, "", e);
                    }
                }
            }
            // Authenticate the connection if appropriate.
            if (bindRequest != null) {
                try {
                    conn.bind(bindRequest);
                } catch (final LDAPException le) {
                    Debug.debugException(le);
                    tool.wrapErr(0, wrapColumn, ERR_INTERACTIVE_LDAP_CANNOT_AUTHENTICATE.get(le.getResultString()));
                    if (promptForYesNo(INFO_INTERACTIVE_LDAP_RETRY_PROMPT.get(), true, true)) {
                        promptForLDAPArguments(argList, test);
                        return;
                    } else {
                        throw new LDAPException(le.getResultCode(), "", le);
                    }
                }
            }
        } finally {
            conn.close();
        }
    }
}
Also used : TrustStoreTrustManager(com.unboundid.util.ssl.TrustStoreTrustManager) BindRequest(com.unboundid.ldap.sdk.BindRequest) EXTERNALBindRequest(com.unboundid.ldap.sdk.EXTERNALBindRequest) DIGESTMD5BindRequest(com.unboundid.ldap.sdk.DIGESTMD5BindRequest) SimpleBindRequest(com.unboundid.ldap.sdk.SimpleBindRequest) PLAINBindRequest(com.unboundid.ldap.sdk.PLAINBindRequest) CRAMMD5BindRequest(com.unboundid.ldap.sdk.CRAMMD5BindRequest) PLAINBindRequest(com.unboundid.ldap.sdk.PLAINBindRequest) DN(com.unboundid.ldap.sdk.DN) TrustAllTrustManager(com.unboundid.util.ssl.TrustAllTrustManager) SSLUtil(com.unboundid.util.ssl.SSLUtil) DNArgument(com.unboundid.util.args.DNArgument) SimpleBindRequest(com.unboundid.ldap.sdk.SimpleBindRequest) IntegerArgument(com.unboundid.util.args.IntegerArgument) DIGESTMD5BindRequest(com.unboundid.ldap.sdk.DIGESTMD5BindRequest) KeyStoreKeyManager(com.unboundid.util.ssl.KeyStoreKeyManager) KeyManager(javax.net.ssl.KeyManager) KeyStoreKeyManager(com.unboundid.util.ssl.KeyStoreKeyManager) LDAPConnectionHandlerConfiguration(com.unboundid.ldap.sdk.unboundidds.LDAPConnectionHandlerConfiguration) BooleanArgument(com.unboundid.util.args.BooleanArgument) CRAMMD5BindRequest(com.unboundid.ldap.sdk.CRAMMD5BindRequest) LDAPConnection(com.unboundid.ldap.sdk.LDAPConnection) ArgumentException(com.unboundid.util.args.ArgumentException) LDAPException(com.unboundid.ldap.sdk.LDAPException) StringArgument(com.unboundid.util.args.StringArgument) TrustManager(javax.net.ssl.TrustManager) TrustAllTrustManager(com.unboundid.util.ssl.TrustAllTrustManager) TrustStoreTrustManager(com.unboundid.util.ssl.TrustStoreTrustManager) EXTERNALBindRequest(com.unboundid.ldap.sdk.EXTERNALBindRequest) LDAPException(com.unboundid.ldap.sdk.LDAPException) ExtendedResult(com.unboundid.ldap.sdk.ExtendedResult) File(java.io.File) StartTLSExtendedRequest(com.unboundid.ldap.sdk.extensions.StartTLSExtendedRequest)

Example 3 with DIGESTMD5BindRequest

use of com.unboundid.ldap.sdk.DIGESTMD5BindRequest in project ldapsdk by pingidentity.

the class AuthenticationDetailsTestCase method testAuthTypeDIGESTMD5Anonymous.

/**
 * Tests the behavior for the case in which the JSON object has an
 * authentication-details field that has an authentication type of DIGEST-MD5
 * and is configured for anonymous authentication.
 *
 * @throws  Exception  If an unexpected problem occurs.
 */
@Test()
public void testAuthTypeDIGESTMD5Anonymous() throws Exception {
    final InMemoryDirectoryServer ds = getTestDS();
    final JSONObject o = new JSONObject(new JSONField("server-details", new JSONObject(new JSONField("single-server", new JSONObject(new JSONField("address", "localhost"), new JSONField("port", ds.getListenPort()))))), new JSONField("authentication-details", new JSONObject(new JSONField("authentication-type", "DIGEST-MD5"), new JSONField("authentication-id", "dn:"), new JSONField("password", ""))));
    final LDAPConnectionDetailsJSONSpecification spec = new LDAPConnectionDetailsJSONSpecification(o);
    assertNotNull(spec.getBindRequest());
    assertTrue(spec.getBindRequest() instanceof DIGESTMD5BindRequest);
    final DIGESTMD5BindRequest bindRequest = (DIGESTMD5BindRequest) spec.getBindRequest();
    assertEquals(bindRequest.getAuthenticationID(), "dn:");
    assertNull(bindRequest.getAuthorizationID());
    assertEquals(bindRequest.getPasswordString(), "");
    assertNull(bindRequest.getRealm());
    assertNotNull(bindRequest.getAllowedQoP());
    assertEquals(bindRequest.getAllowedQoP(), Collections.singletonList(SASLQualityOfProtection.AUTH));
}
Also used : InMemoryDirectoryServer(com.unboundid.ldap.listener.InMemoryDirectoryServer) DIGESTMD5BindRequest(com.unboundid.ldap.sdk.DIGESTMD5BindRequest) Test(org.testng.annotations.Test)

Example 4 with DIGESTMD5BindRequest

use of com.unboundid.ldap.sdk.DIGESTMD5BindRequest in project ldapsdk by pingidentity.

the class AuthenticationDetailsTestCase method testAuthTypeDIGESTMD5NonAnonymousSingleQoP.

/**
 * Tests the behavior for the case in which the JSON object has an
 * authentication-details field that has an authentication type of DIGEST-MD5
 * and is configured for non-anonymous authentication with a single allowed
 * quality of protection.
 *
 * @throws  Exception  If an unexpected problem occurs.
 */
@Test()
public void testAuthTypeDIGESTMD5NonAnonymousSingleQoP() throws Exception {
    final InMemoryDirectoryServer ds = getTestDS();
    final JSONObject o = new JSONObject(new JSONField("server-details", new JSONObject(new JSONField("single-server", new JSONObject(new JSONField("address", "localhost"), new JSONField("port", ds.getListenPort()))))), new JSONField("authentication-details", new JSONObject(new JSONField("authentication-type", "DIGEST-MD5"), new JSONField("authentication-id", "u:john.doe"), new JSONField("authorization-id", "u:someone.else"), new JSONField("password", "password"), new JSONField("realm", "dc=example,dc=com"), new JSONField("qop", "auth-conf"))));
    final LDAPConnectionDetailsJSONSpecification spec = new LDAPConnectionDetailsJSONSpecification(o);
    assertNotNull(spec.getBindRequest());
    assertTrue(spec.getBindRequest() instanceof DIGESTMD5BindRequest);
    final DIGESTMD5BindRequest bindRequest = (DIGESTMD5BindRequest) spec.getBindRequest();
    assertEquals(bindRequest.getAuthenticationID(), "u:john.doe");
    assertEquals(bindRequest.getAuthorizationID(), "u:someone.else");
    assertEquals(bindRequest.getPasswordString(), "password");
    assertEquals(bindRequest.getRealm(), "dc=example,dc=com");
    assertNotNull(bindRequest.getAllowedQoP());
    assertEquals(bindRequest.getAllowedQoP(), Collections.singletonList(SASLQualityOfProtection.AUTH_CONF));
}
Also used : InMemoryDirectoryServer(com.unboundid.ldap.listener.InMemoryDirectoryServer) DIGESTMD5BindRequest(com.unboundid.ldap.sdk.DIGESTMD5BindRequest) Test(org.testng.annotations.Test)

Example 5 with DIGESTMD5BindRequest

use of com.unboundid.ldap.sdk.DIGESTMD5BindRequest in project ldapsdk by pingidentity.

the class SASLUtilsTestCase method testValidDIGESTMD5WithAllProperties.

/**
 * Tests the ability to create a valid DIGEST-MD5 bind request with a full set
 * of properties.
 *
 * @throws  Exception  If an unexpected problem occurs.
 */
@Test()
public void testValidDIGESTMD5WithAllProperties() throws Exception {
    final BindRequest bindRequest = SASLUtils.createBindRequest(null, "password", null, "mech=DIGEST-MD5", "authID=u:test.user", "realm=example.com", "authzID=u:another.user", "qop=auth-conf,auth-int,auth");
    assertNotNull(bindRequest);
    assertTrue(bindRequest instanceof DIGESTMD5BindRequest);
    final DIGESTMD5BindRequest digestMD5Bind = (DIGESTMD5BindRequest) bindRequest;
    assertNotNull(digestMD5Bind.getAuthenticationID());
    assertEquals(digestMD5Bind.getAuthenticationID(), "u:test.user");
    assertNotNull(digestMD5Bind.getPasswordString());
    assertEquals(digestMD5Bind.getPasswordString(), "password");
    assertNotNull(digestMD5Bind.getAuthorizationID());
    assertEquals(digestMD5Bind.getAuthorizationID(), "u:another.user");
    assertNotNull(digestMD5Bind.getRealm());
    assertEquals(digestMD5Bind.getRealm(), "example.com");
    assertNotNull(digestMD5Bind.getAllowedQoP());
    assertEquals(digestMD5Bind.getAllowedQoP(), Arrays.asList(SASLQualityOfProtection.AUTH_CONF, SASLQualityOfProtection.AUTH_INT, SASLQualityOfProtection.AUTH));
}
Also used : ANONYMOUSBindRequest(com.unboundid.ldap.sdk.ANONYMOUSBindRequest) GSSAPIBindRequest(com.unboundid.ldap.sdk.GSSAPIBindRequest) UnboundIDCertificatePlusPasswordBindRequest(com.unboundid.ldap.sdk.unboundidds.UnboundIDCertificatePlusPasswordBindRequest) BindRequest(com.unboundid.ldap.sdk.BindRequest) SCRAMSHA512BindRequest(com.unboundid.ldap.sdk.SCRAMSHA512BindRequest) SingleUseTOTPBindRequest(com.unboundid.ldap.sdk.unboundidds.SingleUseTOTPBindRequest) PLAINBindRequest(com.unboundid.ldap.sdk.PLAINBindRequest) UnboundIDYubiKeyOTPBindRequest(com.unboundid.ldap.sdk.unboundidds.UnboundIDYubiKeyOTPBindRequest) EXTERNALBindRequest(com.unboundid.ldap.sdk.EXTERNALBindRequest) DIGESTMD5BindRequest(com.unboundid.ldap.sdk.DIGESTMD5BindRequest) UnboundIDDeliveredOTPBindRequest(com.unboundid.ldap.sdk.unboundidds.UnboundIDDeliveredOTPBindRequest) OAUTHBEARERBindRequest(com.unboundid.ldap.sdk.OAUTHBEARERBindRequest) UnboundIDTOTPBindRequest(com.unboundid.ldap.sdk.unboundidds.UnboundIDTOTPBindRequest) SCRAMSHA1BindRequest(com.unboundid.ldap.sdk.SCRAMSHA1BindRequest) SCRAMSHA256BindRequest(com.unboundid.ldap.sdk.SCRAMSHA256BindRequest) CRAMMD5BindRequest(com.unboundid.ldap.sdk.CRAMMD5BindRequest) DIGESTMD5BindRequest(com.unboundid.ldap.sdk.DIGESTMD5BindRequest) Test(org.testng.annotations.Test)

Aggregations

DIGESTMD5BindRequest (com.unboundid.ldap.sdk.DIGESTMD5BindRequest)8 Test (org.testng.annotations.Test)5 BindRequest (com.unboundid.ldap.sdk.BindRequest)4 CRAMMD5BindRequest (com.unboundid.ldap.sdk.CRAMMD5BindRequest)4 PLAINBindRequest (com.unboundid.ldap.sdk.PLAINBindRequest)4 InMemoryDirectoryServer (com.unboundid.ldap.listener.InMemoryDirectoryServer)3 EXTERNALBindRequest (com.unboundid.ldap.sdk.EXTERNALBindRequest)3 LDAPException (com.unboundid.ldap.sdk.LDAPException)3 ANONYMOUSBindRequest (com.unboundid.ldap.sdk.ANONYMOUSBindRequest)2 GSSAPIBindRequest (com.unboundid.ldap.sdk.GSSAPIBindRequest)2 OAUTHBEARERBindRequest (com.unboundid.ldap.sdk.OAUTHBEARERBindRequest)2 SCRAMSHA1BindRequest (com.unboundid.ldap.sdk.SCRAMSHA1BindRequest)2 SCRAMSHA256BindRequest (com.unboundid.ldap.sdk.SCRAMSHA256BindRequest)2 SCRAMSHA512BindRequest (com.unboundid.ldap.sdk.SCRAMSHA512BindRequest)2 SimpleBindRequest (com.unboundid.ldap.sdk.SimpleBindRequest)2 SingleUseTOTPBindRequest (com.unboundid.ldap.sdk.unboundidds.SingleUseTOTPBindRequest)2 UnboundIDCertificatePlusPasswordBindRequest (com.unboundid.ldap.sdk.unboundidds.UnboundIDCertificatePlusPasswordBindRequest)2 UnboundIDDeliveredOTPBindRequest (com.unboundid.ldap.sdk.unboundidds.UnboundIDDeliveredOTPBindRequest)2 UnboundIDTOTPBindRequest (com.unboundid.ldap.sdk.unboundidds.UnboundIDTOTPBindRequest)2 UnboundIDYubiKeyOTPBindRequest (com.unboundid.ldap.sdk.unboundidds.UnboundIDYubiKeyOTPBindRequest)2