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

Yannick Lecaillez
01.59.2015 c9be76aa5748caa7e04fd35386eb08b5c40d968a
OPENDJ-1959: Duplicated WARNING messages
25 files modified
623 ■■■■ changed files
opendj-cli/src/main/java/com/forgerock/opendj/cli/CommonArguments.java 2 ●●● patch | view | raw | blame | history
opendj-maven-plugin/src/main/resources/config/xml/org/forgerock/opendj/server/config/AdministrationConnectorConfiguration.xml 4 ●●●● patch | view | raw | blame | history
opendj-maven-plugin/src/main/resources/config/xml/org/forgerock/opendj/server/config/Package.xml 4 ●●●● patch | view | raw | blame | history
opendj-server-legacy/resource/config/config.ldif 6 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/resource/schema/02-config.ldif 1 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/quicksetup/SecurityOptions.java 2 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/quicksetup/installer/Installer.java 23 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/quicksetup/installer/offline/OfflineInstaller.java 5 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/admin/AdministrationConnector.java 40 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/backends/TrustStoreBackend.java 49 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/config/ConfigConstants.java 4 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/crypto/CryptoManagerImpl.java 19 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/protocols/http/HTTPConnectionHandler.java 27 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/protocols/jmx/JmxConnectionHandler.java 9 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/protocols/jmx/RmiConnector.java 18 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/protocols/ldap/LDAPConnectionHandler.java 24 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/replication/protocol/ReplSessionSecurity.java 20 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/tools/SSLConnectionFactory.java 4 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/types/CryptoManager.java 13 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/util/CertificateManager.java 6 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/util/Platform.java 98 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/util/SelectableCertificateKeyManager.java 150 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/util/cli/LDAPConnectionConsoleInteraction.java 5 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/messages/org/opends/messages/extension.properties 3 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/test/java/org/opends/server/util/CertificateManagerTestCase.java 87 ●●●● patch | view | raw | blame | history
opendj-cli/src/main/java/com/forgerock/opendj/cli/CommonArguments.java
@@ -1301,7 +1301,7 @@
     */
    public static StringArgument getCertNickName() throws ArgumentException {
        return new StringArgument(OPTION_LONG_CERT_NICKNAME.toLowerCase(), OPTION_SHORT_CERT_NICKNAME,
                OPTION_LONG_CERT_NICKNAME, false, false, true, INFO_NICKNAME_PLACEHOLDER.get(), null,
                OPTION_LONG_CERT_NICKNAME, false, true, true, INFO_NICKNAME_PLACEHOLDER.get(), null,
                OPTION_LONG_CERT_NICKNAME, INFO_ARGUMENT_DESCRIPTION_CERT_NICKNAME.get());
    }
opendj-maven-plugin/src/main/resources/config/xml/org/forgerock/opendj/server/config/AdministrationConnectorConfiguration.xml
@@ -23,7 +23,7 @@
  !
  !
  !      Copyright 2007-2008 Sun Microsystems, Inc.
  !      Portions Copyright 2012 ForgeRock, AS.
  !      Portions Copyright 2012-2015 ForgeRock AS.
  ! -->
<adm:managed-object name="administration-connector"
  plural-name="administration-connectors"
@@ -139,7 +139,7 @@
      </ldap:attribute>
    </adm:profile>
  </adm:property>
  <adm:property name="ssl-cert-nickname" mandatory="true">
  <adm:property name="ssl-cert-nickname" mandatory="true" multi-valued="true">
    <adm:synopsis>
      Specifies the nickname (also called the alias) of the certificate
      that the
opendj-maven-plugin/src/main/resources/config/xml/org/forgerock/opendj/server/config/Package.xml
@@ -23,7 +23,7 @@
  !
  !
  !      Copyright 2007-2009 Sun Microsystems, Inc.
  !      Portions Copyright 2011-2013 ForgeRock AS
  !      Portions Copyright 2011-2015 ForgeRock AS
  ! -->
<adm:package name="org.forgerock.opendj.server.config"
  xmlns:adm="http://opendj.forgerock.org/admin"
@@ -80,7 +80,7 @@
      </ldap:attribute>
    </adm:profile>
  </adm:property>
  <adm:property name="ssl-cert-nickname">
  <adm:property name="ssl-cert-nickname" multi-valued="true">
    <adm:TODO>Need a better default description.</adm:TODO>
    <adm:synopsis>
      Specifies the nickname (also called the alias) of the certificate
opendj-server-legacy/resource/config/config.ldif
@@ -105,6 +105,7 @@
objectClass: ds-cfg-crypto-manager
cn: Crypto Manager
ds-cfg-ssl-cert-nickname: ads-certificate
ds-cfg-ssl-cert-nickname: ads-certificate-ec
ds-cfg-ssl-encryption: false
dn: cn=Account Status Notification Handlers,cn=config
@@ -334,6 +335,7 @@
ds-cfg-use-ssl: false
ds-cfg-ssl-client-auth-policy: optional
ds-cfg-ssl-cert-nickname: server-cert
ds-cfg-ssl-cert-nickname: server-cert-ec
dn: cn=LDAPS Connection Handler,cn=Connection Handlers,cn=config
objectClass: top
@@ -358,6 +360,7 @@
ds-cfg-use-ssl: true
ds-cfg-ssl-client-auth-policy: optional
ds-cfg-ssl-cert-nickname: server-cert
ds-cfg-ssl-cert-nickname: server-cert-ec
ds-cfg-key-manager-provider: cn=JKS,cn=Key Manager Providers,cn=config
ds-cfg-trust-manager-provider: cn=JKS,cn=Trust Manager Providers,cn=config
@@ -381,6 +384,7 @@
ds-cfg-use-ssl: false
ds-cfg-ssl-client-auth-policy: optional
ds-cfg-ssl-cert-nickname: server-cert
ds-cfg-ssl-cert-nickname: server-cert-ec
ds-cfg-config-file: config/http-config.json
ds-cfg-authentication-required: true
@@ -404,6 +408,7 @@
ds-cfg-use-ssl: false
ds-cfg-listen-port: 1689
ds-cfg-ssl-cert-nickname: server-cert
ds-cfg-ssl-cert-nickname: server-cert-ec
dn: cn=Entry Caches,cn=config
objectClass: top
@@ -2455,6 +2460,7 @@
ds-cfg-listen-address: 0.0.0.0
ds-cfg-listen-port: 4444
ds-cfg-ssl-cert-nickname: admin-cert
ds-cfg-ssl-cert-nickname: admin-cert-ec
ds-cfg-key-manager-provider: cn=Administration,cn=Key Manager Providers,cn=config
ds-cfg-trust-manager-provider: cn=Administration,cn=Trust Manager Providers,cn=config
opendj-server-legacy/resource/schema/02-config.ldif
@@ -549,7 +549,6 @@
  NAME 'ds-cfg-ssl-cert-nickname'
  EQUALITY caseIgnoreMatch
  SYNTAX 1.3.6.1.4.1.1466.115.121.1.15
  SINGLE-VALUE
  X-ORIGIN 'OpenDS Directory Server' )
