use of com.unboundid.ldap.sdk.PLAINBindRequest 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();
}
}
}
use of com.unboundid.ldap.sdk.PLAINBindRequest in project ldapsdk by pingidentity.
the class InMemoryDirectoryServerTestCase method testBindDirect.
/**
* Provides a set of tests covering the ability to perform a bind directly
* against the {@code InMemoryDirectoryServer} class without using a
* connection.
*
* @throws Exception If an unexpected problem occurs.
*/
@Test()
public void testBindDirect() throws Exception {
final InMemoryDirectoryServer ds = getTestDS();
BindResult bindResult = ds.bind("cn=Directory Manager", "password");
assertResultCodeEquals(bindResult, ResultCode.SUCCESS);
try {
ds.bind("cn=Directory Manager", "wrong");
fail("Expected an exception when trying to perform a direct simple " + "bind with the wrong password");
} catch (final LDAPException le) {
assertResultCodeEquals(le, ResultCode.INVALID_CREDENTIALS);
}
bindResult = ds.bind(new PLAINBindRequest("dn:cn=Directory Manager", "password"));
assertResultCodeEquals(bindResult, ResultCode.SUCCESS);
try {
ds.bind(new PLAINBindRequest("dn:cn=Directory Manager", "wrong"));
fail("Expected an exception when trying to perform a direct PLAIN " + "bind with the wrong password");
} catch (final LDAPException le) {
assertResultCodeEquals(le, ResultCode.INVALID_CREDENTIALS);
}
try {
ds.bind(new CRAMMD5BindRequest("dn:cn=Directory Manager", "password"));
fail("Expected an exception when trying to perform a direct CRAM-MD5 " + "bind with the wrong password");
} catch (final LDAPException le) {
assertResultCodeEquals(le, ResultCode.AUTH_METHOD_NOT_SUPPORTED);
}
}
use of com.unboundid.ldap.sdk.PLAINBindRequest in project ldapsdk by pingidentity.
the class InMemoryDirectoryServerTestCase method testSASLBindWithAuthorizationIdentity.
/**
* Provides test coverage for the ability to process a SASL bind operation,
* including the authorization identity request control.
*
* @throws Exception If an unexpected problem occurs.
*/
@Test()
public void testSASLBindWithAuthorizationIdentity() throws Exception {
final InMemoryDirectoryServer ds = getTestDS(true, true);
final LDAPConnection conn = ds.getConnection();
final RootDSE rootDSE = conn.getRootDSE();
assertNotNull(rootDSE);
assertTrue(rootDSE.supportsSASLMechanism("PLAIN"));
assertTrue(rootDSE.supportsControl(AuthorizationIdentityRequestControl.AUTHORIZATION_IDENTITY_REQUEST_OID));
// Test a successful anonymous bind.
PLAINBindRequest bindRequest = new PLAINBindRequest("dn:", "", new AuthorizationIdentityRequestControl());
BindResult bindResult = conn.bind(bindRequest);
assertEquals(bindResult.getResultCode(), ResultCode.SUCCESS);
AuthorizationIdentityResponseControl authzIDResponse = AuthorizationIdentityResponseControl.get(bindResult);
assertNotNull(authzIDResponse);
String authzID = authzIDResponse.getAuthorizationID();
assertNotNull(authzID);
assertTrue(authzID.equals("dn:"));
// Perform the same test without the authorization identity request control.
bindRequest = new PLAINBindRequest("dn:", "");
bindResult = conn.bind(bindRequest);
assertEquals(bindResult.getResultCode(), ResultCode.SUCCESS);
assertFalse(bindResult.hasResponseControl(AuthorizationIdentityResponseControl.AUTHORIZATION_IDENTITY_RESPONSE_OID));
// Test an anonymous bind with a password.
bindRequest = new PLAINBindRequest("dn:", "password");
try {
bindResult = conn.bind(bindRequest);
fail("Expected an exception when trying to bind anonymously with a " + "password");
} catch (final LDAPException le) {
assertEquals(le.getResultCode(), ResultCode.INVALID_CREDENTIALS);
}
// Test an anonymous bind with an authzID.
bindRequest = new PLAINBindRequest("dn:", "dn:cn=Directory Manager", "");
try {
bindResult = conn.bind(bindRequest);
fail("Expected an exception when trying to bind anonymously with an " + "authorization ID");
} catch (final LDAPException le) {
assertEquals(le.getResultCode(), ResultCode.INVALID_CREDENTIALS);
}
// Test with a DN-style authID and no authzID.
bindRequest = new PLAINBindRequest("dn:uid=test.user,ou=People,dc=example,dc=com", "password", new AuthorizationIdentityRequestControl());
bindResult = conn.bind(bindRequest);
assertEquals(bindResult.getResultCode(), ResultCode.SUCCESS);
authzIDResponse = AuthorizationIdentityResponseControl.get(bindResult);
assertNotNull(authzIDResponse);
authzID = authzIDResponse.getAuthorizationID();
assertNotNull(authzID);
assertTrue(authzID.startsWith("dn:"));
assertEquals(new DN(authzID.substring(3)), new DN("uid=test.user,ou=People,dc=example,dc=com"));
// Test with a DN-style authID that is an additional bind user.
bindRequest = new PLAINBindRequest("dn:cn=Directory Manager", "password", new AuthorizationIdentityRequestControl());
bindResult = conn.bind(bindRequest);
assertEquals(bindResult.getResultCode(), ResultCode.SUCCESS);
authzIDResponse = AuthorizationIdentityResponseControl.get(bindResult);
assertNotNull(authzIDResponse);
authzID = authzIDResponse.getAuthorizationID();
assertNotNull(authzID);
assertTrue(authzID.startsWith("dn:"));
assertEquals(new DN(authzID.substring(3)), new DN("cn=Directory Manager"));
// Test with a u-style authID and an authzID that is an additional bind
// user.
bindRequest = new PLAINBindRequest("u:test.user", "dn:cn=Directory Manager", "password", new AuthorizationIdentityRequestControl());
bindResult = conn.bind(bindRequest);
assertEquals(bindResult.getResultCode(), ResultCode.SUCCESS);
authzIDResponse = AuthorizationIdentityResponseControl.get(bindResult);
assertNotNull(authzIDResponse);
authzID = authzIDResponse.getAuthorizationID();
assertNotNull(authzID);
assertTrue(authzID.startsWith("dn:"));
assertEquals(new DN(authzID.substring(3)), new DN("cn=Directory Manager"));
// Test a bind as a nonexistent dn-style authentication ID.
bindRequest = new PLAINBindRequest("dn:cn=missing", "password");
try {
bindResult = conn.bind(bindRequest);
fail("Expected an exception when trying to bind with a nonexistent " + "dn-style authentication ID");
} catch (final LDAPException le) {
assertEquals(le.getResultCode(), ResultCode.INVALID_CREDENTIALS);
}
// Test a bind as a nonexistent u-style authentication ID.
bindRequest = new PLAINBindRequest("u:missing", "password");
try {
bindResult = conn.bind(bindRequest);
fail("Expected an exception when trying to bind with a nonexistent " + "u-style authentication ID");
} catch (final LDAPException le) {
assertEquals(le.getResultCode(), ResultCode.INVALID_CREDENTIALS);
}
// Test a bind as a nonexistent dn-style authorization ID.
bindRequest = new PLAINBindRequest("dn:cn=Directory Manager", "dn:cn=missing", "password");
try {
bindResult = conn.bind(bindRequest);
fail("Expected an exception when trying to bind with a nonexistent " + "authorization ID");
} catch (final LDAPException le) {
assertEquals(le.getResultCode(), ResultCode.INVALID_CREDENTIALS);
}
// Test a bind with an incorrect password.
bindRequest = new PLAINBindRequest("u:test.user", "wrong");
try {
bindResult = conn.bind(bindRequest);
fail("Expected an exception when trying to bind anonymously with an " + "authorization ID");
} catch (final LDAPException le) {
assertEquals(le.getResultCode(), ResultCode.INVALID_CREDENTIALS);
}
// Test a bind with an unsupported critical control.
bindRequest = new PLAINBindRequest("u:test.user", "wrong", new Control("1.2.3.4", true));
try {
bindResult = conn.bind(bindRequest);
fail("Expected an exception when trying to bind anonymously with an " + "authorization ID");
} catch (final LDAPException le) {
assertEquals(le.getResultCode(), ResultCode.UNAVAILABLE_CRITICAL_EXTENSION);
}
final Control[] unbindControls = { new Control("1.2.3.4", false), new Control("1.2.3.5", false, new ASN1OctetString("foo")) };
conn.close(unbindControls);
}
use of com.unboundid.ldap.sdk.PLAINBindRequest in project ldapsdk by pingidentity.
the class InMemoryDirectoryServerTestCase method testAuthenticationRequiredOperationTypes.
/**
* Provides a set of test cases that cover the ability to process operations
* on unauthenticated connections when authentication is required.
*
* Provides a set of test cases to that operations are properly rejected if
* they are not allowed.
*
* @throws Exception If an unexpected problem occurs.
*/
@Test()
public void testAuthenticationRequiredOperationTypes() throws Exception {
final InMemoryDirectoryServerConfig cfg = new InMemoryDirectoryServerConfig("dc=example,dc=com");
cfg.setAuthenticationRequiredOperationTypes(EnumSet.allOf(OperationType.class));
cfg.addAdditionalBindCredentials("cn=Directory Manager", "password");
cfg.setCodeLogDetails(createTempFile().getAbsolutePath(), true);
final InMemoryDirectoryServer ds = new InMemoryDirectoryServer(cfg);
ds.startListening();
final LDAPConnection unauthenticatedConn = ds.getConnection();
try {
// Ensure that an anonymous simple bind is not allowed.
unauthenticatedConn.bind("", "");
fail("Expected an anonymous simple bind to fail when authentication is " + "required for bind operations");
} catch (final LDAPException le) {
assertResultCodeEquals(le, ResultCode.INVALID_CREDENTIALS);
}
try {
// Ensure that an anonymous SASL bind is not allowed.
unauthenticatedConn.bind(new PLAINBindRequest("dn:", ""));
fail("Expected an anonymous PLAIN bind to fail when authentication is " + "required for bind operations");
} catch (final LDAPException le) {
assertResultCodeEquals(le, ResultCode.INVALID_CREDENTIALS);
}
final LDAPConnection authenticatedConn = ds.getConnection();
authenticatedConn.bind("cn=Directory Manager", "password");
try {
unauthenticatedConn.add("dn: dc=example,dc=com", "objectClass: top", "objectClass: domain", "dc: example");
} catch (final LDAPException le) {
assertEquals(le.getResultCode(), ResultCode.INSUFFICIENT_ACCESS_RIGHTS);
}
authenticatedConn.add("dn: dc=example,dc=com", "objectClass: top", "objectClass: domain", "dc: example");
ds.add("dn: ou=People,dc=example,dc=com", "objectClass: top", "objectClass: organizationalUnit", "ou: People");
try {
unauthenticatedConn.compare("dc=example,dc=com", "dc", "example");
} catch (final LDAPException le) {
assertEquals(le.getResultCode(), ResultCode.INSUFFICIENT_ACCESS_RIGHTS);
}
assertTrue(authenticatedConn.compare("dc=example,dc=com", "dc", "example").compareMatched());
assertTrue(ds.compare("dc=example,dc=com", "dc", "example").compareMatched());
try {
unauthenticatedConn.processExtendedOperation(new WhoAmIExtendedRequest());
} catch (final LDAPException le) {
assertEquals(le.getResultCode(), ResultCode.INSUFFICIENT_ACCESS_RIGHTS);
}
assertEquals(authenticatedConn.processExtendedOperation(new WhoAmIExtendedRequest()).getResultCode(), ResultCode.SUCCESS);
assertEquals(ds.processExtendedOperation(new WhoAmIExtendedRequest()).getResultCode(), ResultCode.SUCCESS);
try {
unauthenticatedConn.modify("dn: dc=example,dc=com", "changetype: modify", "replace: description", "description: foo");
} catch (final LDAPException le) {
assertEquals(le.getResultCode(), ResultCode.INSUFFICIENT_ACCESS_RIGHTS);
}
authenticatedConn.modify("dn: dc=example,dc=com", "changetype: modify", "replace: description", "description: foo");
ds.modify("dn: dc=example,dc=com", "changetype: modify", "replace: description", "description: bar");
try {
unauthenticatedConn.modifyDN("ou=People,dc=example,dc=com", "ou=Users", true);
} catch (final LDAPException le) {
assertEquals(le.getResultCode(), ResultCode.INSUFFICIENT_ACCESS_RIGHTS);
}
authenticatedConn.modifyDN("ou=People,dc=example,dc=com", "ou=Users", true);
ds.modifyDN("ou=Users,dc=example,dc=com", "ou=Persons", true);
try {
unauthenticatedConn.search("dc=example,dc=com", SearchScope.BASE, "(objectClass=*)");
} catch (final LDAPException le) {
assertEquals(le.getResultCode(), ResultCode.INSUFFICIENT_ACCESS_RIGHTS);
}
authenticatedConn.search("dc=example,dc=com", SearchScope.BASE, "(objectClass=*)");
ds.search("dc=example,dc=com", SearchScope.BASE, "(objectClass=*)");
try {
unauthenticatedConn.delete("ou=Persons,dc=example,dc=com");
} catch (final LDAPException le) {
assertEquals(le.getResultCode(), ResultCode.INSUFFICIENT_ACCESS_RIGHTS);
}
authenticatedConn.delete("ou=Persons,dc=example,dc=com");
ds.delete("dc=example,dc=com");
authenticatedConn.close();
unauthenticatedConn.close();
ds.shutDown(true);
}
use of com.unboundid.ldap.sdk.PLAINBindRequest in project ldapsdk by pingidentity.
the class InMemoryDirectoryServerPasswordEncodingTestCase method testOnlySecondaryEncoders.
/**
* Tests the behavior for the case in which the server is only configured with
* secondary password encoders but no primary encoder.
*
* @throws Exception If an unexpected problem occurs.
*/
@Test()
public void testOnlySecondaryEncoders() throws Exception {
// Create an in-memory directory server instance with support for a lot of
// password encoders.
final InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig("dc=example,dc=com");
final MessageDigest sha1Digest = CryptoHelper.getMessageDigest("SHA-1");
config.setPasswordEncoders(null, new ClearInMemoryPasswordEncoder("{CLEAR}", null), new ClearInMemoryPasswordEncoder("{HEX}", HexPasswordEncoderOutputFormatter.getLowercaseInstance()), new ClearInMemoryPasswordEncoder("{BASE64}", Base64PasswordEncoderOutputFormatter.getInstance()), new UnsaltedMessageDigestInMemoryPasswordEncoder("{SHA}", Base64PasswordEncoderOutputFormatter.getInstance(), sha1Digest));
assertNotNull(config.getPasswordAttributes());
assertFalse(config.getPasswordAttributes().isEmpty());
assertEquals(config.getPasswordAttributes(), Collections.singleton("userPassword"));
assertNull(config.getPrimaryPasswordEncoder());
assertNotNull(config.getSecondaryPasswordEncoders());
assertFalse(config.getSecondaryPasswordEncoders().isEmpty());
assertNotNull(config.toString());
final InMemoryDirectoryServer ds = new InMemoryDirectoryServer(config);
ds.startListening();
// Add some base entries to the server.
final LDAPConnection conn = ds.getConnection();
conn.add("dn: dc=example,dc=com", "objectClass: top", "objectClass: domain", "dc: example");
conn.add("dn: ou=People,dc=example,dc=com", "objectClass: top", "objectClass: organizationalUnit", "ou: People");
// Add an entry with a userPassword value in the clear. Make sure that it
// remains in the clear and that we can use it to bind.
conn.add("dn: uid=test.unencoded,ou=People,dc=example,dc=com", "objectClass: top", "objectClass: person", "objectClass: organizationalPerson", "objectClass: inetOrgPerson", "uid: test.unencoded", "givenName: Test", "sn: Unencoded", "cn: Test Unencoded", "userPassword: password");
assertEquals(ds.getEntry("uid=test.unencoded,ou=People,dc=example,dc=com", "userPassword").getAttributeValue("userPassword"), "password");
assertResultCodeEquals(conn, new SimpleBindRequest("uid=test.unencoded,ou=People,dc=example,dc=com", "password"), ResultCode.SUCCESS);
assertResultCodeEquals(conn, new PLAINBindRequest("dn:uid=test.unencoded,ou=People,dc=example,dc=com", "password"), ResultCode.SUCCESS);
// Add an entry with a pre-encoded userPassword value. Make sure that it
// stays pre-encoded and that we can also use it to bind.
final String hexPassword = "{HEX}" + StaticUtils.toHex(StaticUtils.getBytes("password"));
conn.add("dn: uid=test.encoded,ou=People,dc=example,dc=com", "objectClass: top", "objectClass: person", "objectClass: organizationalPerson", "objectClass: inetOrgPerson", "uid: test.encoded", "givenName: Test", "sn: Encoded", "cn: Test Encoded", "userPassword: " + hexPassword);
assertEquals(ds.getEntry("uid=test.encoded,ou=People,dc=example,dc=com", "userPassword").getAttributeValue("userPassword"), hexPassword);
assertResultCodeEquals(conn, new SimpleBindRequest("uid=test.encoded,ou=People,dc=example,dc=com", "password"), ResultCode.SUCCESS);
assertResultCodeEquals(conn, new PLAINBindRequest("dn:uid=test.encoded,ou=People,dc=example,dc=com", "password"), ResultCode.SUCCESS);
// Modify the entry with the unencoded password to use a different unencoded
// password. Verify that it is updated properly and the new password can
// be used.
conn.modify("dn: uid=test.unencoded,ou=People,dc=example,dc=com", "changetype: modify", "delete: userPassword", "userPassword: password", "-", "add: userPassword", "userPassword: newPassword");
assertEquals(ds.getEntry("uid=test.unencoded,ou=People,dc=example,dc=com", "userPassword").getAttributeValue("userPassword"), "newPassword");
assertResultCodeEquals(conn, new SimpleBindRequest("uid=test.unencoded,ou=People,dc=example,dc=com", "newPassword"), ResultCode.SUCCESS);
assertResultCodeEquals(conn, new PLAINBindRequest("dn:uid=test.unencoded,ou=People,dc=example,dc=com", "newPassword"), ResultCode.SUCCESS);
// Modify the entry with the encoded password to use a different encoded
// password. Verify that it is updated properly and the new password can
// be used.
final String hexNewPassword = "{HEX}" + StaticUtils.toHex(StaticUtils.getBytes("newPassword"));
conn.modify("dn: uid=test.encoded,ou=People,dc=example,dc=com", "changetype: modify", "delete: userPassword", "userPassword: " + hexPassword, "-", "add: userPassword", "userPassword: " + hexNewPassword);
assertEquals(ds.getEntry("uid=test.encoded,ou=People,dc=example,dc=com", "userPassword").getAttributeValue("userPassword"), hexNewPassword);
assertResultCodeEquals(conn, new SimpleBindRequest("uid=test.encoded,ou=People,dc=example,dc=com", "newPassword"), ResultCode.SUCCESS);
assertResultCodeEquals(conn, new PLAINBindRequest("dn:uid=test.encoded,ou=People,dc=example,dc=com", "newPassword"), ResultCode.SUCCESS);
conn.close();
ds.shutDown(true);
}
Aggregations