Search in sources :

Example 1 with CredentialSource

use of org.wildfly.security.credential.source.CredentialSource in project wildfly by wildfly.

the class SingleSignOnSessionFactoryBuilder method getValue.

@Override
public SingleSignOnSessionFactory getValue() {
    KeyStore store = this.keyStore.getValue();
    String alias = this.keyAlias;
    CredentialSource source = this.credentialSource.getValue();
    try {
        if (!store.containsAlias(alias)) {
            UndertowLogger.ROOT_LOGGER.missingKeyStoreEntry(alias);
        }
        if (!store.entryInstanceOf(alias, KeyStore.PrivateKeyEntry.class)) {
            UndertowLogger.ROOT_LOGGER.keyStoreEntryNotPrivate(alias);
        }
        PasswordCredential credential = source.getCredential(PasswordCredential.class);
        if (credential == null) {
            UndertowLogger.ROOT_LOGGER.missingCredential(source.toString());
        }
        ClearPassword password = credential.getPassword(ClearPassword.class);
        if (password == null) {
            UndertowLogger.ROOT_LOGGER.credentialNotClearPassword(credential.toString());
        }
        KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) store.getEntry(alias, new KeyStore.PasswordProtection(password.getPassword()));
        KeyPair keyPair = new KeyPair(entry.getCertificate().getPublicKey(), entry.getPrivateKey());
        Optional<SSLContext> context = Optional.ofNullable(this.sslContext).map(dependency -> dependency.getValue());
        return new DefaultSingleSignOnSessionFactory(this.manager.getValue(), keyPair, connection -> context.ifPresent(ctx -> connection.setSSLSocketFactory(ctx.getSocketFactory())));
    } catch (GeneralSecurityException | IOException e) {
        throw new IllegalArgumentException(e);
    }
}
Also used : ClearPassword(org.wildfly.security.password.interfaces.ClearPassword) KeyPair(java.security.KeyPair) ValueDependency(org.wildfly.clustering.service.ValueDependency) SSLContext(javax.net.ssl.SSLContext) Value(org.jboss.msc.value.Value) CredentialSource(org.wildfly.security.credential.source.CredentialSource) OperationContext(org.jboss.as.controller.OperationContext) DefaultSingleSignOnSessionFactory(org.wildfly.security.http.util.sso.DefaultSingleSignOnSessionFactory) GeneralSecurityException(java.security.GeneralSecurityException) CredentialSourceDependency(org.jboss.as.clustering.controller.CredentialSourceDependency) PasswordCredential(org.wildfly.security.credential.PasswordCredential) InjectedValueDependency(org.wildfly.clustering.service.InjectedValueDependency) ServiceTarget(org.jboss.msc.service.ServiceTarget) UndertowLogger(org.wildfly.extension.undertow.logging.UndertowLogger) SingleSignOnSessionFactory(org.wildfly.security.http.util.sso.SingleSignOnSessionFactory) CommonUnaryRequirement(org.jboss.as.clustering.controller.CommonUnaryRequirement) ServiceBuilder(org.jboss.msc.service.ServiceBuilder) IOException(java.io.IOException) KeyStore(java.security.KeyStore) ResourceServiceBuilder(org.jboss.as.clustering.controller.ResourceServiceBuilder) Objects(java.util.Objects) ModelNodes(org.jboss.as.clustering.dmr.ModelNodes) ValueService(org.jboss.msc.service.ValueService) Stream(java.util.stream.Stream) OperationFailedException(org.jboss.as.controller.OperationFailedException) SingleSignOnManager(org.wildfly.security.http.util.sso.SingleSignOnManager) Optional(java.util.Optional) ClearPassword(org.wildfly.security.password.interfaces.ClearPassword) ModelNode(org.jboss.dmr.ModelNode) Attribute(org.wildfly.extension.undertow.ApplicationSecurityDomainSingleSignOnDefinition.Attribute) Builder(org.wildfly.clustering.service.Builder) KeyPair(java.security.KeyPair) GeneralSecurityException(java.security.GeneralSecurityException) PasswordCredential(org.wildfly.security.credential.PasswordCredential) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) KeyStore(java.security.KeyStore) DefaultSingleSignOnSessionFactory(org.wildfly.security.http.util.sso.DefaultSingleSignOnSessionFactory) CredentialSource(org.wildfly.security.credential.source.CredentialSource)