attributeTypes: ( 1.3.6.1.4.1.26027.1.1.92
  NAME 'ds-cfg-strict-format'
opendj-server-legacy/src/main/java/org/opends/quicksetup/SecurityOptions.java
@@ -40,6 +40,8 @@
  /** Alias of a self-signed certificate. */
  public static final String SELF_SIGNED_CERT_ALIAS = "server-cert";
  /** Alias of a self-signed certificate using elliptic curve. */
  public static final String SELF_SIGNED_EC_CERT_ALIAS = SELF_SIGNED_CERT_ALIAS + "-ec";
  /**
   * The different type of security options that we can have.
opendj-server-legacy/src/main/java/org/opends/quicksetup/installer/Installer.java
@@ -135,6 +135,7 @@
import org.opends.server.util.DynamicConstants;
import org.opends.server.util.SetupUtils;
import org.opends.server.util.StaticUtils;
import org.opends.server.util.Platform.KeyType;
import com.forgerock.opendj.util.OperatingSystem;
@@ -221,8 +222,10 @@
  /** A static String that contains the class name of ConfigFileHandler. */
  protected static final String DEFAULT_CONFIG_CLASS_NAME = "org.opends.server.extensions.ConfigFileHandler";
  /** Alias of a self-signed certificate. */
  protected static final String SELF_SIGNED_CERT_ALIAS = SecurityOptions.SELF_SIGNED_CERT_ALIAS;
  /** Aliases of self-signed certificates. */
  protected static final String SELF_SIGNED_CERT_ALIASES[] = new String[] {
    SecurityOptions.SELF_SIGNED_CERT_ALIAS,
    SecurityOptions.SELF_SIGNED_EC_CERT_ALIAS };
  /**
   * The threshold in minutes used to know whether we must display a warning
@@ -983,10 +986,14 @@
        String pwd = getSelfSignedCertificatePwd();
        final CertificateManager certManager =
            new CertificateManager(getSelfSignedKeystorePath(), CertificateManager.KEY_STORE_TYPE_JKS, pwd);
        certManager.generateSelfSignedCertificate(SELF_SIGNED_CERT_ALIAS, getSelfSignedCertificateSubjectDN(),
        for (String alias : SELF_SIGNED_CERT_ALIASES)
        {
          final KeyType keyType = KeyType.getTypeOrDefault(alias);
          certManager.generateSelfSignedCertificate(keyType, alias, getSelfSignedCertificateSubjectDN(keyType),
            getSelfSignedCertificateValidity());
        SetupUtils.exportCertificate(certManager, SELF_SIGNED_CERT_ALIAS, getTemporaryCertificatePath());
        configureTrustStore(CertificateManager.KEY_STORE_TYPE_JKS, SELF_SIGNED_CERT_ALIAS, pwd);
          SetupUtils.exportCertificate(certManager, alias, getTemporaryCertificatePath());
          configureTrustStore(CertificateManager.KEY_STORE_TYPE_JKS, alias, pwd);
        }
        break;
      case JKS:
@@ -1040,7 +1047,7 @@
  private void configureTrustStore(final String type, final String keyStoreAlias, final String password)
      throws Exception
  {
    final String alias = keyStoreAlias != null ? keyStoreAlias : SELF_SIGNED_CERT_ALIAS;
    final String alias = keyStoreAlias != null ? keyStoreAlias : SELF_SIGNED_CERT_ALIASES[0];
    final CertificateManager trustMgr = new CertificateManager(getTrustManagerPath(), type, password);
    trustMgr.addCertificate(alias, new File(getTemporaryCertificatePath()));
@@ -3891,9 +3898,9 @@
   *
   * @return the Subject DN to be used to generate the self-signed certificate.
   */
  private String getSelfSignedCertificateSubjectDN()
  private String getSelfSignedCertificateSubjectDN(KeyType keyType)
  {
    return "cn=" + Rdn.escapeValue(getUserData().getHostName()) + ",O=OpenDJ Self-Signed Certificate";
    return "cn=" + Rdn.escapeValue(getUserData().getHostName()) + ",O=OpenDJ " + keyType + " Self-Signed Certificate";
  }
  /**
opendj-server-legacy/src/main/java/org/opends/quicksetup/installer/offline/OfflineInstaller.java
@@ -381,7 +381,10 @@
            CertificateManager.KEY_STORE_TYPE_JKS,
            getSelfSignedCertificatePwd());
        try {
          cm.removeCertificate(SELF_SIGNED_CERT_ALIAS);
          for (String alias : SELF_SIGNED_CERT_ALIASES)
          {
            cm.removeCertificate(alias);
          }
        } catch (KeyStoreException e) {
          logger.info(LocalizableMessage.raw("Error deleting self signed certification", e));
        }
opendj-server-legacy/src/main/java/org/opends/server/admin/AdministrationConnector.java
@@ -63,6 +63,7 @@
import org.opends.server.types.FilePermission;
import org.opends.server.types.InitializationException;
import org.opends.server.util.CertificateManager;
import org.opends.server.util.Platform.KeyType;
import org.opends.server.util.SetupUtils;
/**
@@ -329,7 +330,7 @@
    /** {@inheritDoc} */
    @Override
    public String getSSLCertNickname()
    public SortedSet<String> getSSLCertNickname()
    {
      return config.getSSLCertNickname();
    }
@@ -456,7 +457,7 @@
      AdministrationConnectorCfg config = root.getAdministrationConnector();
      // Check if certificate generation is needed
      String certAlias = config.getSSLCertNickname();
      final SortedSet<String> certAliases = config.getSSLCertNickname();
      KeyManagerProviderCfg keyMgrConfig = root.getKeyManagerProvider(config
          .getKeyManagerProvider());
      TrustManagerProviderCfg trustMgrConfig = root
@@ -535,32 +536,39 @@
              .getKeyStoreType(), pwd);
      String hostName =
        SetupUtils.getHostNameForCertificate(DirectoryServer.getServerRoot());
      String subjectDN = "cn="
          + Rdn.escapeValue(hostName) + ",O="
          + FRIENDLY_NAME + " Self-Signed Certificate";
      certManager.generateSelfSignedCertificate(certAlias, subjectDN,
          ADMIN_CERT_VALIDITY);
      // Export the certificate
      // Temporary exported certificate's file
      String tempCertPath = getFullPath("config" + File.separator
          + "admin-cert.txt");
      SetupUtils.exportCertificate(certManager, certAlias, tempCertPath);
      // Create a new trust store and import the server certificate
      // into it
      CertificateManager trustManager = new CertificateManager(truststorePath,
          CertificateManager.KEY_STORE_TYPE_JKS, pwd);
      trustManager.addCertificate(certAlias, new File(tempCertPath));
      for (String certAlias : certAliases)
      {
        final KeyType keyType = KeyType.getTypeOrDefault(certAlias);
        final String subjectDN =
            "cn=" + Rdn.escapeValue(hostName) + ",O=" + FRIENDLY_NAME + " " + keyType + " Self-Signed Certificate";
        certManager.generateSelfSignedCertificate(keyType, certAlias, subjectDN, ADMIN_CERT_VALIDITY);
        SetupUtils.exportCertificate(certManager, certAlias, tempCertPath);
        // import the server certificate into it
        final File tempCertFile = new File(tempCertPath);
        trustManager.addCertificate(certAlias, tempCertFile);
        tempCertFile.delete();
      }
      // Generate a password file
      if (!new File(pinFilePath).exists())
      {
        FileWriter file = new FileWriter(pinFilePath);
        PrintWriter out = new PrintWriter(file);
        try (final FileWriter file = new FileWriter(pinFilePath);
             final PrintWriter out = new PrintWriter(file))
        {
        out.println(pwd);
        out.flush();
        out.close();
        file.close();
        }
      }
      // Change the password file permission if possible
