mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

lutoff
04.48.2007 d4a7fd6fa94a8f357092200e9f32926ea7f2126e
Fix for issue #1830 (dsconfig: add support for secure connections)
Standard secure args are now part of dsconfig CLI.

it' also include the following dsconfig interface changes:

use -z instead of -Z for --unit-size short option
use -m instead of -M for --unit-time short option (consistency with --unit-size short option)
2 files added
7 files modified
2360 ■■■■ changed files
opends/src/guitools/org/opends/guitools/replicationcli/ReplicationCliArgumentParser.java 41 ●●●● patch | view | raw | blame | history
opends/src/guitools/org/opends/guitools/statuspanel/StatusCliArgumentParser.java 10 ●●●● patch | view | raw | blame | history
opends/src/guitools/org/opends/guitools/uninstaller/UninstallerArgumentParser.java 8 ●●●● patch | view | raw | blame | history
opends/src/messages/messages/dsconfig.properties 11 ●●●●● patch | view | raw | blame | history
opends/src/server/org/opends/server/admin/client/cli/SecureConnectionCliArgs.java 779 ●●●●● patch | view | raw | blame | history
opends/src/server/org/opends/server/admin/client/cli/SecureConnectionCliParser.java 449 ●●●●● patch | view | raw | blame | history
opends/src/server/org/opends/server/tools/dsconfig/LDAPManagementContextFactory.java 737 ●●●● patch | view | raw | blame | history
opends/src/server/org/opends/server/tools/dsconfig/SubCommandHandler.java 4 ●●●● patch | view | raw | blame | history
opends/tests/unit-tests-testng/src/server/org/opends/server/tools/dsconfig/DsconfigLdapConnectionTestCase.java 321 ●●●●● patch | view | raw | blame | history
opends/src/guitools/org/opends/guitools/replicationcli/ReplicationCliArgumentParser.java
@@ -353,13 +353,13 @@
      new ArrayList<Argument>(createGlobalArguments(outStream));
    Argument[] argsToRemove = {
      hostNameArg,
      portArg,
      bindDnArg,
      bindPasswordFileArg,
      bindPasswordArg,
      useSSLArg,
      useStartTLSArg
      secureArgsList.hostNameArg,
      secureArgsList.portArg,
      secureArgsList.bindDnArg,
      secureArgsList.bindPasswordFileArg,
      secureArgsList.bindPasswordArg,
      secureArgsList.useSSLArg,
      secureArgsList.useStartTLSArg
    };
    for (int i=0; i<argsToRemove.length; i++)
