Search in sources :

Example 21 with StringArgument

use of com.unboundid.util.args.StringArgument in project ldapsdk by pingidentity.

the class ManageCertificates method getKeystorePassword.

/**
 * Retrieves the password needed to access the keystore.
 *
 * @param  keystoreFile  The path to the keystore file for which to get the
 *                       password.
 * @param  prefix        The prefix string to use for the arguments.  This may
 *                       be {@code null} if no prefix is needed.
 *
 * @return  The password needed to access the keystore, or {@code null} if
 *          no keystore password was configured.
 *
 * @throws  LDAPException  If a problem is encountered while trying to get the
 *                         keystore password.
 */
@Nullable()
private char[] getKeystorePassword(@NotNull final File keystoreFile, @Nullable final String prefix) throws LDAPException {
    final String prefixDash;
    if (prefix == null) {
        prefixDash = "";
    } else {
        prefixDash = prefix + '-';
    }
    final StringArgument keystorePasswordArgument = subCommandParser.getStringArgument(prefixDash + "keystore-password");
    if ((keystorePasswordArgument != null) && keystorePasswordArgument.isPresent()) {
        final char[] keystorePWChars = keystorePasswordArgument.getValue().toCharArray();
        if ((!keystoreFile.exists()) && (keystorePWChars.length < 6)) {
            throw new LDAPException(ResultCode.PARAM_ERROR, ERR_MANAGE_CERTS_GET_KS_PW_TOO_SHORT.get());
        }
        return keystorePWChars;
    }
    final FileArgument keystorePasswordFileArgument = subCommandParser.getFileArgument(prefixDash + "keystore-password-file");
    if ((keystorePasswordFileArgument != null) && keystorePasswordFileArgument.isPresent()) {
        final File f = keystorePasswordFileArgument.getValue();
        try {
            final char[] passwordChars = getPasswordFileReader().readPassword(f);
            if (passwordChars.length < 6) {
                throw new LDAPException(ResultCode.PARAM_ERROR, ERR_MANAGE_CERTS_GET_KS_PW_TOO_SHORT.get());
            }
            return passwordChars;
        } catch (final LDAPException e) {
            Debug.debugException(e);
            throw e;
        } catch (final Exception e) {
            Debug.debugException(e);
            throw new LDAPException(ResultCode.LOCAL_ERROR, ERR_MANAGE_CERTS_GET_KS_PW_ERROR_READING_FILE.get(f.getAbsolutePath(), StaticUtils.getExceptionMessage(e)), e);
        }
    }
    final BooleanArgument promptArgument = subCommandParser.getBooleanArgument("prompt-for-" + prefixDash + "keystore-password");
    if ((promptArgument != null) && promptArgument.isPresent()) {
        out();
        if (keystoreFile.exists() && (!"new".equals(prefix))) {
            // We're only going to prompt once.
            if ((prefix != null) && prefix.equals("current")) {
                return promptForPassword(INFO_MANAGE_CERTS_KEY_KS_PW_EXISTING_CURRENT_PROMPT.get(keystoreFile.getAbsolutePath()), false);
            } else {
                return promptForPassword(INFO_MANAGE_CERTS_KEY_KS_PW_EXISTING_PROMPT.get(keystoreFile.getAbsolutePath()), false);
            }
        } else {
            // twice to prevent setting the wrong password because of a typo.
            while (true) {
                final String prompt1;
                if ("new".equals(prefix)) {
                    prompt1 = INFO_MANAGE_CERTS_KEY_KS_PW_EXISTING_NEW_PROMPT.get();
                } else {
                    prompt1 = INFO_MANAGE_CERTS_KEY_KS_PW_NEW_PROMPT_1.get(keystoreFile.getAbsolutePath());
                }
                final char[] pwChars = promptForPassword(prompt1, false);
                if (pwChars.length < 6) {
                    wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GET_KS_PW_TOO_SHORT.get());
                    err();
                    continue;
                }
                final char[] confirmChars = promptForPassword(INFO_MANAGE_CERTS_KEY_KS_PW_NEW_PROMPT_2.get(), true);
                if (Arrays.equals(pwChars, confirmChars)) {
                    Arrays.fill(confirmChars, '\u0000');
                    return pwChars;
                } else {
                    wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_KEY_KS_PW_PROMPT_MISMATCH.get());
                    err();
                }
            }
        }
    }
    return null;
}
Also used : LDAPException(com.unboundid.ldap.sdk.LDAPException) BooleanArgument(com.unboundid.util.args.BooleanArgument) ASN1BitString(com.unboundid.asn1.ASN1BitString) FileArgument(com.unboundid.util.args.FileArgument) File(java.io.File) ArgumentException(com.unboundid.util.args.ArgumentException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) LDAPException(com.unboundid.ldap.sdk.LDAPException) IOException(java.io.IOException) StringArgument(com.unboundid.util.args.StringArgument) Nullable(com.unboundid.util.Nullable)