@@ -578,10 +586,6 @@
        // Log a warning that the permissions were not set.
        logger.warn(WARN_ADMIN_SET_PERMISSIONS_FAILED, pinFilePath);
      }
      // Delete the exported certificate
      File f = new File(tempCertPath);
      f.delete();
    }
    catch (InitializationException e)
    {
opendj-server-legacy/src/main/java/org/opends/server/backends/TrustStoreBackend.java
@@ -81,6 +81,7 @@
import org.opends.server.types.*;
import org.opends.server.util.CertificateManager;
import org.opends.server.util.SetupUtils;
import org.opends.server.util.Platform.KeyType;
/**
 * This class defines a backend used to provide an LDAP view of public keys
@@ -1030,30 +1031,19 @@
  public KeyManager[] getKeyManagers()
         throws DirectoryException
  {
    KeyStore keyStore;
    FileInputStream inputStream = null;
    try
    final KeyStore keyStore;
    try (final FileInputStream inputStream = new FileInputStream(getFileForPath(trustStoreFile)))
    {
      keyStore = KeyStore.getInstance(trustStoreType);
      inputStream =
           new FileInputStream(getFileForPath(trustStoreFile));
      keyStore.load(inputStream, trustStorePIN);
    }
    catch (Exception e)
    {
      logger.traceException(e);
      LocalizableMessage message = ERR_TRUSTSTORE_CANNOT_LOAD.get(
          trustStoreFile, getExceptionMessage(e));
      throw new DirectoryException(DirectoryServer.getServerErrorResultCode(),
                                   message, e);
    }
    finally
    {
      close(inputStream);
    }
    try
    {
@@ -1216,9 +1206,11 @@
      {
        try
        {
          final KeyType keyType = KeyType.getTypeOrDefault(certAlias);
          certificateManager.generateSelfSignedCertificate(
             keyType,
             certAlias,
             getADSCertificateSubjectDN(),
             getADSCertificateSubjectDN(keyType),
             getADSCertificateValidity());
        }
        catch (Exception e)
@@ -1362,12 +1354,10 @@
   * @throws java.net.UnknownHostException If the server host name could not be
   *                                       determined.
   */
  private static String getADSCertificateSubjectDN()
       throws UnknownHostException
  private static String getADSCertificateSubjectDN(KeyType keyType) throws UnknownHostException
  {
    String hostName =
      SetupUtils.getHostNameForCertificate(DirectoryServer.getServerRoot());
    return "cn=" + Rdn.escapeValue(hostName) + ",O=OpenDJ Certificate";
    final String hostName = SetupUtils.getHostNameForCertificate(DirectoryServer.getServerRoot());
    return "cn=" + Rdn.escapeValue(hostName) + ",O=OpenDJ " + keyType + " Certificate";
  }
  /**
@@ -1439,13 +1429,12 @@
  public static void createPINFile(String path, String pin)
       throws IOException
  {
    FileWriter file = new FileWriter(path);
    PrintWriter out = new PrintWriter(file);
    try (final FileWriter file = new FileWriter(path);
         final PrintWriter out = new PrintWriter(file))
    {
    out.println(pin);
    out.flush();
    out.close();
    }
    try {
      if (!FilePermission.setPermissions(new File(path),
@@ -1468,13 +1457,15 @@
  private void generateInstanceCertificateIfAbsent()
       throws InitializationException
  {
    String certAlias = ADS_CERTIFICATE_ALIAS;
    final String certAliases[] = { ADS_CERTIFICATE_ALIAS, ADS_CERTIFICATE_EC_ALIAS };
    for (String certAlias : certAliases)
    {
    try
    {
      if (certificateManager.aliasInUse(certAlias))
      {
        return;
          continue;
      }
    }
    catch (Exception e)
@@ -1486,9 +1477,11 @@
    try
    {
        final KeyType keyType = KeyType.getTypeOrDefault(certAlias);
      certificateManager.generateSelfSignedCertificate(
            keyType,
           certAlias,
           getADSCertificateSubjectDN(),
            getADSCertificateSubjectDN(keyType),
           getADSCertificateValidity());
    }
    catch (Exception e)
@@ -1497,7 +1490,7 @@
           certAlias, trustStoreFile, getExceptionMessage(e));
      throw new InitializationException(message, e);
    }
    }
  }
}
opendj-server-legacy/src/main/java/org/opends/server/config/ConfigConstants.java
@@ -2821,6 +2821,10 @@
   */
  public static final String ADS_CERTIFICATE_ALIAS = "ads-certificate";
  /**
   * Alias of the local instance certificate in the ADS keystore using elliptic curve.
   */
  public static final String ADS_CERTIFICATE_EC_ALIAS = ADS_CERTIFICATE_ALIAS + "-ec";
  /**
opendj-server-legacy/src/main/java/org/opends/server/crypto/CryptoManagerImpl.java
@@ -49,7 +49,6 @@
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509ExtendedKeyManager;
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.i18n.slf4j.LocalizedLogger;
@@ -209,8 +208,8 @@
  // TODO: Move the following configuration to replication configuration.
  // TODO: https://opends.dev.java.net/issues/show_bug.cgi?id=2473
  /** The name of the local certificate to use for SSL. */
  private final String sslCertNickname;
  /** The names of the local certificates to use for SSL. */
  private final SortedSet<String> sslCertNicknames;
  /** Whether replication sessions use SSL encryption. */
  private final boolean sslEncryption;
@@ -296,7 +295,7 @@
    applyConfigurationChange(config);
    // Secure replication related...
    sslCertNickname = config.getSSLCertNickname();
    sslCertNicknames = config.getSSLCertNickname();
    sslEncryption   = config.isSSLEncryption();
    sslProtocols    = config.getSSLProtocol();
    sslCipherSuites = config.getSSLCipherSuite();
@@ -2868,7 +2867,7 @@
  /** {@inheritDoc} */
  @Override
  public SSLContext getSslContext(String sslCertNickname)
  public SSLContext getSslContext(SortedSet<String> sslCertNicknames)
       throws ConfigException
  {
    SSLContext sslContext;
@@ -2881,16 +2880,16 @@
      sslContext = SSLContext.getInstance("TLS");
      if (sslCertNickname == null)
      if (sslCertNicknames == null)
      {
        sslContext.init(keyManagers, trustManagers, null);
      }
      else
      {
        X509ExtendedKeyManager[] extendedKeyManagers =
        KeyManager[] extendedKeyManagers =
             SelectableCertificateKeyManager.wrap(
                  keyManagers,
                  sslCertNickname);
                  sslCertNicknames);
        sslContext.init(extendedKeyManagers, trustManagers, null);
      }
    }
@@ -2910,9 +2909,9 @@
  /** {@inheritDoc} */
  @Override
  public String getSslCertNickname()
  public SortedSet<String> getSslCertNicknames()
  {
    return sslCertNickname;
    return sslCertNicknames;
  }
  /** {@inheritDoc} */
