use of com.unboundid.util.args.DNArgument in project ldapsdk by pingidentity.
the class CommandLineToolInteractiveModeProcessor method promptForLDAPArguments.
/**
* Interactively prompts for the arguments used to connect and optionally
* authenticate to the directory server.
*
* @param argList The list to which the string representations of all LDAP
* arguments should be added.
* @param test Indicates whether to attempt to use the arguments to
* establish an LDAP connection.
*
* @throws LDAPException If a problem is encountered while interacting with
* the user, or if the user wants to quit.
*/
private void promptForLDAPArguments(@NotNull final List<String> argList, final boolean test) throws LDAPException {
final LDAPCommandLineTool ldapTool = (LDAPCommandLineTool) tool;
argList.clear();
// Get the address of the directory server.
final String defaultHostname;
final StringArgument hostnameArgument = parser.getStringArgument("hostname");
if (hostnameArgument.isPresent()) {
defaultHostname = hostnameArgument.getValue();
} else {
defaultHostname = "localhost";
}
ArgumentHelper.reset(hostnameArgument);
final String hostname = promptForString(INFO_INTERACTIVE_LDAP_PROMPT_HOST.get(), defaultHostname, true);
ArgumentHelper.addValueSuppressException(hostnameArgument, hostname);
argList.add("--hostname");
argList.add(hostname);
// If this tool is running with access to Directory Server data, and if the
// selected hostname is "localhost" or a loopback address, then try to load
// information about the server's connection handlers.
List<LDAPConnectionHandlerConfiguration> serverListenerConfigs = null;
final File dsInstanceRoot = InternalSDKHelper.getPingIdentityServerRoot();
if (dsInstanceRoot != null) {
final File configFile = StaticUtils.constructPath(dsInstanceRoot, "config", "config.ldif");
if (configFile.exists() && configFile.isFile()) {
try {
serverListenerConfigs = LDAPConnectionHandlerConfiguration.readConfiguration(configFile, true);
} catch (final Exception e) {
Debug.debugException(e);
}
}
}
// Determine the type of connection security to use.
final BooleanArgument useSSLArgument = parser.getBooleanArgument("useSSL");
final BooleanArgument useStartTLSArgument = parser.getBooleanArgument("useStartTLS");
final String defaultSecurityChoice;
if (useSSLArgument.isPresent()) {
defaultSecurityChoice = "1";
} else if (useStartTLSArgument.isPresent()) {
defaultSecurityChoice = "3";
} else if ((serverListenerConfigs != null) && (!serverListenerConfigs.isEmpty())) {
final LDAPConnectionHandlerConfiguration cfg = serverListenerConfigs.get(0);
if (cfg.usesSSL()) {
defaultSecurityChoice = "1";
} else if (cfg.supportsStartTLS()) {
defaultSecurityChoice = "3";
} else {
defaultSecurityChoice = "5";
}
} else {
defaultSecurityChoice = "1";
}
ArgumentHelper.reset(useSSLArgument);
ArgumentHelper.reset(useStartTLSArgument);
final boolean useSSL;
final boolean useStartTLS;
final boolean defaultTrust;
final int securityType = getNumberedMenuChoice(INFO_INTERACTIVE_LDAP_SECURITY_PROMPT.get(), false, defaultSecurityChoice, INFO_INTERACTIVE_LDAP_SECURITY_OPTION_SSL_DEFAULT.get(), INFO_INTERACTIVE_LDAP_SECURITY_OPTION_SSL_MANUAL.get(), INFO_INTERACTIVE_LDAP_SECURITY_OPTION_START_TLS_DEFAULT.get(), INFO_INTERACTIVE_LDAP_SECURITY_OPTION_START_TLS_MANUAL.get(), INFO_INTERACTIVE_LDAP_SECURITY_OPTION_NONE.get());
switch(securityType) {
case 0:
useSSL = true;
useStartTLS = false;
defaultTrust = true;
argList.add("--useSSL");
ArgumentHelper.incrementOccurrencesSuppressException(useSSLArgument);
break;
case 1:
useSSL = true;
useStartTLS = false;
defaultTrust = false;
argList.add("--useSSL");
ArgumentHelper.incrementOccurrencesSuppressException(useSSLArgument);
break;
case 2:
useSSL = false;
useStartTLS = true;
defaultTrust = true;
argList.add("--useStartTLS");
ArgumentHelper.incrementOccurrencesSuppressException(useStartTLSArgument);
break;
case 3:
useSSL = false;
useStartTLS = true;
defaultTrust = false;
argList.add("--useStartTLS");
ArgumentHelper.incrementOccurrencesSuppressException(useStartTLSArgument);
break;
case 4:
default:
useSSL = false;
useStartTLS = false;
defaultTrust = false;
break;
}
// If we are to use security without default trust configuration, then
// prompt for the appropriate settings.
BindRequest bindRequest = null;
boolean trustAll = false;
byte[] keyStorePIN = null;
byte[] trustStorePIN = null;
File keyStorePath = null;
File trustStorePath = null;
String certificateNickname = null;
String keyStoreFormat = null;
String trustStoreFormat = null;
final StringArgument keyStorePasswordArgument = parser.getStringArgument("keyStorePassword");
final StringArgument trustStorePasswordArgument = parser.getStringArgument("trustStorePassword");
final StringArgument saslOptionArgument = parser.getStringArgument("saslOption");
if (!defaultTrust) {
// If the user wants to connect securely, then get the appropriate set of
// arguments pertaining to key and trust managers.
ArgumentHelper.reset(keyStorePasswordArgument);
ArgumentHelper.reset(trustStorePasswordArgument);
ArgumentHelper.reset(parser.getNamedArgument("keyStorePasswordFile"));
ArgumentHelper.reset(parser.getNamedArgument("promptForKeyStorePassword"));
ArgumentHelper.reset(parser.getNamedArgument("trustStorePasswordFile"));
ArgumentHelper.reset(parser.getNamedArgument("promptForTrustStorePassword"));
if (useSSL || useStartTLS) {
final StringArgument keyStorePathArgument = parser.getStringArgument("keyStorePath");
final StringArgument keyStoreFormatArgument = parser.getStringArgument("keyStoreFormat");
// Determine if a client certificate should be presented.
final String defaultStoreTypeChoice;
if (keyStoreFormatArgument.isPresent()) {
final String format = keyStoreFormatArgument.getValue();
if (format.equalsIgnoreCase(CryptoHelper.KEY_STORE_TYPE_PKCS_12)) {
defaultStoreTypeChoice = "3";
} else {
defaultStoreTypeChoice = "2";
}
} else if (keyStorePathArgument.isPresent()) {
defaultStoreTypeChoice = "2";
} else {
defaultStoreTypeChoice = "1";
}
final String defaultKeyStorePath;
if (keyStorePathArgument.isPresent()) {
defaultKeyStorePath = keyStorePathArgument.getValue();
} else {
defaultKeyStorePath = null;
}
final String defaultCertNickname;
final StringArgument certNicknameArgument = parser.getStringArgument("certNickname");
if (certNicknameArgument.isPresent()) {
defaultCertNickname = certNicknameArgument.getValue();
} else {
defaultCertNickname = null;
}
ArgumentHelper.reset(keyStorePathArgument);
ArgumentHelper.reset(keyStoreFormatArgument);
ArgumentHelper.reset(certNicknameArgument);
final int keystoreType = getNumberedMenuChoice(INFO_INTERACTIVE_LDAP_CLIENT_CERT_PROMPT.get(), false, defaultStoreTypeChoice, INFO_INTERACTIVE_LDAP_CLIENT_CERT_OPTION_NO.get(), INFO_INTERACTIVE_LDAP_CLIENT_CERT_OPTION_JKS.get(), INFO_INTERACTIVE_LDAP_CLIENT_CERT_OPTION_PKCS12.get());
ArgumentHelper.reset(keyStoreFormatArgument);
switch(keystoreType) {
case 1:
keyStoreFormat = CryptoHelper.KEY_STORE_TYPE_JKS;
break;
case 2:
keyStoreFormat = CryptoHelper.KEY_STORE_TYPE_PKCS_12;
break;
case 0:
default:
break;
}
if (keyStoreFormat != null) {
ArgumentHelper.addValueSuppressException(keyStoreFormatArgument, keyStoreFormat);
// Get the path to the keystore file.
keyStorePath = promptForPath(INFO_INTERACTIVE_LDAP_KEYSTORE_PATH_PROMPT.get(), defaultKeyStorePath, true, true, true, true, false);
argList.add("--keyStorePath");
argList.add(keyStorePath.getAbsolutePath());
ArgumentHelper.addValueSuppressException(keyStorePathArgument, keyStorePath.getAbsolutePath());
// Get the PIN needed to access the keystore.
keyStorePIN = promptForPassword(INFO_INTERACTIVE_LDAP_KEYSTORE_PIN_PROMPT.get(), null, false);
if (keyStorePIN != null) {
argList.add("--keyStorePassword");
argList.add("***REDACTED***");
ArgumentHelper.addValueSuppressException(keyStorePasswordArgument, StaticUtils.toUTF8String(keyStorePIN));
}
argList.add("--keyStoreFormat");
argList.add(keyStoreFormat);
certificateNickname = promptForString(INFO_INTERACTIVE_LDAP_CERT_NICKNAME_PROMPT.get(), defaultCertNickname, false);
if (certificateNickname != null) {
argList.add("--certNickname");
argList.add(certificateNickname);
ArgumentHelper.addValueSuppressException(certNicknameArgument, certificateNickname);
}
if (ldapTool.supportsAuthentication() && promptForYesNo(INFO_INTERACTIVE_LDAP_CERT_AUTH_PROMPT.get(), false, true)) {
bindRequest = new EXTERNALBindRequest();
argList.add("--saslOption");
argList.add("mech=EXTERNAL");
ArgumentHelper.reset(saslOptionArgument);
ArgumentHelper.addValueSuppressException(saslOptionArgument, "mech=EXTERNAL");
}
}
// Determine how to trust the server certificate.
final BooleanArgument trustAllArgument = parser.getBooleanArgument("trustAll");
final StringArgument trustStorePathArgument = parser.getStringArgument("trustStorePath");
final StringArgument trustStoreFormatArgument = parser.getStringArgument("trustStoreFormat");
final String defaultTrustTypeChoice;
if (trustAllArgument.isPresent()) {
defaultTrustTypeChoice = "4";
} else if (trustStoreFormatArgument.isPresent()) {
final String format = trustStoreFormatArgument.getValue();
if (format.equalsIgnoreCase(CryptoHelper.KEY_STORE_TYPE_PKCS_12)) {
defaultTrustTypeChoice = "3";
} else {
defaultTrustTypeChoice = "2";
}
} else if (trustStorePathArgument.isPresent()) {
defaultTrustTypeChoice = "2";
} else {
defaultTrustTypeChoice = "1";
}
final String defaultTrustStorePath;
if (trustStorePathArgument.isPresent()) {
defaultTrustStorePath = trustStorePathArgument.getValue();
} else {
defaultTrustStorePath = null;
}
ArgumentHelper.reset(trustAllArgument);
ArgumentHelper.reset(trustStorePathArgument);
ArgumentHelper.reset(trustStoreFormatArgument);
final int trustType = getNumberedMenuChoice(INFO_INTERACTIVE_LDAP_TRUST_PROMPT.get(), false, defaultTrustTypeChoice, INFO_INTERACTIVE_LDAP_TRUST_OPTION_PROMPT.get(), INFO_INTERACTIVE_LDAP_TRUST_OPTION_JKS.get(), INFO_INTERACTIVE_LDAP_TRUST_OPTION_PKCS12.get(), INFO_INTERACTIVE_LDAP_TRUST_OPTION_BLIND.get());
switch(trustType) {
case 1:
trustStoreFormat = CryptoHelper.KEY_STORE_TYPE_JKS;
break;
case 2:
trustStoreFormat = CryptoHelper.KEY_STORE_TYPE_PKCS_12;
break;
case 3:
trustAll = true;
argList.add("--trustAll");
ArgumentHelper.incrementOccurrencesSuppressException(trustAllArgument);
break;
case 0:
default:
// We will interactively prompt the user about whether to trust the
// certificate in the test section below. However, to avoid
// prompting the user twice, we will configure the tool behind the
// scenes to trust all certificates.
ArgumentHelper.incrementOccurrencesSuppressException(trustAllArgument);
break;
}
if (trustStoreFormat != null) {
ArgumentHelper.addValueSuppressException(trustStoreFormatArgument, trustStoreFormat);
// Get the path to the truststore file.
trustStorePath = promptForPath(INFO_INTERACTIVE_LDAP_TRUSTSTORE_PATH_PROMPT.get(), defaultTrustStorePath, true, true, true, true, false);
argList.add("--trustStorePath");
argList.add(trustStorePath.getAbsolutePath());
ArgumentHelper.addValueSuppressException(trustStorePathArgument, trustStorePath.getAbsolutePath());
// Get the PIN needed to access the truststore.
trustStorePIN = promptForPassword(INFO_INTERACTIVE_LDAP_TRUSTSTORE_PIN_PROMPT.get(), null, false);
if (trustStorePIN != null) {
argList.add("--trustStorePassword");
argList.add("***REDACTED***");
ArgumentHelper.addValueSuppressException(trustStorePasswordArgument, StaticUtils.toUTF8String(trustStorePIN));
}
argList.add("--trustStoreFormat");
argList.add(trustStoreFormat);
}
} else {
ArgumentHelper.reset(parser.getNamedArgument("keyStorePath"));
ArgumentHelper.reset(parser.getNamedArgument("keyStoreFormat"));
ArgumentHelper.reset(parser.getNamedArgument("trustStorePath"));
ArgumentHelper.reset(parser.getNamedArgument("trustStoreFormat"));
ArgumentHelper.reset(parser.getNamedArgument("certNickname"));
}
}
// Get the port of the directory server.
int defaultPort;
final IntegerArgument portArgument = parser.getIntegerArgument("port");
if (portArgument.getNumOccurrences() > 0) {
// Note -- We're using getNumOccurrences here because isPresent also
// returns true if there is a default value, and that could be wrong in
// this case because the default value doesn't know about SSL.
defaultPort = portArgument.getValue();
} else if (useSSL) {
defaultPort = 636;
if (serverListenerConfigs != null) {
for (final LDAPConnectionHandlerConfiguration cfg : serverListenerConfigs) {
if (cfg.usesSSL()) {
defaultPort = cfg.getPort();
break;
}
}
}
} else if (useStartTLS) {
defaultPort = 389;
if (serverListenerConfigs != null) {
for (final LDAPConnectionHandlerConfiguration cfg : serverListenerConfigs) {
if (cfg.supportsStartTLS()) {
defaultPort = cfg.getPort();
break;
}
}
}
} else {
defaultPort = 389;
if (serverListenerConfigs != null) {
for (final LDAPConnectionHandlerConfiguration cfg : serverListenerConfigs) {
if (!cfg.usesSSL()) {
defaultPort = cfg.getPort();
break;
}
}
}
}
ArgumentHelper.reset(portArgument);
final int port = promptForInteger(INFO_INTERACTIVE_LDAP_PROMPT_PORT.get(), defaultPort, 1, 65_535, true);
argList.add("--port");
argList.add(String.valueOf(port));
ArgumentHelper.addValueSuppressException(portArgument, String.valueOf(port));
// Determine how to authenticate to the directory server.
if (ldapTool.supportsAuthentication()) {
final DNArgument bindDNArgument = parser.getDNArgument("bindDN");
final StringArgument bindPasswordArgument = parser.getStringArgument("bindPassword");
ArgumentHelper.reset(bindPasswordArgument);
ArgumentHelper.reset(parser.getNamedArgument("bindPasswordFile"));
ArgumentHelper.reset(parser.getNamedArgument("promptForBindPassword"));
if (bindRequest == null) {
final String defaultAuthTypeChoice;
final String defaultBindDN;
if (saslOptionArgument.isPresent()) {
defaultAuthTypeChoice = "2";
defaultBindDN = null;
} else {
defaultAuthTypeChoice = "1";
if (bindDNArgument.isPresent()) {
defaultBindDN = bindDNArgument.getStringValue();
} else {
defaultBindDN = null;
}
}
ArgumentHelper.reset(bindDNArgument);
boolean useSimpleAuth = false;
boolean useSASLAuth = false;
final int authMethod = getNumberedMenuChoice(INFO_INTERACTIVE_LDAP_AUTH_PROMPT.get(), false, defaultAuthTypeChoice, INFO_INTERACTIVE_LDAP_AUTH_OPTION_SIMPLE.get(), INFO_INTERACTIVE_LDAP_AUTH_OPTION_SASL.get(), INFO_INTERACTIVE_LDAP_AUTH_OPTION_NONE.get());
switch(authMethod) {
case 0:
useSimpleAuth = true;
break;
case 1:
useSASLAuth = true;
break;
case 2:
default:
break;
}
if (useSimpleAuth) {
ArgumentHelper.reset(saslOptionArgument);
final DN bindDN = promptForDN(INFO_INTERACTIVE_LDAP_AUTH_BIND_DN_PROMPT.get(), defaultBindDN, true);
if (bindDN.isNullDN()) {
bindRequest = new SimpleBindRequest();
argList.add("--bindDN");
argList.add("");
argList.add("--bindPassword");
argList.add("");
ArgumentHelper.addValueSuppressException(bindDNArgument, "");
ArgumentHelper.addValueSuppressException(bindPasswordArgument, "");
} else {
final byte[] bindPassword = promptForPassword(INFO_INTERACTIVE_LDAP_AUTH_PW_PROMPT.get(), null, true);
bindRequest = new SimpleBindRequest(bindDN, bindPassword);
argList.add("--bindDN");
argList.add(bindDN.toString());
argList.add("--bindPassword");
argList.add("***REDACTED***");
ArgumentHelper.addValueSuppressException(bindDNArgument, bindDN.toString());
ArgumentHelper.addValueSuppressException(bindPasswordArgument, StaticUtils.toUTF8String(bindPassword));
}
} else if (useSASLAuth) {
String defaultMechChoice = null;
String defaultAuthID = null;
String defaultAuthzID = null;
String defaultRealm = null;
if (saslOptionArgument.isPresent()) {
for (final String saslOption : saslOptionArgument.getValues()) {
final String lowerOption = StaticUtils.toLowerCase(saslOption);
if (lowerOption.equals("mech=cram-md5")) {
defaultMechChoice = "1";
} else if (lowerOption.equals("mech=digest-md5")) {
defaultMechChoice = "2";
} else if (lowerOption.equals("mech=plain")) {
defaultMechChoice = "3";
} else if (lowerOption.startsWith("authid=")) {
defaultAuthID = saslOption.substring(7);
} else if (lowerOption.startsWith("authzid=")) {
defaultAuthzID = saslOption.substring(8);
} else if (lowerOption.startsWith("realm=")) {
defaultRealm = saslOption.substring(6);
}
}
}
ArgumentHelper.reset(saslOptionArgument);
final int mech = getNumberedMenuChoice(INFO_INTERACTIVE_LDAP_AUTH_SASL_PROMPT.get(), false, defaultMechChoice, INFO_INTERACTIVE_LDAP_SASL_OPTION_CRAM_MD5.get(), INFO_INTERACTIVE_LDAP_SASL_OPTION_DIGEST_MD5.get(), INFO_INTERACTIVE_LDAP_SASL_OPTION_PLAIN.get());
switch(mech) {
case 0:
String authID = promptForString(INFO_INTERACTIVE_LDAP_AUTH_AUTHID_PROMPT.get(), defaultAuthID, true);
byte[] pw = promptForPassword(INFO_INTERACTIVE_LDAP_AUTH_PW_PROMPT.get(), null, true);
bindRequest = new CRAMMD5BindRequest(authID, pw);
argList.add("--saslOption");
argList.add("mech=CRAM-MD5");
argList.add("--saslOption");
argList.add("authID=" + authID);
argList.add("--bindPassword");
argList.add("***REDACTED***");
ArgumentHelper.addValueSuppressException(saslOptionArgument, "mech=CRAM-MD5");
ArgumentHelper.addValueSuppressException(saslOptionArgument, "authID=" + authID);
ArgumentHelper.addValueSuppressException(bindPasswordArgument, StaticUtils.toUTF8String(pw));
break;
case 1:
authID = promptForString(INFO_INTERACTIVE_LDAP_AUTH_AUTHID_PROMPT.get(), defaultAuthID, true);
String authzID = promptForString(INFO_INTERACTIVE_LDAP_AUTH_AUTHZID_PROMPT.get(), defaultAuthzID, false);
final String realm = promptForString(INFO_INTERACTIVE_LDAP_AUTH_REALM_PROMPT.get(), defaultRealm, false);
pw = promptForPassword(INFO_INTERACTIVE_LDAP_AUTH_PW_PROMPT.get(), null, true);
bindRequest = new DIGESTMD5BindRequest(authID, authzID, pw, realm);
argList.add("--saslOption");
argList.add("mech=DIGEST-MD5");
argList.add("--saslOption");
argList.add("authID=" + authID);
ArgumentHelper.addValueSuppressException(saslOptionArgument, "mech=DIGEST-MD5");
ArgumentHelper.addValueSuppressException(saslOptionArgument, "authID=" + authID);
if (authzID != null) {
argList.add("--saslOption");
argList.add("authzID=" + authzID);
ArgumentHelper.addValueSuppressException(saslOptionArgument, "authzID=" + authzID);
}
if (realm != null) {
argList.add("--saslOption");
argList.add("realm=" + realm);
ArgumentHelper.addValueSuppressException(saslOptionArgument, "realm=" + realm);
}
argList.add("--bindPassword");
argList.add("***REDACTED***");
ArgumentHelper.addValueSuppressException(bindPasswordArgument, StaticUtils.toUTF8String(pw));
break;
case 2:
authID = promptForString(INFO_INTERACTIVE_LDAP_AUTH_AUTHID_PROMPT.get(), defaultAuthID, true);
authzID = promptForString(INFO_INTERACTIVE_LDAP_AUTH_AUTHZID_PROMPT.get(), defaultAuthzID, false);
pw = promptForPassword(INFO_INTERACTIVE_LDAP_AUTH_PW_PROMPT.get(), null, true);
bindRequest = new PLAINBindRequest(authID, authzID, pw);
argList.add("--saslOption");
argList.add("mech=PLAIN");
argList.add("--saslOption");
argList.add("authID=" + authID);
ArgumentHelper.addValueSuppressException(saslOptionArgument, "mech=PLAIN");
ArgumentHelper.addValueSuppressException(saslOptionArgument, "authID=" + authID);
if (authzID != null) {
argList.add("--saslOption");
argList.add("authzID=" + authzID);
ArgumentHelper.addValueSuppressException(saslOptionArgument, "authzID=" + authzID);
}
argList.add("--bindPassword");
argList.add("***REDACTED***");
ArgumentHelper.addValueSuppressException(bindPasswordArgument, StaticUtils.toUTF8String(pw));
break;
}
}
} else {
ArgumentHelper.reset(bindDNArgument);
}
}
if (test) {
// Perform the necessary initialization for SSL/TLS communication.
final SSLUtil sslUtil;
if (useSSL || useStartTLS) {
final KeyManager keyManager;
if (keyStorePath == null) {
keyManager = null;
} else {
final char[] pinChars;
if (keyStorePIN == null) {
pinChars = null;
} else {
final String pinString = StaticUtils.toUTF8String(keyStorePIN);
pinChars = pinString.toCharArray();
}
try {
keyManager = new KeyStoreKeyManager(keyStorePath, pinChars, keyStoreFormat, certificateNickname, true);
} catch (final Exception e) {
Debug.debugException(e);
tool.wrapErr(0, wrapColumn, ERR_INTERACTIVE_LDAP_CANNOT_CREATE_KEY_MANAGER.get(StaticUtils.getExceptionMessage(e)));
if (promptForYesNo(INFO_INTERACTIVE_LDAP_RETRY_PROMPT.get(), true, true)) {
promptForLDAPArguments(argList, test);
return;
} else {
throw new LDAPException(ResultCode.LOCAL_ERROR, "", e);
}
}
}
final TrustManager trustManager;
if (trustAll) {
trustManager = new TrustAllTrustManager();
} else if (trustStorePath == null) {
trustManager = InternalSDKHelper.getPreferredPromptTrustManagerChain(null);
} else {
final char[] pinChars;
if (trustStorePIN == null) {
pinChars = null;
} else {
final String pinString = StaticUtils.toUTF8String(trustStorePIN);
pinChars = pinString.toCharArray();
}
try {
trustManager = new TrustStoreTrustManager(trustStorePath, pinChars, trustStoreFormat, true);
} catch (final Exception e) {
Debug.debugException(e);
tool.wrapErr(0, wrapColumn, ERR_INTERACTIVE_LDAP_CANNOT_CREATE_TRUST_MANAGER.get(StaticUtils.getExceptionMessage(e)));
if (promptForYesNo(INFO_INTERACTIVE_LDAP_RETRY_PROMPT.get(), true, true)) {
promptForLDAPArguments(argList, test);
return;
} else {
throw new LDAPException(ResultCode.LOCAL_ERROR, "", e);
}
}
}
sslUtil = new SSLUtil(keyManager, trustManager);
} else {
sslUtil = null;
}
// Create and establish the connection.
final LDAPConnection conn;
if (useSSL) {
try {
conn = new LDAPConnection(sslUtil.createSSLSocketFactory());
} catch (final Exception e) {
Debug.debugException(e);
tool.wrapErr(0, wrapColumn, ERR_INTERACTIVE_LDAP_CANNOT_CREATE_SOCKET_FACTORY.get(StaticUtils.getExceptionMessage(e)), e);
if (promptForYesNo(INFO_INTERACTIVE_LDAP_RETRY_PROMPT.get(), true, true)) {
promptForLDAPArguments(argList, test);
return;
} else {
throw new LDAPException(ResultCode.LOCAL_ERROR, "", e);
}
}
} else {
conn = new LDAPConnection();
}
try {
try {
conn.connect(hostname, port);
} catch (final LDAPException le) {
Debug.debugException(le);
tool.wrapErr(0, wrapColumn, ERR_INTERACTIVE_LDAP_CANNOT_CONNECT.get(hostname, port, le.getResultString()));
if (promptForYesNo(INFO_INTERACTIVE_LDAP_RETRY_PROMPT.get(), true, true)) {
promptForLDAPArguments(argList, test);
return;
} else {
throw new LDAPException(le.getResultCode(), "", le);
}
}
// If we should use StartTLS to secure the connection, then do so now.
if (useStartTLS) {
try {
final ExtendedResult startTLSResult = conn.processExtendedOperation(new StartTLSExtendedRequest(sslUtil.createSSLContext()));
if (startTLSResult.getResultCode() != ResultCode.SUCCESS) {
throw new LDAPException(startTLSResult);
}
} catch (final Exception e) {
Debug.debugException(e);
final String msg;
if (e instanceof LDAPException) {
msg = ((LDAPException) e).getResultString();
} else {
msg = StaticUtils.getExceptionMessage(e);
}
tool.wrapErr(0, wrapColumn, ERR_INTERACTIVE_LDAP_CANNOT_PERFORM_STARTTLS.get(msg));
if (promptForYesNo(INFO_INTERACTIVE_LDAP_RETRY_PROMPT.get(), true, true)) {
promptForLDAPArguments(argList, test);
return;
} else {
throw new LDAPException(ResultCode.LOCAL_ERROR, "", e);
}
}
}
// Authenticate the connection if appropriate.
if (bindRequest != null) {
try {
conn.bind(bindRequest);
} catch (final LDAPException le) {
Debug.debugException(le);
tool.wrapErr(0, wrapColumn, ERR_INTERACTIVE_LDAP_CANNOT_AUTHENTICATE.get(le.getResultString()));
if (promptForYesNo(INFO_INTERACTIVE_LDAP_RETRY_PROMPT.get(), true, true)) {
promptForLDAPArguments(argList, test);
return;
} else {
throw new LDAPException(le.getResultCode(), "", le);
}
}
}
} finally {
conn.close();
}
}
}
use of com.unboundid.util.args.DNArgument in project ldapsdk by pingidentity.
the class GenerateSourceFromSchema method addNonLDAPArguments.
/**
* {@inheritDoc}
*/
@Override()
public void addNonLDAPArguments(@NotNull final ArgumentParser parser) throws ArgumentException {
outputDirectoryArg = new FileArgument('d', "outputDirectory", false, 1, INFO_GEN_SOURCE_VALUE_PLACEHOLDER_PATH.get(), INFO_GEN_SOURCE_ARG_DESCRIPTION_OUTPUT_DIRECTORY.get(), true, true, false, true);
outputDirectoryArg.addLongIdentifier("output-directory", true);
parser.addArgument(outputDirectoryArg);
structuralClassArg = new StringArgument('s', "structuralClass", true, 1, INFO_GEN_SOURCE_VALUE_PLACEHOLDER_NAME.get(), INFO_GEN_SOURCE_ARG_DESCRIPTION_STRUCTURAL_CLASS.get());
structuralClassArg.addLongIdentifier("structural-class", true);
parser.addArgument(structuralClassArg);
auxiliaryClassArg = new StringArgument('a', "auxiliaryClass", false, 0, INFO_GEN_SOURCE_VALUE_PLACEHOLDER_NAME.get(), INFO_GEN_SOURCE_ARG_DESCRIPTION_AUXILIARY_CLASS.get());
auxiliaryClassArg.addLongIdentifier("auxiliary-class", true);
parser.addArgument(auxiliaryClassArg);
rdnAttributeArg = new StringArgument('r', "rdnAttribute", true, 0, INFO_GEN_SOURCE_VALUE_PLACEHOLDER_NAME.get(), INFO_GEN_SOURCE_ARG_DESCRIPTION_RDN_ATTRIBUTE.get());
rdnAttributeArg.addLongIdentifier("rdn-attribute", true);
parser.addArgument(rdnAttributeArg);
lazyAttributeArg = new StringArgument('l', "lazyAttribute", false, 0, INFO_GEN_SOURCE_VALUE_PLACEHOLDER_NAME.get(), INFO_GEN_SOURCE_ARG_DESCRIPTION_LAZY_ATTRIBUTE.get());
lazyAttributeArg.addLongIdentifier("lazy-attribute", true);
parser.addArgument(lazyAttributeArg);
operationalAttributeArg = new StringArgument('O', "operationalAttribute", false, 0, INFO_GEN_SOURCE_VALUE_PLACEHOLDER_NAME.get(), INFO_GEN_SOURCE_ARG_DESCRIPTION_OPERATIONAL_ATTRIBUTE.get());
operationalAttributeArg.addLongIdentifier("operational-attribute", true);
parser.addArgument(operationalAttributeArg);
defaultParentDNArg = new DNArgument('b', "defaultParentDN", false, 1, INFO_GEN_SOURCE_VALUE_PLACEHOLDER_DN.get(), INFO_GEN_SOURCE_ARG_DESCRIPTION_DEFAULT_PARENT_DN.get());
defaultParentDNArg.addLongIdentifier("default-parent-dn", true);
parser.addArgument(defaultParentDNArg);
packageNameArg = new StringArgument('n', "packageName", false, 1, INFO_GEN_SOURCE_VALUE_PLACEHOLDER_NAME.get(), INFO_GEN_SOURCE_ARG_DESCRIPTION_PACKAGE_NAME.get());
packageNameArg.addLongIdentifier("package-name", true);
parser.addArgument(packageNameArg);
classNameArg = new StringArgument('c', "className", false, 1, INFO_GEN_SOURCE_VALUE_PLACEHOLDER_NAME.get(), INFO_GEN_SOURCE_ARG_DESCRIPTION_CLASS_NAME.get());
classNameArg.addLongIdentifier("class-name", true);
parser.addArgument(classNameArg);
terseArg = new BooleanArgument('t', "terse", 1, INFO_GEN_SOURCE_ARG_DESCRIPTION_TERSE.get());
parser.addArgument(terseArg);
}
use of com.unboundid.util.args.DNArgument in project ldapsdk by pingidentity.
the class TransformLDIF method addToolArguments.
/**
* {@inheritDoc}
*/
@Override()
public void addToolArguments(@NotNull final ArgumentParser parser) throws ArgumentException {
// Add arguments pertaining to the source and target LDIF files.
sourceLDIF = new FileArgument('l', "sourceLDIF", false, 0, null, INFO_TRANSFORM_LDIF_ARG_DESC_SOURCE_LDIF.get(), true, true, true, false);
sourceLDIF.addLongIdentifier("inputLDIF", true);
sourceLDIF.addLongIdentifier("source-ldif", true);
sourceLDIF.addLongIdentifier("input-ldif", true);
sourceLDIF.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_LDIF.get());
parser.addArgument(sourceLDIF);
sourceFromStandardInput = new BooleanArgument(null, "sourceFromStandardInput", 1, INFO_TRANSFORM_LDIF_ARG_DESC_SOURCE_STD_IN.get());
sourceFromStandardInput.addLongIdentifier("source-from-standard-input", true);
sourceFromStandardInput.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_LDIF.get());
parser.addArgument(sourceFromStandardInput);
parser.addRequiredArgumentSet(sourceLDIF, sourceFromStandardInput);
parser.addExclusiveArgumentSet(sourceLDIF, sourceFromStandardInput);
targetLDIF = new FileArgument('o', "targetLDIF", false, 1, null, INFO_TRANSFORM_LDIF_ARG_DESC_TARGET_LDIF.get(), false, true, true, false);
targetLDIF.addLongIdentifier("outputLDIF", true);
targetLDIF.addLongIdentifier("target-ldif", true);
targetLDIF.addLongIdentifier("output-ldif", true);
targetLDIF.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_LDIF.get());
parser.addArgument(targetLDIF);
targetToStandardOutput = new BooleanArgument(null, "targetToStandardOutput", 1, INFO_TRANSFORM_LDIF_ARG_DESC_TARGET_STD_OUT.get());
targetToStandardOutput.addLongIdentifier("target-to-standard-output", true);
targetToStandardOutput.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_LDIF.get());
parser.addArgument(targetToStandardOutput);
parser.addExclusiveArgumentSet(targetLDIF, targetToStandardOutput);
sourceContainsChangeRecords = new BooleanArgument(null, "sourceContainsChangeRecords", INFO_TRANSFORM_LDIF_ARG_DESC_SOURCE_CONTAINS_CHANGE_RECORDS.get());
sourceContainsChangeRecords.addLongIdentifier("source-contains-change-records", true);
sourceContainsChangeRecords.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_LDIF.get());
parser.addArgument(sourceContainsChangeRecords);
appendToTargetLDIF = new BooleanArgument(null, "appendToTargetLDIF", INFO_TRANSFORM_LDIF_ARG_DESC_APPEND_TO_TARGET.get());
appendToTargetLDIF.addLongIdentifier("append-to-target-ldif", true);
appendToTargetLDIF.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_LDIF.get());
parser.addArgument(appendToTargetLDIF);
parser.addExclusiveArgumentSet(targetToStandardOutput, appendToTargetLDIF);
wrapColumn = new IntegerArgument(null, "wrapColumn", false, 1, null, INFO_TRANSFORM_LDIF_ARG_DESC_WRAP_COLUMN.get(), 5, Integer.MAX_VALUE);
wrapColumn.addLongIdentifier("wrap-column", true);
wrapColumn.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_LDIF.get());
parser.addArgument(wrapColumn);
sourceCompressed = new BooleanArgument('C', "sourceCompressed", INFO_TRANSFORM_LDIF_ARG_DESC_SOURCE_COMPRESSED.get());
sourceCompressed.addLongIdentifier("inputCompressed", true);
sourceCompressed.addLongIdentifier("source-compressed", true);
sourceCompressed.addLongIdentifier("input-compressed", true);
sourceCompressed.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_LDIF.get());
parser.addArgument(sourceCompressed);
compressTarget = new BooleanArgument('c', "compressTarget", INFO_TRANSFORM_LDIF_ARG_DESC_COMPRESS_TARGET.get());
compressTarget.addLongIdentifier("compressOutput", true);
compressTarget.addLongIdentifier("compress", true);
compressTarget.addLongIdentifier("compress-target", true);
compressTarget.addLongIdentifier("compress-output", true);
compressTarget.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_LDIF.get());
parser.addArgument(compressTarget);
encryptTarget = new BooleanArgument(null, "encryptTarget", INFO_TRANSFORM_LDIF_ARG_DESC_ENCRYPT_TARGET.get());
encryptTarget.addLongIdentifier("encryptOutput", true);
encryptTarget.addLongIdentifier("encrypt", true);
encryptTarget.addLongIdentifier("encrypt-target", true);
encryptTarget.addLongIdentifier("encrypt-output", true);
encryptTarget.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_LDIF.get());
parser.addArgument(encryptTarget);
encryptionPassphraseFile = new FileArgument(null, "encryptionPassphraseFile", false, 1, null, INFO_TRANSFORM_LDIF_ARG_DESC_ENCRYPTION_PW_FILE.get(), true, true, true, false);
encryptionPassphraseFile.addLongIdentifier("encryptionPasswordFile", true);
encryptionPassphraseFile.addLongIdentifier("encryption-passphrase-file", true);
encryptionPassphraseFile.addLongIdentifier("encryption-password-file", true);
encryptionPassphraseFile.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_LDIF.get());
parser.addArgument(encryptionPassphraseFile);
// Add arguments pertaining to attribute scrambling.
scrambleAttribute = new StringArgument('a', "scrambleAttribute", false, 0, INFO_TRANSFORM_LDIF_PLACEHOLDER_ATTR_NAME.get(), INFO_TRANSFORM_LDIF_ARG_DESC_SCRAMBLE_ATTR.get());
scrambleAttribute.addLongIdentifier("attributeName", true);
scrambleAttribute.addLongIdentifier("scramble-attribute", true);
scrambleAttribute.addLongIdentifier("attribute-name", true);
scrambleAttribute.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_SCRAMBLE.get());
parser.addArgument(scrambleAttribute);
scrambleJSONField = new StringArgument(null, "scrambleJSONField", false, 0, INFO_TRANSFORM_LDIF_PLACEHOLDER_FIELD_NAME.get(), INFO_TRANSFORM_LDIF_ARG_DESC_SCRAMBLE_JSON_FIELD.get(scrambleAttribute.getIdentifierString()));
scrambleJSONField.addLongIdentifier("scramble-json-field", true);
scrambleJSONField.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_SCRAMBLE.get());
parser.addArgument(scrambleJSONField);
parser.addDependentArgumentSet(scrambleJSONField, scrambleAttribute);
randomSeed = new IntegerArgument('s', "randomSeed", false, 1, null, INFO_TRANSFORM_LDIF_ARG_DESC_RANDOM_SEED.get());
randomSeed.addLongIdentifier("random-seed", true);
randomSeed.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_SCRAMBLE.get());
parser.addArgument(randomSeed);
// Add arguments pertaining to replacing attribute values with a generated
// value using a sequential counter.
sequentialAttribute = new StringArgument('S', "sequentialAttribute", false, 0, INFO_TRANSFORM_LDIF_PLACEHOLDER_ATTR_NAME.get(), INFO_TRANSFORM_LDIF_ARG_DESC_SEQUENTIAL_ATTR.get(sourceContainsChangeRecords.getIdentifierString()));
sequentialAttribute.addLongIdentifier("sequentialAttributeName", true);
sequentialAttribute.addLongIdentifier("sequential-attribute", true);
sequentialAttribute.addLongIdentifier("sequential-attribute-name", true);
sequentialAttribute.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_SEQUENTIAL.get());
parser.addArgument(sequentialAttribute);
parser.addExclusiveArgumentSet(sourceContainsChangeRecords, sequentialAttribute);
initialSequentialValue = new IntegerArgument('i', "initialSequentialValue", false, 1, null, INFO_TRANSFORM_LDIF_ARG_DESC_INITIAL_SEQUENTIAL_VALUE.get(sequentialAttribute.getIdentifierString()));
initialSequentialValue.addLongIdentifier("initial-sequential-value", true);
initialSequentialValue.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_SEQUENTIAL.get());
parser.addArgument(initialSequentialValue);
parser.addDependentArgumentSet(initialSequentialValue, sequentialAttribute);
sequentialValueIncrement = new IntegerArgument(null, "sequentialValueIncrement", false, 1, null, INFO_TRANSFORM_LDIF_ARG_DESC_SEQUENTIAL_INCREMENT.get(sequentialAttribute.getIdentifierString()));
sequentialValueIncrement.addLongIdentifier("sequential-value-increment", true);
sequentialValueIncrement.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_SEQUENTIAL.get());
parser.addArgument(sequentialValueIncrement);
parser.addDependentArgumentSet(sequentialValueIncrement, sequentialAttribute);
textBeforeSequentialValue = new StringArgument(null, "textBeforeSequentialValue", false, 1, null, INFO_TRANSFORM_LDIF_ARG_DESC_SEQUENTIAL_TEXT_BEFORE.get(sequentialAttribute.getIdentifierString()));
textBeforeSequentialValue.addLongIdentifier("text-before-sequential-value", true);
textBeforeSequentialValue.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_SEQUENTIAL.get());
parser.addArgument(textBeforeSequentialValue);
parser.addDependentArgumentSet(textBeforeSequentialValue, sequentialAttribute);
textAfterSequentialValue = new StringArgument(null, "textAfterSequentialValue", false, 1, null, INFO_TRANSFORM_LDIF_ARG_DESC_SEQUENTIAL_TEXT_AFTER.get(sequentialAttribute.getIdentifierString()));
textAfterSequentialValue.addLongIdentifier("text-after-sequential-value", true);
textAfterSequentialValue.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_SEQUENTIAL.get());
parser.addArgument(textAfterSequentialValue);
parser.addDependentArgumentSet(textAfterSequentialValue, sequentialAttribute);
// Add arguments pertaining to attribute value replacement.
replaceValuesAttribute = new StringArgument(null, "replaceValuesAttribute", false, 1, INFO_TRANSFORM_LDIF_PLACEHOLDER_ATTR_NAME.get(), INFO_TRANSFORM_LDIF_ARG_DESC_REPLACE_VALUES_ATTR.get(sourceContainsChangeRecords.getIdentifierString()));
replaceValuesAttribute.addLongIdentifier("replace-values-attribute", true);
replaceValuesAttribute.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_REPLACE_VALUES.get());
parser.addArgument(replaceValuesAttribute);
parser.addExclusiveArgumentSet(sourceContainsChangeRecords, replaceValuesAttribute);
replacementValue = new StringArgument(null, "replacementValue", false, 0, null, INFO_TRANSFORM_LDIF_ARG_DESC_REPLACEMENT_VALUE.get(replaceValuesAttribute.getIdentifierString()));
replacementValue.addLongIdentifier("replacement-value", true);
replacementValue.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_REPLACE_VALUES.get());
parser.addArgument(replacementValue);
parser.addDependentArgumentSet(replaceValuesAttribute, replacementValue);
parser.addDependentArgumentSet(replacementValue, replaceValuesAttribute);
// Add arguments pertaining to adding missing attributes.
addAttributeName = new StringArgument(null, "addAttributeName", false, 1, INFO_TRANSFORM_LDIF_PLACEHOLDER_ATTR_NAME.get(), INFO_TRANSFORM_LDIF_ARG_DESC_ADD_ATTR.get("--addAttributeValue", sourceContainsChangeRecords.getIdentifierString()));
addAttributeName.addLongIdentifier("add-attribute-name", true);
addAttributeName.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_ADD_ATTR.get());
parser.addArgument(addAttributeName);
parser.addExclusiveArgumentSet(sourceContainsChangeRecords, addAttributeName);
addAttributeValue = new StringArgument(null, "addAttributeValue", false, 0, null, INFO_TRANSFORM_LDIF_ARG_DESC_ADD_VALUE.get(addAttributeName.getIdentifierString()));
addAttributeValue.addLongIdentifier("add-attribute-value", true);
addAttributeValue.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_ADD_ATTR.get());
parser.addArgument(addAttributeValue);
parser.addDependentArgumentSet(addAttributeName, addAttributeValue);
parser.addDependentArgumentSet(addAttributeValue, addAttributeName);
addToExistingValues = new BooleanArgument(null, "addToExistingValues", INFO_TRANSFORM_LDIF_ARG_DESC_ADD_MERGE_VALUES.get(addAttributeName.getIdentifierString(), addAttributeValue.getIdentifierString()));
addToExistingValues.addLongIdentifier("add-to-existing-values", true);
addToExistingValues.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_ADD_ATTR.get());
parser.addArgument(addToExistingValues);
parser.addDependentArgumentSet(addToExistingValues, addAttributeName);
addAttributeBaseDN = new DNArgument(null, "addAttributeBaseDN", false, 1, null, INFO_TRANSFORM_LDIF_ARG_DESC_ADD_BASE_DN.get(addAttributeName.getIdentifierString()));
addAttributeBaseDN.addLongIdentifier("add-attribute-base-dn", true);
addAttributeBaseDN.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_ADD_ATTR.get());
parser.addArgument(addAttributeBaseDN);
parser.addDependentArgumentSet(addAttributeBaseDN, addAttributeName);
addAttributeScope = new ScopeArgument(null, "addAttributeScope", false, null, INFO_TRANSFORM_LDIF_ARG_DESC_ADD_SCOPE.get(addAttributeBaseDN.getIdentifierString(), addAttributeName.getIdentifierString()));
addAttributeScope.addLongIdentifier("add-attribute-scope", true);
addAttributeScope.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_ADD_ATTR.get());
parser.addArgument(addAttributeScope);
parser.addDependentArgumentSet(addAttributeScope, addAttributeName);
addAttributeFilter = new FilterArgument(null, "addAttributeFilter", false, 1, null, INFO_TRANSFORM_LDIF_ARG_DESC_ADD_FILTER.get(addAttributeName.getIdentifierString()));
addAttributeFilter.addLongIdentifier("add-attribute-filter", true);
addAttributeFilter.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_ADD_ATTR.get());
parser.addArgument(addAttributeFilter);
parser.addDependentArgumentSet(addAttributeFilter, addAttributeName);
// Add arguments pertaining to renaming attributes.
renameAttributeFrom = new StringArgument(null, "renameAttributeFrom", false, 0, INFO_TRANSFORM_LDIF_PLACEHOLDER_ATTR_NAME.get(), INFO_TRANSFORM_LDIF_ARG_DESC_RENAME_FROM.get());
renameAttributeFrom.addLongIdentifier("rename-attribute-from", true);
renameAttributeFrom.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_RENAME.get());
parser.addArgument(renameAttributeFrom);
renameAttributeTo = new StringArgument(null, "renameAttributeTo", false, 0, INFO_TRANSFORM_LDIF_PLACEHOLDER_ATTR_NAME.get(), INFO_TRANSFORM_LDIF_ARG_DESC_RENAME_TO.get(renameAttributeFrom.getIdentifierString()));
renameAttributeTo.addLongIdentifier("rename-attribute-to", true);
renameAttributeTo.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_RENAME.get());
parser.addArgument(renameAttributeTo);
parser.addDependentArgumentSet(renameAttributeFrom, renameAttributeTo);
parser.addDependentArgumentSet(renameAttributeTo, renameAttributeFrom);
// Add arguments pertaining to flattening subtrees.
flattenBaseDN = new DNArgument(null, "flattenBaseDN", false, 1, null, INFO_TRANSFORM_LDIF_ARG_DESC_FLATTEN_BASE_DN.get());
flattenBaseDN.addLongIdentifier("flatten-base-dn", true);
flattenBaseDN.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_FLATTEN.get());
parser.addArgument(flattenBaseDN);
parser.addExclusiveArgumentSet(sourceContainsChangeRecords, flattenBaseDN);
flattenAddOmittedRDNAttributesToEntry = new BooleanArgument(null, "flattenAddOmittedRDNAttributesToEntry", 1, INFO_TRANSFORM_LDIF_ARG_DESC_FLATTEN_ADD_OMITTED_TO_ENTRY.get());
flattenAddOmittedRDNAttributesToEntry.addLongIdentifier("flatten-add-omitted-rdn-attributes-to-entry", true);
flattenAddOmittedRDNAttributesToEntry.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_FLATTEN.get());
parser.addArgument(flattenAddOmittedRDNAttributesToEntry);
parser.addDependentArgumentSet(flattenAddOmittedRDNAttributesToEntry, flattenBaseDN);
flattenAddOmittedRDNAttributesToRDN = new BooleanArgument(null, "flattenAddOmittedRDNAttributesToRDN", 1, INFO_TRANSFORM_LDIF_ARG_DESC_FLATTEN_ADD_OMITTED_TO_RDN.get());
flattenAddOmittedRDNAttributesToRDN.addLongIdentifier("flatten-add-omitted-rdn-attributes-to-rdn", true);
flattenAddOmittedRDNAttributesToRDN.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_FLATTEN.get());
parser.addArgument(flattenAddOmittedRDNAttributesToRDN);
parser.addDependentArgumentSet(flattenAddOmittedRDNAttributesToRDN, flattenBaseDN);
flattenExcludeFilter = new FilterArgument(null, "flattenExcludeFilter", false, 1, null, INFO_TRANSFORM_LDIF_ARG_DESC_FLATTEN_EXCLUDE_FILTER.get());
flattenExcludeFilter.addLongIdentifier("flatten-exclude-filter", true);
flattenExcludeFilter.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_FLATTEN.get());
parser.addArgument(flattenExcludeFilter);
parser.addDependentArgumentSet(flattenExcludeFilter, flattenBaseDN);
// Add arguments pertaining to moving subtrees.
moveSubtreeFrom = new DNArgument(null, "moveSubtreeFrom", false, 0, null, INFO_TRANSFORM_LDIF_ARG_DESC_MOVE_SUBTREE_FROM.get());
moveSubtreeFrom.addLongIdentifier("move-subtree-from", true);
moveSubtreeFrom.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_MOVE.get());
parser.addArgument(moveSubtreeFrom);
moveSubtreeTo = new DNArgument(null, "moveSubtreeTo", false, 0, null, INFO_TRANSFORM_LDIF_ARG_DESC_MOVE_SUBTREE_TO.get(moveSubtreeFrom.getIdentifierString()));
moveSubtreeTo.addLongIdentifier("move-subtree-to", true);
moveSubtreeTo.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_MOVE.get());
parser.addArgument(moveSubtreeTo);
parser.addDependentArgumentSet(moveSubtreeFrom, moveSubtreeTo);
parser.addDependentArgumentSet(moveSubtreeTo, moveSubtreeFrom);
// Add arguments pertaining to redacting attribute values.
redactAttribute = new StringArgument(null, "redactAttribute", false, 0, INFO_TRANSFORM_LDIF_PLACEHOLDER_ATTR_NAME.get(), INFO_TRANSFORM_LDIF_ARG_DESC_REDACT_ATTR.get());
redactAttribute.addLongIdentifier("redact-attribute", true);
redactAttribute.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_REDACT.get());
parser.addArgument(redactAttribute);
hideRedactedValueCount = new BooleanArgument(null, "hideRedactedValueCount", INFO_TRANSFORM_LDIF_ARG_DESC_HIDE_REDACTED_COUNT.get());
hideRedactedValueCount.addLongIdentifier("hide-redacted-value-count", true);
hideRedactedValueCount.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_REDACT.get());
parser.addArgument(hideRedactedValueCount);
parser.addDependentArgumentSet(hideRedactedValueCount, redactAttribute);
// Add arguments pertaining to excluding attributes and entries.
excludeAttribute = new StringArgument(null, "excludeAttribute", false, 0, INFO_TRANSFORM_LDIF_PLACEHOLDER_ATTR_NAME.get(), INFO_TRANSFORM_LDIF_ARG_DESC_EXCLUDE_ATTR.get());
excludeAttribute.addLongIdentifier("suppressAttribute", true);
excludeAttribute.addLongIdentifier("exclude-attribute", true);
excludeAttribute.addLongIdentifier("suppress-attribute", true);
excludeAttribute.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_EXCLUDE.get());
parser.addArgument(excludeAttribute);
excludeEntryBaseDN = new DNArgument(null, "excludeEntryBaseDN", false, 1, null, INFO_TRANSFORM_LDIF_ARG_DESC_EXCLUDE_ENTRY_BASE_DN.get(sourceContainsChangeRecords.getIdentifierString()));
excludeEntryBaseDN.addLongIdentifier("suppressEntryBaseDN", true);
excludeEntryBaseDN.addLongIdentifier("exclude-entry-base-dn", true);
excludeEntryBaseDN.addLongIdentifier("suppress-entry-base-dn", true);
excludeEntryBaseDN.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_EXCLUDE.get());
parser.addArgument(excludeEntryBaseDN);
parser.addExclusiveArgumentSet(sourceContainsChangeRecords, excludeEntryBaseDN);
excludeEntryScope = new ScopeArgument(null, "excludeEntryScope", false, null, INFO_TRANSFORM_LDIF_ARG_DESC_EXCLUDE_ENTRY_SCOPE.get(sourceContainsChangeRecords.getIdentifierString()));
excludeEntryScope.addLongIdentifier("suppressEntryScope", true);
excludeEntryScope.addLongIdentifier("exclude-entry-scope", true);
excludeEntryScope.addLongIdentifier("suppress-entry-scope", true);
excludeEntryScope.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_EXCLUDE.get());
parser.addArgument(excludeEntryScope);
parser.addExclusiveArgumentSet(sourceContainsChangeRecords, excludeEntryScope);
excludeEntryFilter = new FilterArgument(null, "excludeEntryFilter", false, 1, null, INFO_TRANSFORM_LDIF_ARG_DESC_EXCLUDE_ENTRY_FILTER.get(sourceContainsChangeRecords.getIdentifierString()));
excludeEntryFilter.addLongIdentifier("suppressEntryFilter", true);
excludeEntryFilter.addLongIdentifier("exclude-entry-filter", true);
excludeEntryFilter.addLongIdentifier("suppress-entry-filter", true);
excludeEntryFilter.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_EXCLUDE.get());
parser.addArgument(excludeEntryFilter);
parser.addExclusiveArgumentSet(sourceContainsChangeRecords, excludeEntryFilter);
excludeNonMatchingEntries = new BooleanArgument(null, "excludeNonMatchingEntries", INFO_TRANSFORM_LDIF_ARG_DESC_EXCLUDE_NON_MATCHING.get());
excludeNonMatchingEntries.addLongIdentifier("exclude-non-matching-entries", true);
excludeNonMatchingEntries.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_EXCLUDE.get());
parser.addArgument(excludeNonMatchingEntries);
parser.addDependentArgumentSet(excludeNonMatchingEntries, excludeEntryBaseDN, excludeEntryScope, excludeEntryFilter);
// Add arguments for excluding records based on their change types.
excludeChangeType = new StringArgument(null, "excludeChangeType", false, 0, INFO_TRANSFORM_LDIF_PLACEHOLDER_CHANGE_TYPES.get(), INFO_TRANSFORM_LDIF_ARG_DESC_EXCLUDE_CHANGE_TYPE.get(), StaticUtils.setOf("add", "delete", "modify", "moddn"));
excludeChangeType.addLongIdentifier("exclude-change-type", true);
excludeChangeType.addLongIdentifier("exclude-changetype", true);
excludeChangeType.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_EXCLUDE.get());
parser.addArgument(excludeChangeType);
// Add arguments for excluding records that don't have a change type.
excludeRecordsWithoutChangeType = new BooleanArgument(null, "excludeRecordsWithoutChangeType", 1, INFO_TRANSFORM_LDIF_EXCLUDE_WITHOUT_CHANGETYPE.get());
excludeRecordsWithoutChangeType.addLongIdentifier("exclude-records-without-change-type", true);
excludeRecordsWithoutChangeType.addLongIdentifier("exclude-records-without-changetype", true);
excludeRecordsWithoutChangeType.setArgumentGroupName(INFO_TRANSFORM_LDIF_ARG_GROUP_EXCLUDE.get());
parser.addArgument(excludeRecordsWithoutChangeType);
// Add the remaining arguments.
schemaPath = new FileArgument(null, "schemaPath", false, 0, null, INFO_TRANSFORM_LDIF_ARG_DESC_SCHEMA_PATH.get(), true, true, false, false);
schemaPath.addLongIdentifier("schemaFile", true);
schemaPath.addLongIdentifier("schemaDirectory", true);
schemaPath.addLongIdentifier("schema-path", true);
schemaPath.addLongIdentifier("schema-file", true);
schemaPath.addLongIdentifier("schema-directory", true);
parser.addArgument(schemaPath);
numThreads = new IntegerArgument('t', "numThreads", false, 1, null, INFO_TRANSFORM_LDIF_ARG_DESC_NUM_THREADS.get(), 1, Integer.MAX_VALUE, 1);
numThreads.addLongIdentifier("num-threads", true);
parser.addArgument(numThreads);
processDNs = new BooleanArgument('d', "processDNs", INFO_TRANSFORM_LDIF_ARG_DESC_PROCESS_DNS.get());
processDNs.addLongIdentifier("process-dns", true);
parser.addArgument(processDNs);
// Ensure that at least one kind of transformation was requested.
parser.addRequiredArgumentSet(scrambleAttribute, sequentialAttribute, replaceValuesAttribute, addAttributeName, renameAttributeFrom, flattenBaseDN, moveSubtreeFrom, redactAttribute, excludeAttribute, excludeEntryBaseDN, excludeEntryScope, excludeEntryFilter, excludeChangeType, excludeRecordsWithoutChangeType);
}
use of com.unboundid.util.args.DNArgument in project ldapsdk by pingidentity.
the class DeliverOneTimePassword method addNonLDAPArguments.
/**
* {@inheritDoc}
*/
@Override()
public void addNonLDAPArguments(@NotNull final ArgumentParser parser) throws ArgumentException {
bindDN = new DNArgument('D', "bindDN", false, 1, INFO_DELIVER_OTP_PLACEHOLDER_DN.get(), INFO_DELIVER_OTP_DESCRIPTION_BIND_DN.get());
bindDN.setArgumentGroupName(INFO_DELIVER_OTP_GROUP_ID_AND_AUTH.get());
bindDN.addLongIdentifier("bind-dn", true);
parser.addArgument(bindDN);
userName = new StringArgument('n', "userName", false, 1, INFO_DELIVER_OTP_PLACEHOLDER_USERNAME.get(), INFO_DELIVER_OTP_DESCRIPTION_USERNAME.get());
userName.setArgumentGroupName(INFO_DELIVER_OTP_GROUP_ID_AND_AUTH.get());
userName.addLongIdentifier("user-name", true);
parser.addArgument(userName);
bindPassword = new StringArgument('w', "bindPassword", false, 1, INFO_DELIVER_OTP_PLACEHOLDER_PASSWORD.get(), INFO_DELIVER_OTP_DESCRIPTION_BIND_PW.get());
bindPassword.setSensitive(true);
bindPassword.setArgumentGroupName(INFO_DELIVER_OTP_GROUP_ID_AND_AUTH.get());
bindPassword.addLongIdentifier("bind-password", true);
parser.addArgument(bindPassword);
bindPasswordFile = new FileArgument('j', "bindPasswordFile", false, 1, INFO_DELIVER_OTP_PLACEHOLDER_PATH.get(), INFO_DELIVER_OTP_DESCRIPTION_BIND_PW_FILE.get(), true, true, true, false);
bindPasswordFile.setArgumentGroupName(INFO_DELIVER_OTP_GROUP_ID_AND_AUTH.get());
bindPasswordFile.addLongIdentifier("bind-password-file", true);
parser.addArgument(bindPasswordFile);
promptForBindPassword = new BooleanArgument(null, "promptForBindPassword", 1, INFO_DELIVER_OTP_DESCRIPTION_BIND_PW_PROMPT.get());
promptForBindPassword.setArgumentGroupName(INFO_DELIVER_OTP_GROUP_ID_AND_AUTH.get());
promptForBindPassword.addLongIdentifier("prompt-for-bind-password", true);
parser.addArgument(promptForBindPassword);
deliveryMechanism = new StringArgument('m', "deliveryMechanism", false, 0, INFO_DELIVER_OTP_PLACEHOLDER_NAME.get(), INFO_DELIVER_OTP_DESCRIPTION_MECH.get());
deliveryMechanism.setArgumentGroupName(INFO_DELIVER_OTP_GROUP_DELIVERY_MECH.get());
deliveryMechanism.addLongIdentifier("delivery-mechanism", true);
parser.addArgument(deliveryMechanism);
messageSubject = new StringArgument('s', "messageSubject", false, 1, INFO_DELIVER_OTP_PLACEHOLDER_SUBJECT.get(), INFO_DELIVER_OTP_DESCRIPTION_SUBJECT.get());
messageSubject.setArgumentGroupName(INFO_DELIVER_OTP_GROUP_DELIVERY_MECH.get());
messageSubject.addLongIdentifier("message-subject", true);
parser.addArgument(messageSubject);
fullTextBeforeOTP = new StringArgument('f', "fullTextBeforeOTP", false, 1, INFO_DELIVER_OTP_PLACEHOLDER_FULL_BEFORE.get(), INFO_DELIVER_OTP_DESCRIPTION_FULL_BEFORE.get());
fullTextBeforeOTP.setArgumentGroupName(INFO_DELIVER_OTP_GROUP_DELIVERY_MECH.get());
fullTextBeforeOTP.addLongIdentifier("full-text-before-otp", true);
parser.addArgument(fullTextBeforeOTP);
fullTextAfterOTP = new StringArgument('F', "fullTextAfterOTP", false, 1, INFO_DELIVER_OTP_PLACEHOLDER_FULL_AFTER.get(), INFO_DELIVER_OTP_DESCRIPTION_FULL_AFTER.get());
fullTextAfterOTP.setArgumentGroupName(INFO_DELIVER_OTP_GROUP_DELIVERY_MECH.get());
fullTextAfterOTP.addLongIdentifier("full-text-after-otp", true);
parser.addArgument(fullTextAfterOTP);
compactTextBeforeOTP = new StringArgument('c', "compactTextBeforeOTP", false, 1, INFO_DELIVER_OTP_PLACEHOLDER_COMPACT_BEFORE.get(), INFO_DELIVER_OTP_DESCRIPTION_COMPACT_BEFORE.get());
compactTextBeforeOTP.setArgumentGroupName(INFO_DELIVER_OTP_GROUP_DELIVERY_MECH.get());
compactTextBeforeOTP.addLongIdentifier("compact-text-before-otp", true);
parser.addArgument(compactTextBeforeOTP);
compactTextAfterOTP = new StringArgument('C', "compactTextAfterOTP", false, 1, INFO_DELIVER_OTP_PLACEHOLDER_COMPACT_AFTER.get(), INFO_DELIVER_OTP_DESCRIPTION_COMPACT_AFTER.get());
compactTextAfterOTP.setArgumentGroupName(INFO_DELIVER_OTP_GROUP_DELIVERY_MECH.get());
compactTextAfterOTP.addLongIdentifier("compact-text-after-otp", true);
parser.addArgument(compactTextAfterOTP);
// Either the bind DN or username must have been provided.
parser.addRequiredArgumentSet(bindDN, userName);
// Only one option may be used for specifying the user identity.
parser.addExclusiveArgumentSet(bindDN, userName);
// Only one option may be used for specifying the bind password.
parser.addExclusiveArgumentSet(bindPassword, bindPasswordFile, promptForBindPassword);
}
use of com.unboundid.util.args.DNArgument in project ldapsdk by pingidentity.
the class ManageCertificates method doGenerateOrSignCertificateOrCSR.
/**
* Performs the necessary processing for the generate-self-signed-certificate,
* generate-certificate-signing-request, and sign-certificate-signing-request
* subcommands.
*
* @return A result code that indicates whether the processing completed
* successfully.
*/
@NotNull()
private ResultCode doGenerateOrSignCertificateOrCSR() {
// Figure out which subcommand we're processing.
final boolean isGenerateCertificate;
final boolean isGenerateCSR;
final boolean isSignCSR;
final SubCommand selectedSubCommand = globalParser.getSelectedSubCommand();
if (selectedSubCommand.hasName("generate-self-signed-certificate")) {
isGenerateCertificate = true;
isGenerateCSR = false;
isSignCSR = false;
} else if (selectedSubCommand.hasName("generate-certificate-signing-request")) {
isGenerateCertificate = false;
isGenerateCSR = true;
isSignCSR = false;
} else {
Validator.ensureTrue(selectedSubCommand.hasName("sign-certificate-signing-request"));
isGenerateCertificate = false;
isGenerateCSR = false;
isSignCSR = true;
}
// Get the values of a number of configured arguments.
final StringArgument aliasArgument = subCommandParser.getStringArgument("alias");
final String alias = aliasArgument.getValue();
final File keystorePath = getKeystorePath();
final boolean isNewKeystore = (!keystorePath.exists());
DN subjectDN = null;
final DNArgument subjectDNArgument = subCommandParser.getDNArgument("subject-dn");
if ((subjectDNArgument != null) && subjectDNArgument.isPresent()) {
subjectDN = subjectDNArgument.getValue();
}
File inputFile = null;
final FileArgument inputFileArgument = subCommandParser.getFileArgument("input-file");
if ((inputFileArgument != null) && inputFileArgument.isPresent()) {
inputFile = inputFileArgument.getValue();
}
File outputFile = null;
final FileArgument outputFileArgument = subCommandParser.getFileArgument("output-file");
if ((outputFileArgument != null) && outputFileArgument.isPresent()) {
outputFile = outputFileArgument.getValue();
}
boolean outputPEM = true;
final StringArgument outputFormatArgument = subCommandParser.getStringArgument("output-format");
if ((outputFormatArgument != null) && outputFormatArgument.isPresent()) {
final String format = outputFormatArgument.getValue().toLowerCase();
if (format.equals("der") || format.equals("binary") || format.equals("bin")) {
outputPEM = false;
}
}
if ((!outputPEM) && (outputFile == null)) {
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_NO_FILE_WITH_DER.get());
return ResultCode.PARAM_ERROR;
}
final BooleanArgument replaceExistingCertificateArgument = subCommandParser.getBooleanArgument("replace-existing-certificate");
final boolean replaceExistingCertificate = ((replaceExistingCertificateArgument != null) && replaceExistingCertificateArgument.isPresent());
if (replaceExistingCertificate && (!keystorePath.exists())) {
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_REPLACE_WITHOUT_KS.get());
return ResultCode.PARAM_ERROR;
}
final BooleanArgument inheritExtensionsArgument = subCommandParser.getBooleanArgument("inherit-extensions");
final boolean inheritExtensions = ((inheritExtensionsArgument != null) && inheritExtensionsArgument.isPresent());
final BooleanArgument includeRequestedExtensionsArgument = subCommandParser.getBooleanArgument("include-requested-extensions");
final boolean includeRequestedExtensions = ((includeRequestedExtensionsArgument != null) && includeRequestedExtensionsArgument.isPresent());
final BooleanArgument noPromptArgument = subCommandParser.getBooleanArgument("no-prompt");
final boolean noPrompt = ((noPromptArgument != null) && noPromptArgument.isPresent());
final BooleanArgument displayKeytoolCommandArgument = subCommandParser.getBooleanArgument("display-keytool-command");
final boolean displayKeytoolCommand = ((displayKeytoolCommandArgument != null) && displayKeytoolCommandArgument.isPresent());
int daysValid = 365;
final IntegerArgument daysValidArgument = subCommandParser.getIntegerArgument("days-valid");
if ((daysValidArgument != null) && daysValidArgument.isPresent()) {
daysValid = daysValidArgument.getValue();
}
Date validityStartTime = null;
final TimestampArgument validityStartTimeArgument = subCommandParser.getTimestampArgument("validity-start-time");
if ((validityStartTimeArgument != null) && validityStartTimeArgument.isPresent()) {
validityStartTime = validityStartTimeArgument.getValue();
}
PublicKeyAlgorithmIdentifier keyAlgorithmIdentifier = null;
String keyAlgorithmName = null;
final StringArgument keyAlgorithmArgument = subCommandParser.getStringArgument("key-algorithm");
if ((keyAlgorithmArgument != null) && keyAlgorithmArgument.isPresent()) {
final String name = keyAlgorithmArgument.getValue();
keyAlgorithmIdentifier = PublicKeyAlgorithmIdentifier.forName(name);
if (keyAlgorithmIdentifier == null) {
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_UNKNOWN_KEY_ALG.get(name));
return ResultCode.PARAM_ERROR;
} else {
keyAlgorithmName = keyAlgorithmIdentifier.getName();
}
}
Integer keySizeBits = null;
final IntegerArgument keySizeBitsArgument = subCommandParser.getIntegerArgument("key-size-bits");
if ((keySizeBitsArgument != null) && keySizeBitsArgument.isPresent()) {
keySizeBits = keySizeBitsArgument.getValue();
}
if ((keyAlgorithmIdentifier != null) && (keyAlgorithmIdentifier != PublicKeyAlgorithmIdentifier.RSA) && (keySizeBits == null)) {
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_NO_KEY_SIZE_FOR_NON_RSA_KEY.get());
return ResultCode.PARAM_ERROR;
}
String signatureAlgorithmName = null;
SignatureAlgorithmIdentifier signatureAlgorithmIdentifier = null;
final StringArgument signatureAlgorithmArgument = subCommandParser.getStringArgument("signature-algorithm");
if ((signatureAlgorithmArgument != null) && signatureAlgorithmArgument.isPresent()) {
final String name = signatureAlgorithmArgument.getValue();
signatureAlgorithmIdentifier = SignatureAlgorithmIdentifier.forName(name);
if (signatureAlgorithmIdentifier == null) {
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_UNKNOWN_SIG_ALG.get(name));
return ResultCode.PARAM_ERROR;
} else {
signatureAlgorithmName = signatureAlgorithmIdentifier.getJavaName();
}
}
if ((keyAlgorithmIdentifier != null) && (keyAlgorithmIdentifier != PublicKeyAlgorithmIdentifier.RSA) && (signatureAlgorithmIdentifier == null)) {
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_NO_SIG_ALG_FOR_NON_RSA_KEY.get());
return ResultCode.PARAM_ERROR;
}
// Build a subject alternative name extension, if appropriate.
final ArrayList<X509CertificateExtension> extensionList = new ArrayList<>(10);
final GeneralNamesBuilder sanBuilder = new GeneralNamesBuilder();
final LinkedHashSet<String> sanValues = new LinkedHashSet<>(StaticUtils.computeMapCapacity(10));
final StringArgument sanDNSArgument = subCommandParser.getStringArgument("subject-alternative-name-dns");
if ((sanDNSArgument != null) && sanDNSArgument.isPresent()) {
for (final String value : sanDNSArgument.getValues()) {
sanBuilder.addDNSName(value);
sanValues.add("DNS:" + value);
}
}
final StringArgument sanIPArgument = subCommandParser.getStringArgument("subject-alternative-name-ip-address");
if ((sanIPArgument != null) && sanIPArgument.isPresent()) {
for (final String value : sanIPArgument.getValues()) {
try {
sanBuilder.addIPAddress(LDAPConnectionOptions.DEFAULT_NAME_RESOLVER.getByName(value));
sanValues.add("IP:" + value);
} catch (final Exception e) {
// This should never happen.
Debug.debugException(e);
throw new RuntimeException(e);
}
}
}
final StringArgument sanEmailArgument = subCommandParser.getStringArgument("subject-alternative-name-email-address");
if ((sanEmailArgument != null) && sanEmailArgument.isPresent()) {
for (final String value : sanEmailArgument.getValues()) {
sanBuilder.addRFC822Name(value);
sanValues.add("EMAIL:" + value);
}
}
final StringArgument sanURIArgument = subCommandParser.getStringArgument("subject-alternative-name-uri");
if ((sanURIArgument != null) && sanURIArgument.isPresent()) {
for (final String value : sanURIArgument.getValues()) {
sanBuilder.addUniformResourceIdentifier(value);
sanValues.add("URI:" + value);
}
}
final StringArgument sanOIDArgument = subCommandParser.getStringArgument("subject-alternative-name-oid");
if ((sanOIDArgument != null) && sanOIDArgument.isPresent()) {
for (final String value : sanOIDArgument.getValues()) {
sanBuilder.addRegisteredID(new OID(value));
sanValues.add("OID:" + value);
}
}
if (!sanValues.isEmpty()) {
try {
extensionList.add(new SubjectAlternativeNameExtension(false, sanBuilder.build()));
} catch (final Exception e) {
// This should never happen.
Debug.debugException(e);
throw new RuntimeException(e);
}
}
// Build a set of issuer alternative name extension values.
final GeneralNamesBuilder ianBuilder = new GeneralNamesBuilder();
final LinkedHashSet<String> ianValues = new LinkedHashSet<>(StaticUtils.computeMapCapacity(10));
final StringArgument ianDNSArgument = subCommandParser.getStringArgument("issuer-alternative-name-dns");
if ((ianDNSArgument != null) && ianDNSArgument.isPresent()) {
for (final String value : ianDNSArgument.getValues()) {
ianBuilder.addDNSName(value);
ianValues.add("DNS:" + value);
}
}
final StringArgument ianIPArgument = subCommandParser.getStringArgument("issuer-alternative-name-ip-address");
if ((ianIPArgument != null) && ianIPArgument.isPresent()) {
for (final String value : ianIPArgument.getValues()) {
try {
ianBuilder.addIPAddress(LDAPConnectionOptions.DEFAULT_NAME_RESOLVER.getByName(value));
ianValues.add("IP:" + value);
} catch (final Exception e) {
// This should never happen.
Debug.debugException(e);
throw new RuntimeException(e);
}
}
}
final StringArgument ianEmailArgument = subCommandParser.getStringArgument("issuer-alternative-name-email-address");
if ((ianEmailArgument != null) && ianEmailArgument.isPresent()) {
for (final String value : ianEmailArgument.getValues()) {
ianBuilder.addRFC822Name(value);
ianValues.add("EMAIL:" + value);
}
}
final StringArgument ianURIArgument = subCommandParser.getStringArgument("issuer-alternative-name-uri");
if ((ianURIArgument != null) && ianURIArgument.isPresent()) {
for (final String value : ianURIArgument.getValues()) {
ianBuilder.addUniformResourceIdentifier(value);
ianValues.add("URI:" + value);
}
}
final StringArgument ianOIDArgument = subCommandParser.getStringArgument("issuer-alternative-name-oid");
if ((ianOIDArgument != null) && ianOIDArgument.isPresent()) {
for (final String value : ianOIDArgument.getValues()) {
ianBuilder.addRegisteredID(new OID(value));
ianValues.add("OID:" + value);
}
}
if (!ianValues.isEmpty()) {
try {
extensionList.add(new IssuerAlternativeNameExtension(false, ianBuilder.build()));
} catch (final Exception e) {
// This should never happen.
Debug.debugException(e);
throw new RuntimeException(e);
}
}
// Build a basic constraints extension, if appropriate.
BasicConstraintsExtension basicConstraints = null;
final BooleanValueArgument basicConstraintsIsCAArgument = subCommandParser.getBooleanValueArgument("basic-constraints-is-ca");
if ((basicConstraintsIsCAArgument != null) && basicConstraintsIsCAArgument.isPresent()) {
final boolean isCA = basicConstraintsIsCAArgument.getValue();
Integer pathLength = null;
final IntegerArgument pathLengthArgument = subCommandParser.getIntegerArgument("basic-constraints-maximum-path-length");
if ((pathLengthArgument != null) && pathLengthArgument.isPresent()) {
if (isCA) {
pathLength = pathLengthArgument.getValue();
} else {
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_BC_PATH_LENGTH_WITHOUT_CA.get());
return ResultCode.PARAM_ERROR;
}
}
basicConstraints = new BasicConstraintsExtension(false, isCA, pathLength);
extensionList.add(basicConstraints);
}
// Build a key usage extension, if appropriate.
KeyUsageExtension keyUsage = null;
final StringArgument keyUsageArgument = subCommandParser.getStringArgument("key-usage");
if ((keyUsageArgument != null) && keyUsageArgument.isPresent()) {
boolean digitalSignature = false;
boolean nonRepudiation = false;
boolean keyEncipherment = false;
boolean dataEncipherment = false;
boolean keyAgreement = false;
boolean keyCertSign = false;
boolean crlSign = false;
boolean encipherOnly = false;
boolean decipherOnly = false;
for (final String value : keyUsageArgument.getValues()) {
if (value.equalsIgnoreCase("digital-signature") || value.equalsIgnoreCase("digitalSignature")) {
digitalSignature = true;
} else if (value.equalsIgnoreCase("non-repudiation") || value.equalsIgnoreCase("nonRepudiation") || value.equalsIgnoreCase("content-commitment") || value.equalsIgnoreCase("contentCommitment")) {
nonRepudiation = true;
} else if (value.equalsIgnoreCase("key-encipherment") || value.equalsIgnoreCase("keyEncipherment")) {
keyEncipherment = true;
} else if (value.equalsIgnoreCase("data-encipherment") || value.equalsIgnoreCase("dataEncipherment")) {
dataEncipherment = true;
} else if (value.equalsIgnoreCase("key-agreement") || value.equalsIgnoreCase("keyAgreement")) {
keyAgreement = true;
} else if (value.equalsIgnoreCase("key-cert-sign") || value.equalsIgnoreCase("keyCertSign")) {
keyCertSign = true;
} else if (value.equalsIgnoreCase("crl-sign") || value.equalsIgnoreCase("crlSign")) {
crlSign = true;
} else if (value.equalsIgnoreCase("encipher-only") || value.equalsIgnoreCase("encipherOnly")) {
encipherOnly = true;
} else if (value.equalsIgnoreCase("decipher-only") || value.equalsIgnoreCase("decipherOnly")) {
decipherOnly = true;
} else {
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_INVALID_KEY_USAGE.get(value));
return ResultCode.PARAM_ERROR;
}
}
keyUsage = new KeyUsageExtension(false, digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment, keyAgreement, keyCertSign, crlSign, encipherOnly, decipherOnly);
extensionList.add(keyUsage);
}
// Build an extended key usage extension, if appropriate.
ExtendedKeyUsageExtension extendedKeyUsage = null;
final StringArgument extendedKeyUsageArgument = subCommandParser.getStringArgument("extended-key-usage");
if ((extendedKeyUsageArgument != null) && extendedKeyUsageArgument.isPresent()) {
final List<String> values = extendedKeyUsageArgument.getValues();
final ArrayList<OID> keyPurposeIDs = new ArrayList<>(values.size());
for (final String value : values) {
if (value.equalsIgnoreCase("server-auth") || value.equalsIgnoreCase("serverAuth") || value.equalsIgnoreCase("server-authentication") || value.equalsIgnoreCase("serverAuthentication") || value.equalsIgnoreCase("tls-server-authentication") || value.equalsIgnoreCase("tlsServerAuthentication")) {
keyPurposeIDs.add(ExtendedKeyUsageID.TLS_SERVER_AUTHENTICATION.getOID());
} else if (value.equalsIgnoreCase("client-auth") || value.equalsIgnoreCase("clientAuth") || value.equalsIgnoreCase("client-authentication") || value.equalsIgnoreCase("clientAuthentication") || value.equalsIgnoreCase("tls-client-authentication") || value.equalsIgnoreCase("tlsClientAuthentication")) {
keyPurposeIDs.add(ExtendedKeyUsageID.TLS_CLIENT_AUTHENTICATION.getOID());
} else if (value.equalsIgnoreCase("code-signing") || value.equalsIgnoreCase("codeSigning")) {
keyPurposeIDs.add(ExtendedKeyUsageID.CODE_SIGNING.getOID());
} else if (value.equalsIgnoreCase("email-protection") || value.equalsIgnoreCase("emailProtection")) {
keyPurposeIDs.add(ExtendedKeyUsageID.EMAIL_PROTECTION.getOID());
} else if (value.equalsIgnoreCase("time-stamping") || value.equalsIgnoreCase("timeStamping")) {
keyPurposeIDs.add(ExtendedKeyUsageID.TIME_STAMPING.getOID());
} else if (value.equalsIgnoreCase("ocsp-signing") || value.equalsIgnoreCase("ocspSigning")) {
keyPurposeIDs.add(ExtendedKeyUsageID.OCSP_SIGNING.getOID());
} else if (OID.isStrictlyValidNumericOID(value)) {
keyPurposeIDs.add(new OID(value));
} else {
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_INVALID_EXTENDED_KEY_USAGE.get(value));
return ResultCode.PARAM_ERROR;
}
}
try {
extendedKeyUsage = new ExtendedKeyUsageExtension(false, keyPurposeIDs);
} catch (final Exception e) {
// This should never happen.
Debug.debugException(e);
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_EXTENDED_KEY_USAGE_ERROR.get());
e.printStackTrace(getErr());
return ResultCode.PARAM_ERROR;
}
extensionList.add(extendedKeyUsage);
}
// Build a list of generic extensions.
final ArrayList<X509CertificateExtension> genericExtensions = new ArrayList<>(5);
final StringArgument extensionArgument = subCommandParser.getStringArgument("extension");
if ((extensionArgument != null) && extensionArgument.isPresent()) {
for (final String value : extensionArgument.getValues()) {
try {
final int firstColonPos = value.indexOf(':');
final int secondColonPos = value.indexOf(':', firstColonPos + 1);
final OID oid = new OID(value.substring(0, firstColonPos));
if (!oid.isStrictlyValidNumericOID()) {
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_EXT_MALFORMED_OID.get(value, oid.toString()));
return ResultCode.PARAM_ERROR;
}
final boolean criticality;
final String criticalityString = value.substring(firstColonPos + 1, secondColonPos);
if (criticalityString.equalsIgnoreCase("true") || criticalityString.equalsIgnoreCase("t") || criticalityString.equalsIgnoreCase("yes") || criticalityString.equalsIgnoreCase("y") || criticalityString.equalsIgnoreCase("on") || criticalityString.equalsIgnoreCase("1")) {
criticality = true;
} else if (criticalityString.equalsIgnoreCase("false") || criticalityString.equalsIgnoreCase("f") || criticalityString.equalsIgnoreCase("no") || criticalityString.equalsIgnoreCase("n") || criticalityString.equalsIgnoreCase("off") || criticalityString.equalsIgnoreCase("0")) {
criticality = false;
} else {
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_EXT_INVALID_CRITICALITY.get(value, criticalityString));
return ResultCode.PARAM_ERROR;
}
final byte[] valueBytes;
try {
valueBytes = StaticUtils.fromHex(value.substring(secondColonPos + 1));
} catch (final Exception e) {
Debug.debugException(e);
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_EXT_INVALID_VALUE.get(value));
return ResultCode.PARAM_ERROR;
}
final X509CertificateExtension extension = new X509CertificateExtension(oid, criticality, valueBytes);
genericExtensions.add(extension);
extensionList.add(extension);
} catch (final Exception e) {
Debug.debugException(e);
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_EXT_MALFORMED.get(value));
return ResultCode.PARAM_ERROR;
}
}
}
final String keystoreType;
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();
}
// If there is a private key, then see if we need to use a private key
// password that is different from the keystore password.
final char[] privateKeyPassword;
try {
privateKeyPassword = getPrivateKeyPassword(keystore, alias, keystorePassword);
} catch (final LDAPException le) {
Debug.debugException(le);
wrapErr(0, WRAP_COLUMN, le.getMessage());
return le.getResultCode();
}
// perform the appropriate processing for that.
if (replaceExistingCertificate) {
// specified alias.
if (!hasKeyAlias(keystore, alias)) {
if (hasCertificateAlias(keystore, alias)) {
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_REPLACE_ALIAS_IS_CERT.get(alias, keystorePath.getAbsolutePath()));
return ResultCode.PARAM_ERROR;
} else {
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_REPLACE_NO_SUCH_ALIAS.get(alias, keystorePath.getAbsolutePath()));
return ResultCode.PARAM_ERROR;
}
}
// Get the certificate to replace, along with its key pair.
final X509Certificate certToReplace;
final KeyPair keyPair;
try {
final Certificate[] chain = keystore.getCertificateChain(alias);
certToReplace = new X509Certificate(chain[0].getEncoded());
final PublicKey publicKey = chain[0].getPublicKey();
final PrivateKey privateKey = (PrivateKey) keystore.getKey(alias, privateKeyPassword);
keyPair = new KeyPair(publicKey, privateKey);
} catch (final Exception e) {
Debug.debugException(e);
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_REPLACE_COULD_NOT_GET_CERT.get(alias));
e.printStackTrace(getErr());
return ResultCode.LOCAL_ERROR;
}
// Assign the remaining values using information in the existing
// certificate.
signatureAlgorithmIdentifier = SignatureAlgorithmIdentifier.forOID(certToReplace.getSignatureAlgorithmOID());
if (signatureAlgorithmIdentifier == null) {
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_UNKNOWN_SIG_ALG_IN_CERT.get(certToReplace.getSignatureAlgorithmOID()));
return ResultCode.PARAM_ERROR;
} else {
signatureAlgorithmName = signatureAlgorithmIdentifier.getJavaName();
}
if (subjectDN == null) {
subjectDN = certToReplace.getSubjectDN();
}
if (inheritExtensions) {
for (final X509CertificateExtension extension : certToReplace.getExtensions()) {
if ((extension instanceof AuthorityKeyIdentifierExtension) || (extension instanceof IssuerAlternativeNameExtension)) {
// This extension applies to the issuer. We won't include this in
// the set of inherited extensions.
} else if (extension instanceof SubjectKeyIdentifierExtension) {
// The generated certificate will automatically include a subject
// key identifier extension, so we don't need to include it.
} else if (extension instanceof BasicConstraintsExtension) {
// Don't override a value already provided on the command line.
if (basicConstraints == null) {
basicConstraints = (BasicConstraintsExtension) extension;
extensionList.add(basicConstraints);
}
} else if (extension instanceof ExtendedKeyUsageExtension) {
// Don't override a value already provided on the command line.
if (extendedKeyUsage == null) {
extendedKeyUsage = (ExtendedKeyUsageExtension) extension;
extensionList.add(extendedKeyUsage);
}
} else if (extension instanceof KeyUsageExtension) {
// Don't override a value already provided on the command line.
if (keyUsage == null) {
keyUsage = (KeyUsageExtension) extension;
extensionList.add(keyUsage);
}
} else if (extension instanceof SubjectAlternativeNameExtension) {
// line.
if (sanValues.isEmpty()) {
final SubjectAlternativeNameExtension e = (SubjectAlternativeNameExtension) extension;
for (final String dnsName : e.getDNSNames()) {
sanValues.add("DNS:" + dnsName);
}
for (final InetAddress ipAddress : e.getIPAddresses()) {
sanValues.add("IP:" + ipAddress.getHostAddress());
}
for (final String emailAddress : e.getRFC822Names()) {
sanValues.add("EMAIL:" + emailAddress);
}
for (final String uri : e.getUniformResourceIdentifiers()) {
sanValues.add("URI:" + uri);
}
for (final OID oid : e.getRegisteredIDs()) {
sanValues.add("OID:" + oid.toString());
}
extensionList.add(extension);
}
} else {
genericExtensions.add(extension);
extensionList.add(extension);
}
}
}
// Create an array with the final set of extensions to include in the
// certificate or certificate signing request.
final X509CertificateExtension[] extensions = new X509CertificateExtension[extensionList.size()];
extensionList.toArray(extensions);
// a keytool command that we could use to accomplish it.
if (isGenerateCertificate) {
if (displayKeytoolCommand) {
final ArrayList<String> keytoolArguments = new ArrayList<>(30);
keytoolArguments.add("-selfcert");
keytoolArguments.add("-keystore");
keytoolArguments.add(keystorePath.getAbsolutePath());
keytoolArguments.add("-storetype");
keytoolArguments.add(keystoreType);
keytoolArguments.add("-storepass");
keytoolArguments.add("*****REDACTED*****");
keytoolArguments.add("-keypass");
keytoolArguments.add("*****REDACTED*****");
keytoolArguments.add("-alias");
keytoolArguments.add(alias);
keytoolArguments.add("-dname");
keytoolArguments.add(subjectDN.toString());
keytoolArguments.add("-sigalg");
keytoolArguments.add(signatureAlgorithmName);
keytoolArguments.add("-validity");
keytoolArguments.add(String.valueOf(daysValid));
if (validityStartTime != null) {
keytoolArguments.add("-startdate");
keytoolArguments.add(formatValidityStartTime(validityStartTime));
}
addExtensionArguments(keytoolArguments, basicConstraints, keyUsage, extendedKeyUsage, sanValues, ianValues, genericExtensions);
displayKeytoolCommand(keytoolArguments);
}
// Generate the self-signed certificate.
final long notBefore;
if (validityStartTime == null) {
notBefore = System.currentTimeMillis();
} else {
notBefore = validityStartTime.getTime();
}
final long notAfter = notBefore + TimeUnit.DAYS.toMillis(daysValid);
final X509Certificate certificate;
final Certificate[] chain;
try {
certificate = X509Certificate.generateSelfSignedCertificate(signatureAlgorithmIdentifier, keyPair, subjectDN, notBefore, notAfter, extensions);
chain = new Certificate[] { certificate.toCertificate() };
} catch (final Exception e) {
Debug.debugException(e);
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_ERROR_GENERATING_CERT.get());
e.printStackTrace(getErr());
return ResultCode.LOCAL_ERROR;
}
// Update the keystore with the new certificate.
try {
keystore.setKeyEntry(alias, keyPair.getPrivate(), privateKeyPassword, chain);
writeKeystore(keystore, keystorePath, keystorePassword);
} catch (final Exception e) {
Debug.debugException(e);
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_ERROR_UPDATING_KEYSTORE.get());
e.printStackTrace(getErr());
return ResultCode.LOCAL_ERROR;
}
// Display the certificate we just generated to the end user.
out();
wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_GEN_CERT_SUCCESSFULLY_GENERATED_SELF_CERT.get());
printCertificate(certificate, "", false);
// If we should write an output file, then do that now.
if (outputFile != null) {
try (PrintStream ps = new PrintStream(outputFile)) {
final byte[] certBytes = certificate.getX509CertificateBytes();
if (outputPEM) {
writePEMCertificate(ps, certBytes);
} else {
ps.write(certBytes);
}
out();
wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_GEN_CERT_WROTE_OUTPUT_FILE.get(outputFile.getAbsolutePath()));
} catch (final Exception e) {
Debug.debugException(e);
err();
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_ERROR_WRITING_CERT.get(outputFile.getAbsolutePath()));
e.printStackTrace(getErr());
return ResultCode.LOCAL_ERROR;
}
}
return ResultCode.SUCCESS;
} else {
// Build the keytool command used to generate the certificate signing
// request.
Validator.ensureTrue(isGenerateCSR);
if (displayKeytoolCommand) {
final ArrayList<String> keytoolArguments = new ArrayList<>(30);
keytoolArguments.add("-certreq");
keytoolArguments.add("-keystore");
keytoolArguments.add(keystorePath.getAbsolutePath());
keytoolArguments.add("-storetype");
keytoolArguments.add(keystoreType);
keytoolArguments.add("-storepass");
keytoolArguments.add("*****REDACTED*****");
keytoolArguments.add("-keypass");
keytoolArguments.add("*****REDACTED*****");
keytoolArguments.add("-alias");
keytoolArguments.add(alias);
keytoolArguments.add("-dname");
keytoolArguments.add(subjectDN.toString());
keytoolArguments.add("-sigalg");
keytoolArguments.add(signatureAlgorithmName);
addExtensionArguments(keytoolArguments, basicConstraints, keyUsage, extendedKeyUsage, sanValues, ianValues, genericExtensions);
if (outputFile != null) {
keytoolArguments.add("-file");
keytoolArguments.add(outputFile.getAbsolutePath());
}
displayKeytoolCommand(keytoolArguments);
}
// Generate the certificate signing request.
final PKCS10CertificateSigningRequest certificateSigningRequest;
try {
certificateSigningRequest = PKCS10CertificateSigningRequest.generateCertificateSigningRequest(signatureAlgorithmIdentifier, keyPair, subjectDN, extensions);
} catch (final Exception e) {
Debug.debugException(e);
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_ERROR_GENERATING_CSR.get());
e.printStackTrace(getErr());
return ResultCode.LOCAL_ERROR;
}
// location.
try {
final PrintStream ps;
if (outputFile == null) {
ps = getOut();
} else {
ps = new PrintStream(outputFile);
}
if (outputPEM) {
writePEMCertificateSigningRequest(ps, certificateSigningRequest.getPKCS10CertificateSigningRequestBytes());
} else {
ps.write(certificateSigningRequest.getPKCS10CertificateSigningRequestBytes());
}
if (outputFile != null) {
ps.close();
}
} catch (final Exception e) {
Debug.debugException(e);
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_ERROR_WRITING_CSR.get());
e.printStackTrace(getErr());
return ResultCode.LOCAL_ERROR;
}
// able to see it.
if (outputFile != null) {
out();
wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_GEN_CERT_SUCCESSFULLY_GENERATED_CSR.get(outputFile.getAbsolutePath()));
}
return ResultCode.SUCCESS;
}
}
// certificate. Perform any remaining argument assignment and validation.
if ((subjectDN == null) && (!isSignCSR)) {
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_NO_SUBJECT_DN_WITHOUT_REPLACE.get());
return ResultCode.PARAM_ERROR;
}
if (keyAlgorithmIdentifier == null) {
keyAlgorithmIdentifier = PublicKeyAlgorithmIdentifier.RSA;
keyAlgorithmName = keyAlgorithmIdentifier.getName();
}
if (keySizeBits == null) {
keySizeBits = 2048;
}
if ((signatureAlgorithmIdentifier == null) && (!isSignCSR)) {
signatureAlgorithmIdentifier = SignatureAlgorithmIdentifier.SHA_256_WITH_RSA;
signatureAlgorithmName = signatureAlgorithmIdentifier.getJavaName();
}
// certificate.
if (isGenerateCertificate || isGenerateCSR) {
// keystore.
if (hasKeyAlias(keystore, alias) || hasCertificateAlias(keystore, alias)) {
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_ALIAS_EXISTS_WITHOUT_REPLACE.get(alias));
return ResultCode.PARAM_ERROR;
}
if (displayKeytoolCommand) {
final ArrayList<String> keytoolArguments = new ArrayList<>(30);
keytoolArguments.add("-genkeypair");
keytoolArguments.add("-keystore");
keytoolArguments.add(keystorePath.getAbsolutePath());
keytoolArguments.add("-storetype");
keytoolArguments.add(keystoreType);
keytoolArguments.add("-storepass");
keytoolArguments.add("*****REDACTED*****");
keytoolArguments.add("-keypass");
keytoolArguments.add("*****REDACTED*****");
keytoolArguments.add("-alias");
keytoolArguments.add(alias);
keytoolArguments.add("-dname");
keytoolArguments.add(subjectDN.toString());
keytoolArguments.add("-keyalg");
keytoolArguments.add(keyAlgorithmName);
keytoolArguments.add("-keysize");
keytoolArguments.add(String.valueOf(keySizeBits));
keytoolArguments.add("-sigalg");
keytoolArguments.add(signatureAlgorithmName);
keytoolArguments.add("-validity");
keytoolArguments.add(String.valueOf(daysValid));
if (validityStartTime != null) {
keytoolArguments.add("-startdate");
keytoolArguments.add(formatValidityStartTime(validityStartTime));
}
addExtensionArguments(keytoolArguments, basicConstraints, keyUsage, extendedKeyUsage, sanValues, ianValues, genericExtensions);
displayKeytoolCommand(keytoolArguments);
}
// Generate the self-signed certificate.
final long notBefore;
if (validityStartTime == null) {
notBefore = System.currentTimeMillis();
} else {
notBefore = validityStartTime.getTime();
}
final long notAfter = notBefore + TimeUnit.DAYS.toMillis(daysValid);
final X509CertificateExtension[] extensions = new X509CertificateExtension[extensionList.size()];
extensionList.toArray(extensions);
final Certificate[] chain;
final KeyPair keyPair;
final X509Certificate certificate;
try {
final ObjectPair<X509Certificate, KeyPair> p = X509Certificate.generateSelfSignedCertificate(signatureAlgorithmIdentifier, keyAlgorithmIdentifier, keySizeBits, subjectDN, notBefore, notAfter, extensions);
certificate = p.getFirst();
chain = new Certificate[] { certificate.toCertificate() };
keyPair = p.getSecond();
} catch (final Exception e) {
Debug.debugException(e);
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_ERROR_GENERATING_CERT.get());
e.printStackTrace(getErr());
return ResultCode.LOCAL_ERROR;
}
// Update the keystore with the new certificate.
try {
keystore.setKeyEntry(alias, keyPair.getPrivate(), privateKeyPassword, chain);
writeKeystore(keystore, keystorePath, keystorePassword);
} catch (final Exception e) {
Debug.debugException(e);
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_ERROR_UPDATING_KEYSTORE.get());
e.printStackTrace(getErr());
return ResultCode.LOCAL_ERROR;
}
if (isNewKeystore) {
out();
wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_GEN_CERT_CERT_CREATED_KEYSTORE.get(getUserFriendlyKeystoreType(keystoreType)));
}
// file.
if (isGenerateCertificate) {
out();
wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_GEN_CERT_SUCCESSFULLY_GENERATED_SELF_CERT.get());
printCertificate(certificate, "", false);
// If we should write an output file, then do that now.
if (outputFile != null) {
try (PrintStream ps = new PrintStream(outputFile)) {
final byte[] certBytes = certificate.getX509CertificateBytes();
if (outputPEM) {
writePEMCertificate(ps, certBytes);
} else {
ps.write(certBytes);
}
out();
wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_GEN_CERT_WROTE_OUTPUT_FILE.get(outputFile.getAbsolutePath()));
} catch (final Exception e) {
Debug.debugException(e);
err();
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_ERROR_WRITING_CERT.get(outputFile.getAbsolutePath()));
e.printStackTrace(getErr());
return ResultCode.LOCAL_ERROR;
}
}
return ResultCode.SUCCESS;
}
// If we're generating a certificate signing request, then put together
// the appropriate set of arguments for that.
Validator.ensureTrue(isGenerateCSR);
out();
wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_GEN_CERT_SUCCESSFULLY_GENERATED_KEYPAIR.get());
if (displayKeytoolCommand) {
final ArrayList<String> keytoolArguments = new ArrayList<>(30);
keytoolArguments.add("-certreq");
keytoolArguments.add("-keystore");
keytoolArguments.add(keystorePath.getAbsolutePath());
keytoolArguments.add("-storetype");
keytoolArguments.add(keystoreType);
keytoolArguments.add("-storepass");
keytoolArguments.add("*****REDACTED*****");
keytoolArguments.add("-keypass");
keytoolArguments.add("*****REDACTED*****");
keytoolArguments.add("-alias");
keytoolArguments.add(alias);
keytoolArguments.add("-dname");
keytoolArguments.add(subjectDN.toString());
keytoolArguments.add("-sigalg");
keytoolArguments.add(signatureAlgorithmName);
addExtensionArguments(keytoolArguments, basicConstraints, keyUsage, extendedKeyUsage, sanValues, ianValues, genericExtensions);
if (outputFile != null) {
keytoolArguments.add("-file");
keytoolArguments.add(outputFile.getAbsolutePath());
}
displayKeytoolCommand(keytoolArguments);
}
// Generate the certificate signing request.
final PKCS10CertificateSigningRequest certificateSigningRequest;
try {
certificateSigningRequest = PKCS10CertificateSigningRequest.generateCertificateSigningRequest(signatureAlgorithmIdentifier, keyPair, subjectDN, extensions);
} catch (final Exception e) {
Debug.debugException(e);
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_ERROR_GENERATING_CSR.get());
e.printStackTrace(getErr());
return ResultCode.LOCAL_ERROR;
}
// location.
try {
final PrintStream ps;
if (outputFile == null) {
ps = getOut();
} else {
ps = new PrintStream(outputFile);
}
if (outputPEM) {
writePEMCertificateSigningRequest(ps, certificateSigningRequest.getPKCS10CertificateSigningRequestBytes());
} else {
ps.write(certificateSigningRequest.getPKCS10CertificateSigningRequestBytes());
}
if (outputFile != null) {
ps.close();
}
} catch (final Exception e) {
Debug.debugException(e);
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_ERROR_WRITING_CSR.get());
e.printStackTrace(getErr());
return ResultCode.LOCAL_ERROR;
}
// able to see it.
if (outputFile != null) {
out();
wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_GEN_CERT_SUCCESSFULLY_GENERATED_CSR.get(outputFile.getAbsolutePath()));
}
return ResultCode.SUCCESS;
}
// If we've gotten here, then we should be signing a certificate signing
// request. Make sure that the keystore already has a private key entry
// with the specified alias.
Validator.ensureTrue(isSignCSR);
if (!hasKeyAlias(keystore, alias)) {
if (hasCertificateAlias(keystore, alias)) {
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_SIGN_ALIAS_IS_CERT.get(alias, keystorePath.getAbsolutePath()));
return ResultCode.PARAM_ERROR;
} else {
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_SIGN_NO_SUCH_ALIAS.get(alias, keystorePath.getAbsolutePath()));
return ResultCode.PARAM_ERROR;
}
}
// Get the signing certificate and its key pair.
final PrivateKey issuerPrivateKey;
final X509Certificate issuerCertificate;
try {
final Certificate[] chain = keystore.getCertificateChain(alias);
issuerCertificate = new X509Certificate(chain[0].getEncoded());
issuerPrivateKey = (PrivateKey) keystore.getKey(alias, privateKeyPassword);
} catch (final Exception e) {
Debug.debugException(e);
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_SIGN_CANNOT_GET_SIGNING_CERT.get(alias));
e.printStackTrace(getErr());
return ResultCode.LOCAL_ERROR;
}
// Make sure that we can decode the certificate signing request.
final PKCS10CertificateSigningRequest csr;
try {
csr = readCertificateSigningRequestFromFile(inputFile);
} catch (final LDAPException le) {
Debug.debugException(le);
wrapErr(0, WRAP_COLUMN, le.getMessage());
return le.getResultCode();
}
// Make sure that we can verify the certificate signing request's signature.
try {
csr.verifySignature();
} catch (final CertException ce) {
Debug.debugException(ce);
wrapErr(0, WRAP_COLUMN, ce.getMessage());
return ResultCode.PARAM_ERROR;
}
// Prompt about whether to sign the request, if appropriate.
if (!noPrompt) {
out();
wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_GEN_CERT_SIGN_CONFIRM.get());
out();
printCertificateSigningRequest(csr, false, "");
out();
try {
if (!promptForYesNo(INFO_MANAGE_CERTS_GEN_CERT_PROMPT_SIGN.get())) {
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_SIGN_CANCELED.get());
return ResultCode.USER_CANCELED;
}
} catch (final LDAPException le) {
Debug.debugException(le);
err();
wrapErr(0, WRAP_COLUMN, le.getMessage());
return le.getResultCode();
}
}
// from it.
if ((subjectDN == null) || (signatureAlgorithmIdentifier == null) || includeRequestedExtensions) {
if (subjectDN == null) {
subjectDN = csr.getSubjectDN();
}
if (signatureAlgorithmIdentifier == null) {
signatureAlgorithmIdentifier = SignatureAlgorithmIdentifier.forOID(csr.getSignatureAlgorithmOID());
if (signatureAlgorithmIdentifier == null) {
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_UNKNOWN_SIG_ALG_IN_CSR.get(csr.getSignatureAlgorithmOID()));
return ResultCode.PARAM_ERROR;
} else {
signatureAlgorithmName = signatureAlgorithmIdentifier.getJavaName();
}
}
if (includeRequestedExtensions) {
for (final X509CertificateExtension extension : csr.getExtensions()) {
if ((extension instanceof AuthorityKeyIdentifierExtension) || (extension instanceof IssuerAlternativeNameExtension)) {
// This extension applies to the issuer. We won't include this in
// the set of inherited extensions.
} else if (extension instanceof SubjectKeyIdentifierExtension) {
// The generated certificate will automatically include a subject
// key identifier extension, so we don't need to include it.
} else if (extension instanceof BasicConstraintsExtension) {
// Don't override a value already provided on the command line.
if (basicConstraints == null) {
basicConstraints = (BasicConstraintsExtension) extension;
extensionList.add(basicConstraints);
}
} else if (extension instanceof ExtendedKeyUsageExtension) {
// Don't override a value already provided on the command line.
if (extendedKeyUsage == null) {
extendedKeyUsage = (ExtendedKeyUsageExtension) extension;
extensionList.add(extendedKeyUsage);
}
} else if (extension instanceof KeyUsageExtension) {
// Don't override a value already provided on the command line.
if (keyUsage == null) {
keyUsage = (KeyUsageExtension) extension;
extensionList.add(keyUsage);
}
} else if (extension instanceof SubjectAlternativeNameExtension) {
// line.
if (sanValues.isEmpty()) {
final SubjectAlternativeNameExtension e = (SubjectAlternativeNameExtension) extension;
for (final String dnsName : e.getDNSNames()) {
sanBuilder.addDNSName(dnsName);
sanValues.add("DNS:" + dnsName);
}
for (final InetAddress ipAddress : e.getIPAddresses()) {
sanBuilder.addIPAddress(ipAddress);
sanValues.add("IP:" + ipAddress.getHostAddress());
}
for (final String emailAddress : e.getRFC822Names()) {
sanBuilder.addRFC822Name(emailAddress);
sanValues.add("EMAIL:" + emailAddress);
}
for (final String uri : e.getUniformResourceIdentifiers()) {
sanBuilder.addUniformResourceIdentifier(uri);
sanValues.add("URI:" + uri);
}
for (final OID oid : e.getRegisteredIDs()) {
sanBuilder.addRegisteredID(oid);
sanValues.add("OID:" + oid.toString());
}
try {
extensionList.add(new SubjectAlternativeNameExtension(false, sanBuilder.build()));
} catch (final Exception ex) {
// This should never happen.
Debug.debugException(ex);
throw new RuntimeException(ex);
}
}
} else {
genericExtensions.add(extension);
extensionList.add(extension);
}
}
}
}
// Generate the keytool arguments to use to sign the requested certificate.
final ArrayList<String> keytoolArguments = new ArrayList<>(30);
keytoolArguments.add("-gencert");
keytoolArguments.add("-keystore");
keytoolArguments.add(keystorePath.getAbsolutePath());
keytoolArguments.add("-storetype");
keytoolArguments.add(keystoreType);
keytoolArguments.add("-storepass");
keytoolArguments.add("*****REDACTED*****");
keytoolArguments.add("-keypass");
keytoolArguments.add("*****REDACTED*****");
keytoolArguments.add("-alias");
keytoolArguments.add(alias);
keytoolArguments.add("-dname");
keytoolArguments.add(subjectDN.toString());
keytoolArguments.add("-sigalg");
keytoolArguments.add(signatureAlgorithmName);
keytoolArguments.add("-validity");
keytoolArguments.add(String.valueOf(daysValid));
if (validityStartTime != null) {
keytoolArguments.add("-startdate");
keytoolArguments.add(formatValidityStartTime(validityStartTime));
}
addExtensionArguments(keytoolArguments, basicConstraints, keyUsage, extendedKeyUsage, sanValues, ianValues, genericExtensions);
keytoolArguments.add("-infile");
keytoolArguments.add(inputFile.getAbsolutePath());
if (outputFile != null) {
keytoolArguments.add("-outfile");
keytoolArguments.add(outputFile.getAbsolutePath());
}
if (outputPEM) {
keytoolArguments.add("-rfc");
}
if (displayKeytoolCommand) {
displayKeytoolCommand(keytoolArguments);
}
// Generate the signed certificate.
final long notBefore;
if (validityStartTime == null) {
notBefore = System.currentTimeMillis();
} else {
notBefore = validityStartTime.getTime();
}
final long notAfter = notBefore + TimeUnit.DAYS.toMillis(daysValid);
final X509CertificateExtension[] extensions = new X509CertificateExtension[extensionList.size()];
extensionList.toArray(extensions);
final X509Certificate signedCertificate;
try {
signedCertificate = X509Certificate.generateIssuerSignedCertificate(signatureAlgorithmIdentifier, issuerCertificate, issuerPrivateKey, csr.getPublicKeyAlgorithmOID(), csr.getPublicKeyAlgorithmParameters(), csr.getEncodedPublicKey(), csr.getDecodedPublicKey(), subjectDN, notBefore, notAfter, extensions);
} catch (final Exception e) {
Debug.debugException(e);
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_ERROR_SIGNING_CERT.get());
e.printStackTrace(getErr());
return ResultCode.LOCAL_ERROR;
}
// Write the signed certificate signing request to the appropriate location.
try {
final PrintStream ps;
if (outputFile == null) {
ps = getOut();
} else {
ps = new PrintStream(outputFile);
}
if (outputPEM) {
writePEMCertificate(ps, signedCertificate.getX509CertificateBytes());
} else {
ps.write(signedCertificate.getX509CertificateBytes());
}
if (outputFile != null) {
ps.close();
}
} catch (final Exception e) {
Debug.debugException(e);
wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_GEN_CERT_ERROR_WRITING_SIGNED_CERT.get());
e.printStackTrace(getErr());
return ResultCode.LOCAL_ERROR;
}
// able to see it.
if (outputFile != null) {
out();
wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_GEN_CERT_SUCCESSFULLY_SIGNED_CERT.get(outputFile.getAbsolutePath()));
}
return ResultCode.SUCCESS;
}
Aggregations