Example 22 with StringArgument

use of com.unboundid.util.args.StringArgument in project ldapsdk by pingidentity.

the class ManageCertificates method doDeleteCertificate.

/**
 * Performs the necessary processing for the delete-certificate subcommand.
 *
 * @return  A result code that indicates whether the processing completed
 *          successfully.
 */
@NotNull()
private ResultCode doDeleteCertificate() {
    // Get the values of a number of configured arguments.
    final StringArgument aliasArgument = subCommandParser.getStringArgument("alias");
    final String alias = aliasArgument.getValue();
    final BooleanArgument noPromptArgument = subCommandParser.getBooleanArgument("no-prompt");
    final boolean noPrompt = ((noPromptArgument != null) && noPromptArgument.isPresent());
    final String keystoreType;
    final File keystorePath = getKeystorePath();
    try {
        keystoreType = inferKeystoreType(keystorePath);
    } catch (final LDAPException le) {
        Debug.debugException(le);
        wrapErr(0, WRAP_COLUMN, le.getMessage());
        return le.getResultCode();
    }
    final char[] keystorePassword;
    try {
        keystorePassword = getKeystorePassword(keystorePath);
    } catch (final LDAPException le) {
        Debug.debugException(le);
        wrapErr(0, WRAP_COLUMN, le.getMessage());
        return le.getResultCode();
    }
    final BooleanArgument displayKeytoolCommandArgument = subCommandParser.getBooleanArgument("display-keytool-command");
    if ((displayKeytoolCommandArgument != null) && displayKeytoolCommandArgument.isPresent()) {
        final ArrayList<String> keytoolArgs = new ArrayList<>(10);
        keytoolArgs.add("-delete");
        keytoolArgs.add("-keystore");
        keytoolArgs.add(keystorePath.getAbsolutePath());
        keytoolArgs.add("-storetype");
        keytoolArgs.add(keystoreType);
        keytoolArgs.add("-storepass");
        keytoolArgs.add("*****REDACTED*****");
        keytoolArgs.add("-alias");
        keytoolArgs.add(alias);
        displayKeytoolCommand(keytoolArgs);
    }
    // Get the keystore.
    final KeyStore keystore;
    try {
        keystore = getKeystore(keystoreType, keystorePath, keystorePassword);
    } catch (final LDAPException le) {
        Debug.debugException(le);
        wrapErr(0, WRAP_COLUMN, le.getMessage());
        return le.getResultCode();
    }
    // Get the entry for the specified alias.
    final boolean hasPrivateKey;
    final ArrayList<X509Certificate> certList = new ArrayList<>(5);
    if (hasCertificateAlias(keystore, alias)) {
        try {
            hasPrivateKey = false;
            certList.add(new X509Certificate(keystore.getCertificate(alias).getEncoded()));
        } catch (final Exception e) {
            Debug.debugException(e);
            wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_DELETE_CERT_ERROR_GETTING_CERT.get(alias));
            e.printStackTrace(getErr());
            return ResultCode.LOCAL_ERROR;
        }
    } else if (hasKeyAlias(keystore, alias)) {
        try {
            hasPrivateKey = true;
            for (final Certificate c : keystore.getCertificateChain(alias)) {
                certList.add(new X509Certificate(c.getEncoded()));
            }
        } catch (final Exception e) {
            Debug.debugException(e);
            wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_DELETE_CERT_ERROR_GETTING_CHAIN.get(alias));
            e.printStackTrace(getErr());
            return ResultCode.LOCAL_ERROR;
        }
    } else {
        wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_DELETE_CERT_ERROR_ALIAS_NOT_CERT_OR_KEY.get(alias));
        return ResultCode.PARAM_ERROR;
    }
    // Prompt about whether to perform the delete, if appropriate.
    if (!noPrompt) {
        out();
        if (!hasPrivateKey) {
            wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_DELETE_CERT_CONFIRM_DELETE_CERT.get());
        } else {
            wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_DELETE_CERT_CONFIRM_DELETE_CHAIN.get());
        }
        for (final X509Certificate c : certList) {
            out();
            printCertificate(c, "", false);
        }
        out();
        try {
            if (!promptForYesNo(INFO_MANAGE_CERTS_DELETE_CERT_PROMPT_DELETE.get())) {
                wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_DELETE_CERT_CANCELED.get());
                return ResultCode.USER_CANCELED;
            }
        } catch (final LDAPException le) {
            Debug.debugException(le);
            err();
            wrapErr(0, WRAP_COLUMN, le.getMessage());
            return le.getResultCode();
        }
    }
    // Delete the entry from the keystore.
    try {
        keystore.deleteEntry(alias);
    } catch (final Exception e) {
        Debug.debugException(e);
        wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_DELETE_CERT_DELETE_ERROR.get(alias));
        e.printStackTrace(getErr());
        return ResultCode.LOCAL_ERROR;
    }
    // Write the updated keystore to disk.
    try {
        writeKeystore(keystore, keystorePath, keystorePassword);
    } catch (final LDAPException le) {
        Debug.debugException(le);
        wrapErr(0, WRAP_COLUMN, le.getMessage());
        return le.getResultCode();
    }
    if (certList.size() == 1) {
        out();
        wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_DELETE_CERT_DELETED_CERT.get());
    } else {
        out();
        wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_DELETE_CERT_DELETED_CHAIN.get());
    }
    return ResultCode.SUCCESS;
}
Also used : BooleanArgument(com.unboundid.util.args.BooleanArgument) ArrayList(java.util.ArrayList) ASN1BitString(com.unboundid.asn1.ASN1BitString) KeyStore(java.security.KeyStore) ArgumentException(com.unboundid.util.args.ArgumentException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) LDAPException(com.unboundid.ldap.sdk.LDAPException) IOException(java.io.IOException) StringArgument(com.unboundid.util.args.StringArgument) LDAPException(com.unboundid.ldap.sdk.LDAPException) File(java.io.File) Certificate(java.security.cert.Certificate) NotNull(com.unboundid.util.NotNull)