opendj-server-legacy/src/main/java/org/opends/server/protocols/http/HTTPConnectionHandler.java
@@ -40,12 +40,15 @@
import java.net.InetAddress;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
@@ -873,7 +876,8 @@
    DN keyMgrDN = config.getKeyManagerProviderDN();
    KeyManagerProvider<?> keyManagerProvider = DirectoryServer.getKeyManagerProvider(keyMgrDN);
    if (keyManagerProvider == null) {
    if (keyManagerProvider == null)
    {
      logger.error(ERR_NULL_KEY_PROVIDER_MANAGER, keyMgrDN, friendlyName);
      logger.warn(INFO_DISABLE_CONNECTION, friendlyName);
      keyManagerProvider = new NullKeyManagerProvider();
@@ -886,20 +890,29 @@
      enabled = false;
    }
    String alias = config.getSSLCertNickname();
    KeyManager[] keyManagers;
    if (alias == null)
    final SortedSet<String> aliases = new TreeSet<>(config.getSSLCertNickname());
    final KeyManager[] keyManagers;
    if (aliases.isEmpty())
    {
      keyManagers = keyManagerProvider.getKeyManagers();
    }
    else
    {
      if (! keyManagerProvider.containsKeyWithAlias(alias)) {
        logger.error(ERR_KEYSTORE_DOES_NOT_CONTAIN_ALIAS, alias, friendlyName);
      final Iterator<String> it = aliases.iterator();
      while (it.hasNext())
      {
        if (!keyManagerProvider.containsKeyWithAlias(it.next()))
        {
          logger.error(ERR_KEYSTORE_DOES_NOT_CONTAIN_ALIAS, aliases, friendlyName);
          it.remove();
        }
      }
      if (aliases.isEmpty())
      {
        logger.warn(INFO_DISABLE_CONNECTION, friendlyName);
        enabled = false;
      }
      keyManagers = SelectableCertificateKeyManager.wrap(keyManagerProvider.getKeyManagers(), alias);
      keyManagers = SelectableCertificateKeyManager.wrap(keyManagerProvider.getKeyManagers(), aliases);
    }
    DN trustMgrDN = config.getTrustManagerProviderDN();
opendj-server-legacy/src/main/java/org/opends/server/protocols/jmx/JmxConnectionHandler.java
@@ -36,6 +36,7 @@
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.SortedSet;
import java.util.concurrent.CopyOnWriteArrayList;
import org.forgerock.i18n.LocalizableMessage;
@@ -175,7 +176,7 @@
  }
  private boolean notEqualsNotNull(String o1, String o2)
  private <T> boolean notEqualsNotNull(T o1, T o2)
  {
    return o1 != null && !o1.equals(o2);
  }
@@ -284,13 +285,13 @@
  /**
   * Retrieves the nickname of the server certificate that should be
   * Retrieves the nicknames of the server certificates that should be
   * used in conjunction with this JMX connection handler.
   *
   * @return The nickname of the server certificate that should be
   * @return The nicknames of the server certificates that should be
   *         used in conjunction with this JMX connection handler.
   */
  public String getSSLServerCertNickname() {
  public SortedSet<String> getSSLServerCertNicknames() {
    return currentConfig.getSSLCertNickname();
  }
opendj-server-legacy/src/main/java/org/opends/server/protocols/jmx/RmiConnector.java
@@ -32,6 +32,7 @@
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.HashMap;
import java.util.SortedSet;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLSocketFactory;
@@ -279,26 +280,19 @@
        // SERVER SIDE
        // ---------------------
        // Get a Server socket factory
        KeyManager[] keyManagers;
        KeyManagerProvider provider = DirectoryServer
            .getKeyManagerProvider(jmxConnectionHandler
                .getKeyManagerProviderDN());
        final KeyManager[] keyManagers;
        if (provider == null) {
          keyManagers = new NullKeyManagerProvider().getKeyManagers();
        }
        else
        {
          String nickname = jmxConnectionHandler.getSSLServerCertNickname();
          if (nickname == null)
          {
            keyManagers = provider.getKeyManagers();
          }
          else
          {
            keyManagers =
                 SelectableCertificateKeyManager.wrap(provider.getKeyManagers(),
                                                      nickname);
          }
          final SortedSet<String> nicknames = jmxConnectionHandler.getSSLServerCertNicknames();
          keyManagers = nicknames == null
              ? provider.getKeyManagers()
              : SelectableCertificateKeyManager.wrap(provider.getKeyManagers(), nicknames);
        }
        SSLContext ctx = SSLContext.getInstance("TLSv1");
opendj-server-legacy/src/main/java/org/opends/server/protocols/ldap/LDAPConnectionHandler.java
@@ -1422,21 +1422,29 @@
        disableAndWarnIfUseSSL(config);
      }
      String alias = config.getSSLCertNickname();
      KeyManager[] keyManagers;
      if (alias == null)
      final SortedSet<String> aliases = new TreeSet<>(config.getSSLCertNickname());
      final KeyManager[] keyManagers;
      if (aliases.isEmpty())
      {
        keyManagers = keyManagerProvider.getKeyManagers();
      }
      else
      {
        if (!keyManagerProvider.containsKeyWithAlias(alias))
        final Iterator<String> it = aliases.iterator();
        while (it.hasNext())
        {
          logger.error(ERR_KEYSTORE_DOES_NOT_CONTAIN_ALIAS, alias, friendlyName);
          if (!keyManagerProvider.containsKeyWithAlias(it.next()))
          {
            logger.error(ERR_KEYSTORE_DOES_NOT_CONTAIN_ALIAS, aliases, friendlyName);
            it.remove();
          }
        }
        if (aliases.isEmpty())
        {
          disableAndWarnIfUseSSL(config);
        }
        keyManagers = SelectableCertificateKeyManager.wrap(
            keyManagerProvider.getKeyManagers(), alias, friendlyName);
        keyManagers = SelectableCertificateKeyManager.wrap(keyManagerProvider.getKeyManagers(), aliases, friendlyName);
      }
      DN trustMgrDN = config.getTrustManagerProviderDN();
@@ -1462,8 +1470,6 @@
    }
  }
  /**
   * Enqueue a connection finalizer which will be invoked after a short delay.
   *
opendj-server-legacy/src/main/java/org/opends/server/replication/protocol/ReplSessionSecurity.java
@@ -60,9 +60,9 @@
  private final boolean sslEncryption;
  /**
   * The name of the local certificate to use, or null if none is specified.
   * The names of the local certificates to use, or null if none is specified.
   */
  private final String sslCertNickname;
  private final SortedSet<String> sslCertNicknames;
  /**
   * The set of enabled SSL protocols, or null for the default set.
@@ -86,7 +86,7 @@
  public ReplSessionSecurity() throws ConfigException
  {
    // Currently use global settings from the crypto manager.
    this(DirectoryConfig.getCryptoManager().getSslCertNickname(),
    this(DirectoryConfig.getCryptoManager().getSslCertNicknames(),
        DirectoryConfig.getCryptoManager().getSslProtocols(),
        DirectoryConfig.getCryptoManager().getSslCipherSuites(),
        DirectoryConfig.getCryptoManager().isSslEncryption());
@@ -98,8 +98,8 @@
   * Create a ReplSessionSecurity instance from the supplied configuration
   * values.
   *
   * @param sslCertNickname
   *          The name of the local certificate to use, or null if none is
   * @param sslCertNicknames
   *          The names of the local certificates to use, or null if none is
   *          specified.
   * @param sslProtocols
   *          The protocols that should be enabled, or null if the default
@@ -112,7 +112,7 @@
   * @throws ConfigException
   *           If the supplied configuration was not valid.
   */
  public ReplSessionSecurity(final String sslCertNickname,
  public ReplSessionSecurity(final SortedSet<String> sslCertNicknames,
      final SortedSet<String> sslProtocols,
      final SortedSet<String> sslCipherSuites,
      final boolean sslEncryption) throws ConfigException
@@ -138,7 +138,7 @@
    }
    this.sslEncryption = sslEncryption;
    this.sslCertNickname = sslCertNickname;
    this.sslCertNicknames = sslCertNicknames;
  }
