Search in sources :

Example 1 with TruststoreProvider

use of org.keycloak.truststore.TruststoreProvider in project keycloak by keycloak.

the class NginxProxySslClientCertificateLookup method loadKeycloakTrustStore.

/**
 *  Loading truststore @ first login
 *
 * @param kcsession
 * @return
 */
public boolean loadKeycloakTrustStore(KeycloakSession kcsession) {
    if (!isTruststoreLoaded) {
        log.debug(" Loading Keycloak truststore ...");
        KeycloakSessionFactory factory = kcsession.getKeycloakSessionFactory();
        TruststoreProviderFactory truststoreFactory = (TruststoreProviderFactory) factory.getProviderFactory(TruststoreProvider.class, "file");
        TruststoreProvider provider = truststoreFactory.create(kcsession);
        if (provider != null && provider.getTruststore() != null) {
            truststore = provider.getTruststore();
            trustedRootCerts = new HashSet<>(provider.getRootCertificates().values());
            intermediateCerts = new HashSet<>(provider.getIntermediateCertificates().values());
            log.debug("Keycloak truststore loaded for NGINX x509cert-lookup provider.");
            isTruststoreLoaded = true;
        }
    }
    return isTruststoreLoaded;
}
Also used : TruststoreProviderFactory(org.keycloak.truststore.TruststoreProviderFactory) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory) TruststoreProvider(org.keycloak.truststore.TruststoreProvider)

Example 2 with TruststoreProvider

use of org.keycloak.truststore.TruststoreProvider in project keycloak by keycloak.

the class LDAPOperationManager method authenticate.

/**
 * <p>
 * Performs a simple authentication using the given DN and password to bind to the authentication context.
 * </p>
 *
 * @param dn
 * @param password
 * @throws AuthenticationException if authentication is not successful
 */
