Search in sources :

Example 1 with SchemaValidator

use of com.unboundid.ldap.sdk.schema.SchemaValidator 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;
}
Also used : MinimalLogFormatter(com.unboundid.util.MinimalLogFormatter) TrustStoreTrustManager(com.unboundid.util.ssl.TrustStoreTrustManager) Schema(com.unboundid.ldap.sdk.schema.Schema) DN(com.unboundid.ldap.sdk.DN) TrustAllTrustManager(com.unboundid.util.ssl.TrustAllTrustManager) LinkedHashMap(java.util.LinkedHashMap) SSLUtil(com.unboundid.util.ssl.SSLUtil) StreamHandler(java.util.logging.StreamHandler) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(java.util.List) KeyStoreKeyManager(com.unboundid.util.ssl.KeyStoreKeyManager) KeyManager(javax.net.ssl.KeyManager) KeyStoreKeyManager(com.unboundid.util.ssl.KeyStoreKeyManager) SchemaValidator(com.unboundid.ldap.sdk.schema.SchemaValidator) CertException(com.unboundid.util.ssl.cert.CertException) ArgumentException(com.unboundid.util.args.ArgumentException) CertException(com.unboundid.util.ssl.cert.CertException) LDAPException(com.unboundid.ldap.sdk.LDAPException) FileHandler(java.util.logging.FileHandler) TrustManager(javax.net.ssl.TrustManager) TrustAllTrustManager(com.unboundid.util.ssl.TrustAllTrustManager) TrustStoreTrustManager(com.unboundid.util.ssl.TrustStoreTrustManager) LDAPException(com.unboundid.ldap.sdk.LDAPException) OperationType(com.unboundid.ldap.sdk.OperationType) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) TreeMap(java.util.TreeMap) File(java.io.File) NotNull(com.unboundid.util.NotNull)

Aggregations

DN (com.unboundid.ldap.sdk.DN)1 LDAPException (com.unboundid.ldap.sdk.LDAPException)1 OperationType (com.unboundid.ldap.sdk.OperationType)1 Schema (com.unboundid.ldap.sdk.schema.Schema)1 SchemaValidator (com.unboundid.ldap.sdk.schema.SchemaValidator)1 MinimalLogFormatter (com.unboundid.util.MinimalLogFormatter)1 NotNull (com.unboundid.util.NotNull)1 ArgumentException (com.unboundid.util.args.ArgumentException)1 KeyStoreKeyManager (com.unboundid.util.ssl.KeyStoreKeyManager)1 SSLUtil (com.unboundid.util.ssl.SSLUtil)1 TrustAllTrustManager (com.unboundid.util.ssl.TrustAllTrustManager)1 TrustStoreTrustManager (com.unboundid.util.ssl.TrustStoreTrustManager)1 CertException (com.unboundid.util.ssl.cert.CertException)1 File (java.io.File)1 ArrayList (java.util.ArrayList)1 Iterator (java.util.Iterator)1 LinkedHashMap (java.util.LinkedHashMap)1 List (java.util.List)1 Map (java.util.Map)1 TreeMap (java.util.TreeMap)1