@@ -169,8 +169,7 @@
      // Create a new SSL context every time to make sure we pick up the
      // latest contents of the trust store.
      final CryptoManager cryptoManager = DirectoryConfig.getCryptoManager();
      final SSLContext sslContext = cryptoManager
          .getSslContext(sslCertNickname);
      final SSLContext sslContext = cryptoManager.getSslContext(sslCertNicknames);
      final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
      secureSocket = (SSLSocket) sslSocketFactory.createSocket(
@@ -232,8 +231,7 @@
      // Create a new SSL context every time to make sure we pick up the
      // latest contents of the trust store.
      final CryptoManager cryptoManager = DirectoryConfig.getCryptoManager();
      final SSLContext sslContext = cryptoManager
          .getSslContext(sslCertNickname);
      final SSLContext sslContext = cryptoManager.getSslContext(sslCertNicknames);
      final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
      secureSocket = (SSLSocket) sslSocketFactory.createSocket(
opendj-server-legacy/src/main/java/org/opends/server/tools/SSLConnectionFactory.java
@@ -45,6 +45,7 @@
import org.opends.server.extensions.BlindTrustManagerProvider;
import org.forgerock.i18n.slf4j.LocalizedLogger;
import org.opends.server.util.CollectionUtils;
import org.opends.server.util.ExpirationCheckTrustManager;
import org.opends.server.util.SelectableCertificateKeyManager;
@@ -123,8 +124,7 @@
        if (clientAlias != null)
        {
          keyManagers = SelectableCertificateKeyManager.wrap(keyManagers,
                                                             clientAlias);
          keyManagers = SelectableCertificateKeyManager.wrap(keyManagers, CollectionUtils.newTreeSet(clientAlias));
        }
      }
opendj-server-legacy/src/main/java/org/opends/server/types/CryptoManager.java
@@ -22,7 +22,7 @@
 *
 *
 *      Copyright 2006-2009 Sun Microsystems, Inc.
 *      Portions Copyright 2014 ForgeRock AS
 *      Portions Copyright 2014-2015 ForgeRock AS
 */
package org.opends.server.types;
@@ -400,20 +400,19 @@
   * Create an SSL context that may be used for communication to
   * another ADS component.
   *
   * @param sslCertNickname The name of the local certificate to use,
   * @param sslCertNicknames The names of the local certificates to use,
   *                        or null if none is specified.
   * @return A new SSL Context.
   * @throws ConfigException If the context
   * could not be created.
   */
  SSLContext getSslContext(String sslCertNickname)
       throws ConfigException;
  SSLContext getSslContext(SortedSet<String> sslCertNicknames) throws ConfigException;
  /**
   * Get the name of the local certificate to use for SSL.
   * @return The name of the local certificate to use for SSL.
   * Get the names of the local certificates to use for SSL.
   * @return The names of the local certificates to use for SSL.
   */
  String getSslCertNickname();
  SortedSet<String> getSslCertNicknames();
  /**
   * Determine whether SSL encryption is enabled.
opendj-server-legacy/src/main/java/org/opends/server/util/CertificateManager.java
@@ -33,6 +33,7 @@
import java.util.Enumeration;
import org.forgerock.i18n.LocalizableMessage;
import static org.opends.messages.UtilityMessages.*;
import org.opends.server.util.Platform.KeyType;
/**
 * This class provides an interface for generating self-signed certificates and
@@ -249,6 +250,7 @@
  /**
   * Generates a self-signed certificate using the provided information.
   *
   * @param  keyType    Specifies the key size, key and signature algorithms.
   * @param  alias      The nickname to use for the certificate in the key
   *                    store.  For the server certificate, it should generally
   *                    be "server-cert".  It must not be {@code null} or empty.
@@ -263,7 +265,7 @@
   *                                 positive integer, or the alias is already
   *                                 in the keystore.
   */
  public void generateSelfSignedCertificate(String alias, String subjectDN,
  public void generateSelfSignedCertificate(KeyType keyType, String alias, String subjectDN,
                                            int validity)
  throws KeyStoreException, IllegalArgumentException {
    ensureValid(alias, CERT_ALIAS_MSG);
@@ -278,7 +280,7 @@
    }
    keyStore = null;
    Platform.generateSelfSignedCertificate(getKeyStore(), keyStoreType,
        keyStorePath, alias, password, subjectDN, validity);
        keyStorePath, keyType, alias, password, subjectDN, validity);
  }