public void authenticate(String dn, String password) throws AuthenticationException {
    if (password == null || password.isEmpty()) {
        throw new AuthenticationException("Empty password used");
    }
    LdapContext authCtx = null;
    StartTlsResponse tlsResponse = null;
    try {
        Hashtable<Object, Object> env = LDAPContextManager.getNonAuthConnectionProperties(config);
        // Never use connection pool to prevent password caching
        env.put("com.sun.jndi.ldap.connect.pool", "false");
        if (!this.config.isStartTls()) {
            env.put(Context.SECURITY_AUTHENTICATION, "simple");
            env.put(Context.SECURITY_PRINCIPAL, dn);
            env.put(Context.SECURITY_CREDENTIALS, password);
        }
        authCtx = new InitialLdapContext(env, null);
        if (config.isStartTls()) {
            SSLSocketFactory sslSocketFactory = null;
            String useTruststoreSpi = config.getUseTruststoreSpi();
            if (useTruststoreSpi != null && useTruststoreSpi.equals(LDAPConstants.USE_TRUSTSTORE_ALWAYS)) {
                TruststoreProvider provider = session.getProvider(TruststoreProvider.class);
                sslSocketFactory = provider.getSSLSocketFactory();
            }
            tlsResponse = LDAPContextManager.startTLS(authCtx, "simple", dn, password.toCharArray(), sslSocketFactory);
            // Exception should be already thrown by LDAPContextManager.startTLS if "startTLS" could not be established, but rather do some additional check
            if (tlsResponse == null) {
                throw new AuthenticationException("Null TLS Response returned from the authentication");
            }
        }
    } catch (AuthenticationException ae) {
        if (logger.isDebugEnabled()) {
            logger.debugf(ae, "Authentication failed for DN [%s]", dn);
        }
        throw ae;
    } catch (RuntimeException re) {
        if (logger.isDebugEnabled()) {
            logger.debugf(re, "LDAP Connection TimeOut for DN [%s]", dn);
        }
        throw re;
    } catch (Exception e) {
        logger.errorf(e, "Unexpected exception when validating password of DN [%s]", dn);
        throw new AuthenticationException("Unexpected exception when validating password of user");
    } finally {
        if (tlsResponse != null) {
            try {
                tlsResponse.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (authCtx != null) {
            try {
                authCtx.close();
            } catch (NamingException e) {
                e.printStackTrace();
            }
        }
    }
}
Also used : AuthenticationException(javax.naming.AuthenticationException) IOException(java.io.IOException) TruststoreProvider(org.keycloak.truststore.TruststoreProvider) NamingException(javax.naming.NamingException) AuthenticationException(javax.naming.AuthenticationException) NameAlreadyBoundException(javax.naming.NameAlreadyBoundException) IOException(java.io.IOException) ModelException(org.keycloak.models.ModelException) StartTlsResponse(javax.naming.ldap.StartTlsResponse) InitialLdapContext(javax.naming.ldap.InitialLdapContext) NamingException(javax.naming.NamingException) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) InitialLdapContext(javax.naming.ldap.InitialLdapContext) LdapContext(javax.naming.ldap.LdapContext)

Example 3 with TruststoreProvider

use of org.keycloak.truststore.TruststoreProvider in project keycloak by keycloak.

the class WebAuthnRegisterFactory method create.

@Override
public RequiredActionProvider create(KeycloakSession session) {
    WebAuthnRegister webAuthnRegister = null;
    TruststoreProvider truststoreProvider = session.getProvider(TruststoreProvider.class);
    if (truststoreProvider == null || truststoreProvider.getTruststore() == null) {
        webAuthnRegister = createProvider(session, new NullCertPathTrustworthinessValidator());
    } else {
        KeyStoreTrustAnchorsProvider trustAnchorsProvider = new KeyStoreTrustAnchorsProvider();
        trustAnchorsProvider.setKeyStore(truststoreProvider.getTruststore());
        TrustAnchorsResolverImpl resolverImpl = new TrustAnchorsResolverImpl(trustAnchorsProvider);
        TrustAnchorCertPathTrustworthinessValidator trustValidator = new TrustAnchorCertPathTrustworthinessValidator(resolverImpl);
        webAuthnRegister = createProvider(session, trustValidator);
    }
    return webAuthnRegister;
}
Also used : NullCertPathTrustworthinessValidator(com.webauthn4j.validator.attestation.trustworthiness.certpath.NullCertPathTrustworthinessValidator) TrustAnchorCertPathTrustworthinessValidator(com.webauthn4j.validator.attestation.trustworthiness.certpath.TrustAnchorCertPathTrustworthinessValidator) TrustAnchorsResolverImpl(com.webauthn4j.anchor.TrustAnchorsResolverImpl) TruststoreProvider(org.keycloak.truststore.TruststoreProvider) KeyStoreTrustAnchorsProvider(com.webauthn4j.anchor.KeyStoreTrustAnchorsProvider)

Example 4 with TruststoreProvider

use of org.keycloak.truststore.TruststoreProvider in project keycloak by keycloak.

the class LDAPContextManager method createLdapContext.

private void createLdapContext() throws NamingException {
    Hashtable<Object, Object> connProp = getConnectionProperties(ldapConfig);
    if (!LDAPConstants.AUTH_TYPE_NONE.equals(ldapConfig.getAuthType())) {
        vaultCharSecret = getVaultSecret();
        if (vaultCharSecret != null && !ldapConfig.isStartTls()) {
            connProp.put(SECURITY_CREDENTIALS, vaultCharSecret.getAsArray().orElse(ldapConfig.getBindCredential().toCharArray()));
        }
    }
    ldapContext = new InitialLdapContext(connProp, null);
    if (ldapConfig.isStartTls()) {
        SSLSocketFactory sslSocketFactory = null;
        String useTruststoreSpi = ldapConfig.getUseTruststoreSpi();
        if (useTruststoreSpi != null && useTruststoreSpi.equals(LDAPConstants.USE_TRUSTSTORE_ALWAYS)) {
            TruststoreProvider provider = session.getProvider(TruststoreProvider.class);
            sslSocketFactory = provider.getSSLSocketFactory();
        }
        tlsResponse = startTLS(ldapContext, ldapConfig.getAuthType(), ldapConfig.getBindDN(), vaultCharSecret.getAsArray().orElse(ldapConfig.getBindCredential().toCharArray()), sslSocketFactory);
        // Exception should be already thrown by LDAPContextManager.startTLS if "startTLS" could not be established, but rather do some additional check
        if (tlsResponse == null) {
            throw new NamingException("Wasn't able to establish LDAP connection through StartTLS");
        }
    }
}
Also used : InitialLdapContext(javax.naming.ldap.InitialLdapContext) NamingException(javax.naming.NamingException) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) TruststoreProvider(org.keycloak.truststore.TruststoreProvider)

Example 5 with TruststoreProvider

use of org.keycloak.truststore.TruststoreProvider in project keycloak by keycloak.

the class DefaultHttpClientFactory method lazyInit.