Example 2 with CredentialSource

use of org.wildfly.security.credential.source.CredentialSource in project fuse-karaf by jboss-fuse.

the class CreateCredentialStoreTest method shouldCreateInitializeAndPersistCredentialStore.

@Test
public void shouldCreateInitializeAndPersistCredentialStore() throws IOException, GeneralSecurityException {
    final File storeFile = new File(tmp.getRoot(), "credential.store");
    final Map<String, String> attributes = Collections.singletonMap("location", storeFile.getAbsolutePath());
    final Provider provider = new WildFlyElytronProvider();
    final CredentialSource credentialSource = IdentityCredentials.NONE.withCredential(new PasswordCredential(ClearPassword.createRaw(ClearPassword.ALGORITHM_CLEAR, "test".toCharArray())));
    CreateCredentialStore.createCredentialStore(KeyStoreCredentialStore.KEY_STORE_CREDENTIAL_STORE, attributes, credentialSource, provider);
    assertThat(storeFile).exists().isFile();
}
Also used : PasswordCredential(org.wildfly.security.credential.PasswordCredential) File(java.io.File) WildFlyElytronProvider(org.wildfly.security.WildFlyElytronProvider) WildFlyElytronProvider(org.wildfly.security.WildFlyElytronProvider) Provider(java.security.Provider) CredentialSource(org.wildfly.security.credential.source.CredentialSource) Test(org.junit.Test)

Example 3 with CredentialSource

use of org.wildfly.security.credential.source.CredentialSource in project fuse-karaf by jboss-fuse.

the class CreateCredentialStore method execute.

/**
 * Performs the creation of Credential store according to the given command line options.
 */
@Override
public Object execute() throws Exception {
    final Map<String, String> attributes = attributesFromOptions(storeAttributes);
    final Provider providerToUse = ProviderHelper.provider(provider);
    final Map<String, String> credentialSourceConfiguration = createCredentialSourceConfiguration(credentialType, credentialAttributes);
    final CredentialSource credential = credentialType.createCredentialSource(credentialSourceConfiguration);
    createCredentialStore(storeAlgorithm, attributes, credential, providerToUse);
    final ShellTable table = new ShellTable();
    table.column(new Col("Variable"));
    table.column(new Col("Value"));
    final StringBuilder buffy = new StringBuilder();
    if (credentialType != Defaults.CREDENTIAL_TYPE) {
        appendConfigurationTo(Collections.singletonMap("CREDENTIAL_STORE_PROTECTION_TYPE", credentialType.name()), table, buffy);
    }
    appendConfigurationTo(credentialSourceConfiguration, table, buffy);
    appendConfigurationTo(attributes.entrySet().stream().collect(Collectors.toMap(e -> "CREDENTIAL_STORE_ATTR_" + e.getKey(), Entry::getValue)), table, buffy);
    System.out.println("In order to use this credential store set the following environment variables");
    table.print(System.out);
    System.out.println("Or simply use this:");
    System.out.print(buffy.toString());
    return null;
}
Also used : Col(org.apache.karaf.shell.support.table.Col) Entry(java.util.Map.Entry) ShellTable(org.apache.karaf.shell.support.table.ShellTable) Provider(java.security.Provider) CredentialSource(org.wildfly.security.credential.source.CredentialSource)

Example 4 with CredentialSource

use of org.wildfly.security.credential.source.CredentialSource in project wildfly by wildfly.

the class AbstractDataSourceAdd method secondRuntimeStep.