@@ -518,14 +518,13 @@
    disableReplicationSubCmd = new SubCommand(this,
        DISABLE_REPLICATION_SUBCMD_NAME,
        INFO_DESCRIPTION_SUBCMD_DISABLE_REPLICATION.get());
    bindDnArg = new StringArgument("bindDN", OPTION_SHORT_BINDDN,
    secureArgsList.bindDnArg = new StringArgument("bindDN", OPTION_SHORT_BINDDN,
        OPTION_LONG_BINDDN, false, false, true, OPTION_VALUE_BINDDN,
        "cn=Directory Manager", null,
        INFO_DESCRIPTION_DISABLE_REPLICATION_BINDDN.get());
    Argument[] argsToAdd = {
        hostNameArg, portArg,
        useSSLArg, useStartTLSArg, bindDnArg
    };
    Argument[] argsToAdd = { secureArgsList.hostNameArg,
        secureArgsList.portArg, secureArgsList.useSSLArg,
        secureArgsList.useStartTLSArg, secureArgsList.bindDnArg };
    for (int i=0; i<argsToAdd.length; i++)
    {
      disableReplicationSubCmd.addArgument(argsToAdd[i]);
@@ -825,7 +824,7 @@
   */
  public boolean useSSLToDisable()
  {
    return useSSLArg.isPresent();
    return secureArgsList.useSSLArg.isPresent();
  }
  /**
@@ -837,7 +836,7 @@
   */
  public boolean useStartTLSToDisable()
  {
    return useStartTLSArg.isPresent();
    return secureArgsList.useStartTLSArg.isPresent();
  }
  /**
@@ -1054,7 +1053,7 @@
   */
  public String getHostNameToDisable()
  {
    return getValue(hostNameArg);
    return getValue(secureArgsList.hostNameArg);
  }
  /**
@@ -1065,7 +1064,7 @@
   */
  public String getDefaultHostNameToDisable()
  {
    return getDefaultValue(hostNameArg);
    return getDefaultValue(secureArgsList.hostNameArg);
  }
  /**
@@ -1076,7 +1075,7 @@
   */
  public String getBindDNToDisable()
  {
    return getValue(bindDnArg);
    return getValue(secureArgsList.bindDnArg);
  }
  /**
@@ -1087,7 +1086,7 @@
   */
  public String getDefaultBindDnToDisable()
  {
    return getDefaultValue(bindDnArg);
    return getDefaultValue(secureArgsList.bindDnArg);
  }
  /**
@@ -1186,7 +1185,7 @@
   */
  public int getPortToDisable()
  {
    return getValue(portArg);
    return getValue(secureArgsList.portArg);
  }
  /**
@@ -1197,7 +1196,7 @@
   */
  public int getDefaultPortToDisable()
  {
    return getDefaultValue(portArg);
    return getDefaultValue(secureArgsList.portArg);
  }
  /**
@@ -1424,7 +1423,7 @@
    {
        {useStartTLSSourceArg, useSSLSourceArg},
        {useStartTLSDestinationArg, useSSLDestinationArg},
        {adminUidArg, bindDnArg}
        {adminUidArg, secureArgsList.bindDnArg}
    };
    for (int i=0; i< conflictingPairs.length; i++)
opends/src/guitools/org/opends/guitools/statuspanel/StatusCliArgumentParser.java
@@ -75,8 +75,8 @@
  {
    ArrayList<Argument> defaultArgs =
      new ArrayList<Argument>(createGlobalArguments(outStream));
    defaultArgs.remove(portArg);
    defaultArgs.remove(hostNameArg);
    defaultArgs.remove(secureArgsList.portArg);
    defaultArgs.remove(secureArgsList.hostNameArg);
    defaultArgs.remove(verboseArg);
    noPromptArg = new BooleanArgument(
        ToolConstants.OPTION_LONG_NO_PROMPT,
@@ -107,9 +107,9 @@
  public String getExplicitBindDn()
  {
    String dn = null;
    if (bindDnArg.isPresent())
    if (secureArgsList.bindDnArg.isPresent())
    {
      dn = bindDnArg.getValue();
      dn = secureArgsList.bindDnArg.getValue();
    }
    return dn;
  }
@@ -122,6 +122,6 @@
   */
  public String getDefaultBindDn()
  {
    return bindDnArg.getDefaultValue();
    return secureArgsList.bindDnArg.getDefaultValue();
  }
}
opends/src/guitools/org/opends/guitools/uninstaller/UninstallerArgumentParser.java
@@ -178,18 +178,18 @@
    ArrayList<Argument> defaultArgs =
      new ArrayList<Argument>(createGlobalArguments(System.err));
    int index = defaultArgs.indexOf(bindDnArg);
    int index = defaultArgs.indexOf(secureArgsList.bindDnArg);
    if (index != -1)
    {
      defaultArgs.add(index, adminUidArg);
      defaultArgs.remove(bindDnArg);
      defaultArgs.remove(secureArgsList.bindDnArg);
    }
    else
    {
      defaultArgs.add(adminUidArg);
    }
    defaultArgs.remove(hostNameArg);
    defaultArgs.remove(portArg);
    defaultArgs.remove(secureArgsList.hostNameArg);
    defaultArgs.remove(secureArgsList.portArg);
    defaultArgs.remove(verboseArg);
    UserData uData = new UserData();
    referencedHostNameArg = new StringArgument("referencedHostName",
opends/src/messages/messages/dsconfig.properties
@@ -402,4 +402,13 @@
SEVERE_ERR_DSCFG_BAD_PORT_NUMBER_1371=Invalid port number "%s". Please enter a valid port number between 1 and 65535
INFO_DSCFG_GENERIC_TYPE_OPTION_1372=Generic %s
INFO_DSCFG_HEADING_CONNECTION_PARAMETERS_1373=>>>> Specify OpenDS LDAP connection parameters
INFO_DSCFG_PROMPT_SECURITY_USE_SECURE_CTX_1374=Do you want a secure connection?
INFO_DSCFG_PROMPT_SECURITY_USE_SSL_1375=SSL
INFO_DSCFG_PROMPT_SECURITY_USE_START_TSL_1376=StartTSL
INFO_DSCFG_PROMPT_SECURITY_USE_TRUST_ALL_1377=Do you want to trust any server certificates (trustALL)?
INFO_DSCFG_PROMPT_SECURITY_TRUSTSTORE_PATH_1378=Truststore path:
INFO_DSCFG_PROMPT_SECURITY_TRUSTSTORE_PASSWORD_1379=Password for truststore '%s':
INFO_DSCFG_PROMPT_SECURITY_KEYSTORE_NEEDED_1380=Do you want to perform secure authentication (client side authentication)?
INFO_DSCFG_PROMPT_SECURITY_KEYSTORE_PATH_1381=Keystore path:
INFO_DSCFG_PROMPT_SECURITY_KEYSTORE_PASSWORD_1382=Password for keystore '%s':
INFO_DSCFG_PROMPT_SECURITY_CERTIFICATE_NAME_1383=Certificate nickname:
opends/src/server/org/opends/server/admin/client/cli/SecureConnectionCliArgs.java
New file
@@ -0,0 +1,779 @@
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at
 * trunk/opends/resource/legal-notices/OpenDS.LICENSE
 * or https://OpenDS.dev.java.net/OpenDS.LICENSE.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at
 * trunk/opends/resource/legal-notices/OpenDS.LICENSE.  If applicable,
 * add the following below this CDDL HEADER, with the fields enclosed
 * by brackets "[]" replaced with your own identifying information:
 *      Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 *
 *
 *      Portions Copyright 2007 Sun Microsystems, Inc.
 */
package org.opends.server.admin.client.cli;
import static org.opends.server.admin.client.cli.DsFrameworkCliReturnCode.*;
import static org.opends.server.loggers.debug.DebugLogger.debugEnabled;
import static org.opends.server.loggers.debug.DebugLogger.getTracer;
import static org.opends.messages.ToolMessages.*;
import org.opends.messages.Message;
import org.opends.messages.MessageBuilder;
import static org.opends.server.tools.ToolConstants.*;
import static org.opends.server.util.ServerConstants.MAX_LINE_WIDTH;
import static org.opends.server.util.StaticUtils.wrapText;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.KeyManager;
import org.opends.admin.ads.util.ApplicationKeyManager;
import org.opends.admin.ads.util.ApplicationTrustManager;
import org.opends.server.loggers.debug.DebugTracer;
import org.opends.server.types.DebugLogLevel;
import org.opends.server.util.PasswordReader;
import org.opends.server.util.SelectableCertificateKeyManager;
import org.opends.server.util.args.Argument;
import org.opends.server.util.args.ArgumentException;
import org.opends.server.util.args.BooleanArgument;
import org.opends.server.util.args.FileBasedArgument;
import org.opends.server.util.args.IntegerArgument;
import org.opends.server.util.args.StringArgument;
/**
 * This is a commodity class that can be used to check the arguments required
 * to establish a secure connection in the command line.  It can be used
 * to generate an ApplicationTrustManager object based on the options provided
 * by the user in the command line.
 *
 */
public final class SecureConnectionCliArgs
{
  /**
   * The 'hostName' global argument.
   */
  public StringArgument hostNameArg = null;
  /**
   * The 'port' global argument.
   */
  public IntegerArgument portArg = null;
  /**
   * The 'binDN' global argument.
   */
  public StringArgument bindDnArg = null;
  /**
   * The 'bindPasswordFile' global argument.
   */
  public FileBasedArgument bindPasswordFileArg = null;
  /**
   * The 'bindPassword' global argument.
   */
  public StringArgument bindPasswordArg = null;
  /**
   * The 'trustAllArg' global argument.
   */
  public BooleanArgument trustAllArg = null;
  /**
   * The 'trustStore' global argument.
   */
  public StringArgument trustStorePathArg = null;
  /**
   * The 'trustStorePassword' global argument.
   */
  public StringArgument trustStorePasswordArg = null;
  /**
   * The 'trustStorePasswordFile' global argument.
   */
  public FileBasedArgument trustStorePasswordFileArg = null;
  /**
   * The 'keyStore' global argument.
   */
  public StringArgument keyStorePathArg = null;
  /**
   * The 'keyStorePassword' global argument.
   */
  public StringArgument keyStorePasswordArg = null;
  /**
   * The 'keyStorePasswordFile' global argument.
   */
  public FileBasedArgument keyStorePasswordFileArg = null;
  /**
   * The 'certNicknameArg' global argument.
   */
  public StringArgument certNicknameArg = null;
  /**
   * The 'useSSLArg' global argument.
   */
  public BooleanArgument useSSLArg = null;
  /**
   * The 'useStartTLSArg' global argument.
   */
  public BooleanArgument useStartTLSArg = null;
  // the trust manager.
  private ApplicationTrustManager trustManager;
  /**
   * The tracer object for the debug logger.
   */
  private static final DebugTracer TRACER = getTracer();
  /**
   * End Of Line.
   */
  public static String EOL = System.getProperty("line.separator");
  /**
   * The Logger.
   */
  static private final Logger LOG =
    Logger.getLogger(SecureConnectionCliArgs.class.getName());
  /**
   * Creates a new instance of secure arguments.
   */
  public SecureConnectionCliArgs()
  {
  }
  /**
   * Get the bindDN which has to be used for the command.
   *
   * @return The bindDN specified by the command line argument, or the
   *         default value, if not specified.
   */
  public String getBindDN()
  {
    if (bindDnArg.isPresent())
    {
      return bindDnArg.getValue();
    }
    else
    {
      return bindDnArg.getDefaultValue();
    }
  }
  /**
   * Get the password which has to be used for the command.
   *
   * @param dn
   *          The user DN for which to password could be asked.
   * @param out
   *          The input stream to used if we have to prompt to the
   *          user.
   * @param err
   *          The error stream to used if we have to prompt to the
   *          user.
   * @param clearArg
   *          The password StringArgument argument.
   * @param fileArg
   *          The password FileBased argument.
   * @return The password stored into the specified file on by the
   *         command line argument, or prompts it if not specified.
   */
  public String getBindPassword(String dn,
      OutputStream out, OutputStream err, StringArgument clearArg,
      FileBasedArgument fileArg)
  {
    if (clearArg.isPresent())
    {
      String bindPasswordValue = clearArg.getValue();
      if(bindPasswordValue != null && bindPasswordValue.equals("-"))
      {
        // read the password from the stdin.
        try
        {
          out.write(INFO_LDAPAUTH_PASSWORD_PROMPT.get(dn).getBytes());
          out.flush();
          char[] pwChars = PasswordReader.readPassword();
          bindPasswordValue = new String(pwChars);
        } catch(Exception ex)
        {
          if (debugEnabled())
          {
            TRACER.debugCaught(DebugLogLevel.ERROR, ex);
          }
          try
          {
            err.write(wrapText(ex.getMessage(), MAX_LINE_WIDTH).getBytes());
            err.write(EOL.getBytes());
          }
          catch (IOException e)
          {
          }
          return null;
        }
      }
      return bindPasswordValue;
    }
    else
    if (fileArg.isPresent())
    {
      return fileArg.getValue();
    }
    else
    {
      // read the password from the stdin.
      try
      {
        out.write(INFO_LDAPAUTH_PASSWORD_PROMPT.get(dn).toString().getBytes());
        out.flush();
        char[] pwChars = PasswordReader.readPassword();
        return new String(pwChars);
      }
      catch (Exception ex)
      {
        if (debugEnabled())
        {
          TRACER.debugCaught(DebugLogLevel.ERROR, ex);
        }
        try
        {
          err.write(wrapText(ex.getMessage(), MAX_LINE_WIDTH).getBytes());
          err.write(EOL.getBytes());
        }
        catch (IOException e)
        {
        }
        return null;
      }
    }
  }
  /**
   * Get the password which has to be used for the command.
   *
   * @param dn
   *          The user DN for which to password could be asked.
   * @param out
   *          The input stream to used if we have to prompt to the
   *          user.
   * @param err
   *          The error stream to used if we have to prompt to the
   *          user.
   * @return The password stored into the specified file on by the
   *         command line argument, or prompts it if not specified.
   */
  public String getBindPassword(String dn, OutputStream out, OutputStream err)
  {
    return getBindPassword(dn, out, err, bindPasswordArg, bindPasswordFileArg);
  }
  /**
   * Get the password which has to be used for the command without prompting
   * the user.  If no password was specified, return null.
   *
   * @param clearArg
   *          The password StringArgument argument.
   * @param fileArg
   *          The password FileBased argument.
   * @return The password stored into the specified file on by the
   *         command line argument, or null it if not specified.
   */
  public String getBindPassword(StringArgument clearArg,
      FileBasedArgument fileArg)
  {
    String pwd;
    if (clearArg.isPresent())
    {
      pwd = clearArg.getValue();
    }
    else
    if (fileArg.isPresent())
    {
      pwd = fileArg.getValue();
    }
    else
    {
      pwd = null;
    }
    return pwd;
  }
  /**
   * Get the password which has to be used for the command without prompting
   * the user.  If no password was specified, return null.
   *
   * @return The password stored into the specified file on by the
   *         command line argument, or null it if not specified.
   */
  public String getBindPassword()
  {
    return getBindPassword(bindPasswordArg, bindPasswordFileArg);
  }
  /**
   * Initialize Global option.
   *
   * @throws ArgumentException
   *           If there is a problem with any of the parameters used
   *           to create this argument.
   * @return a ArrayList with the options created.
   */
  public LinkedHashSet<Argument> createGlobalArguments()
  throws ArgumentException
  {
    LinkedHashSet<Argument> set = new LinkedHashSet<Argument>();
    useSSLArg = new BooleanArgument("useSSL", OPTION_SHORT_USE_SSL,
        OPTION_LONG_USE_SSL, INFO_DESCRIPTION_USE_SSL.get());
    set.add(useSSLArg);
    useStartTLSArg = new BooleanArgument("startTLS", OPTION_SHORT_START_TLS,
        OPTION_LONG_START_TLS,
        INFO_DESCRIPTION_START_TLS.get());
    set.add(useStartTLSArg);
    hostNameArg = new StringArgument("host", OPTION_SHORT_HOST,
        OPTION_LONG_HOST, false, false, true, OPTION_VALUE_HOST, "localhost",
        null, INFO_DESCRIPTION_HOST.get());
    set.add(hostNameArg);
    portArg = new IntegerArgument("port", OPTION_SHORT_PORT, OPTION_LONG_PORT,
        false, false, true, OPTION_VALUE_PORT, 389, null,
        INFO_DESCRIPTION_PORT.get());
    set.add(portArg);
    bindDnArg = new StringArgument("bindDN", OPTION_SHORT_BINDDN,
        OPTION_LONG_BINDDN, false, false, true, OPTION_VALUE_BINDDN,
        "cn=Directory Manager", null, INFO_DESCRIPTION_BINDDN.get());
    set.add(bindDnArg);
    bindPasswordArg = new StringArgument("bindPassword",
        OPTION_SHORT_BINDPWD, OPTION_LONG_BINDPWD, false, false, true,
        OPTION_VALUE_BINDPWD, null, null, INFO_DESCRIPTION_BINDPASSWORD.get());
    set.add(bindPasswordArg);
    bindPasswordFileArg = new FileBasedArgument("bindPasswordFile",
        OPTION_SHORT_BINDPWD_FILE, OPTION_LONG_BINDPWD_FILE, false, false,
        OPTION_VALUE_BINDPWD_FILE, null, null,
        INFO_DESCRIPTION_BINDPASSWORDFILE.get());
    set.add(bindPasswordFileArg);
    trustAllArg = new BooleanArgument("trustAll", OPTION_SHORT_TRUSTALL,
        OPTION_LONG_TRUSTALL, INFO_DESCRIPTION_TRUSTALL.get());
    set.add(trustAllArg);
    trustStorePathArg = new StringArgument("trustStorePath",
        OPTION_SHORT_TRUSTSTOREPATH, OPTION_LONG_TRUSTSTOREPATH, false,
        false, true, OPTION_VALUE_TRUSTSTOREPATH, null, null,
        INFO_DESCRIPTION_TRUSTSTOREPATH.get());
    set.add(trustStorePathArg);
    trustStorePasswordArg = new StringArgument("trustStorePassword",
        OPTION_SHORT_TRUSTSTORE_PWD, OPTION_LONG_TRUSTSTORE_PWD, false, false,
        true, OPTION_VALUE_TRUSTSTORE_PWD, null, null,
        INFO_DESCRIPTION_TRUSTSTOREPASSWORD.get());
    set.add(trustStorePasswordArg);
    trustStorePasswordFileArg = new FileBasedArgument("trustStorePasswordFile",
        OPTION_SHORT_TRUSTSTORE_PWD_FILE, OPTION_LONG_TRUSTSTORE_PWD_FILE,
        false, false, OPTION_VALUE_TRUSTSTORE_PWD_FILE, null, null,
        INFO_DESCRIPTION_TRUSTSTOREPASSWORD_FILE.get());
    set.add(trustStorePasswordFileArg);
    keyStorePathArg = new StringArgument("keyStorePath",
        OPTION_SHORT_KEYSTOREPATH, OPTION_LONG_KEYSTOREPATH, false, false,
        true, OPTION_VALUE_KEYSTOREPATH, null, null,
        INFO_DESCRIPTION_KEYSTOREPATH.get());
    set.add(keyStorePathArg);
    keyStorePasswordArg = new StringArgument("keyStorePassword",
        OPTION_SHORT_KEYSTORE_PWD,
        OPTION_LONG_KEYSTORE_PWD, false, false, true,
        OPTION_VALUE_KEYSTORE_PWD, null, null,
        INFO_DESCRIPTION_KEYSTOREPASSWORD.get());
    set.add(keyStorePasswordArg);
    keyStorePasswordFileArg = new FileBasedArgument("keystorePasswordFile",
        OPTION_SHORT_KEYSTORE_PWD_FILE, OPTION_LONG_KEYSTORE_PWD_FILE, false,
        false, OPTION_VALUE_KEYSTORE_PWD_FILE, null, null,
        INFO_DESCRIPTION_KEYSTOREPASSWORD_FILE.get());
    set.add(keyStorePasswordFileArg);
    certNicknameArg = new StringArgument("certNickname",
        OPTION_SHORT_CERT_NICKNAME, OPTION_LONG_CERT_NICKNAME,
        false, false, true, OPTION_VALUE_CERT_NICKNAME, null, null,
        INFO_DESCRIPTION_CERT_NICKNAME.get());
    set.add(certNicknameArg);
    return set;
  }
  /**
   * Get the host name which has to be used for the command.
   *
   * @return The host name specified by the command line argument, or
   *         the default value, if not specified.
   */
  public String getHostName()
  {
    if (hostNameArg.isPresent())
    {
      return hostNameArg.getValue();
    }
    else
    {
      return hostNameArg.getDefaultValue();
    }
  }
  /**
   * Get the port which has to be used for the command.
   *
   * @return The port specified by the command line argument, or the
   *         default value, if not specified.
   */
  public String getPort()
  {
    if (portArg.isPresent())
    {
      return portArg.getValue();
    }
    else
    {
      return portArg.getDefaultValue();
    }
  }
  /**
   * Indication if provided global options are validate.
   *
   * @param buf the MessageBuilder to write the error messages.
   * @return return code.
   */
  public int validateGlobalOptions(MessageBuilder buf)
  {
    ArrayList<Message> errors = new ArrayList<Message>();
    // Couldn't have at the same time bindPassword and bindPasswordFile
    if (bindPasswordArg.isPresent() && bindPasswordFileArg.isPresent()) {
      Message message = ERR_TOOL_CONFLICTING_ARGS.get(
              bindPasswordArg.getLongIdentifier(),
              bindPasswordFileArg.getLongIdentifier());
      errors.add(message);
    }
    // Couldn't have at the same time trustAll and
    // trustStore related arg
    if (trustAllArg.isPresent() && trustStorePathArg.isPresent()) {
      Message message = ERR_TOOL_CONFLICTING_ARGS.get(
              trustAllArg.getLongIdentifier(),
              trustStorePathArg.getLongIdentifier());
      errors.add(message);
    }
    if (trustAllArg.isPresent() && trustStorePasswordArg.isPresent()) {
      Message message = ERR_TOOL_CONFLICTING_ARGS.get(
              trustAllArg.getLongIdentifier(),
              trustStorePasswordArg.getLongIdentifier());
      errors.add(message);
    }
    if (trustAllArg.isPresent() && trustStorePasswordFileArg.isPresent()) {
      Message message = ERR_TOOL_CONFLICTING_ARGS.get(
              trustAllArg.getLongIdentifier(),
              trustStorePasswordFileArg.getLongIdentifier());
      errors.add(message);
    }
    // Couldn't have at the same time trustStorePasswordArg and
    // trustStorePasswordFileArg
    if (trustStorePasswordArg.isPresent()
            && trustStorePasswordFileArg.isPresent()) {
      Message message = ERR_TOOL_CONFLICTING_ARGS.get(
              trustStorePasswordArg.getLongIdentifier(),
              trustStorePasswordFileArg.getLongIdentifier());
      errors.add(message);
    }
    // Couldn't have at the same time startTLSArg and
    // useSSLArg
    if (useStartTLSArg.isPresent()
            && useSSLArg.isPresent()) {
      Message message = ERR_TOOL_CONFLICTING_ARGS.get(
              useStartTLSArg
                      .getLongIdentifier(), useSSLArg.getLongIdentifier());
      errors.add(message);
    }
    if (errors.size() > 0)
    {
      for (Message error : errors)
      {
        if (buf.length() > 0)
        {
          buf.append(EOL);
        }
        buf.append(error);
      }
      return CONFLICTING_ARGS.getReturnCode();
    }
    return SUCCESSFUL_NOP.getReturnCode();
  }
  /**
   * Indication if provided global options are validate.
   *
   * @param err the stream to be used to print error message.
   * @return return code.
   */
  public int validateGlobalOptions(PrintStream err)
  {
    MessageBuilder buf = new MessageBuilder();
    int returnValue = validateGlobalOptions(buf);
    if (buf.length() > 0)
    {
      err.println(wrapText(buf.toString(), MAX_LINE_WIDTH));
    }
    return returnValue;
  }
  /**
   * Indicate if the SSL mode is required.
   *
   * @return True if SSL mode is required
   */
  public boolean useSSL()
  {
    if (useSSLArg.isPresent())
    {
      return true;
    }
    else
    {
      return false ;
    }
  }
  /**
   * Indicate if the startTLS mode is required.
   *
   * @return True if startTLS mode is required
   */
  public boolean useStartTLS()
  {
    if (useStartTLSArg.isPresent())
    {
      return true;
    }
    else
    {
      return false ;
    }
  }
  /**
   * Handle TrustStore.
   *
   * @return The trustStore manager to be used for the command.
   */
  public ApplicationTrustManager getTrustManager()
  {
    if (trustManager == null)
    {
      KeyStore truststore = null ;
      if (trustAllArg.isPresent())
      {
        // Running a null TrustManager  will force createLdapsContext and
        // createStartTLSContext to use a bindTrustManager.
        return null ;
      }
      else
        if (trustStorePathArg.isPresent())
        {
          try
          {
            FileInputStream fos =
              new FileInputStream(trustStorePathArg.getValue());
            String trustStorePasswordStringValue = null;
            char[] trustStorePasswordValue = null;
            if (trustStorePasswordArg.isPresent())
            {
              trustStorePasswordStringValue = trustStorePasswordArg.getValue();
            }
            else if (trustStorePasswordFileArg.isPresent())
            {
              trustStorePasswordStringValue =
                trustStorePasswordFileArg.getValue();
            }
            if (trustStorePasswordStringValue !=  null)
            {
              trustStorePasswordStringValue = System
              .getProperty("javax.net.ssl.trustStorePassword");
            }
            if (trustStorePasswordStringValue !=  null)
            {
              trustStorePasswordValue =
                trustStorePasswordStringValue.toCharArray();
            }
            truststore = KeyStore.getInstance(KeyStore.getDefaultType());
            truststore.load(fos, trustStorePasswordValue);
            fos.close();
          }
          catch (KeyStoreException e)
          {
            // Nothing to do: if this occurs we will systematically refuse the
            // certificates.  Maybe we should avoid this and be strict, but we
            // are in a best effort mode.
            LOG.log(Level.WARNING, "Error with the truststore", e);
          }
          catch (NoSuchAlgorithmException e)
          {
            // Nothing to do: if this occurs we will systematically refuse the
            // certificates.  Maybe we should avoid this and be strict, but we
            // are in a best effort mode.
            LOG.log(Level.WARNING, "Error with the truststore", e);
          }
          catch (CertificateException e)
          {
            // Nothing to do: if this occurs we will systematically refuse the
            // certificates.  Maybe we should avoid this and be strict, but we
            // are in a best effort mode.
            LOG.log(Level.WARNING, "Error with the truststore", e);
          }
          catch (IOException e)
          {
            // Nothing to do: if this occurs we will systematically refuse the
            // certificates.  Maybe we should avoid this and be strict, but we
            // are in a best effort mode.
            LOG.log(Level.WARNING, "Error with the truststore", e);
          }
        }
      trustManager = new ApplicationTrustManager(truststore);
    }
    return trustManager;
  }
  /**
   * Handle KeyStore.
   *
   * @return The keyStore manager to be used for the command.
   */
  public KeyManager getKeyManager()
  {
    KeyStore keyStore = null;
    String keyStorePasswordStringValue = null;
    char[] keyStorePasswordValue = null;
    if (keyStorePathArg.isPresent())
    {
      try
      {
        FileInputStream fos = new FileInputStream(keyStorePathArg.getValue());
        if (keyStorePasswordArg.isPresent())
        {
          keyStorePasswordStringValue = keyStorePasswordArg.getValue();
        }
        else if (keyStorePasswordFileArg.isPresent())
        {
          keyStorePasswordStringValue = keyStorePasswordFileArg.getValue();
        }
        if (keyStorePasswordStringValue != null)
        {
          keyStorePasswordValue = keyStorePasswordStringValue.toCharArray();
        }
        keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(fos,keyStorePasswordValue);
        fos.close();
      }
      catch (KeyStoreException e)
      {
        // Nothing to do: if this occurs we will systematically refuse
        // the
        // certificates. Maybe we should avoid this and be strict, but
        // we are in a best effort mode.
        LOG.log(Level.WARNING, "Error with the keystore", e);
      }
      catch (NoSuchAlgorithmException e)
      {
        // Nothing to do: if this occurs we will systematically refuse
        // the
        // certificates. Maybe we should avoid this and be strict, but
        // we are
        // in a best effort mode.
        LOG.log(Level.WARNING, "Error with the keystore", e);
      }
      catch (CertificateException e)
      {
        // Nothing to do: if this occurs we will systematically refuse
        // the
        // certificates. Maybe we should avoid this and be strict, but
        // we are
        // in a best effort mode.
        LOG.log(Level.WARNING, "Error with the keystore", e);
      }
      catch (IOException e)
      {
        // Nothing to do: if this occurs we will systematically refuse
        // the
        // certificates. Maybe we should avoid this and be strict, but
        // we are
        // in a best effort mode.
        LOG.log(Level.WARNING, "Error with the keystore", e);
      }
      char[] password = null;
      if (keyStorePasswordStringValue != null)
      {
        password = keyStorePasswordStringValue.toCharArray();
      }
      ApplicationKeyManager akm = new ApplicationKeyManager(keyStore,password);
      if (certNicknameArg.isPresent())
      {
        return new SelectableCertificateKeyManager(akm, certNicknameArg
            .getValue());
      }
      else
      {
        return akm;
      }
    }
    else
    {
      return null;
    }
  }
}
opends/src/server/org/opends/server/admin/client/cli/SecureConnectionCliParser.java
@@ -27,7 +27,6 @@
package org.opends.server.admin.client.cli;
import static org.opends.server.admin.client.cli.DsFrameworkCliReturnCode.*;
import static org.opends.server.loggers.debug.DebugLogger.debugEnabled;
import static org.opends.server.loggers.debug.DebugLogger.getTracer;
import static org.opends.messages.ToolMessages.*;
@@ -37,33 +36,23 @@
import static org.opends.server.util.ServerConstants.MAX_LINE_WIDTH;
import static org.opends.server.util.StaticUtils.wrapText;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.KeyManager;
import org.opends.admin.ads.util.ApplicationKeyManager;
import org.opends.admin.ads.util.ApplicationTrustManager;
import org.opends.server.loggers.debug.DebugTracer;
import org.opends.server.types.DebugLogLevel;
import org.opends.server.util.PasswordReader;
import org.opends.server.util.SelectableCertificateKeyManager;
import org.opends.server.util.args.Argument;
import org.opends.server.util.args.ArgumentException;
import org.opends.server.util.args.BooleanArgument;
import org.opends.server.util.args.FileBasedArgument;
import org.opends.server.util.args.IntegerArgument;
import org.opends.server.util.args.StringArgument;
import org.opends.server.util.args.SubCommandArgumentParser;
@@ -82,87 +71,14 @@
  protected BooleanArgument showUsageArg = null;
  /**
   * The 'hostName' global argument.
   */
  protected StringArgument hostNameArg = null;
  /**
   * The 'port' global argument.
   */
  protected IntegerArgument portArg = null;
  /**
   * The 'binDN' global argument.
   */
  protected StringArgument bindDnArg = null;
  /**
   * The 'bindPasswordFile' global argument.
   */
  protected FileBasedArgument bindPasswordFileArg = null;
  /**
   * The 'bindPassword' global argument.
   */
  protected StringArgument bindPasswordArg = null;
  /**
   * The 'verbose' global argument.
   */
  protected BooleanArgument verboseArg = null;
  /**
   * The 'trustAllArg' global argument.
   * The secure args list object.
   */
  protected BooleanArgument trustAllArg = null;
  /**
   * The 'trustStore' global argument.
   */
  protected StringArgument trustStorePathArg = null;
  /**
   * The 'trustStorePassword' global argument.
   */
  protected StringArgument trustStorePasswordArg = null;
  /**
   * The 'trustStorePasswordFile' global argument.
   */
  protected FileBasedArgument trustStorePasswordFileArg = null;
  /**
   * The 'keyStore' global argument.
   */
  protected StringArgument keyStorePathArg = null;
  /**
   * The 'keyStorePassword' global argument.
   */
  protected StringArgument keyStorePasswordArg = null;
  /**
   * The 'keyStorePasswordFile' global argument.
   */
  protected FileBasedArgument keyStorePasswordFileArg = null;
  /**
   * The 'certNicknameArg' global argument.
   */
  protected StringArgument certNicknameArg = null;
  /**
   * The 'useSSLArg' global argument.
   */
  protected BooleanArgument useSSLArg = null;
  /**
   * The 'useStartTLSArg' global argument.
   */
  protected BooleanArgument useStartTLSArg = null;
  // the trust manager.
  private ApplicationTrustManager trustManager;
  protected SecureConnectionCliArgs secureArgsList ;
  /**
   * The tracer object for the debug logger.
@@ -208,14 +124,7 @@
   */
  public String getBindDN()
  {
    if (bindDnArg.isPresent())
    {
      return bindDnArg.getValue();
    }
    else
    {
      return bindDnArg.getDefaultValue();
    }
    return secureArgsList.getBindDN();
  }
  /**
@@ -322,7 +231,8 @@
   */
  public String getBindPassword(String dn, OutputStream out, OutputStream err)
  {
    return getBindPassword(dn, out, err, bindPasswordArg, bindPasswordFileArg);
    return getBindPassword(dn, out, err, secureArgsList.bindPasswordArg,
        secureArgsList.bindPasswordFileArg);
  }
  /**
@@ -365,7 +275,8 @@
   */
  public String getBindPassword()
  {
    return getBindPassword(bindPasswordArg, bindPasswordFileArg);
    return getBindPassword(secureArgsList.bindPasswordArg,
        secureArgsList.bindPasswordFileArg);
  }
  /**
@@ -382,94 +293,14 @@
      OutputStream outStream)
  throws ArgumentException
  {
    LinkedHashSet<Argument> set = new LinkedHashSet<Argument>();
    secureArgsList = new SecureConnectionCliArgs();
    LinkedHashSet<Argument> set = secureArgsList.createGlobalArguments();
    showUsageArg = new BooleanArgument("showUsage", OPTION_SHORT_HELP,
        OPTION_LONG_HELP, INFO_DESCRIPTION_SHOWUSAGE.get());
    setUsageArgument(showUsageArg, outStream);
    set.add(showUsageArg);
    useSSLArg = new BooleanArgument("useSSL", OPTION_SHORT_USE_SSL,
        OPTION_LONG_USE_SSL, INFO_DESCRIPTION_USE_SSL.get());
    set.add(useSSLArg);
    useStartTLSArg = new BooleanArgument("startTLS", OPTION_SHORT_START_TLS,
        OPTION_LONG_START_TLS,
        INFO_DESCRIPTION_START_TLS.get());
    set.add(useStartTLSArg);
    hostNameArg = new StringArgument("host", OPTION_SHORT_HOST,
        OPTION_LONG_HOST, false, false, true, OPTION_VALUE_HOST, "localhost",
        null, INFO_DESCRIPTION_HOST.get());
    set.add(hostNameArg);
    portArg = new IntegerArgument("port", OPTION_SHORT_PORT, OPTION_LONG_PORT,
        false, false, true, OPTION_VALUE_PORT, 389, null,
        INFO_DESCRIPTION_PORT.get());
    set.add(portArg);
    bindDnArg = new StringArgument("bindDN", OPTION_SHORT_BINDDN,
        OPTION_LONG_BINDDN, false, false, true, OPTION_VALUE_BINDDN,
        "cn=Directory Manager", null, INFO_DESCRIPTION_BINDDN.get());
    set.add(bindDnArg);
    bindPasswordArg = new StringArgument("bindPassword",
        OPTION_SHORT_BINDPWD, OPTION_LONG_BINDPWD, false, false, true,
        OPTION_VALUE_BINDPWD, null, null, INFO_DESCRIPTION_BINDPASSWORD.get());
    set.add(bindPasswordArg);
    bindPasswordFileArg = new FileBasedArgument("bindPasswordFile",
        OPTION_SHORT_BINDPWD_FILE, OPTION_LONG_BINDPWD_FILE, false, false,
        OPTION_VALUE_BINDPWD_FILE, null, null,
        INFO_DESCRIPTION_BINDPASSWORDFILE.get());
    set.add(bindPasswordFileArg);
    trustAllArg = new BooleanArgument("trustAll", OPTION_SHORT_TRUSTALL,
        OPTION_LONG_TRUSTALL, INFO_DESCRIPTION_TRUSTALL.get());
    set.add(trustAllArg);
    trustStorePathArg = new StringArgument("trustStorePath",
        OPTION_SHORT_TRUSTSTOREPATH, OPTION_LONG_TRUSTSTOREPATH, false,
        false, true, OPTION_VALUE_TRUSTSTOREPATH, null, null,
        INFO_DESCRIPTION_TRUSTSTOREPATH.get());
    set.add(trustStorePathArg);
    trustStorePasswordArg = new StringArgument("trustStorePassword",
        OPTION_SHORT_TRUSTSTORE_PWD, OPTION_LONG_TRUSTSTORE_PWD, false, false,
        true, OPTION_VALUE_TRUSTSTORE_PWD, null, null,
        INFO_DESCRIPTION_TRUSTSTOREPASSWORD.get());
    set.add(trustStorePasswordArg);
    trustStorePasswordFileArg = new FileBasedArgument("trustStorePasswordFile",
        OPTION_SHORT_TRUSTSTORE_PWD_FILE, OPTION_LONG_TRUSTSTORE_PWD_FILE,
        false, false, OPTION_VALUE_TRUSTSTORE_PWD_FILE, null, null,
        INFO_DESCRIPTION_TRUSTSTOREPASSWORD_FILE.get());
    set.add(trustStorePasswordFileArg);
    keyStorePathArg = new StringArgument("keyStorePath",
        OPTION_SHORT_KEYSTOREPATH, OPTION_LONG_KEYSTOREPATH, false, false,
        true, OPTION_VALUE_KEYSTOREPATH, null, null,
        INFO_DESCRIPTION_KEYSTOREPATH.get());
    set.add(keyStorePathArg);
    keyStorePasswordArg = new StringArgument("keyStorePassword",
        OPTION_SHORT_KEYSTORE_PWD,
        OPTION_LONG_KEYSTORE_PWD, false, false, true,
        OPTION_VALUE_KEYSTORE_PWD, null, null,
        INFO_DESCRIPTION_KEYSTOREPASSWORD.get());
    set.add(keyStorePasswordArg);
    keyStorePasswordFileArg = new FileBasedArgument("keystorePasswordFile",
        OPTION_SHORT_KEYSTORE_PWD_FILE, OPTION_LONG_KEYSTORE_PWD_FILE, false,
        false, OPTION_VALUE_KEYSTORE_PWD_FILE, null, null,
        INFO_DESCRIPTION_KEYSTOREPASSWORD_FILE.get());
    set.add(keyStorePasswordFileArg);
    certNicknameArg = new StringArgument("certNickname",
        OPTION_SHORT_CERT_NICKNAME, OPTION_LONG_CERT_NICKNAME,
        false, false, true, OPTION_VALUE_CERT_NICKNAME, null, null,
        INFO_DESCRIPTION_CERT_NICKNAME.get());
    set.add(certNicknameArg);
    verboseArg = new BooleanArgument("verbose", OPTION_SHORT_VERBOSE,
        OPTION_LONG_VERBOSE, INFO_DESCRIPTION_VERBOSE.get());
    set.add(verboseArg);
@@ -500,14 +331,7 @@
   */
  public String getHostName()
  {
    if (hostNameArg.isPresent())
    {
      return hostNameArg.getValue();
    }
    else
    {
      return hostNameArg.getDefaultValue();
    }
    return secureArgsList.getHostName();
  }
  /**
@@ -518,14 +342,7 @@
   */
  public String getPort()
  {
    if (portArg.isPresent())
    {
      return portArg.getValue();
    }
    else
    {
      return portArg.getDefaultValue();
    }
    return secureArgsList.getPort();
  }
  /**
@@ -536,70 +353,7 @@
   */
  public int validateGlobalOptions(MessageBuilder buf)
  {
    ArrayList<Message> errors = new ArrayList<Message>();
    // Couldn't have at the same time bindPassword and bindPasswordFile
    if (bindPasswordArg.isPresent() && bindPasswordFileArg.isPresent()) {
      Message message = ERR_TOOL_CONFLICTING_ARGS.get(
              bindPasswordArg.getLongIdentifier(),
              bindPasswordFileArg.getLongIdentifier());
      errors.add(message);
    }
    // Couldn't have at the same time trustAll and
    // trustStore related arg
    if (trustAllArg.isPresent() && trustStorePathArg.isPresent()) {
      Message message = ERR_TOOL_CONFLICTING_ARGS.get(
              trustAllArg.getLongIdentifier(),
              trustStorePathArg.getLongIdentifier());
      errors.add(message);
    }
    if (trustAllArg.isPresent() && trustStorePasswordArg.isPresent()) {
      Message message = ERR_TOOL_CONFLICTING_ARGS.get(
              trustAllArg.getLongIdentifier(),
              trustStorePasswordArg.getLongIdentifier());
      errors.add(message);
    }
    if (trustAllArg.isPresent() && trustStorePasswordFileArg.isPresent()) {
      Message message = ERR_TOOL_CONFLICTING_ARGS.get(
              trustAllArg.getLongIdentifier(),
              trustStorePasswordFileArg.getLongIdentifier());
      errors.add(message);
    }
    // Couldn't have at the same time trustStorePasswordArg and
    // trustStorePasswordFileArg
    if (trustStorePasswordArg.isPresent()
            && trustStorePasswordFileArg.isPresent()) {
      Message message = ERR_TOOL_CONFLICTING_ARGS.get(
              trustStorePasswordArg.getLongIdentifier(),
              trustStorePasswordFileArg.getLongIdentifier());
      errors.add(message);
    }
    // Couldn't have at the same time startTLSArg and
    // useSSLArg
    if (useStartTLSArg.isPresent()
            && useSSLArg.isPresent()) {
      Message message = ERR_TOOL_CONFLICTING_ARGS.get(
              useStartTLSArg
                      .getLongIdentifier(), useSSLArg.getLongIdentifier());
      errors.add(message);
    }
    if (errors.size() > 0)
    {
      for (Message error : errors)
      {
        if (buf.length() > 0)
        {
          buf.append(EOL);
        }
        buf.append(error);
      }
      return CONFLICTING_ARGS.getReturnCode();
    }
    return SUCCESSFUL_NOP.getReturnCode();
    return secureArgsList.validateGlobalOptions(buf) ;
  }
  /**
   * Indication if provided global options are validate.
@@ -643,14 +397,7 @@
   */
  public boolean useSSL()
  {
    if (useSSLArg.isPresent())
    {
      return true;
    }
    else
    {
      return false ;
    }
    return secureArgsList.useSSL();
  }
  /**
@@ -660,14 +407,7 @@
   */
  public boolean useStartTLS()
  {
    if (useStartTLSArg.isPresent())
    {
      return true;
    }
    else
    {
      return false ;
    }
    return secureArgsList.useStartTLS();
  }
  /**
@@ -677,83 +417,7 @@
   */
  public ApplicationTrustManager getTrustManager()
  {
    if (trustManager == null)
    {
      KeyStore truststore = null ;
      if (trustAllArg.isPresent())
      {
        // Running a null TrustManager  will force createLdapsContext and
        // createStartTLSContext to use a bindTrustManager.
        return null ;
      }
      else
        if (trustStorePathArg.isPresent())
        {
          try
          {
            FileInputStream fos =
              new FileInputStream(trustStorePathArg.getValue());
            String trustStorePasswordStringValue = null;
            char[] trustStorePasswordValue = null;
            if (trustStorePasswordArg.isPresent())
            {
              trustStorePasswordStringValue = trustStorePasswordArg.getValue();
            }
            else if (trustStorePasswordFileArg.isPresent())
            {
              trustStorePasswordStringValue =
                trustStorePasswordFileArg.getValue();
            }
            if (trustStorePasswordStringValue !=  null)
            {
              trustStorePasswordStringValue = System
              .getProperty("javax.net.ssl.trustStorePassword");
            }
            if (trustStorePasswordStringValue !=  null)
            {
              trustStorePasswordValue =
                trustStorePasswordStringValue.toCharArray();
            }
            truststore = KeyStore.getInstance(KeyStore.getDefaultType());
            truststore.load(fos, trustStorePasswordValue);
            fos.close();
          }
          catch (KeyStoreException e)
          {
            // Nothing to do: if this occurs we will systematically refuse the
            // certificates.  Maybe we should avoid this and be strict, but we
            // are in a best effort mode.
            LOG.log(Level.WARNING, "Error with the truststore", e);
          }
          catch (NoSuchAlgorithmException e)
          {
            // Nothing to do: if this occurs we will systematically refuse the
            // certificates.  Maybe we should avoid this and be strict, but we
            // are in a best effort mode.
            LOG.log(Level.WARNING, "Error with the truststore", e);
          }
          catch (CertificateException e)
          {
            // Nothing to do: if this occurs we will systematically refuse the
            // certificates.  Maybe we should avoid this and be strict, but we
            // are in a best effort mode.
            LOG.log(Level.WARNING, "Error with the truststore", e);
          }
          catch (IOException e)
          {
            // Nothing to do: if this occurs we will systematically refuse the
            // certificates.  Maybe we should avoid this and be strict, but we
            // are in a best effort mode.
            LOG.log(Level.WARNING, "Error with the truststore", e);
          }
        }
      trustManager = new ApplicationTrustManager(truststore);
    }
    return trustManager;
    return secureArgsList.getTrustManager();
  }
  /**
@@ -763,85 +427,6 @@
   */
  public KeyManager getKeyManager()
  {
    KeyStore keyStore = null;
    String keyStorePasswordStringValue = null;
    char[] keyStorePasswordValue = null;
    if (keyStorePathArg.isPresent())
    {
      try
      {
        FileInputStream fos = new FileInputStream(keyStorePathArg.getValue());
        if (keyStorePasswordArg.isPresent())
        {
          keyStorePasswordStringValue = keyStorePasswordArg.getValue();
        }
        else if (keyStorePasswordFileArg.isPresent())
        {
          keyStorePasswordStringValue = keyStorePasswordFileArg.getValue();
        }
        if (keyStorePasswordStringValue != null)
        {
          keyStorePasswordValue = keyStorePasswordStringValue.toCharArray();
        }
        keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(fos,keyStorePasswordValue);
        fos.close();
      }
      catch (KeyStoreException e)
      {
        // Nothing to do: if this occurs we will systematically refuse
        // the
        // certificates. Maybe we should avoid this and be strict, but
        // we are in a best effort mode.
        LOG.log(Level.WARNING, "Error with the keystore", e);
      }
      catch (NoSuchAlgorithmException e)
      {
        // Nothing to do: if this occurs we will systematically refuse
        // the
        // certificates. Maybe we should avoid this and be strict, but
        // we are
        // in a best effort mode.
        LOG.log(Level.WARNING, "Error with the keystore", e);
      }
      catch (CertificateException e)
      {
        // Nothing to do: if this occurs we will systematically refuse
        // the
        // certificates. Maybe we should avoid this and be strict, but
        // we are
        // in a best effort mode.
        LOG.log(Level.WARNING, "Error with the keystore", e);
      }
      catch (IOException e)
      {
        // Nothing to do: if this occurs we will systematically refuse
        // the
        // certificates. Maybe we should avoid this and be strict, but
        // we are
        // in a best effort mode.
        LOG.log(Level.WARNING, "Error with the keystore", e);
      }
      char[] password = null;
      if (keyStorePasswordStringValue != null)
      {
        password = keyStorePasswordStringValue.toCharArray();
      }
      ApplicationKeyManager akm = new ApplicationKeyManager(keyStore,password);
      if (certNicknameArg.isPresent())
      {
        return new SelectableCertificateKeyManager(akm, certNicknameArg
            .getValue());
      }
      else
      {
        return akm;
      }
    }
    else
    {
      return null;
    }
    return secureArgsList.getKeyManager() ;
  }
}
opends/src/server/org/opends/server/tools/dsconfig/LDAPManagementContextFactory.java
@@ -27,31 +27,46 @@
package org.opends.server.tools.dsconfig;
import static org.opends.messages.DSConfigMessages.*;
import static org.opends.messages.ToolMessages.*;
import static org.opends.server.tools.ToolConstants.*;
import java.io.File;
import java.io.FileInputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.KeyStore;
import java.util.LinkedHashSet;
import javax.naming.NamingException;
import javax.naming.ldap.InitialLdapContext;
import javax.net.ssl.KeyManager;
import javax.net.ssl.TrustManager;
import org.opends.admin.ads.util.ApplicationKeyManager;
import org.opends.admin.ads.util.ApplicationTrustManager;
import org.opends.admin.ads.util.ConnectionUtils;
import org.opends.messages.Message;
import org.opends.messages.MessageBuilder;
import org.opends.server.admin.client.AuthenticationException;
import org.opends.server.admin.client.AuthenticationNotSupportedException;
import org.opends.server.admin.client.CommunicationException;
import org.opends.server.admin.client.ManagementContext;
import org.opends.server.admin.client.cli.DsFrameworkCliReturnCode;
import org.opends.server.admin.client.cli.SecureConnectionCliArgs;
import org.opends.server.admin.client.ldap.JNDIDirContextAdaptor;
import org.opends.server.admin.client.ldap.LDAPConnection;
import org.opends.server.admin.client.ldap.LDAPManagementContext;
import org.opends.server.protocols.ldap.LDAPResultCode;
import org.opends.server.tools.ClientException;
import org.opends.server.util.SelectableCertificateKeyManager;
import org.opends.server.util.args.Argument;
import org.opends.server.util.args.ArgumentException;
import org.opends.server.util.args.FileBasedArgument;
import org.opends.server.util.args.IntegerArgument;
import org.opends.server.util.args.StringArgument;
import org.opends.server.util.args.SubCommandArgumentParser;
import org.opends.server.util.cli.CLIException;
import org.opends.server.util.cli.ConsoleApplication;
import org.opends.server.util.cli.Menu;
import org.opends.server.util.cli.MenuBuilder;
import org.opends.server.util.cli.MenuResult;
import org.opends.server.util.cli.ValidationCallback;
@@ -62,32 +77,17 @@
public final class LDAPManagementContextFactory implements
    ManagementContextFactory {
  // The default bind DN which will be used to manage the directory
  // server.
  private static final String DEFAULT_BIND_DN = "cn=directory manager";
  // The SecureConnectionCliArgsList object.
  private SecureConnectionCliArgs secureArgsList = null;
  // The management context.
  private ManagementContext context = null;
  // The argument which should be used to specify the bind DN.
  private StringArgument bindDNArgument;
  // Indicate if we need to display the heading
  private boolean isHeadingDisplayed = false;
  // The argument which should be used to specify the bind password.
  private StringArgument bindPasswordArgument;
  // The argument which should be used to specify the location of the
  // bind password file.
  private FileBasedArgument bindPasswordFileArgument;
  // The argument which should be used to specify the directory server
  // LDAP host address.
  private StringArgument hostArgument;
  // The argument which should be used to specify the directory server
  // LDAP port.
  private IntegerArgument portArgument;
  // the Console application
  private ConsoleApplication app;
  /**
   * Creates a new LDAP management context factory.
@@ -105,12 +105,123 @@
      throws ArgumentException, ClientException {
    // Lazily create the LDAP management context.
    if (context == null) {
      boolean isHeadingDisplayed = false;
      this.app = app ;
      isHeadingDisplayed = false;
      boolean secureConnection =
        (
            secureArgsList.useSSLArg.isPresent()
            ||
            secureArgsList.useStartTLSArg.isPresent()
            ||
            secureArgsList.trustAllArg.isPresent()
            ||
            secureArgsList.trustStorePathArg.isPresent()
            ||
            secureArgsList.trustStorePasswordArg.isPresent()
            ||
            secureArgsList.trustStorePasswordFileArg.isPresent()
            ||
            secureArgsList.keyStorePathArg.isPresent()
            ||
            secureArgsList.keyStorePasswordArg.isPresent()
            ||
            secureArgsList.keyStorePasswordFileArg.isPresent()
        );
      if (app.isInteractive() && !secureConnection )
      {
        if (!isHeadingDisplayed)
        {
          app.println();
          app.println();
          app.println(INFO_DSCFG_HEADING_CONNECTION_PARAMETERS.get());
          isHeadingDisplayed = true;
        }
        try
        {
          app.println();
          secureConnection = app.confirmAction(
              INFO_DSCFG_PROMPT_SECURITY_USE_SECURE_CTX.get(),
              secureConnection);
        }
        catch (CLIException e)
        {
          // Should never happen.
          throw new RuntimeException(e);
        }
      }
      boolean useSSL = secureArgsList.useSSL();
      boolean useStartTSL = secureArgsList.useStartTLS();
      KeyManager keyManager = null ;
      TrustManager trustManager = null;
      boolean connectionTypeIsSet =
        (secureArgsList.useSSLArg.isPresent()
            ||
         secureArgsList.useStartTLSArg.isPresent() );
      if (app.isInteractive() && secureConnection && ! connectionTypeIsSet)
      {
        if (!isHeadingDisplayed)
        {
          app.println();
          app.println();
          app.println(INFO_DSCFG_HEADING_CONNECTION_PARAMETERS.get());
          isHeadingDisplayed = true;
        }
        // Construct the SSL/StartTLS menu.
        MenuBuilder<Boolean> builder = new MenuBuilder<Boolean>(app);
        builder.addNumberedOption(INFO_DSCFG_PROMPT_SECURITY_USE_SSL.get(),
            MenuResult.success(true));
        builder.addNumberedOption(INFO_DSCFG_PROMPT_SECURITY_USE_START_TSL
            .get(), MenuResult.success(false));
        builder.setDefault(INFO_DSCFG_PROMPT_SECURITY_USE_SSL.get(),
            MenuResult.success(true));
        Menu<Boolean> menu = builder.toMenu();
        try
        {
          MenuResult<Boolean> result = menu.run();
          if (result.isSuccess())
          {
            if (result.getValue())
            {
              useSSL = true;
            }
            else
            {
              useStartTSL = true;
            }
          }
          else
          {
            // Should never happen.
            throw new RuntimeException();
          }
        }
        catch (CLIException e)
        {
          throw new RuntimeException(e);
        }
      }
      if (secureConnection)
      {
        if (useSSL || useStartTSL)
        {
          // Get truststore info
          trustManager = getTrustManager();
          // Check if we need client side authentication
          keyManager = getKeyManager();
        }
      }
      // Get the LDAP host.
      String hostName = hostArgument.getValue();
      String hostName = secureArgsList.hostNameArg.getValue();
      final String tmpHostName = hostName;
      if (app.isInteractive() && !hostArgument.isPresent()) {
      if (app.isInteractive() && !secureArgsList.hostNameArg.isPresent()) {
        if (!isHeadingDisplayed) {
          app.println();
          app.println();
@@ -151,9 +262,24 @@
      }
      // Get the LDAP port.
      int portNumber = portArgument.getIntValue();
      int portNumber ;
      if (!useSSL)
      {
        portNumber = secureArgsList.portArg.getIntValue();
      }
      else
      {
        if (secureArgsList.portArg.isPresent())
        {
          portNumber = secureArgsList.portArg.getIntValue();
        }
        else
        {
        portNumber = 636;
        }
      }
      final int tmpPortNumber = portNumber;
      if (app.isInteractive() && !portArgument.isPresent()) {
      if (app.isInteractive() && !secureArgsList.portArg.isPresent()) {
        if (!isHeadingDisplayed) {
          app.println();
          app.println();
@@ -198,9 +324,11 @@
      }
      // Get the LDAP bind credentials.
      String bindDN = bindDNArgument.getValue();
      String bindDN = secureArgsList.bindDnArg.getValue();
      final String tmpBindDN = bindDN;
      if (app.isInteractive() && !bindDNArgument.isPresent()) {
      if (app.isInteractive() && (keyManager == null)
          && !secureArgsList.bindDnArg.isPresent())
      {
        if (!isHeadingDisplayed) {
          app.println();
          app.println();
@@ -231,56 +359,121 @@
        }
      }
      String bindPassword = bindPasswordArgument.getValue();
      String bindPassword = secureArgsList.bindPasswordArg.getValue();
      if (keyManager == null)
      {
        if (secureArgsList.bindPasswordFileArg.isPresent())
        {
          // Read from file if it exists.
          bindPassword = secureArgsList.bindPasswordFileArg.getValue();
      if (bindPasswordFileArgument.isPresent()) {
        // Read from file if it exists.
        bindPassword = bindPasswordFileArgument.getValue();
        if (bindPassword == null) {
          throw ArgumentExceptionFactory.missingBindPassword(bindDN);
          if (bindPassword == null)
          {
            throw ArgumentExceptionFactory.missingBindPassword(bindDN);
          }
        }
      } else if (bindPassword == null || bindPassword.equals("-")) {
        // Read the password from the stdin.
        if (!app.isInteractive()) {
          throw ArgumentExceptionFactory
              .unableToReadBindPasswordInteractively();
        }
        else if (bindPassword == null || bindPassword.equals("-"))
        {
          // Read the password from the stdin.
          if (!app.isInteractive())
          {
            throw ArgumentExceptionFactory
                .unableToReadBindPasswordInteractively();
          }
        if (!isHeadingDisplayed) {
          app.println();
          app.println();
          app.println(INFO_DSCFG_HEADING_CONNECTION_PARAMETERS.get());
          isHeadingDisplayed = true;
        }
          if (!isHeadingDisplayed)
          {
            app.println();
            app.println();
            app.println(INFO_DSCFG_HEADING_CONNECTION_PARAMETERS.get());
            isHeadingDisplayed = true;
          }
        try {
          app.println();
          Message prompt = INFO_LDAPAUTH_PASSWORD_PROMPT.get(bindDN);
          bindPassword = app.readPassword(prompt);
        } catch (Exception e) {
          throw ArgumentExceptionFactory.unableToReadConnectionParameters(e);
          try
          {
            app.println();
            Message prompt = INFO_LDAPAUTH_PASSWORD_PROMPT.get(bindDN);
            bindPassword = app.readPassword(prompt);
          }
          catch (Exception e)
          {
            throw ArgumentExceptionFactory
                .unableToReadConnectionParameters(e);
          }
        }
      }
      // Create the management context.
      try {
        LDAPConnection conn = JNDIDirContextAdaptor.simpleBind(hostName,
            portNumber, bindDN, bindPassword);
        context = LDAPManagementContext.createFromContext(conn);
      } catch (AuthenticationNotSupportedException e) {
        Message message = ERR_DSCFG_ERROR_LDAP_SIMPLE_BIND_NOT_SUPPORTED.get();
        throw new ClientException(LDAPResultCode.AUTH_METHOD_NOT_SUPPORTED,
            message);
      } catch (AuthenticationException e) {
        Message message = ERR_DSCFG_ERROR_LDAP_SIMPLE_BIND_FAILED.get(bindDN);
        throw new ClientException(LDAPResultCode.INVALID_CREDENTIALS, message);
      } catch (CommunicationException e) {
        Message message = ERR_DSCFG_ERROR_LDAP_FAILED_TO_CONNECT.get(hostName,
            String.valueOf(portNumber));
        throw new ClientException(LDAPResultCode.CLIENT_SIDE_CONNECT_ERROR,
            message);
      // Do we have a secure connection ?
      LDAPConnection conn ;
      if (useSSL)
      {
        InitialLdapContext ctx = null;
        String ldapsUrl = "ldaps://" + hostName + ":" + portNumber;
        try
        {
          ctx = ConnectionUtils.createLdapsContext(ldapsUrl, bindDN,
              bindPassword, ConnectionUtils.getDefaultLDAPTimeout(), null,
              trustManager, keyManager);
          conn = JNDIDirContextAdaptor.adapt(ctx);
        }
        catch (NamingException e)
        {
          Message message = ERR_DSCFG_ERROR_LDAP_FAILED_TO_CONNECT.get(
              hostName, String.valueOf(portNumber));
          throw new ClientException(LDAPResultCode.CLIENT_SIDE_CONNECT_ERROR,
              message) ;
        }
      }
      else if (useStartTSL)
      {
        InitialLdapContext ctx = null;
        String ldapUrl = "ldap://" + hostName + ":" + portNumber;
        try
        {
          ctx = ConnectionUtils.createStartTLSContext(ldapUrl, bindDN,
              bindPassword, ConnectionUtils.getDefaultLDAPTimeout(), null,
              trustManager, keyManager, null);
          conn = JNDIDirContextAdaptor.adapt(ctx);
        }
        catch (NamingException e)
        {
          Message message = ERR_DSCFG_ERROR_LDAP_FAILED_TO_CONNECT.get(
              hostName, String.valueOf(portNumber));
          throw new ClientException(LDAPResultCode.CLIENT_SIDE_CONNECT_ERROR,
              message) ;
        }
      }
      else
      {
        // Create the management context.
        try
        {
          conn = JNDIDirContextAdaptor.simpleBind(hostName, portNumber,
              bindDN, bindPassword);
        }
        catch (AuthenticationNotSupportedException e)
        {
          Message message = ERR_DSCFG_ERROR_LDAP_SIMPLE_BIND_NOT_SUPPORTED
              .get();
          throw new ClientException(LDAPResultCode.AUTH_METHOD_NOT_SUPPORTED,
              message);
        }
        catch (AuthenticationException e)
        {
          Message message = ERR_DSCFG_ERROR_LDAP_SIMPLE_BIND_FAILED
              .get(bindDN);
          throw new ClientException(LDAPResultCode.INVALID_CREDENTIALS,
              message);
        }
        catch (CommunicationException e)
        {
          Message message = ERR_DSCFG_ERROR_LDAP_FAILED_TO_CONNECT.get(
              hostName, String.valueOf(portNumber));
          throw new ClientException(LDAPResultCode.CLIENT_SIDE_CONNECT_ERROR,
              message);
        }
      }
      context = LDAPManagementContext.createFromContext(conn);
    }
    return context;
  }
@@ -293,33 +486,16 @@
  public void registerGlobalArguments(SubCommandArgumentParser parser)
      throws ArgumentException {
    // Create the global arguments.
    hostArgument = new StringArgument("host", OPTION_SHORT_HOST,
        OPTION_LONG_HOST, false, false, true, OPTION_VALUE_HOST, "localhost",
        null, INFO_DESCRIPTION_HOST.get());
    secureArgsList = new SecureConnectionCliArgs();
    LinkedHashSet<Argument> args = secureArgsList.createGlobalArguments();
    portArgument = new IntegerArgument("port", OPTION_SHORT_PORT,
        OPTION_LONG_PORT, false, false, true, OPTION_VALUE_PORT, 389, null,
        INFO_DESCRIPTION_PORT.get());
    bindDNArgument = new StringArgument("bindDN", OPTION_SHORT_BINDDN,
        OPTION_LONG_BINDDN, false, false, true, OPTION_VALUE_BINDDN,
        DEFAULT_BIND_DN, null, INFO_DESCRIPTION_BINDDN.get());
    bindPasswordArgument = new StringArgument("bindPassword",
        OPTION_SHORT_BINDPWD, OPTION_LONG_BINDPWD, false, false, true,
        OPTION_VALUE_BINDPWD, null, null, INFO_DESCRIPTION_BINDPASSWORD.get());
    bindPasswordFileArgument = new FileBasedArgument("bindPasswordFile",
        OPTION_SHORT_BINDPWD_FILE, OPTION_LONG_BINDPWD_FILE, false, false,
        OPTION_VALUE_BINDPWD_FILE, null, null,
        INFO_DESCRIPTION_BINDPASSWORDFILE.get());
    // Register the global arguments.
    parser.addGlobalArgument(hostArgument);
    parser.addGlobalArgument(portArgument);
    parser.addGlobalArgument(bindDNArgument);
    parser.addGlobalArgument(bindPasswordArgument);
    parser.addGlobalArgument(bindPasswordFileArgument);
    for (Argument arg : args)
    {
      parser.addGlobalArgument(arg);
    }
  }
@@ -330,12 +506,365 @@
  public void validateGlobalArguments() throws ArgumentException {
    // Make sure that the user didn't specify any conflicting
    // arguments.
    if (bindPasswordArgument.isPresent()
        && bindPasswordFileArgument.isPresent()) {
      Message message = ERR_TOOL_CONFLICTING_ARGS.get(bindPasswordArgument
          .getLongIdentifier(), bindPasswordFileArgument.getLongIdentifier());
      throw new ArgumentException(message);
    MessageBuilder buf = new MessageBuilder();
    int v = secureArgsList.validateGlobalOptions(buf);
    if (v != DsFrameworkCliReturnCode.SUCCESSFUL_NOP.getReturnCode())
    {
      throw new ArgumentException(buf.toMessage());
    }
  }
  /**
   * Get the trust manager.
   *
   * @return The trust manager based on CLI args on interactive prompt.
   *
   * @throws ArgumentException If an error occurs when getting args values.
   */
  private ApplicationTrustManager getTrustManager()
  throws ArgumentException
  {
    boolean trustAll = secureArgsList.trustAllArg.isPresent();
    if (app.isInteractive() && !secureArgsList.trustAllArg.isPresent())
    {
      if (!isHeadingDisplayed)
      {
        app.println();
        app.println();
        app.println(INFO_DSCFG_HEADING_CONNECTION_PARAMETERS.get());
        isHeadingDisplayed = true;
      }
      try
      {
        app.println();
        trustAll = app.confirmAction(INFO_DSCFG_PROMPT_SECURITY_USE_TRUST_ALL
            .get(), false);
      }
      catch (CLIException e)
      {
        // Should never happen.
        throw new RuntimeException(e);
      }
    }
    // Trust everything, so no trust manager
    if (trustAll)
    {
      return null;
    }
    // If we not trust all server certificates, we have to get info
    // about truststore. First get the truststore path.
    String truststorePath = secureArgsList.trustStorePathArg.getValue();
    if (app.isInteractive() && !secureArgsList.trustStorePathArg.isPresent())
    {
      if (!isHeadingDisplayed)
      {
        app.println();
        app.println();
        app.println(INFO_DSCFG_HEADING_CONNECTION_PARAMETERS.get());
        isHeadingDisplayed = true;
      }
      ValidationCallback<String> callback = new ValidationCallback<String>()
      {
        public String validate(ConsoleApplication app, String input)
            throws CLIException
        {
          String ninput = input.trim();
          if (ninput.length() == 0)
          {
            return ninput;
          }
          File f = new File(ninput);
          if (f.exists() && f.canRead() && !f.isDirectory())
          {
            return ninput;
          }
          else
          {
            return null;
          }
        }
      };
      try
      {
        app.println();
        truststorePath = app.readValidatedInput(
            INFO_DSCFG_PROMPT_SECURITY_TRUSTSTORE_PATH.get(), callback);
      }
      catch (CLIException e)
      {
        throw ArgumentExceptionFactory.unableToReadConnectionParameters(e);
      }
    }
    // Then the truststore password.
    String truststorePassword = secureArgsList.trustStorePasswordArg.getValue();
    if (secureArgsList.trustStorePasswordFileArg.isPresent())
    {
      // Read from file if it exists.
      truststorePassword = secureArgsList.trustStorePasswordFileArg.getValue();
      if (app.isInteractive() && (truststorePassword == null))
      {
          throw ArgumentExceptionFactory
            .missingValueInPropertyArgument(secureArgsList.
                trustStorePasswordArg.getName());
      }
    }
    else if (truststorePassword == null || truststorePassword.equals("-"))
    {
      // Read the password from the stdin.
      if (!app.isInteractive())
      {
        truststorePassword = null;
      }
      else
      {
      if (!isHeadingDisplayed)
        {
          app.println();
          app.println();
          app.println(INFO_DSCFG_HEADING_CONNECTION_PARAMETERS.get());
          isHeadingDisplayed = true;
        }
        try
        {
          app.println();
          Message prompt = INFO_DSCFG_PROMPT_SECURITY_TRUSTSTORE_PASSWORD
              .get(truststorePath);
          truststorePassword = app.readPassword(prompt);
        }
        catch (Exception e)
        {
          throw ArgumentExceptionFactory.unableToReadConnectionParameters(e);
        }
      }
    }
    // We'we got all the information to get the trustore manager
    try
    {
      FileInputStream fos = new FileInputStream(truststorePath);
      KeyStore truststore = KeyStore.getInstance(KeyStore.getDefaultType());
      if (truststorePassword != null)
      {
        truststore.load(fos, truststorePassword.toCharArray());
      }
      else
      {
        truststore.load(fos, null);
      }
      fos.close();
      return new ApplicationTrustManager(truststore);
    }
    catch (Exception e)
    {
      throw ArgumentExceptionFactory.unableToReadConnectionParameters(e);
    }
  }
  /**
   * Get the key manager.
   *
   * @return The key manager based on CLI args on interactive prompt.
   *
   * @throws ArgumentException If an error occurs when getting args values.
   */
  private KeyManager getKeyManager()
  throws ArgumentException
  {
    // Do we need client side authentication ?
    // If one of the client side authentication args is set, we assume that we
    // need client side authentication.
    boolean weDontKnowThatWeNeedKeystore =
      ! ( secureArgsList.keyStorePathArg.isPresent()
          ||
          secureArgsList.keyStorePasswordArg.isPresent()
          ||
          secureArgsList.keyStorePasswordFileArg.isPresent()
          ||
          secureArgsList.certNicknameArg.isPresent()
          );
    // We don't have specific key manager parameter set and
    // we are not in interactive mode ; just return null
    if (weDontKnowThatWeNeedKeystore && !app.isInteractive())
    {
      return null;
    }
    if (app.isInteractive() && weDontKnowThatWeNeedKeystore)
    {
      boolean needKeystore = false ;
      if (!isHeadingDisplayed)
      {
        app.println();
        app.println();
        app.println(INFO_DSCFG_HEADING_CONNECTION_PARAMETERS.get());
        isHeadingDisplayed = true;
      }
      try
      {
        app.println();
        needKeystore = app.confirmAction(
            INFO_DSCFG_PROMPT_SECURITY_KEYSTORE_NEEDED.get(), needKeystore);
        if (! needKeystore )
        {
          return null;
        }
      }
      catch (CLIException e)
      {
        // Should never happen.
        throw new RuntimeException(e);
      }
    }
    // Get info about keystore. First get the keystore path.
    String keystorePath = secureArgsList.keyStorePathArg.getValue();
    if (app.isInteractive() && !secureArgsList.keyStorePathArg.isPresent())
    {
      if (!isHeadingDisplayed)
      {
        app.println();
        app.println();
        app.println(INFO_DSCFG_HEADING_CONNECTION_PARAMETERS.get());
        isHeadingDisplayed = true;
      }
      ValidationCallback<String> callback = new ValidationCallback<String>()
      {
        public String validate(ConsoleApplication app, String input)
            throws CLIException
        {
          String ninput = input.trim();
          if (ninput.length() == 0)
          {
            return ninput;
          }
          File f = new File(ninput);
          if (f.exists() && f.canRead() && !f.isDirectory())
          {
            return ninput;
          }
          else
          {
            return null;
          }
        }
      };
      try
      {
        app.println();
        keystorePath = app.readValidatedInput(
            INFO_DSCFG_PROMPT_SECURITY_KEYSTORE_PATH.get(), callback);
      }
      catch (CLIException e)
      {
        throw ArgumentExceptionFactory.unableToReadConnectionParameters(e);
      }
    }
    // Then the keystore password.
    String keystorePassword = secureArgsList.keyStorePasswordArg.getValue();
    if (secureArgsList.keyStorePasswordFileArg.isPresent())
    {
      // Read from file if it exists.
      keystorePassword = secureArgsList.keyStorePasswordFileArg.getValue();
      if (keystorePassword == null)
      {
        throw ArgumentExceptionFactory.missingBindPassword(keystorePassword);
      }
    }
    else if (keystorePassword == null || keystorePassword.equals("-"))
    {
      // Read the password from the stdin.
      if (!app.isInteractive())
      {
        throw ArgumentExceptionFactory
            .unableToReadBindPasswordInteractively();
      }
      if (!isHeadingDisplayed)
      {
        app.println();
        app.println();
        app.println(INFO_DSCFG_HEADING_CONNECTION_PARAMETERS.get());
        isHeadingDisplayed = true;
      }
      try
      {
        app.println();
        Message prompt = INFO_DSCFG_PROMPT_SECURITY_KEYSTORE_PASSWORD
            .get(keystorePath);
        keystorePassword = app.readPassword(prompt);
      }
      catch (Exception e)
      {
        throw ArgumentExceptionFactory.unableToReadConnectionParameters(e);
      }
    }
    // finally the certificate name, if needed.
    String certifNickname = secureArgsList.certNicknameArg.getValue();
    if (app.isInteractive() && !secureArgsList.certNicknameArg.isPresent())
    {
      if (!isHeadingDisplayed)
      {
        app.println();
        app.println();
        app.println(INFO_DSCFG_HEADING_CONNECTION_PARAMETERS.get());
        isHeadingDisplayed = true;
      }
      ValidationCallback<String> callback = new ValidationCallback<String>() {
        public String validate(ConsoleApplication app, String input)
            throws CLIException {
          return  input.trim();
        }
      };
      try {
        app.println();
        certifNickname = app.readValidatedInput(
            INFO_DSCFG_PROMPT_SECURITY_CERTIFICATE_NAME.get(), callback);
      } catch (CLIException e) {
        throw ArgumentExceptionFactory.unableToReadConnectionParameters(e);
      }
    }
    // We'we got all the information to get the keystore manager
    try
    {
      FileInputStream fos = new FileInputStream(keystorePath);
      KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
      keystore.load(fos, keystorePassword.toCharArray());
      fos.close();
      ApplicationKeyManager akm = new ApplicationKeyManager(keystore,
          keystorePassword.toCharArray());
      if (certifNickname.length() != 0)
      {
        return new SelectableCertificateKeyManager(akm, certifNickname);
      }
      else
      {
        return akm ;
      }
    }
    catch (Exception e)
    {
      throw ArgumentExceptionFactory.unableToReadConnectionParameters(e);
    }
  }
}
opends/src/server/org/opends/server/tools/dsconfig/SubCommandHandler.java
@@ -563,12 +563,12 @@
  /**
   * The value for the short option unit-size.
   */
  private static final char OPTION_DSCFG_SHORT_UNIT_SIZE = 'Z';
  private static final char OPTION_DSCFG_SHORT_UNIT_SIZE = 'z';
  /**
   * The value for the short option unit-time.
   */
  private static final char OPTION_DSCFG_SHORT_UNIT_TIME = 'M';
  private static final char OPTION_DSCFG_SHORT_UNIT_TIME = 'm';
  // The argument which should be used to specify zero or more
  // property names.
opends/tests/unit-tests-testng/src/server/org/opends/server/tools/dsconfig/DsconfigLdapConnectionTestCase.java
New file
@@ -0,0 +1,321 @@
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at
 * trunk/opends/resource/legal-notices/OpenDS.LICENSE
 * or https://OpenDS.dev.java.net/OpenDS.LICENSE.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at
 * trunk/opends/resource/legal-notices/OpenDS.LICENSE.  If applicable,
 * add the following below this CDDL HEADER, with the fields enclosed
 * by brackets "[]" replaced with your own identifying information:
 *      Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 *
 *
 *      Portions Copyright 2006-2007 Sun Microsystems, Inc.
 */
package org.opends.server.tools.dsconfig;
import java.io.File;
import java.io.FileWriter;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.opends.server.TestCaseUtils;
import org.opends.server.DirectoryServerTestCase;
import org.opends.server.core.DirectoryServer;
import static org.testng.Assert.*;
import static org.opends.server.admin.client.cli.DsFrameworkCliReturnCode.*;
/**
 * A set of test cases for the dsservice tool.
 */
public class DsconfigLdapConnectionTestCase extends DirectoryServerTestCase {
  // The path to a file containing an invalid bind password.
  private String invalidPasswordFile;
  // The path to a file containing a valid bind password.
  private String validPasswordFile;
  /**
   * Ensures that the Directory Server is running and performs other necessary
   * setup.
   *
   * @throws  Exception  If an unexpected problem occurs.
   */
  @BeforeClass()
  public void before()
         throws Exception
  {
    TestCaseUtils.startServer();
    File pwFile = File.createTempFile("valid-bind-password-", ".txt");
    pwFile.deleteOnExit();
    FileWriter fileWriter = new FileWriter(pwFile);
    fileWriter.write("password" + System.getProperty("line.separator"));
    fileWriter.close();
    validPasswordFile = pwFile.getAbsolutePath();
    pwFile = File.createTempFile("invalid-bind-password-", ".txt");
    pwFile.deleteOnExit();
    fileWriter = new FileWriter(pwFile);
    fileWriter.write("wrongPassword" + System.getProperty("line.separator"));
    fileWriter.close();
    invalidPasswordFile = pwFile.getAbsolutePath();
  }
  /**
   * Ensures ADS is removed.
   * @throws  Exception  If an unexpected problem occurs.
   */
  @AfterClass()
  public void afterClass()
         throws Exception
  {
  }
  /**
   * Tests list-list-connection-handlers with a malformed bind DN.
   */
  @Test()
  public void testMalformedBindDN()
  {
    String[] args =
    {
      "-n",
      "-Q",
      "list-connection-handlers",
      "-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
      "-D", "malformed",
      "-w", "password"
    };
    assertFalse(DSConfig.main(args, false, null, null)
        == SUCCESSFUL.getReturnCode());
  }
  /**
   * Tests list-connection-handlers with a nonexistent bind DN.
   */
  @Test()
  public void testNonExistentBindDN()
  {
    String[] args =
    {
      "-n",
      "-Q",
      "list-connection-handlers",
      "-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
      "-D", "cn=Does Not Exist",
      "-w", "password"
    };
    assertFalse(DSConfig.main(args, false, System.out, System.err)
        == SUCCESSFUL.getReturnCode());
  }
  /**
   * Tests list-connection-handlers with an invalid password.
   */
  @Test()
  public void testInvalidBindPassword()
  {
    String[] args =
    {
      "-n",
      "-Q",
      "list-connection-handlers",
      "-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
      "-D", "cn=Directory Manager",
      "-w", "wrongPassword"
    };
    assertFalse(DSConfig.main(args, false, System.out, System.err)
        == SUCCESSFUL.getReturnCode());
  }
  /**
   * Tests list-connection-handlers with a valid password read from a file.
   *
   * @throws  Exception  If an unexpected problem occurs.
   */
  @Test()
  public void testValidPasswordFromFile()
         throws Exception
  {
    String[] args =
    {
      "-n",
      "-Q",
      "list-connection-handlers",
      "-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
      "-D", "cn=Directory Manager",
      "-j", validPasswordFile,
    };
    assertEquals(DSConfig.main(args, false, System.out,
        System.err), SUCCESSFUL.getReturnCode());
  }
  /**
   * Tests list-connection-handlers with an invalid password read from a file.
   *
   * @throws  Exception  If an unexpected problem occurs.
   */
  @Test()
  public void testInvalidPasswordFromFile()
         throws Exception
  {
    String[] args =
    {
      "-n",
      "-Q",
      "list-connection-handlers",
      "-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
      "-D", "cn=Directory Manager",
      "-j",invalidPasswordFile
    };
    assertFalse(DSConfig.main(args, false, System.out, System.err)
        == SUCCESSFUL.getReturnCode());
  }
  /**
   * Tests a list-connection-handlerss over SSL using blind trust.
   */
  @Test()
  public void testListConnectionHandlersSSLBlindTrust()
  {
    String[] args =
    {
      "-n",
      "-Q",
      "list-connection-handlers",
      "-p", String.valueOf(TestCaseUtils.getServerLdapsPort()),
      "-w", "password",
      "-Z",
      "-X"
    };
    assertEquals(DSConfig.main(args, false, System.out,
        System.err), SUCCESSFUL.getReturnCode());
  }
  /**
   * Tests list-connection-handlers over SSL using a trust store.
   */
  @Test()
  public void testListConnectionHandlersSSLTrustStore()
  {
    String trustStorePath = DirectoryServer.getServerRoot() + File.separator +
                            "config" + File.separator + "client.truststore";
    String[] args =
    {
      "-n",
      "-Q",
      "list-connection-handlers",
      "-p", String.valueOf(TestCaseUtils.getServerLdapsPort()),
      "-w", "password",
      "-Z",
      "-P", trustStorePath
    };
    assertEquals(DSConfig.main(args, false, System.out,
        System.err), SUCCESSFUL.getReturnCode());
  }
  /**
   * Tests a list-connection-handlers using StartTLS with blind trust.
   */
  @Test()
  public void testListConnectionHandlersStartTLSBlindTrust()
  {
    String[] args =
    {
      "-n",
      "-Q",
      "list-connection-handlers",
      "-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
      "-w", "password",
      "-q",
      "-X"
    };
    assertEquals(DSConfig.main(args, false, null, System.err),
        SUCCESSFUL.getReturnCode());
  }
  /**
   * Tests a list-connection-handlers using StartTLS with a trust store.
   */
  @Test()
  public void testListConnectionHandlersStartTLSTrustStore()
  {
    String trustStorePath = DirectoryServer.getServerRoot() + File.separator +
                            "config" + File.separator + "client.truststore";
    String[] args =
    {
      "-n",
      "-Q",
      "list-connection-handlers",
      "-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
      "-w", "password",
      "-q",
      "-P", trustStorePath
    };
    assertEquals(DSConfig.main(args, false, null, System.err),
        SUCCESSFUL.getReturnCode());
  }
  /**
   * Tests the dsconfig with the "--help" option.
   */
  @Test()
  public void testHelp()
  {
    String[] args = { "--help" };
    assertEquals(DSConfig.main(args, false, null, null),
        SUCCESSFUL.getReturnCode());
    args = new String[] { "-H" };
    assertEquals(DSConfig.main(args, false, null, null),
        SUCCESSFUL.getReturnCode());
    args = new String[] { "-?" };
    assertEquals(DSConfig.main(args, false, null, null),
        SUCCESSFUL.getReturnCode());
  }
}