use of com.unboundid.util.ssl.cert.CertException in project ldapsdk by pingidentity.
the class InMemoryDirectoryServerTool method getConfig.
/**
* Creates a server configuration based on information provided with
* command line arguments.
*
* @return The configuration that was created.
*
* @throws LDAPException If a problem is encountered while creating the
* configuration.
*/
@NotNull()
private InMemoryDirectoryServerConfig getConfig() throws LDAPException {
final List<DN> dnList = baseDNArgument.getValues();
final DN[] baseDNs = new DN[dnList.size()];
dnList.toArray(baseDNs);
final InMemoryDirectoryServerConfig serverConfig = new InMemoryDirectoryServerConfig(baseDNs);
// If a listen port was specified, then update the configuration to use it.
int listenPort = 0;
if (portArgument.isPresent()) {
listenPort = portArgument.getValue();
}
// If schema should be used, then get it.
if (useDefaultSchemaArgument.isPresent()) {
serverConfig.setSchema(Schema.getDefaultStandardSchema());
} else if (useSchemaFileArgument.isPresent()) {
final Map<String, File> schemaFiles = new TreeMap<>();
for (final File f : useSchemaFileArgument.getValues()) {
if (f.exists()) {
if (f.isFile()) {
schemaFiles.put(f.getName(), f);
} else {
for (final File subFile : f.listFiles()) {
if (subFile.isFile()) {
schemaFiles.put(subFile.getName(), subFile);
}
}
}
} else {
throw new LDAPException(ResultCode.PARAM_ERROR, ERR_MEM_DS_TOOL_NO_SUCH_SCHEMA_FILE.get(f.getAbsolutePath()));
}
}
if (!doNotValidateSchemaDefinitionsArgument.isPresent()) {
Schema schema = null;
final List<String> errorMessages = new ArrayList<>();
final SchemaValidator schemaValidator = new SchemaValidator();
for (final File schemaFile : schemaFiles.values()) {
schema = schemaValidator.validateSchema(schemaFile, schema, errorMessages);
}
if (!errorMessages.isEmpty()) {
wrapErr(0, WRAP_COLUMN, WARN_MEM_DS_TOOL_SCHEMA_ISSUES_IDENTIFIED.get());
for (final String message : errorMessages) {
err();
final List<String> wrappedLines = StaticUtils.wrapLine(message, (WRAP_COLUMN - 2));
final Iterator<String> iterator = wrappedLines.iterator();
err("* " + iterator.next());
while (iterator.hasNext()) {
err(" " + iterator.next());
}
}
err();
wrapErr(0, WRAP_COLUMN, WARN_MEM_DS_TOOL_WILL_CONTINUE_WITH_SCHEMA.get(doNotValidateSchemaDefinitionsArgument.getIdentifierString()));
err();
}
}
try {
serverConfig.setSchema(Schema.getSchema(new ArrayList<File>(schemaFiles.values())));
} catch (final Exception e) {
Debug.debugException(e);
final StringBuilder fileList = new StringBuilder();
final Iterator<File> fileIterator = schemaFiles.values().iterator();
while (fileIterator.hasNext()) {
fileList.append(fileIterator.next().getAbsolutePath());
if (fileIterator.hasNext()) {
fileList.append(", ");
}
}
throw new LDAPException(ResultCode.LOCAL_ERROR, ERR_MEM_DS_TOOL_ERROR_READING_SCHEMA.get(fileList, StaticUtils.getExceptionMessage(e)), e);
}
} else {
serverConfig.setSchema(null);
}
// the configuration.
if (additionalBindDNArgument.isPresent()) {
serverConfig.addAdditionalBindCredentials(additionalBindDNArgument.getValue().toString(), additionalBindPasswordArgument.getValue());
}
// configuration with that.
if (maxChangeLogEntriesArgument.isPresent()) {
serverConfig.setMaxChangeLogEntries(maxChangeLogEntriesArgument.getValue());
}
// the configuration with that.
if (maxConcurrentConnectionsArgument.isPresent()) {
serverConfig.setMaxConnections(maxConcurrentConnectionsArgument.getValue());
}
// If a size limit was specified, then update the configuration with that.
if (sizeLimitArgument.isPresent()) {
serverConfig.setMaxSizeLimit(sizeLimitArgument.getValue());
}
// If the password argument was specified, then set the password arguments.
if (passwordAttributeArgument.isPresent()) {
serverConfig.setPasswordAttributes(passwordAttributeArgument.getValues());
}
// Configure password encodings for the server.
final LinkedHashMap<String, InMemoryPasswordEncoder> passwordEncoders = new LinkedHashMap<>(10);
addUnsaltedEncoder("MD5", "MD5", passwordEncoders);
addUnsaltedEncoder("SHA", "SHA-1", passwordEncoders);
addUnsaltedEncoder("SHA1", "SHA-1", passwordEncoders);
addUnsaltedEncoder("SHA-1", "SHA-1", passwordEncoders);
addUnsaltedEncoder("SHA256", "SHA-256", passwordEncoders);
addUnsaltedEncoder("SHA-256", "SHA-256", passwordEncoders);
addUnsaltedEncoder("SHA384", "SHA-384", passwordEncoders);
addUnsaltedEncoder("SHA-384", "SHA-384", passwordEncoders);
addUnsaltedEncoder("SHA512", "SHA-512", passwordEncoders);
addUnsaltedEncoder("SHA-512", "SHA-512", passwordEncoders);
addSaltedEncoder("SMD5", "MD5", passwordEncoders);
addSaltedEncoder("SSHA", "SHA-1", passwordEncoders);
addSaltedEncoder("SSHA1", "SHA-1", passwordEncoders);
addSaltedEncoder("SSHA-1", "SHA-1", passwordEncoders);
addSaltedEncoder("SSHA256", "SHA-256", passwordEncoders);
addSaltedEncoder("SSHA-256", "SHA-256", passwordEncoders);
addSaltedEncoder("SSHA384", "SHA-384", passwordEncoders);
addSaltedEncoder("SSHA-384", "SHA-384", passwordEncoders);
addSaltedEncoder("SSHA512", "SHA-512", passwordEncoders);
addSaltedEncoder("SSHA-512", "SHA-512", passwordEncoders);
addClearEncoder("CLEAR", null, passwordEncoders);
addClearEncoder("BASE64", Base64PasswordEncoderOutputFormatter.getInstance(), passwordEncoders);
addClearEncoder("HEX", HexPasswordEncoderOutputFormatter.getLowercaseInstance(), passwordEncoders);
final InMemoryPasswordEncoder primaryEncoder;
if (defaultPasswordEncodingArgument.isPresent()) {
primaryEncoder = passwordEncoders.remove(StaticUtils.toLowerCase(defaultPasswordEncodingArgument.getValue()));
if (primaryEncoder == null) {
throw new LDAPException(ResultCode.PARAM_ERROR, ERR_MEM_DS_TOOL_UNAVAILABLE_PW_ENCODING.get(defaultPasswordEncodingArgument.getValue(), String.valueOf(passwordEncoders.keySet())));
}
} else {
primaryEncoder = null;
}
serverConfig.setPasswordEncoders(primaryEncoder, passwordEncoders.values());
// Configure the allowed operation types.
if (allowedOperationTypeArgument.isPresent()) {
final EnumSet<OperationType> operationTypes = EnumSet.noneOf(OperationType.class);
for (final String operationTypeName : allowedOperationTypeArgument.getValues()) {
final OperationType name = OperationType.forName(operationTypeName);
if (name == null) {
throw new LDAPException(ResultCode.PARAM_ERROR, ERR_MEM_DS_TOOL_UNSUPPORTED_ALLOWED_OP_TYPE.get(name));
} else {
switch(name) {
case ADD:
case BIND:
case COMPARE:
case DELETE:
case EXTENDED:
case MODIFY:
case MODIFY_DN:
case SEARCH:
operationTypes.add(name);
break;
case ABANDON:
case UNBIND:
default:
throw new LDAPException(ResultCode.PARAM_ERROR, ERR_MEM_DS_TOOL_UNSUPPORTED_ALLOWED_OP_TYPE.get(name));
}
}
}
serverConfig.setAllowedOperationTypes(operationTypes);
}
// Configure the authentication required operation types.
if (authenticationRequiredOperationTypeArgument.isPresent()) {
final EnumSet<OperationType> operationTypes = EnumSet.noneOf(OperationType.class);
for (final String operationTypeName : authenticationRequiredOperationTypeArgument.getValues()) {
final OperationType name = OperationType.forName(operationTypeName);
if (name == null) {
throw new LDAPException(ResultCode.PARAM_ERROR, ERR_MEM_DS_TOOL_UNSUPPORTED_AUTH_REQUIRED_OP_TYPE.get(name));
} else {
switch(name) {
case ADD:
case COMPARE:
case DELETE:
case EXTENDED:
case MODIFY:
case MODIFY_DN:
case SEARCH:
operationTypes.add(name);
break;
case ABANDON:
case UNBIND:
default:
throw new LDAPException(ResultCode.PARAM_ERROR, ERR_MEM_DS_TOOL_UNSUPPORTED_AUTH_REQUIRED_OP_TYPE.get(name));
}
}
}
serverConfig.setAuthenticationRequiredOperationTypes(operationTypes);
}
// handler.
if (accessLogToStandardOutArgument.isPresent()) {
final StreamHandler handler = new StreamHandler(System.out, new MinimalLogFormatter(null, false, false, true));
StaticUtils.setLogHandlerLevel(handler, Level.INFO);
serverConfig.setAccessLogHandler(handler);
} else if (accessLogFileArgument.isPresent()) {
final File logFile = accessLogFileArgument.getValue();
try {
final FileHandler handler = new FileHandler(logFile.getAbsolutePath(), true);
StaticUtils.setLogHandlerLevel(handler, Level.INFO);
handler.setFormatter(new MinimalLogFormatter(null, false, false, true));
serverConfig.setAccessLogHandler(handler);
} catch (final Exception e) {
Debug.debugException(e);
throw new LDAPException(ResultCode.LOCAL_ERROR, ERR_MEM_DS_TOOL_ERROR_CREATING_LOG_HANDLER.get(logFile.getAbsolutePath(), StaticUtils.getExceptionMessage(e)), e);
}
}
// appropriate log handler.
if (jsonAccessLogToStandardOutArgument.isPresent()) {
final StreamHandler handler = new StreamHandler(System.out, new MinimalLogFormatter(null, false, false, true));
StaticUtils.setLogHandlerLevel(handler, Level.INFO);
serverConfig.setJSONAccessLogHandler(handler);
} else if (jsonAccessLogFileArgument.isPresent()) {
final File logFile = jsonAccessLogFileArgument.getValue();
try {
final FileHandler handler = new FileHandler(logFile.getAbsolutePath(), true);
StaticUtils.setLogHandlerLevel(handler, Level.INFO);
handler.setFormatter(new MinimalLogFormatter(null, false, false, true));
serverConfig.setJSONAccessLogHandler(handler);
} catch (final Exception e) {
Debug.debugException(e);
throw new LDAPException(ResultCode.LOCAL_ERROR, ERR_MEM_DS_TOOL_ERROR_CREATING_LOG_HANDLER.get(logFile.getAbsolutePath(), StaticUtils.getExceptionMessage(e)), e);
}
}
// handler.
if (ldapDebugLogToStandardOutArgument.isPresent()) {
final StreamHandler handler = new StreamHandler(System.out, new MinimalLogFormatter(null, false, false, true));
StaticUtils.setLogHandlerLevel(handler, Level.INFO);
serverConfig.setLDAPDebugLogHandler(handler);
} else if (ldapDebugLogFileArgument.isPresent()) {
final File logFile = ldapDebugLogFileArgument.getValue();
try {
final FileHandler handler = new FileHandler(logFile.getAbsolutePath(), true);
StaticUtils.setLogHandlerLevel(handler, Level.INFO);
handler.setFormatter(new MinimalLogFormatter(null, false, false, true));
serverConfig.setLDAPDebugLogHandler(handler);
} catch (final Exception e) {
Debug.debugException(e);
throw new LDAPException(ResultCode.LOCAL_ERROR, ERR_MEM_DS_TOOL_ERROR_CREATING_LOG_HANDLER.get(logFile.getAbsolutePath(), StaticUtils.getExceptionMessage(e)), e);
}
}
// accordingly.
if (codeLogFile.isPresent()) {
serverConfig.setCodeLogDetails(codeLogFile.getValue().getAbsolutePath(), true);
}
// If SSL is to be used, then create the corresponding socket factories.
if (useSSLArgument.isPresent() || useStartTLSArgument.isPresent()) {
final File keyStorePath;
final char[] keyStorePIN;
final String keyStoreType;
if (keyStorePathArgument.isPresent()) {
keyStorePath = keyStorePathArgument.getValue();
keyStorePIN = keyStorePasswordArgument.getValue().toCharArray();
keyStoreType = keyStoreTypeArgument.getValue();
} else {
try {
keyStoreType = CryptoHelper.KEY_STORE_TYPE_JKS;
final ObjectPair<File, char[]> keyStoreInfo = SelfSignedCertificateGenerator.generateTemporarySelfSignedCertificate(getToolName(), keyStoreType);
keyStorePath = keyStoreInfo.getFirst();
keyStorePIN = keyStoreInfo.getSecond();
} catch (final CertException e) {
Debug.debugException(e);
throw new LDAPException(ResultCode.LOCAL_ERROR, e.getMessage(), e);
}
}
try {
final KeyManager keyManager = new KeyStoreKeyManager(keyStorePath, keyStorePIN, keyStoreType, null, true);
final TrustManager trustManager;
if (trustStorePathArgument.isPresent()) {
final char[] password;
if (trustStorePasswordArgument.isPresent()) {
password = trustStorePasswordArgument.getValue().toCharArray();
} else {
password = null;
}
trustManager = new TrustStoreTrustManager(trustStorePathArgument.getValue(), password, trustStoreTypeArgument.getValue(), true);
} else {
trustManager = new TrustAllTrustManager();
}
final SSLUtil serverSSLUtil = new SSLUtil(keyManager, trustManager);
final boolean requestCertificate;
final boolean requireCertificate;
final String clientAuthPolicy = sslClientAuthPolicy.getValue();
if (clientAuthPolicy.equalsIgnoreCase(SSL_CLIENT_AUTH_POLICY_OPTIONAL)) {
requestCertificate = true;
requireCertificate = false;
} else if (clientAuthPolicy.equalsIgnoreCase(SSL_CLIENT_AUTH_POLICY_REQUIRED)) {
requestCertificate = true;
requireCertificate = true;
} else {
requestCertificate = false;
requireCertificate = false;
}
if (useSSLArgument.isPresent()) {
final SSLUtil clientSSLUtil = new SSLUtil(new TrustAllTrustManager());
serverConfig.setListenerConfigs(InMemoryListenerConfig.createLDAPSConfig("LDAPS", null, listenPort, serverSSLUtil.createSSLServerSocketFactory(), clientSSLUtil.createSSLSocketFactory(), requestCertificate, requireCertificate));
} else {
serverConfig.setListenerConfigs(InMemoryListenerConfig.createLDAPConfig("LDAP+StartTLS", null, listenPort, serverSSLUtil.createSSLSocketFactory(), requestCertificate, requireCertificate));
}
} catch (final Exception e) {
Debug.debugException(e);
throw new LDAPException(ResultCode.LOCAL_ERROR, ERR_MEM_DS_TOOL_ERROR_INITIALIZING_SSL.get(StaticUtils.getExceptionMessage(e)), e);
}
} else {
serverConfig.setListenerConfigs(InMemoryListenerConfig.createLDAPConfig("LDAP", listenPort));
}
// them for use.
if (vendorNameArgument.isPresent()) {
serverConfig.setVendorName(vendorNameArgument.getValue());
}
if (vendorVersionArgument.isPresent()) {
serverConfig.setVendorVersion(vendorVersionArgument.getValue());
}
// If equality indexing is to be performed, then configure it.
if (equalityIndexArgument.isPresent()) {
serverConfig.setEqualityIndexAttributes(equalityIndexArgument.getValues());
}
// Update the configuration to indicate whether to generate operational
// attributes.
serverConfig.setGenerateOperationalAttributes(!doNotGenerateOperationalAttributesArgument.isPresent());
return serverConfig;
}
use of com.unboundid.util.ssl.cert.CertException in project ldapsdk by pingidentity.
the class SelfSignedCertificateGenerator method generateSelfSignedCertificate.
/**
* Generates a self-signed certificate in the specified keystore.
*
* @param toolName The name of the tool for which the certificate is to
* be generated.
* @param keyStoreFile The path to the keystore file in which the
* certificate is to be generated. This must not be
* {@code null}, and if the target file exists, then it
* must be a JKS or PKCS #12 keystore. If it does not
* exist, then at least the parent directory must exist.
* @param keyStorePIN The PIN needed to access the keystore. It must not
* be {@code null}.
* @param keyStoreType The key store type for the keystore to be created, if
* it does not already exist. It must not be
* {@code null}.
* @param alias The alias to use for the certificate in the keystore.
* It must not be {@code null}.
*
* @throws CertException If a problem occurs while trying to generate
* self-signed certificate.
*/
public static void generateSelfSignedCertificate(@NotNull final String toolName, @NotNull final File keyStoreFile, @NotNull final String keyStorePIN, @NotNull final String keyStoreType, @NotNull final String alias) throws CertException {
// Try to get a set of all addresses associated with the local system and
// their corresponding canonical hostnames.
final NameResolver nameResolver = LDAPConnectionOptions.DEFAULT_NAME_RESOLVER;
Set<InetAddress> localAddresses = StaticUtils.getAllLocalAddresses(nameResolver, false);
if (localAddresses.isEmpty()) {
localAddresses = StaticUtils.getAllLocalAddresses(nameResolver, true);
}
final Set<String> canonicalHostNames = StaticUtils.getAvailableCanonicalHostNames(nameResolver, localAddresses);
// Construct a subject DN for the certificate.
final DN subjectDN;
if (localAddresses.isEmpty()) {
subjectDN = new DN(new RDN("CN", toolName));
} else {
subjectDN = new DN(new RDN("CN", nameResolver.getCanonicalHostName(localAddresses.iterator().next())), new RDN("OU", toolName));
}
// Generate a timestamp that corresponds to one day ago.
final long oneDayAgoTime = System.currentTimeMillis() - 86_400_000L;
final Date oneDayAgoDate = new Date(oneDayAgoTime);
final SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyyMMddHHmmss");
final String yesterdayTimeStamp = dateFormatter.format(oneDayAgoDate);
// Build the list of arguments to provide to the manage-certificates tool.
final ArrayList<String> argList = new ArrayList<>(30);
argList.add("generate-self-signed-certificate");
argList.add("--keystore");
argList.add(keyStoreFile.getAbsolutePath());
argList.add("--keystore-password");
argList.add(keyStorePIN);
argList.add("--keystore-type");
argList.add(keyStoreType);
argList.add("--alias");
argList.add(alias);
argList.add("--subject-dn");
argList.add(subjectDN.toString());
argList.add("--days-valid");
argList.add("366");
argList.add("--validityStartTime");
argList.add(yesterdayTimeStamp);
argList.add("--key-algorithm");
argList.add("RSA");
argList.add("--key-size-bits");
argList.add("2048");
argList.add("--signature-algorithm");
argList.add("SHA256withRSA");
for (final String hostName : canonicalHostNames) {
argList.add("--subject-alternative-name-dns");
argList.add(hostName);
}
for (final InetAddress address : localAddresses) {
argList.add("--subject-alternative-name-ip-address");
argList.add(StaticUtils.trimInterfaceNameFromHostAddress(address.getHostAddress()));
}
argList.add("--key-usage");
argList.add("digitalSignature");
argList.add("--key-usage");
argList.add("keyEncipherment");
argList.add("--extended-key-usage");
argList.add("server-auth");
argList.add("--extended-key-usage");
argList.add("client-auth");
final ByteArrayOutputStream output = new ByteArrayOutputStream();
final ResultCode resultCode = ManageCertificates.main(null, output, output, argList.toArray(StaticUtils.NO_STRINGS));
if (resultCode != ResultCode.SUCCESS) {
throw new CertException(ERR_SELF_SIGNED_CERT_GENERATOR_ERROR_GENERATING_CERT.get(StaticUtils.toUTF8String(output.toByteArray())));
}
}
use of com.unboundid.util.ssl.cert.CertException in project ldapsdk by pingidentity.
the class SelfSignedCertificateGenerator method generateTemporarySelfSignedCertificate.
/**
* Generates a temporary keystore containing a self-signed certificate for
* use by a listener that supports SSL or StartTLS.
*
* @param toolName The name of the tool for which the certificate is to
* be generated.
* @param keyStoreType The key store type for the keystore to be created.
* It must not be {@code null}.
*
* @return An {@code ObjectPair} containing the path and PIN for the keystore
* that was generated.
*
* @throws CertException If a problem occurs while trying to generate the
* temporary keystore containing the self-signed
* certificate.
*/
@NotNull()
public static ObjectPair<File, char[]> generateTemporarySelfSignedCertificate(@NotNull final String toolName, @NotNull final String keyStoreType) throws CertException {
final File keyStoreFile;
try {
keyStoreFile = File.createTempFile("temp-keystore-", ".jks");
} catch (final Exception e) {
Debug.debugException(e);
throw new CertException(ERR_SELF_SIGNED_CERT_GENERATOR_CANNOT_CREATE_FILE.get(StaticUtils.getExceptionMessage(e)), e);
}
keyStoreFile.delete();
final byte[] randomBytes = new byte[50];
ThreadLocalSecureRandom.get().nextBytes(randomBytes);
final String keyStorePIN = Base64.encode(randomBytes);
generateSelfSignedCertificate(toolName, keyStoreFile, keyStorePIN, keyStoreType, "server-cert");
return new ObjectPair<>(keyStoreFile, keyStorePIN.toCharArray());
}
Aggregations