Example 23 with StringArgument

use of com.unboundid.util.args.StringArgument in project ldapsdk by pingidentity.

the class ManageCertificates method doListCertificates.

/**
 * Performs the necessary processing for the list-certificates subcommand.
 *
 * @return  A result code that indicates whether the processing completed
 *          successfully.
 */
@NotNull()
private ResultCode doListCertificates() {
    // Get the values of a number of configured arguments.
    final BooleanArgument displayPEMArgument = subCommandParser.getBooleanArgument("display-pem-certificate");
    final boolean displayPEM = ((displayPEMArgument != null) && displayPEMArgument.isPresent());
    final BooleanArgument verboseArgument = subCommandParser.getBooleanArgument("verbose");
    final boolean verbose = ((verboseArgument != null) && verboseArgument.isPresent());
    final Map<String, String> missingAliases;
    final Set<String> aliases;
    final StringArgument aliasArgument = subCommandParser.getStringArgument("alias");
    if ((aliasArgument == null) || (!aliasArgument.isPresent())) {
        aliases = Collections.emptySet();
        missingAliases = Collections.emptyMap();
    } else {
        final List<String> values = aliasArgument.getValues();
        aliases = new LinkedHashSet<>(StaticUtils.computeMapCapacity(values.size()));
        missingAliases = new LinkedHashMap<>(StaticUtils.computeMapCapacity(values.size()));
        for (final String alias : values) {
            final String lowerAlias = StaticUtils.toLowerCase(alias);
            aliases.add(StaticUtils.toLowerCase(lowerAlias));
            missingAliases.put(lowerAlias, alias);
        }
    }
    final String keystoreType;
    final File keystorePath = getKeystorePath();
    try {
        keystoreType = inferKeystoreType(keystorePath);
    } catch (final LDAPException le) {
        Debug.debugException(le);
        wrapErr(0, WRAP_COLUMN, le.getMessage());
        return le.getResultCode();
    }
    final char[] keystorePassword;
    try {
        keystorePassword = getKeystorePassword(keystorePath);
    } catch (final LDAPException le) {
        Debug.debugException(le);
        wrapErr(0, WRAP_COLUMN, le.getMessage());
        return le.getResultCode();
    }
    final BooleanArgument displayKeytoolCommandArgument = subCommandParser.getBooleanArgument("display-keytool-command");
    if ((displayKeytoolCommandArgument != null) && displayKeytoolCommandArgument.isPresent()) {
        final ArrayList<String> keytoolArgs = new ArrayList<>(10);
        keytoolArgs.add("-list");
        keytoolArgs.add("-keystore");
        keytoolArgs.add(keystorePath.getAbsolutePath());
        keytoolArgs.add("-storetype");
        keytoolArgs.add(keystoreType);
        if (keystorePassword != null) {
            keytoolArgs.add("-storepass");
            keytoolArgs.add("*****REDACTED*****");
        }
        for (final String alias : missingAliases.values()) {
            keytoolArgs.add("-alias");
            keytoolArgs.add(alias);
        }
        if (displayPEM) {
            keytoolArgs.add("-rfc");
        }
        if (verbose) {
            keytoolArgs.add("-v");
        }
        displayKeytoolCommand(keytoolArgs);
    }
    // Get the keystore.
    final KeyStore keystore;
    try {
        keystore = getKeystore(keystoreType, keystorePath, keystorePassword);
    } catch (final LDAPException le) {
        Debug.debugException(le);
        wrapErr(0, WRAP_COLUMN, le.getMessage());
        return le.getResultCode();
    }
    // Display a message with the keystore type.
    wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_LIST_KEYSTORE_TYPE.get(keystoreType));
    // Iterate through the keystore and display the appropriate certificates.
    final Enumeration<String> aliasEnumeration;
    try {
        aliasEnumeration = keystore.aliases();
    } catch (final Exception e) {
        Debug.debugException(e);
        err();
        wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_LIST_CERTS_CANNOT_GET_ALIASES.get(keystorePath.getAbsolutePath()));
        e.printStackTrace(getErr());
        return ResultCode.LOCAL_ERROR;
    }
    int listedCount = 0;
    ResultCode resultCode = ResultCode.SUCCESS;
    while (aliasEnumeration.hasMoreElements()) {
        final String alias = aliasEnumeration.nextElement();
        final String lowerAlias = StaticUtils.toLowerCase(alias);
        if ((!aliases.isEmpty()) && (missingAliases.remove(lowerAlias) == null)) {
            // We don't care about this alias.
            continue;
        }
        final X509Certificate[] certificateChain;
        try {
            // NOTE:  Keystore entries that have private keys may have a certificate
            // chain associated with them (the end certificate plus all of the
            // issuer certificates).  In that case all of those certificates in the
            // chain will be stored under the same alias, and the only way we can
            // access them is to call the getCertificateChain method.  However, if
            // the keystore only has a certificate for the alias but no private key,
            // then the entry will not have a chain, and the call to
            // getCertificateChain will return null for that alias.  We want to be
            // able to handle both of these cases, so we will first try
            // getCertificateChain to see if we can get a complete chain, but if
            // that returns null, then use getCertificate to see if we can get a
            // single certificate.  That call to getCertificate can also return null
            // because the entry with this alias might be some other type of entry,
            // like a secret key entry.
            Certificate[] chain = keystore.getCertificateChain(alias);
            if ((chain == null) || (chain.length == 0)) {
                final Certificate cert = keystore.getCertificate(alias);
                if (cert == null) {
                    continue;
                } else {
                    chain = new Certificate[] { cert };
                }
            }
            certificateChain = new X509Certificate[chain.length];
            for (int i = 0; i < chain.length; i++) {
                certificateChain[i] = new X509Certificate(chain[i].getEncoded());
            }
        } catch (final Exception e) {
            Debug.debugException(e);
            err();
            wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_LIST_CERTS_ERROR_GETTING_CERT.get(alias, StaticUtils.getExceptionMessage(e)));
            resultCode = ResultCode.LOCAL_ERROR;
            continue;
        }
        listedCount++;
        for (int i = 0; i < certificateChain.length; i++) {
            out();
            if (certificateChain.length == 1) {
                out(INFO_MANAGE_CERTS_LIST_CERTS_LABEL_ALIAS_WITHOUT_CHAIN.get(alias));
            } else {
                out(INFO_MANAGE_CERTS_LIST_CERTS_LABEL_ALIAS_WITH_CHAIN.get(alias, (i + 1), certificateChain.length));
            }
            printCertificate(certificateChain[i], "", verbose);
            if (i == 0) {
                if (hasKeyAlias(keystore, alias)) {
                    out(INFO_MANAGE_CERTS_LIST_CERTS_LABEL_HAS_PK_YES.get());
                } else {
                    out(INFO_MANAGE_CERTS_LIST_CERTS_LABEL_HAS_PK_NO.get());
                }
            }
            CertException signatureVerificationException = null;
            if (certificateChain[i].isSelfSigned()) {
                try {
                    certificateChain[i].verifySignature(null);
                } catch (final CertException ce) {
                    Debug.debugException(ce);
                    signatureVerificationException = ce;
                }
            } else {
                X509Certificate issuerCertificate = null;
                try {
                    final AtomicReference<KeyStore> jvmDefaultTrustStoreRef = new AtomicReference<>();
                    final AtomicReference<DN> missingIssuerRef = new AtomicReference<>();
                    issuerCertificate = getIssuerCertificate(certificateChain[i], keystore, jvmDefaultTrustStoreRef, missingIssuerRef);
                } catch (final Exception e) {
                    Debug.debugException(e);
                }
                if (issuerCertificate == null) {
                    signatureVerificationException = new CertException(ERR_MANAGE_CERTS_LIST_CERTS_VERIFY_SIGNATURE_NO_ISSUER.get(certificateChain[i].getIssuerDN()));
                } else {
                    try {
                        certificateChain[i].verifySignature(issuerCertificate);
                    } catch (final CertException ce) {
                        Debug.debugException(ce);
                        signatureVerificationException = ce;
                    }
                }
            }
            if (signatureVerificationException == null) {
                wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_LIST_CERTS_SIGNATURE_VALID.get());
            } else {
                wrapErr(0, WRAP_COLUMN, signatureVerificationException.getMessage());
            }
            if (displayPEM) {
                out(INFO_MANAGE_CERTS_LIST_CERTS_LABEL_PEM.get());
                writePEMCertificate(getOut(), certificateChain[i].getX509CertificateBytes());
            }
        }
    }
    if (!missingAliases.isEmpty()) {
        err();
        for (final String missingAlias : missingAliases.values()) {
            wrapErr(0, WRAP_COLUMN, WARN_MANAGE_CERTS_LIST_CERTS_ALIAS_NOT_IN_KS.get(missingAlias, keystorePath.getAbsolutePath()));
            resultCode = ResultCode.PARAM_ERROR;
        }
    } else if (listedCount == 0) {
        out();
        if (keystorePassword == null) {
            wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_LIST_CERTS_NO_CERTS_OR_KEYS_WITHOUT_PW.get());
        } else {
            wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_LIST_CERTS_NO_CERTS_OR_KEYS_WITH_PW.get());
        }
    }
    return resultCode;
}
Also used : ArrayList(java.util.ArrayList) DN(com.unboundid.ldap.sdk.DN) ASN1BitString(com.unboundid.asn1.ASN1BitString) BooleanArgument(com.unboundid.util.args.BooleanArgument) AtomicReference(java.util.concurrent.atomic.AtomicReference) KeyStore(java.security.KeyStore) ArgumentException(com.unboundid.util.args.ArgumentException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) LDAPException(com.unboundid.ldap.sdk.LDAPException) IOException(java.io.IOException) StringArgument(com.unboundid.util.args.StringArgument) LDAPException(com.unboundid.ldap.sdk.LDAPException) File(java.io.File) ResultCode(com.unboundid.ldap.sdk.ResultCode) Certificate(java.security.cert.Certificate) NotNull(com.unboundid.util.NotNull)