opendj-server-legacy/src/main/java/org/opends/server/util/Platform.java
@@ -94,19 +94,54 @@
    IMPL = new DefaultPlatformIMPL();
  }
  /** Key size, key algorithm and signature algorithms used. */
  public static enum KeyType
  {
    /** RSA key algorithm with 2048 bits size and SHA1withRSA signing algorithm. */
    RSA("rsa", 2048, "SHA1WithRSA"),
    /** Elliptic Curve key algorithm with 233 bits size and SHA1withECDSA signing algorithm. */
    EC("ec", 233, "SHA1withECDSA");
    /** Default key type used when none can be determined. */
    public final static KeyType DEFAULT = RSA;
    final String keyAlgorithm;
    final int keySize;
    final String signatureAlgorithm;
    private KeyType(String keyAlgorithm, int keySize, String signatureAlgorithm)
    {
      this.keySize = keySize;
      this.keyAlgorithm = keyAlgorithm;
      this.signatureAlgorithm = signatureAlgorithm;
    }
    /**
     * Get a KeyType based on the alias name.
     *
     * @param alias
     *          certificate alias
     * @return KeyTpe deduced from the alias.
     */
    public static KeyType getTypeOrDefault(String alias)
    {
      try
      {
        return KeyType.valueOf(alias.substring(alias.lastIndexOf('-') + 1).toUpperCase());
      }
      catch (Exception e)
      {
        return KeyType.DEFAULT;
      }
    }
  }
  /**
   * Platform base class. Performs all of the certificate management functions.
   */
  private static abstract class PlatformIMPL
  {
    /** Key size, key algorithm and signature algorithms used. */
    private static final int KEY_SIZE = 1024;
    private static final String KEY_ALGORITHM = "rsa";
    private static final String SIG_ALGORITHM = "SHA1WithRSA";
    /** Time values used in validity calculations. */
    private static final int SEC_IN_DAY = 24 * 60 * 60;
@@ -272,8 +307,8 @@
    private final KeyStore generateSelfSignedCertificate(KeyStore ks,
        String ksType, String ksPath, String alias, char[] pwd, String dn,
    private static final KeyStore generateSelfSignedCertificate(KeyStore ks,
        String ksType, String ksPath, KeyType keyType, String alias, char[] pwd, String dn,
        int validity) throws KeyStoreException
    {
      try
@@ -288,26 +323,26 @@
          LocalizableMessage msg = ERR_CERTMGR_ALIAS_ALREADY_EXISTS.get(alias);
          throw new KeyStoreException(msg.toString());
        }
        Object keypair = certKeyGenCons.newInstance(KEY_ALGORITHM,
            SIG_ALGORITHM);
        Object subject = X500NameCons.newInstance(dn);
        Method certAndKeyGenGenerate = certKeyGenClass.getMethod(
            GENERATE_METHOD, int.class);
        certAndKeyGenGenerate.invoke(keypair, KEY_SIZE);
        Method certAndKeyGetPrivateKey = certKeyGenClass
            .getMethod(GET_PRIVATE_KEY_METHOD);
        PrivateKey privatevKey = (PrivateKey) certAndKeyGetPrivateKey
            .invoke(keypair);
        Certificate[] certificateChain = new Certificate[1];
        Method getSelfCertificate = certKeyGenClass.getMethod(
            GET_SELFSIGNED_CERT_METHOD, X500NameClass, long.class);
        int days = validity * SEC_IN_DAY;
        certificateChain[0] = (Certificate) getSelfCertificate.invoke(keypair,
            subject, days);
        ks.setKeyEntry(alias, privatevKey, pwd, certificateChain);
        FileOutputStream fileOutStream = new FileOutputStream(ksPath);
        try (final FileOutputStream fileOutStream = new FileOutputStream(ksPath))
        {
            final Object keypair = certKeyGenCons.newInstance(keyType.keyAlgorithm, keyType.signatureAlgorithm);
            final Method certAndKeyGenGenerate = certKeyGenClass.getMethod(GENERATE_METHOD, int.class);
            certAndKeyGenGenerate.invoke(keypair, keyType.keySize);
            final Method certAndKeyGetPrivateKey = certKeyGenClass.getMethod(GET_PRIVATE_KEY_METHOD);
            final Certificate[] certificateChain = new Certificate[1];
            final Method getSelfCertificate =
                certKeyGenClass.getMethod(GET_SELFSIGNED_CERT_METHOD, X500NameClass, long.class);
            final int days = validity * SEC_IN_DAY;
            final Object subject = X500NameCons.newInstance(dn);
            certificateChain[0] = (Certificate) getSelfCertificate.invoke(keypair, subject, days);
            ks.setKeyEntry(alias , (PrivateKey) certAndKeyGetPrivateKey.invoke(keypair), pwd, certificateChain);
        ks.store(fileOutStream, pwd);
        fileOutStream.close();
        }
      }
      catch (Exception e)
      {
@@ -485,10 +520,12 @@
   * @param ks
   *          The keystore to save the certificate in. May be null if it does
   *          not exist.
   * @param ksType
   * @param keyType
   *          The keystore type to use if the keystore is created.
   * @param ksPath
   *          The path to the keystore if the keystore is created.
   * @param ksType
   *          Specify the key size, key algorithm and signature algorithms used.
   * @param alias
   *          The alias to store the certificate under.
   * @param pwd
@@ -501,11 +538,10 @@
   *           If the self-signed certificate cannot be generated.
   */
  public static void generateSelfSignedCertificate(KeyStore ks, String ksType,
      String ksPath, String alias, char[] pwd, String dn, int validity)
      String ksPath, KeyType keyType, String alias, char[] pwd, String dn, int validity)
      throws KeyStoreException
  {
    IMPL.generateSelfSignedCertificate(ks, ksType, ksPath, alias, pwd, dn,
        validity);
    PlatformIMPL.generateSelfSignedCertificate(ks, ksType, ksPath, keyType, alias, pwd, dn, validity);
  }
  /**
opendj-server-legacy/src/main/java/org/opends/server/util/SelectableCertificateKeyManager.java
@@ -32,12 +32,14 @@
import java.security.Principal;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.SortedSet;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.X509ExtendedKeyManager;
import javax.net.ssl.X509KeyManager;
import static org.opends.messages.ExtensionMessages.INFO_KEYSTORE_DOES_NOT_CONTAIN_ALIAS;
import static org.opends.messages.ExtensionMessages.INFO_MISSING_KEY_TYPE_IN_ALIASES;
/**
 * This class implements an X.509 key manager that will be used to wrap an
@@ -56,8 +58,8 @@
{
  private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
  /** The alias of the certificate that should be selected from the key manager. */
  private final String alias;
  /** The aliases of the certificates that should be selected from the key manager. */
  private final SortedSet<String> aliases;
  /** The key manager that is wrapped by this key manager. */
  private final X509KeyManager keyManager;
@@ -65,41 +67,22 @@
  /** Provide additional troubleshooting aid to localize a misconfigured SSL connection. */
  private final String componentName;
  /**
   * Creates a new instance of this key manager that will wrap the provided key
   * manager and use the certificate with the specified alias.
   *
   * @param  keyManager       The key manager to be wrapped by this key manager.
   * @param  alias            The nickname of the certificate that should be
   *                          selected for operations involving this key manager.
   * @param  componentName    Name of the component to which is associated this key manager
   */
  public SelectableCertificateKeyManager(X509KeyManager keyManager,
                                         String alias, String componentName)
  private SelectableCertificateKeyManager(X509KeyManager keyManager, SortedSet<String> aliases, String componentName)
  {
    super();
    this.keyManager = keyManager;
    this.alias      = alias;
    this.aliases = aliases;
    this.componentName       = componentName;
  }
  /**
   * Creates a new instance of this key manager that will wrap the provided key
   * manager and use the certificate with the specified alias.
   *
   * @param  keyManager  The key manager to be wrapped by this key manager.
   * @param  alias       The nickname of the certificate that should be
   *                     selected for operations involving this key manager.
   */
  public SelectableCertificateKeyManager(X509KeyManager keyManager,
                                         String alias)
  private SelectableCertificateKeyManager(X509KeyManager keyManager, String alias)
  {
    this(keyManager, alias, "[unknown]");
    super();
    this.keyManager = keyManager;
    this.aliases = CollectionUtils.newTreeSet(alias);
    this.componentName = "[unkown]";
  }
  /**
   * Chooses the alias of the client certificate that should be used based on
   * the provided criteria.  This will either return the preferred alias
@@ -115,29 +98,46 @@
   * @return  The alias configured for this key manager, or {@code null} if no
   *          such client certificate is available with that alias.
   */
  @Override
  public String chooseClientAlias(String[] keyType, Principal[] issuers,
                                  Socket socket)
  {
    return findClientAlias(keyType, issuers);
  }
  private String findClientAlias(String keyType[], Principal[] issuers)
  {
    for (String type : keyType)
    {
      String[] clientAliases = keyManager.getClientAliases(type, issuers);
      if (clientAliases != null)
      final String clientAlias = findAlias(keyManager.getClientAliases(type, issuers));
      if ( clientAlias != null )
      {
        for (String clientAlias : clientAliases)
        return clientAlias;
      }
    }
    logger.warn(INFO_MISSING_KEY_TYPE_IN_ALIASES, componentName, aliases.toString(), Arrays.toString(keyType));
    return null;
  }
  private String findAlias(String[] candidates)
        {
          if (clientAlias.equals(alias))
    if (candidates == null)
    {
      return null;
    }
    for (String alias : candidates)
    {
      for (String certificateAlias : aliases)
      {
        if (certificateAlias.equalsIgnoreCase(alias))
          {
            return alias;
          }
        }
      }
    }
    logger.warn(INFO_KEYSTORE_DOES_NOT_CONTAIN_ALIAS, componentName, keyType, alias);
    return null;
  }
  /**
   * Chooses the alias of the client certificate that should be used based on
   * the provided criteria.  This will either return the preferred alias
@@ -157,11 +157,9 @@
  public String chooseEngineClientAlias(String[] keyType, Principal[] issuers,
                                        SSLEngine engine)
  {
    return chooseClientAlias(keyType, issuers, null);
    return findClientAlias(keyType, issuers);
  }
  /**
   * Chooses the alias of the server certificate that should be used based on
   * the provided criteria.  This will either return the preferred alias
@@ -176,27 +174,27 @@
   * @return  The alias configured for this key manager, or {@code null} if no
   *          such server certificate is available with that alias.
   */
  @Override
  public String chooseServerAlias(String keyType, Principal[] issuers,
                                  Socket socket)
  {
    String[] serverAliases = keyManager.getServerAliases(keyType, issuers);
    if (serverAliases != null)
    {
      for (String serverAlias : serverAliases)
      {
        if (serverAlias.equals(alias))
        {
          return alias;
        }
      }
    return findServerAlias(new String[] { keyType }, issuers);
    }
    logger.warn(INFO_KEYSTORE_DOES_NOT_CONTAIN_ALIAS, componentName, keyType, alias);
  private String findServerAlias(String keyType[], Principal[] issuers)
  {
    for (String type : keyType)
    {
      final String serverAlias = findAlias(keyManager.getServerAliases(type, issuers));
      if (serverAlias != null)
      {
        return serverAlias;
      }
    }
    logger.warn(INFO_MISSING_KEY_TYPE_IN_ALIASES, componentName, aliases.toString(), Arrays.toString(keyType));
    return null;
  }
  /**
   * Chooses the alias of the server certificate that should be used based on
   * the provided criteria.  This will either return the preferred alias
@@ -218,23 +216,8 @@
  public String chooseEngineServerAlias(String keyType, Principal[] issuers,
                                        SSLEngine engine)
  {
    String[] serverAliases = keyManager.getServerAliases(keyType, issuers);
    if (serverAliases != null)
    {
      for (String serverAlias : serverAliases)
      {
        if (serverAlias.equalsIgnoreCase(alias))
        {
          return serverAlias;
    return findServerAlias(new String[] { keyType }, issuers);
        }
      }
    }
    logger.warn(INFO_KEYSTORE_DOES_NOT_CONTAIN_ALIAS, componentName, keyType, alias);
    return null;
  }
  /**
   * Retrieves the certificate chain for the provided alias.
@@ -244,13 +227,12 @@
   * @return  The certificate chain for the provided alias, or {@code null} if
   *          no certificate is associated with the provided alias.
   */
  @Override
  public X509Certificate[] getCertificateChain(String alias)
  {
    return keyManager.getCertificateChain(alias);
  }
  /**
   * Retrieves the set of certificate aliases that may be used for client
   * authentication with the given public key type and set of issuers.
@@ -263,13 +245,12 @@
   *          authentication with the given public key type and set of issuers,
   *          or {@code null} if there were none.
   */
  @Override
  public String[] getClientAliases(String keyType, Principal[] issuers)
  {
    return keyManager.getClientAliases(keyType, issuers);
  }
  /**
   * Retrieves the private key for the provided alias.
   *
@@ -278,13 +259,12 @@
   * @return  The private key for the provided alias, or {@code null} if no
   *          private key is available for the provided alias.
   */
  @Override
  public PrivateKey getPrivateKey(String alias)
  {
    return keyManager.getPrivateKey(alias);
  }
  /**
   * Retrieves the set of certificate aliases that may be used for server
   * authentication with the given public key type and set of issuers.
@@ -297,33 +277,31 @@
   *          authentication with the given public key type and set of issuers,
   *          or {@code null} if there were none.
   */
  @Override
  public String[] getServerAliases(String keyType, Principal[] issuers)
  {
    return keyManager.getServerAliases(keyType, issuers);
  }
  /**
   * Wraps the provided set of key managers in selectable certificate key
   * managers using the provided alias.
   *
   * @param  keyManagers      The set of key managers to be wrapped.
   * @param  alias            The alias to use for selecting the desired
   * @param  aliases          The aliases to use for selecting the desired
   *                          certificate.
   * @param  componentName    Name of the component to which is associated this key manager
   *
   * @return  A key manager array
   */
  public static X509ExtendedKeyManager[] wrap(KeyManager[] keyManagers,
                                              String alias, String componentName)
  public static KeyManager[] wrap(KeyManager[] keyManagers,
                                  SortedSet<String> aliases, String componentName)
  {
    X509ExtendedKeyManager[] newKeyManagers =
         new X509ExtendedKeyManager[keyManagers.length];
    final KeyManager[] newKeyManagers = new KeyManager[keyManagers.length];
    for (int i=0; i < keyManagers.length; i++)
    {
      newKeyManagers[i] = new SelectableCertificateKeyManager(
                                   (X509KeyManager) keyManagers[i], alias, componentName);
                                   (X509KeyManager) keyManagers[i], aliases, componentName);
    }
    return newKeyManagers;
@@ -334,12 +312,12 @@
   * managers using the provided alias.
   *
   * @param  keyManagers      The set of key managers to be wrapped.
   * @param  alias            The alias to use for selecting the desired
   * @param  aliases            The aliases to use for selecting the desired
   *                          certificate.
   *
   * @return  A key manager array
   */
  public static X509ExtendedKeyManager[] wrap(KeyManager[] keyManagers, String alias) {
    return wrap(keyManagers, alias, "[unknown]");
  public static KeyManager[] wrap(KeyManager[] keyManagers, SortedSet<String> aliases) {
    return wrap(keyManagers, aliases, "[unknown]");
  }
}
opendj-server-legacy/src/main/java/org/opends/server/util/cli/LDAPConnectionConsoleInteraction.java
@@ -54,6 +54,7 @@
import org.opends.server.tools.LDAPConnectionOptions;
import org.opends.server.tools.SSLConnectionException;
import org.opends.server.tools.SSLConnectionFactory;
import org.opends.server.util.CollectionUtils;
import org.opends.server.util.SelectableCertificateKeyManager;
import com.forgerock.opendj.cli.ArgumentException;
@@ -1309,7 +1310,9 @@
    {
      copySecureArgsList.certNicknameArg.clearValues();
      copySecureArgsList.certNicknameArg.addValue(state.certifNickname);
      return new SelectableCertificateKeyManager(akm, state.certifNickname);
      return SelectableCertificateKeyManager.wrap(
          new KeyManager[] { akm },
          CollectionUtils.newTreeSet(state.certifNickname))[0];
    }
    return akm;
  }