private void lazyInit(KeycloakSession session) {
    if (httpClient == null) {
        synchronized (this) {
            if (httpClient == null) {
                long socketTimeout = config.getLong("socket-timeout-millis", 5000L);
                long establishConnectionTimeout = config.getLong("establish-connection-timeout-millis", -1L);
                int maxPooledPerRoute = config.getInt("max-pooled-per-route", 64);
                int connectionPoolSize = config.getInt("connection-pool-size", 128);
                long connectionTTL = config.getLong("connection-ttl-millis", -1L);
                boolean reuseConnections = config.getBoolean("reuse-connections", true);
                long maxConnectionIdleTime = config.getLong("max-connection-idle-time-millis", 900000L);
                boolean disableCookies = config.getBoolean("disable-cookies", true);
                String clientKeystore = config.get("client-keystore");
                String clientKeystorePassword = config.get("client-keystore-password");
                String clientPrivateKeyPassword = config.get("client-key-password");
                boolean disableTrustManager = config.getBoolean("disable-trust-manager", false);
                boolean expectContinueEnabled = getBooleanConfigWithSysPropFallback("expect-continue-enabled", false);
                boolean resuseConnections = getBooleanConfigWithSysPropFallback("reuse-connections", true);
                // optionally configure proxy mappings
                // direct SPI config (e.g. via standalone.xml) takes precedence over env vars
                // lower case env vars take precedence over upper case env vars
                ProxyMappings proxyMappings = ProxyMappings.valueOf(config.getArray("proxy-mappings"));
                if (proxyMappings == null || proxyMappings.isEmpty()) {
                    logger.debug("Trying to use proxy mapping from env vars");
                    String httpProxy = getEnvVarValue(HTTPS_PROXY);
                    if (isBlank(httpProxy)) {
                        httpProxy = getEnvVarValue(HTTP_PROXY);
                    }
                    String noProxy = getEnvVarValue(NO_PROXY);
                    logger.debugf("httpProxy: %s, noProxy: %s", httpProxy, noProxy);
                    proxyMappings = ProxyMappings.withFixedProxyMapping(httpProxy, noProxy);
                }
                HttpClientBuilder builder = new HttpClientBuilder();
                builder.socketTimeout(socketTimeout, TimeUnit.MILLISECONDS).establishConnectionTimeout(establishConnectionTimeout, TimeUnit.MILLISECONDS).maxPooledPerRoute(maxPooledPerRoute).connectionPoolSize(connectionPoolSize).reuseConnections(reuseConnections).connectionTTL(connectionTTL, TimeUnit.MILLISECONDS).maxConnectionIdleTime(maxConnectionIdleTime, TimeUnit.MILLISECONDS).disableCookies(disableCookies).proxyMappings(proxyMappings).expectContinueEnabled(expectContinueEnabled).reuseConnections(resuseConnections);
                TruststoreProvider truststoreProvider = session.getProvider(TruststoreProvider.class);
                boolean disableTruststoreProvider = truststoreProvider == null || truststoreProvider.getTruststore() == null;
                if (disableTruststoreProvider) {
                    logger.warn("TruststoreProvider is disabled");
                } else {
                    builder.hostnameVerification(HttpClientBuilder.HostnameVerificationPolicy.valueOf(truststoreProvider.getPolicy().name()));
                    try {
                        builder.trustStore(truststoreProvider.getTruststore());
                    } catch (Exception e) {
                        throw new RuntimeException("Failed to load truststore", e);
                    }
                }
                if (disableTrustManager) {
                    logger.warn("TrustManager is disabled");
                    builder.disableTrustManager();
                }
                if (clientKeystore != null) {
                    clientKeystore = EnvUtil.replace(clientKeystore);
                    try {
                        KeyStore clientCertKeystore = KeystoreUtil.loadKeyStore(clientKeystore, clientKeystorePassword);
                        builder.keyStore(clientCertKeystore, clientPrivateKeyPassword);
                    } catch (Exception e) {
                        throw new RuntimeException("Failed to load keystore", e);
                    }
                }
                httpClient = builder.build();
            }
        }
    }
}
Also used : KeyStore(java.security.KeyStore) TruststoreProvider(org.keycloak.truststore.TruststoreProvider) IOException(java.io.IOException)

Aggregations

TruststoreProvider (org.keycloak.truststore.TruststoreProvider)8 IOException (java.io.IOException)3 X509Certificate (java.security.cert.X509Certificate)3 NamingException (javax.naming.NamingException)3 X500Principal (javax.security.auth.x500.X500Principal)3 GeneralSecurityException (java.security.GeneralSecurityException)2 KeyStoreTrustAnchorsProvider (com.webauthn4j.anchor.KeyStoreTrustAnchorsProvider)1 TrustAnchorsResolverImpl (com.webauthn4j.anchor.TrustAnchorsResolverImpl)1 NullCertPathTrustworthinessValidator (com.webauthn4j.validator.attestation.trustworthiness.certpath.NullCertPathTrustworthinessValidator)1 TrustAnchorCertPathTrustworthinessValidator (com.webauthn4j.validator.attestation.trustworthiness.certpath.TrustAnchorCertPathTrustworthinessValidator)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 DataInputStream (java.io.DataInputStream)1 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 InputStream (java.io.InputStream)1 URI (java.net.URI)1 URISyntaxException (java.net.URISyntaxException)1 KeyStore (java.security.KeyStore)1 CRLException (java.security.cert.CRLException)1 CertPathBuilder (java.security.cert.CertPathBuilder)1