Example 24 with StringArgument

use of com.unboundid.util.args.StringArgument in project ldapsdk by pingidentity.

the class ManageCertificates method doCopyKeystore.

/**
 * Performs the necessary processing for the copy-keystore subcommand.
 *
 * @return  A result code that indicates whether the processing completed
 *          successfully.
 */
@NotNull()
private ResultCode doCopyKeystore() {
    // Get the source key store.
    final String sourceKeyStoreType;
    final File sourceKeyStorePath = getKeystorePath("source-keystore");
    try {
        sourceKeyStoreType = inferKeystoreType(sourceKeyStorePath, "source");
    } catch (final LDAPException le) {
        Debug.debugException(le);
        wrapErr(0, WRAP_COLUMN, le.getMessage());
        return le.getResultCode();
    }
    final char[] sourceKeyStorePassword;
    try {
        sourceKeyStorePassword = getKeystorePassword(sourceKeyStorePath, "source");
    } catch (final LDAPException le) {
        Debug.debugException(le);
        wrapErr(0, WRAP_COLUMN, le.getMessage());
        return le.getResultCode();
    }
    final KeyStore sourceKeyStore;
    try {
        sourceKeyStore = getKeystore(sourceKeyStoreType, sourceKeyStorePath, sourceKeyStorePassword);
    } catch (final LDAPException le) {
        Debug.debugException(le);
        wrapErr(0, WRAP_COLUMN, le.getMessage());
        return le.getResultCode();
    }
    // Get the destination key store.
    final String destinationKeyStoreType;
    final File destinationKeyStorePath = getKeystorePath("destination-keystore");
    try {
        destinationKeyStoreType = inferKeystoreType(destinationKeyStorePath, "destination");
    } catch (final LDAPException le) {
        Debug.debugException(le);
        wrapErr(0, WRAP_COLUMN, le.getMessage());
        return le.getResultCode();
    }
    final boolean destinationExists = destinationKeyStorePath.exists();
    char[] destinationKeyStorePassword;
    try {
        destinationKeyStorePassword = getKeystorePassword(destinationKeyStorePath, "destination");
        if (destinationKeyStorePassword == null) {
            destinationKeyStorePassword = sourceKeyStorePassword;
        }
    } catch (final LDAPException le) {
        Debug.debugException(le);
        wrapErr(0, WRAP_COLUMN, le.getMessage());
        return le.getResultCode();
    }
    final KeyStore destinationKeyStore;
    try {
        destinationKeyStore = getKeystore(destinationKeyStoreType, destinationKeyStorePath, destinationKeyStorePassword);
    } catch (final LDAPException le) {
        Debug.debugException(le);
        wrapErr(0, WRAP_COLUMN, le.getMessage());
        return le.getResultCode();
    }
    // Get the value of the aliases argument, if it was provided.
    final Set<String> aliases = new LinkedHashSet<>();
    try {
        final StringArgument aliasArg = subCommandParser.getStringArgument("alias");
        if ((aliasArg != null) && aliasArg.isPresent()) {
            for (final String alias : aliasArg.getValues()) {
                aliases.add(alias);
                if (!sourceKeyStore.containsAlias(alias)) {
                    wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_COPY_KS_NO_SUCH_SOURCE_ALIAS.get(sourceKeyStorePath.getAbsolutePath(), alias));
                    return ResultCode.PARAM_ERROR;
                }
            }
        } else {
            final Enumeration<String> sourceAliases = sourceKeyStore.aliases();
            while (sourceAliases.hasMoreElements()) {
                aliases.add(sourceAliases.nextElement());
            }
        }
    } catch (final Exception e) {
        Debug.debugException(e);
        wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_COPY_KS_CANNOT_GET_SOURCE_ALIASES.get(sourceKeyStorePath.getAbsolutePath(), StaticUtils.getExceptionMessage(e)));
        return ResultCode.LOCAL_ERROR;
    }
    // exists, then exit without doing anything.
    if (aliases.isEmpty() && destinationExists) {
        wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_COPY_KS_NO_CERTS_COPIED_EXISTING_KS.get(sourceKeyStorePath.getAbsolutePath(), destinationKeyStorePath.getAbsolutePath()));
        return ResultCode.SUCCESS;
    }
    // store.
    for (final String alias : aliases) {
        try {
            if (destinationKeyStore.containsAlias(alias)) {
                wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_COPY_KS_CONFLICTING_ALIAS.get(alias, destinationKeyStorePath.getAbsolutePath(), subCommandParser.getCommandName()));
                return ResultCode.CONSTRAINT_VIOLATION;
            }
        } catch (final Exception e) {
            Debug.debugException(e);
            wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_COPY_KS_CANNOT_CHECK_DEST_ALIAS.get(alias, destinationKeyStorePath.getAbsolutePath(), StaticUtils.getExceptionMessage(e)));
            return ResultCode.LOCAL_ERROR;
        }
    }
    // Copy each of the targeted entries from the source key store into the
    // destination key store.
    char[] sourcePrivateKeyPassword = null;
    char[] destinationPrivateKeyPassword = null;
    for (final String alias : aliases) {
        try {
            if (sourceKeyStore.isCertificateEntry(alias)) {
                final Certificate certificate = sourceKeyStore.getCertificate(alias);
                destinationKeyStore.setCertificateEntry(alias, certificate);
            } else {
                if (sourcePrivateKeyPassword == null) {
                    sourcePrivateKeyPassword = getPrivateKeyPassword(sourceKeyStore, alias, "source", sourceKeyStorePassword);
                }
                if (destinationPrivateKeyPassword == null) {
                    destinationPrivateKeyPassword = getPrivateKeyPassword(destinationKeyStore, alias, "destination", destinationKeyStorePassword);
                }
                final Certificate[] chain = sourceKeyStore.getCertificateChain(alias);
                final Key key = sourceKeyStore.getKey(alias, sourcePrivateKeyPassword);
                destinationKeyStore.setKeyEntry(alias, key, destinationPrivateKeyPassword, chain);
            }
        } catch (final Exception e) {
            Debug.debugException(e);
            wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_COPY_KS_ERROR_COPYING_ENTRY.get(alias, sourceKeyStorePath.getAbsolutePath(), destinationKeyStorePath.getAbsolutePath(), StaticUtils.getExceptionMessage(e)));
            return ResultCode.LOCAL_ERROR;
        }
    }
    // Rewrite the destination keystore.
    try {
        writeKeystore(destinationKeyStore, destinationKeyStorePath, destinationKeyStorePassword);
    } catch (final LDAPException le) {
        Debug.debugException(le);
        wrapErr(0, WRAP_COLUMN, le.getMessage());
        return le.getResultCode();
    }
    if (aliases.isEmpty()) {
        // This should only happen if the alias argument was not provided, the
        // source key store is empty, and the destination key store doesn't exist.
        // In that case, the destination key store will have been created.
        wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_COPY_KS_NO_CERTS_COPIED_KS_CREATED.get(sourceKeyStorePath.getAbsolutePath(), destinationKeyStoreType, destinationKeyStorePath.getAbsolutePath()));
    } else {
        // Write a message about the entries that were successfully copied.
        wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_COPY_KS_CERTS_COPIED_HEADER.get(sourceKeyStorePath.getAbsolutePath(), destinationKeyStoreType, destinationKeyStorePath.getAbsolutePath()));
        for (final String alias : aliases) {
            out("* ", alias);
        }
    }
    return ResultCode.SUCCESS;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ASN1BitString(com.unboundid.asn1.ASN1BitString) KeyStore(java.security.KeyStore) ArgumentException(com.unboundid.util.args.ArgumentException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) LDAPException(com.unboundid.ldap.sdk.LDAPException) IOException(java.io.IOException) StringArgument(com.unboundid.util.args.StringArgument) LDAPException(com.unboundid.ldap.sdk.LDAPException) File(java.io.File) Key(java.security.Key) PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) Certificate(java.security.cert.Certificate) NotNull(com.unboundid.util.NotNull)