opendj-server-legacy/src/messages/org/opends/messages/extension.properties
@@ -1022,4 +1022,5 @@
ERR_CHARSET_VALIDATOR_SHORT_RANGE_635=The provided character range \
 definition '%s' is invalid because the range '%s' is too short
ERR_NO_KEY_ENTRY_IN_KEYSTORE_636=There is no private key entry in keystore %s
INFO_KEYSTORE_DOES_NOT_CONTAIN_ALIAS_637=handshake for '%s': cipher is expecting key %s to be of type %s
INFO_MISSING_KEY_TYPE_IN_ALIASES_637=Handshake for '%s': cipher requires \
 the aliase(s) %s \ to contains key(s) of type(s) %s.
opendj-server-legacy/src/test/java/org/opends/server/util/CertificateManagerTestCase.java
@@ -35,9 +35,11 @@
import java.util.Arrays;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.opends.server.TestCaseUtils;
import org.opends.server.util.Platform.KeyType;
import static org.testng.Assert.*;
@@ -65,35 +67,24 @@
  /**
   * The path to a JKS key store file.
   */
  public static final String JKS_KEY_STORE_PATH =
       System.getProperty(TestCaseUtils.PROPERTY_BUILD_DIR,
       BUILD_ROOT + File.separator + "build") +
       File.separator + "unit-tests" + File.separator +
       "package-instance" +
       File.separator + "config" + File.separator + "server.keystore";
  public static final String JKS_KEY_STORE_PATH = TestCaseUtils.getUnitTestRootPath()
       + File.separator + "package-instance" + File.separator + "config" + File.separator + "server.keystore";
  /**
   * The path to a PKCS#12 key store file.
   */
  public static final String PKCS12_KEY_STORE_PATH =
       System.getProperty(TestCaseUtils.PROPERTY_BUILD_DIR,
       BUILD_ROOT + File.separator + "build") +
       File.separator + "unit-tests" + File.separator +
       "package-instance" +
       File.separator + "config" + File.separator + "server-cert.p12";
  public static final String PKCS12_KEY_STORE_PATH = TestCaseUtils.getUnitTestRootPath()
       + File.separator + "package-instance" + File.separator + "config" + File.separator + "server-cert.p12";
  /**
   * The path to the unit test working directory.
   */
  public static final String TEST_DIR =
       System.getProperty(TestCaseUtils.PROPERTY_BUILD_DIR,
       BUILD_ROOT + File.separator + "build") +
       File.separator + "unit-tests" + File.separator +
       "package-instance";
  public static final String TEST_DIR = TestCaseUtils.getUnitTestRootPath()
       + File.separator + "package-instance";