static void secondRuntimeStep(OperationContext context, ModelNode operation, ManagementResourceRegistration datasourceRegistration, ModelNode model, boolean isXa) throws OperationFailedException {
    final ServiceTarget serviceTarget = context.getServiceTarget();
    final ModelNode address = operation.require(OP_ADDR);
    final String dsName = PathAddress.pathAddress(address).getLastElement().getValue();
    final String jndiName = JNDI_NAME.resolveModelAttribute(context, model).asString();
    final ServiceRegistry registry = context.getServiceRegistry(true);
    final List<ServiceName> serviceNames = registry.getServiceNames();
    final boolean elytronEnabled = ELYTRON_ENABLED.resolveModelAttribute(context, model).asBoolean();
    final ServiceName dataSourceServiceName = context.getCapabilityServiceName(Capabilities.DATA_SOURCE_CAPABILITY_NAME, dsName, DataSource.class);
    final ServiceController<?> dataSourceController = registry.getService(dataSourceServiceName);
    final ExceptionSupplier<CredentialSource, Exception> credentialSourceExceptionExceptionSupplier = dataSourceController.getService() instanceof AbstractDataSourceService ? ((AbstractDataSourceService) dataSourceController.getService()).getCredentialSourceSupplierInjector().getOptionalValue() : null;
    final ExceptionSupplier<CredentialSource, Exception> recoveryCredentialSourceExceptionExceptionSupplier = dataSourceController.getService() instanceof AbstractDataSourceService ? ((AbstractDataSourceService) dataSourceController.getService()).getRecoveryCredentialSourceSupplierInjector().getOptionalValue() : null;
    final boolean jta;
    if (isXa) {
        jta = true;
        final ModifiableXaDataSource dataSourceConfig;
        try {
            dataSourceConfig = xaFrom(context, model, dsName, credentialSourceExceptionExceptionSupplier, recoveryCredentialSourceExceptionExceptionSupplier);
        } catch (ValidateException e) {
            throw new OperationFailedException(ConnectorLogger.ROOT_LOGGER.failedToCreate("XaDataSource", operation, e.getLocalizedMessage()));
        }
        final ServiceName xaDataSourceConfigServiceName = XADataSourceConfigService.SERVICE_NAME_BASE.append(dsName);
        final XADataSourceConfigService xaDataSourceConfigService = new XADataSourceConfigService(dataSourceConfig);
        final ServiceBuilder<?> builder = serviceTarget.addService(xaDataSourceConfigServiceName, xaDataSourceConfigService);
        // add dependency on security domain service if applicable
        final DsSecurity dsSecurityConfig = dataSourceConfig.getSecurity();
        if (dsSecurityConfig != null) {
            final String securityDomainName = dsSecurityConfig.getSecurityDomain();
            if (!elytronEnabled && securityDomainName != null) {
                builder.requires(SECURITY_DOMAIN_SERVICE.append(securityDomainName));
            }
        }
        // add dependency on security domain service if applicable for recovery config
        if (dataSourceConfig.getRecovery() != null) {
            final Credential credential = dataSourceConfig.getRecovery().getCredential();
            if (credential != null) {
                final String securityDomainName = credential.getSecurityDomain();
                if (!RECOVERY_ELYTRON_ENABLED.resolveModelAttribute(context, model).asBoolean() && securityDomainName != null) {
                    builder.requires(SECURITY_DOMAIN_SERVICE.append(securityDomainName));
                }
            }
        }
        int propertiesCount = 0;
        for (ServiceName name : serviceNames) {
            if (xaDataSourceConfigServiceName.append("xa-datasource-properties").isParentOf(name)) {
                final ServiceController<?> xaConfigPropertyController = registry.getService(name);
                XaDataSourcePropertiesService xaPropService = (XaDataSourcePropertiesService) xaConfigPropertyController.getService();
                if (!ServiceController.State.UP.equals(xaConfigPropertyController.getState())) {
                    propertiesCount++;
                    xaConfigPropertyController.setMode(ServiceController.Mode.ACTIVE);
                    builder.addDependency(name, String.class, xaDataSourceConfigService.getXaDataSourcePropertyInjector(xaPropService.getName()));
                } else {
                    throw new OperationFailedException(ConnectorLogger.ROOT_LOGGER.serviceAlreadyStarted("Data-source.xa-config-property", name));
                }
            }
        }
        if (propertiesCount == 0) {
            throw ConnectorLogger.ROOT_LOGGER.xaDataSourcePropertiesNotPresent();
        }
        builder.install();
    } else {
        final ModifiableDataSource dataSourceConfig;
        try {
            dataSourceConfig = from(context, model, dsName, credentialSourceExceptionExceptionSupplier);
        } catch (ValidateException e) {
            throw new OperationFailedException(ConnectorLogger.ROOT_LOGGER.failedToCreate("DataSource", operation, e.getLocalizedMessage()));
        }
        jta = dataSourceConfig.isJTA();
        final ServiceName dataSourceCongServiceName = DataSourceConfigService.SERVICE_NAME_BASE.append(dsName);
        final DataSourceConfigService configService = new DataSourceConfigService(dataSourceConfig);
        final ServiceBuilder<?> builder = serviceTarget.addService(dataSourceCongServiceName, configService);
        // add dependency on security domain service if applicable
        final DsSecurity dsSecurityConfig = dataSourceConfig.getSecurity();
        if (dsSecurityConfig != null) {
            final String securityDomainName = dsSecurityConfig.getSecurityDomain();
            if (!elytronEnabled && securityDomainName != null) {
                builder.requires(SECURITY_DOMAIN_SERVICE.append(securityDomainName));
            }
        }
        for (ServiceName name : serviceNames) {
            if (dataSourceCongServiceName.append("connection-properties").isParentOf(name)) {
                final ServiceController<?> connPropServiceController = registry.getService(name);
                ConnectionPropertiesService connPropService = (ConnectionPropertiesService) connPropServiceController.getService();
                if (!ServiceController.State.UP.equals(connPropServiceController.getState())) {
                    connPropServiceController.setMode(ServiceController.Mode.ACTIVE);
                    builder.addDependency(name, String.class, configService.getConnectionPropertyInjector(connPropService.getName()));
                } else {
                    throw new OperationFailedException(ConnectorLogger.ROOT_LOGGER.serviceAlreadyStarted("Data-source.connectionProperty", name));
                }
            }
        }
        builder.install();
    }
    final ServiceName dataSourceServiceNameAlias = AbstractDataSourceService.SERVICE_NAME_BASE.append(jndiName).append(Constants.STATISTICS);
    if (dataSourceController != null) {
        if (!ServiceController.State.UP.equals(dataSourceController.getState())) {
            final boolean statsEnabled = STATISTICS_ENABLED.resolveModelAttribute(context, model).asBoolean();
            DataSourceStatisticsService statsService = new DataSourceStatisticsService(datasourceRegistration, statsEnabled);
            final ServiceBuilder statsServiceSB = serviceTarget.addService(dataSourceServiceName.append(Constants.STATISTICS), statsService);
            statsServiceSB.addAliases(dataSourceServiceNameAlias);
            statsServiceSB.requires(dataSourceServiceName);
            statsServiceSB.addDependency(CommonDeploymentService.getServiceName(ContextNames.bindInfoFor(jndiName)), CommonDeployment.class, statsService.getCommonDeploymentInjector());
            statsServiceSB.setInitialMode(ServiceController.Mode.PASSIVE);
            statsServiceSB.install();
            dataSourceController.setMode(ServiceController.Mode.ACTIVE);
        } else {
            throw new OperationFailedException(ConnectorLogger.ROOT_LOGGER.serviceAlreadyStarted("Data-source", dsName));
        }
    } else {
        throw new OperationFailedException(ConnectorLogger.ROOT_LOGGER.serviceNotAvailable("Data-source", dsName));
    }
    final DataSourceReferenceFactoryService referenceFactoryService = new DataSourceReferenceFactoryService();
    final ServiceName referenceFactoryServiceName = DataSourceReferenceFactoryService.SERVICE_NAME_BASE.append(dsName);
    final ServiceBuilder<?> referenceBuilder = serviceTarget.addService(referenceFactoryServiceName, referenceFactoryService).addDependency(dataSourceServiceName, DataSource.class, referenceFactoryService.getDataSourceInjector());
    referenceBuilder.install();
    final ContextNames.BindInfo bindInfo = ContextNames.bindInfoFor(jndiName);
    final BinderService binderService = new BinderService(bindInfo.getBindName());
    final ServiceBuilder<?> binderBuilder = serviceTarget.addService(bindInfo.getBinderServiceName(), binderService).addDependency(referenceFactoryServiceName, ManagedReferenceFactory.class, binderService.getManagedObjectInjector()).addDependency(bindInfo.getParentContextServiceName(), ServiceBasedNamingStore.class, binderService.getNamingStoreInjector()).addListener(new LifecycleListener() {

        private volatile boolean bound;

        public void handleEvent(final ServiceController<? extends Object> controller, final LifecycleEvent event) {
            switch(event) {
                case UP:
                    {
                        if (jta) {
                            SUBSYSTEM_DATASOURCES_LOGGER.boundDataSource(jndiName);
                        } else {
                            SUBSYSTEM_DATASOURCES_LOGGER.boundNonJTADataSource(jndiName);
                        }
                        bound = true;
                        break;
                    }
                case DOWN:
                    {
                        if (bound) {
                            if (jta) {
                                SUBSYSTEM_DATASOURCES_LOGGER.unboundDataSource(jndiName);
                            } else {
                                SUBSYSTEM_DATASOURCES_LOGGER.unBoundNonJTADataSource(jndiName);
                            }
                        }
                        break;
                    }
                case REMOVED:
                    {
                        SUBSYSTEM_DATASOURCES_LOGGER.debugf("Removed JDBC Data-source [%s]", jndiName);
                        break;
                    }
            }
        }
    });
    binderBuilder.setInitialMode(ServiceController.Mode.ACTIVE);
    binderBuilder.install();
}
Also used : ValidateException(org.jboss.jca.common.api.validator.ValidateException) DataSourceStatisticsService(org.jboss.as.connector.services.datasources.statistics.DataSourceStatisticsService) LifecycleListener(org.jboss.msc.service.LifecycleListener) ServiceBuilder(org.jboss.msc.service.ServiceBuilder) BinderService(org.jboss.as.naming.service.BinderService) LifecycleEvent(org.jboss.msc.service.LifecycleEvent) CredentialSource(org.wildfly.security.credential.source.CredentialSource) ContextNames(org.jboss.as.naming.deployment.ContextNames) Credential(org.jboss.jca.common.api.metadata.common.Credential) DsSecurity(org.jboss.jca.common.api.metadata.ds.DsSecurity) ServiceTarget(org.jboss.msc.service.ServiceTarget) OperationFailedException(org.jboss.as.controller.OperationFailedException) OperationFailedException(org.jboss.as.controller.OperationFailedException) ValidateException(org.jboss.jca.common.api.validator.ValidateException) ServiceName(org.jboss.msc.service.ServiceName) ServiceBasedNamingStore(org.jboss.as.naming.ServiceBasedNamingStore) ServiceRegistry(org.jboss.msc.service.ServiceRegistry) ModelNode(org.jboss.dmr.ModelNode)