Example 25 with StringArgument

use of com.unboundid.util.args.StringArgument in project ldapsdk by pingidentity.

the class ManageCertificates method doTrustServerCertificate.

/**
 * Performs the necessary processing for the trust-server-certificate
 * subcommand.
 *
 * @return  A result code that indicates whether the processing completed
 *          successfully.
 */
@NotNull()
private ResultCode doTrustServerCertificate() {
    // Get the values of a number of configured arguments.
    final StringArgument hostnameArgument = subCommandParser.getStringArgument("hostname");
    final String hostname = hostnameArgument.getValue();
    final IntegerArgument portArgument = subCommandParser.getIntegerArgument("port");
    final int port = portArgument.getValue();
    final String alias;
    final StringArgument aliasArgument = subCommandParser.getStringArgument("alias");
    if ((aliasArgument != null) && aliasArgument.isPresent()) {
        alias = aliasArgument.getValue();
    } else {
        alias = hostname + ':' + port;
    }
    final BooleanArgument useLDAPStartTLSArgument = subCommandParser.getBooleanArgument("use-ldap-start-tls");
    final boolean useLDAPStartTLS = ((useLDAPStartTLSArgument != null) && useLDAPStartTLSArgument.isPresent());
    final BooleanArgument issuersOnlyArgument = subCommandParser.getBooleanArgument("issuers-only");
    final boolean issuersOnly = ((issuersOnlyArgument != null) && issuersOnlyArgument.isPresent());
    final BooleanArgument noPromptArgument = subCommandParser.getBooleanArgument("no-prompt");
    final boolean noPrompt = ((noPromptArgument != null) && noPromptArgument.isPresent());
    final BooleanArgument verboseArgument = subCommandParser.getBooleanArgument("verbose");
    final boolean verbose = ((verboseArgument != null) && verboseArgument.isPresent());
    final String keystoreType;
    final File keystorePath = getKeystorePath();
    final boolean isNewKeystore = (!keystorePath.exists());
    try {
        keystoreType = inferKeystoreType(keystorePath);
    } catch (final LDAPException le) {
        Debug.debugException(le);
        wrapErr(0, WRAP_COLUMN, le.getMessage());
        return le.getResultCode();
    }
    final char[] keystorePassword;
    try {
        keystorePassword = getKeystorePassword(keystorePath);
    } catch (final LDAPException le) {
        Debug.debugException(le);
        wrapErr(0, WRAP_COLUMN, le.getMessage());
        return le.getResultCode();
    }
    // Get the keystore.
    final KeyStore keystore;
    try {
        keystore = getKeystore(keystoreType, keystorePath, keystorePassword);
    } catch (final LDAPException le) {
        Debug.debugException(le);
        wrapErr(0, WRAP_COLUMN, le.getMessage());
        return le.getResultCode();
    }
    // Make sure that the specified alias is not already in use.
    if (hasCertificateAlias(keystore, alias) || hasKeyAlias(keystore, alias)) {
        wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_TRUST_SERVER_ALIAS_IN_USE.get(alias));
        return ResultCode.PARAM_ERROR;
    }
    // Spawn a background thread to establish a connection and get the
    // certificate chain from the target server.
    final LinkedBlockingQueue<Object> responseQueue = new LinkedBlockingQueue<>(10);
    final ManageCertificatesServerCertificateCollector certificateCollector = new ManageCertificatesServerCertificateCollector(this, hostname, port, useLDAPStartTLS, verbose, responseQueue);
    certificateCollector.start();
    Object responseObject = ERR_MANAGE_CERTS_TRUST_SERVER_NO_CERT_CHAIN_RECEIVED.get(hostname + ':' + port);
    try {
        responseObject = responseQueue.poll(90L, TimeUnit.SECONDS);
    } catch (final Exception e) {
        Debug.debugException(e);
    }
    final X509Certificate[] chain;
    if (responseObject instanceof X509Certificate[]) {
        chain = (X509Certificate[]) responseObject;
    } else if (responseObject instanceof CertException) {
        // thread, so we can just return a non-success result.
        return ResultCode.LOCAL_ERROR;
    } else {
        wrapErr(0, WRAP_COLUMN, String.valueOf(responseObject));
        return ResultCode.LOCAL_ERROR;
    }
    try {
        certificateCollector.join(10_000L);
    } catch (final Exception e) {
        Debug.debugException(e);
    }
    // then do so now.
    if (!noPrompt) {
        out();
        wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_TRUST_SERVER_RETRIEVED_CHAIN.get(hostname + ':' + port));
        boolean isFirst = true;
        for (final X509Certificate c : chain) {
            out();
            if (isFirst) {
                isFirst = false;
                if (issuersOnly && (chain.length > 1)) {
                    wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_TRUST_SERVER_NOTE_OMITTED.get());
                    out();
                }
            }
            printCertificate(c, "", verbose);
        }
        out();
        try {
            if (!promptForYesNo(INFO_MANAGE_CERTS_TRUST_SERVER_PROMPT_TRUST.get())) {
                wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_TRUST_SERVER_CHAIN_REJECTED.get());
                return ResultCode.USER_CANCELED;
            }
        } catch (final LDAPException le) {
            Debug.debugException(le);
            err();
            wrapErr(0, WRAP_COLUMN, le.getMessage());
            return le.getResultCode();
        }
    }
    // Add the certificates to the keystore.
    final LinkedHashMap<String, X509Certificate> certsByAlias = new LinkedHashMap<>(StaticUtils.computeMapCapacity(chain.length));
    for (int i = 0; i < chain.length; i++) {
        if (i == 0) {
            if (issuersOnly && (chain.length > 1)) {
                continue;
            }
            certsByAlias.put(alias, chain[i]);
        } else if ((i == 1) && (chain.length == 2)) {
            certsByAlias.put(alias + "-issuer", chain[i]);
        } else {
            certsByAlias.put(alias + "-issuer-" + i, chain[i]);
        }
    }
    for (final Map.Entry<String, X509Certificate> e : certsByAlias.entrySet()) {
        final String certAlias = e.getKey();
        final X509Certificate cert = e.getValue();
        try {
            Validator.ensureFalse((hasCertificateAlias(keystore, certAlias) || hasKeyAlias(keystore, certAlias)), "ERROR:  Alias '" + certAlias + "' is already in use in the " + "keystore.");
            keystore.setCertificateEntry(certAlias, cert.toCertificate());
        } catch (final Exception ex) {
            Debug.debugException(ex);
            wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_TRUST_SERVER_ERROR_ADDING_CERT_TO_KS.get(cert.getSubjectDN()));
            ex.printStackTrace(getErr());
            return ResultCode.LOCAL_ERROR;
        }
    }
    // Save the updated keystore.
    try {
        writeKeystore(keystore, keystorePath, keystorePassword);
    } catch (final LDAPException le) {
        Debug.debugException(le);
        wrapErr(0, WRAP_COLUMN, le.getMessage());
        return le.getResultCode();
    }
    if (isNewKeystore) {
        out();
        wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_TRUST_SERVER_CERT_CREATED_KEYSTORE.get(getUserFriendlyKeystoreType(keystoreType)));
    }
    out();
    if (certsByAlias.size() == 1) {
        wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_TRUST_SERVER_ADDED_CERT_TO_KS.get());
    } else {
        wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_TRUST_SERVER_ADDED_CERTS_TO_KS.get(certsByAlias.size()));
    }
    return ResultCode.SUCCESS;
}
Also used : BooleanArgument(com.unboundid.util.args.BooleanArgument) ASN1BitString(com.unboundid.asn1.ASN1BitString) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) KeyStore(java.security.KeyStore) ArgumentException(com.unboundid.util.args.ArgumentException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) LDAPException(com.unboundid.ldap.sdk.LDAPException) IOException(java.io.IOException) StringArgument(com.unboundid.util.args.StringArgument) LinkedHashMap(java.util.LinkedHashMap) LDAPException(com.unboundid.ldap.sdk.LDAPException) IntegerArgument(com.unboundid.util.args.IntegerArgument) File(java.io.File) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) NotNull(com.unboundid.util.NotNull)

Aggregations

StringArgument (com.unboundid.util.args.StringArgument)64 BooleanArgument (com.unboundid.util.args.BooleanArgument)53 FileArgument (com.unboundid.util.args.FileArgument)45 IntegerArgument (com.unboundid.util.args.IntegerArgument)34 DNArgument (com.unboundid.util.args.DNArgument)28 ArgumentException (com.unboundid.util.args.ArgumentException)19 NotNull (com.unboundid.util.NotNull)18 LDAPException (com.unboundid.ldap.sdk.LDAPException)17 File (java.io.File)17 ASN1BitString (com.unboundid.asn1.ASN1BitString)15 FilterArgument (com.unboundid.util.args.FilterArgument)15 IOException (java.io.IOException)15 UnrecoverableKeyException (java.security.UnrecoverableKeyException)14 ControlArgument (com.unboundid.util.args.ControlArgument)11 KeyStore (java.security.KeyStore)11 Certificate (java.security.cert.Certificate)9 ArrayList (java.util.ArrayList)9 ArgumentParser (com.unboundid.util.args.ArgumentParser)8 ScopeArgument (com.unboundid.util.args.ScopeArgument)8 ASN1OctetString (com.unboundid.asn1.ASN1OctetString)7