@@ -109,7 +100,13 @@
    TestCaseUtils.startServer();
  }
  @DataProvider(name="keyTypes")
  public Object[][] keyTypes() {
    return new Object[][] {
      { KeyType.EC },
      { KeyType.RSA }
    };
  }
  /**
   * Tests the CertificateManager constructor using a null argument for the key
@@ -614,8 +611,8 @@
   *
   * @throws  Exception  If a problem occurs.
   */
  @Test
  public void testGenerateSelfSignedCertificateNullAlias()
  @Test(dataProvider="keyTypes")
  public void testGenerateSelfSignedCertificateNullAlias(KeyType keyType)
         throws Exception
  {
    if (! CERT_MANAGER_AVAILABLE)
@@ -628,7 +625,7 @@
    try
    {
      certManager.generateSelfSignedCertificate(null, "CN=Test,O=test", 365);
      certManager.generateSelfSignedCertificate(keyType, null, "CN=Test,O=test", 365);
      fail("Expected an NPE due to a null alias");
    } catch (NullPointerException npe) {}
  }
@@ -641,8 +638,8 @@
   *
   * @throws  Exception  If a problem occurs.
   */
  @Test
  public void testGenerateSelfSignedCertificateEmptyAlias()
  @Test(dataProvider="keyTypes")
  public void testGenerateSelfSignedCertificateEmptyAlias(KeyType keyType)
         throws Exception
  {
    if (! CERT_MANAGER_AVAILABLE)
@@ -655,7 +652,7 @@
    try
    {
      certManager.generateSelfSignedCertificate("", "CN=Test,O=test", 365);
      certManager.generateSelfSignedCertificate(keyType, "", "CN=Test,O=test", 365);
      fail("Expected an NPE due to an empty alias");
    } catch (NullPointerException npe) {}
  }
@@ -668,8 +665,8 @@
   *
   * @throws  Exception  If a problem occurs.
   */
  @Test
  public void testGenerateSelfSignedCertificateAliasInUse()
  @Test(dataProvider="keyTypes")
  public void testGenerateSelfSignedCertificateAliasInUse(KeyType keyType)
         throws Exception
  {
    if (! CERT_MANAGER_AVAILABLE)
@@ -682,7 +679,7 @@
    try
    {
      certManager.generateSelfSignedCertificate("server-cert", "CN=Test,O=test",
      certManager.generateSelfSignedCertificate(keyType, "server-cert", "CN=Test,O=test",
                                                365);
      fail("Expected an illegal argument exception to a duplicate alias");
    } catch (IllegalArgumentException iae) {}
@@ -696,8 +693,8 @@
   *
   * @throws  Exception  If a problem occurs.
   */
  @Test
  public void testGenerateSelfSignedCertificateNullSubject()
  @Test(dataProvider="keyTypes")
  public void testGenerateSelfSignedCertificateNullSubject(KeyType keyType)
         throws Exception
  {
    if (! CERT_MANAGER_AVAILABLE)
@@ -710,7 +707,7 @@
    try
    {
      certManager.generateSelfSignedCertificate("test-cert", null, 365);
      certManager.generateSelfSignedCertificate(keyType, "test-cert", null, 365);
      fail("Expected an NPE due to a null subject");
    } catch (NullPointerException npe) {}
  }
@@ -723,8 +720,8 @@
   *
   * @throws  Exception  If a problem occurs.
   */
  @Test
  public void testGenerateSelfSignedCertificateEmptySubject()
  @Test(dataProvider="keyTypes")
  public void testGenerateSelfSignedCertificateEmptySubject(KeyType keyType)
         throws Exception
  {
    if (! CERT_MANAGER_AVAILABLE)
@@ -737,7 +734,7 @@
    try
    {
      certManager.generateSelfSignedCertificate("test-cert", "", 365);
      certManager.generateSelfSignedCertificate(keyType, "test-cert", "", 365);
      fail("Expected an NPE due to an empty subject");
    } catch (NullPointerException npe) {}
  }
@@ -750,8 +747,8 @@
   *
   * @throws  Exception  If a problem occurs.
   */
  @Test
  public void testGenerateSelfSignedCertificateInvalidSubject()
  @Test(dataProvider="keyTypes")
  public void testGenerateSelfSignedCertificateInvalidSubject(KeyType keyType)
         throws Exception
  {
    if (! CERT_MANAGER_AVAILABLE)
@@ -768,7 +765,7 @@
         new CertificateManager(path.getAbsolutePath(), "JKS", "password");
    try
    {
      certManager.generateSelfSignedCertificate("test-cert", "invalid", 365);
      certManager.generateSelfSignedCertificate(keyType, "test-cert", "invalid", 365);
      fail("Expected a key store exception due to an invalid subject");
    } catch (KeyStoreException cse) {}
    path.delete();
@@ -782,8 +779,8 @@
   *
   * @throws  Exception  If a problem occurs.
   */
  @Test
  public void testGenerateSelfSignedCertificateInvalidValidity()
  @Test(dataProvider="keyTypes")
  public void testGenerateSelfSignedCertificateInvalidValidity(KeyType keyType)
         throws Exception
  {
    if (! CERT_MANAGER_AVAILABLE)
@@ -796,7 +793,7 @@
    try
    {
      certManager.generateSelfSignedCertificate("test-cert", "CN=Test,o=test",
      certManager.generateSelfSignedCertificate(keyType, "test-cert", "CN=Test,o=test",
                                                0);
      fail("Expected an illegal argument exception due to an invalid validity");
    } catch (IllegalArgumentException iae) {}
@@ -809,8 +806,8 @@
   *
   * @throws  Exception  If a problem occurs.
   */
  @Test
  public void testGenerateSelfSignedCertificateJKS()
  @Test(dataProvider="keyTypes")
  public void testGenerateSelfSignedCertificateJKS(KeyType keyType)
         throws Exception
  {
    if (! CERT_MANAGER_AVAILABLE)
@@ -825,7 +822,7 @@
    CertificateManager certManager =
         new CertificateManager(path.getAbsolutePath(), "JKS", "password");
    certManager.generateSelfSignedCertificate("test-cert", "CN=Test,o=test",
    certManager.generateSelfSignedCertificate(keyType, "test-cert", "CN=Test,o=test",
                                              365);
    assertTrue(certManager.aliasInUse("test-cert"));
    path.delete();
@@ -839,8 +836,8 @@
   *
   * @throws  Exception  If a problem occurs.
   */
  @Test(groups="slow")
  public void testGenerateSelfSignedCertificatePKCS12()
  @Test(groups="slow", dataProvider="keyTypes")
  public void testGenerateSelfSignedCertificatePKCS12(KeyType keyType)
         throws Exception
  {
    if (! CERT_MANAGER_AVAILABLE)
@@ -855,7 +852,7 @@
    CertificateManager certManager =
         new CertificateManager(path.getAbsolutePath(), "PKCS12", "password");
    certManager.generateSelfSignedCertificate("test-cert", "CN=Test,o=test",
    certManager.generateSelfSignedCertificate(keyType, "test-cert", "CN=Test,o=test",
                                              365);
    assertTrue(certManager.aliasInUse("test-cert"));
    path.delete();