Example 5 with CredentialSource

use of org.wildfly.security.credential.source.CredentialSource in project wildfly by wildfly.

the class SingleSignOnSessionFactoryServiceConfigurator method get.

@Override
public SingleSignOnSessionFactory get() {
    KeyStore store = this.keyStore.get();
    String alias = this.keyAlias;
    CredentialSource source = this.credentialSource.get();
    try {
        if (!store.containsAlias(alias)) {
            throw UndertowLogger.ROOT_LOGGER.missingKeyStoreEntry(alias);
        }
        if (!store.entryInstanceOf(alias, KeyStore.PrivateKeyEntry.class)) {
            throw UndertowLogger.ROOT_LOGGER.keyStoreEntryNotPrivate(alias);
        }
        PasswordCredential credential = source.getCredential(PasswordCredential.class);
        if (credential == null) {
            throw UndertowLogger.ROOT_LOGGER.missingCredential(source.toString());
        }
        ClearPassword password = credential.getPassword(ClearPassword.class);
        if (password == null) {
            throw UndertowLogger.ROOT_LOGGER.credentialNotClearPassword(credential.toString());
        }
        KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) store.getEntry(alias, new KeyStore.PasswordProtection(password.getPassword()));
        KeyPair keyPair = new KeyPair(entry.getCertificate().getPublicKey(), entry.getPrivateKey());
        Optional<SSLContext> context = Optional.ofNullable(this.sslContext).map(dependency -> dependency.get());
        return new DefaultSingleSignOnSessionFactory(this.manager.get(), keyPair, connection -> context.ifPresent(ctx -> connection.setSSLSocketFactory(ctx.getSocketFactory())));
    } catch (GeneralSecurityException | IOException e) {
        throw new IllegalArgumentException(e);
    }
}
Also used : ClearPassword(org.wildfly.security.password.interfaces.ClearPassword) KEY_ALIAS(org.wildfly.extension.undertow.ApplicationSecurityDomainSingleSignOnDefinition.Attribute.KEY_ALIAS) KeyPair(java.security.KeyPair) SSLContext(javax.net.ssl.SSLContext) FunctionalService(org.wildfly.clustering.service.FunctionalService) CredentialSource(org.wildfly.security.credential.source.CredentialSource) Function(java.util.function.Function) Supplier(java.util.function.Supplier) CREDENTIAL(org.wildfly.extension.undertow.ApplicationSecurityDomainSingleSignOnDefinition.Attribute.CREDENTIAL) OperationContext(org.jboss.as.controller.OperationContext) CompositeDependency(org.wildfly.clustering.service.CompositeDependency) DefaultSingleSignOnSessionFactory(org.wildfly.security.http.util.sso.DefaultSingleSignOnSessionFactory) GeneralSecurityException(java.security.GeneralSecurityException) CredentialSourceDependency(org.jboss.as.clustering.controller.CredentialSourceDependency) ServiceConfigurator(org.wildfly.clustering.service.ServiceConfigurator) PasswordCredential(org.wildfly.security.credential.PasswordCredential) ServiceTarget(org.jboss.msc.service.ServiceTarget) SupplierDependency(org.wildfly.clustering.service.SupplierDependency) UndertowLogger(org.wildfly.extension.undertow.logging.UndertowLogger) SingleSignOnSessionFactory(org.wildfly.security.http.util.sso.SingleSignOnSessionFactory) CommonUnaryRequirement(org.jboss.as.clustering.controller.CommonUnaryRequirement) ServiceBuilder(org.jboss.msc.service.ServiceBuilder) IOException(java.io.IOException) KeyStore(java.security.KeyStore) Service(org.jboss.msc.Service) SSL_CONTEXT(org.wildfly.extension.undertow.ApplicationSecurityDomainSingleSignOnDefinition.Attribute.SSL_CONTEXT) ServiceSupplierDependency(org.wildfly.clustering.service.ServiceSupplierDependency) KEY_STORE(org.wildfly.extension.undertow.ApplicationSecurityDomainSingleSignOnDefinition.Attribute.KEY_STORE) Consumer(java.util.function.Consumer) ResourceServiceConfigurator(org.jboss.as.clustering.controller.ResourceServiceConfigurator) OperationFailedException(org.jboss.as.controller.OperationFailedException) SingleSignOnManager(org.wildfly.security.http.util.sso.SingleSignOnManager) Optional(java.util.Optional) ClearPassword(org.wildfly.security.password.interfaces.ClearPassword) ModelNode(org.jboss.dmr.ModelNode) KeyPair(java.security.KeyPair) GeneralSecurityException(java.security.GeneralSecurityException) PasswordCredential(org.wildfly.security.credential.PasswordCredential) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) KeyStore(java.security.KeyStore) DefaultSingleSignOnSessionFactory(org.wildfly.security.http.util.sso.DefaultSingleSignOnSessionFactory) CredentialSource(org.wildfly.security.credential.source.CredentialSource)

Aggregations

CredentialSource (org.wildfly.security.credential.source.CredentialSource)12 PasswordCredential (org.wildfly.security.credential.PasswordCredential)7 ClearPassword (org.wildfly.security.password.interfaces.ClearPassword)6 OperationFailedException (org.jboss.as.controller.OperationFailedException)4 IOException (java.io.IOException)3 Provider (java.security.Provider)3 HashMap (java.util.HashMap)3 ModelNode (org.jboss.dmr.ModelNode)3 ServiceBuilder (org.jboss.msc.service.ServiceBuilder)3 ServiceTarget (org.jboss.msc.service.ServiceTarget)3 WildFlyElytronProvider (org.wildfly.security.WildFlyElytronProvider)3 Password (org.wildfly.security.password.Password)3 ClearPasswordSpec (org.wildfly.security.password.spec.ClearPasswordSpec)3 File (java.io.File)2 GeneralSecurityException (java.security.GeneralSecurityException)2 KeyPair (java.security.KeyPair)2 KeyStore (java.security.KeyStore)2 SQLException (java.sql.SQLException)2 Optional (java.util.Optional)2 SSLContext (javax.net.ssl.SSLContext)2