Search in sources :

Example 71 with KeyManager

use of javax.net.ssl.KeyManager in project spring-boot by spring-projects.

the class SslBuilderCustomizerTests method getKeyManagersWhenAliasIsNullShouldNotDecorate.

@Test
void getKeyManagersWhenAliasIsNullShouldNotDecorate() throws Exception {
    Ssl ssl = new Ssl();
    ssl.setKeyPassword("password");
    ssl.setKeyStore("src/test/resources/test.jks");
    SslBuilderCustomizer customizer = new SslBuilderCustomizer(8080, InetAddress.getLocalHost(), ssl, null);
    KeyManager[] keyManagers = ReflectionTestUtils.invokeMethod(customizer, "getKeyManagers", ssl, null);
    Class<?> name = Class.forName("org.springframework.boot.web.embedded.undertow.SslBuilderCustomizer$ConfigurableAliasKeyManager");
    assertThat(keyManagers[0]).isNotInstanceOf(name);
}
Also used : Ssl(org.springframework.boot.web.server.Ssl) KeyManager(javax.net.ssl.KeyManager) Test(org.junit.jupiter.api.Test)

Example 72 with KeyManager

use of javax.net.ssl.KeyManager in project zookeeper by apache.

the class X509Util method createKeyManager.

/**
 * Creates a key manager by loading the key store from the given file of
 * the given type, optionally decrypting it using the given password.
 * @param keyStoreLocation the location of the key store file.
 * @param keyStorePassword optional password to decrypt the key store. If
 *                         empty, assumes the key store is not encrypted.
 * @param keyStoreTypeProp must be JKS, PEM, PKCS12, BCFKS or null. If null,
 *                         attempts to autodetect the key store type from
 *                         the file extension (e.g. .jks / .pem).
 * @return the key manager.
 * @throws KeyManagerException if something goes wrong.
 */
public static X509KeyManager createKeyManager(String keyStoreLocation, String keyStorePassword, String keyStoreTypeProp) throws KeyManagerException {
    if (keyStorePassword == null) {
        keyStorePassword = "";
    }
    try {
        KeyStore ks = loadKeyStore(keyStoreLocation, keyStorePassword, keyStoreTypeProp);
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX");
        kmf.init(ks, keyStorePassword.toCharArray());
        for (KeyManager km : kmf.getKeyManagers()) {
            if (km instanceof X509KeyManager) {
                return (X509KeyManager) km;
            }
        }
        throw new KeyManagerException("Couldn't find X509KeyManager");
    } catch (IOException | GeneralSecurityException | IllegalArgumentException e) {
        throw new KeyManagerException(e);
    }
}
Also used : KeyManagerException(org.apache.zookeeper.common.X509Exception.KeyManagerException) GeneralSecurityException(java.security.GeneralSecurityException) X509KeyManager(javax.net.ssl.X509KeyManager) IOException(java.io.IOException) KeyStore(java.security.KeyStore) X509KeyManager(javax.net.ssl.X509KeyManager) KeyManager(javax.net.ssl.KeyManager) KeyManagerFactory(javax.net.ssl.KeyManagerFactory)

Example 73 with KeyManager

use of javax.net.ssl.KeyManager in project tomcat by apache.

the class SSLUtilBase method getKeyManagers.

@Override
public KeyManager[] getKeyManagers() throws Exception {
    String keyAlias = certificate.getCertificateKeyAlias();
    String algorithm = sslHostConfig.getKeyManagerAlgorithm();
    String keyPass = certificate.getCertificateKeyPassword();
    // defaults vary between JSSE and OpenSSL.
    if (keyPass == null) {
        keyPass = certificate.getCertificateKeystorePassword();
    }
    KeyStore ks = certificate.getCertificateKeystore();
    KeyStore ksUsed = ks;
    /*
         * Use an in memory key store where possible.
         * For PEM format keys and certificates, it allows them to be imported
         * into the expected format.
         * For Java key stores with PKCS8 encoded keys (e.g. JKS files), it
         * enables Tomcat to handle the case where multiple keys exist in the
         * key store, each with a different password. The KeyManagerFactory
         * can't handle that so using an in memory key store with just the
         * required key works around that.
         * Other keys stores (hardware, MS, etc.) will be used as is.
         */
    char[] keyPassArray = keyPass.toCharArray();
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
    if (kmf.getProvider().getInfo().indexOf("FIPS") != -1) {
        // FIPS doesn't like ANY wrapping nor key manipulation.
        if (keyAlias != null) {
            log.warn(sm.getString("sslUtilBase.aliasIgnored", keyAlias));
        }
        kmf.init(ksUsed, keyPassArray);
        return kmf.getKeyManagers();
    }
    if (ks == null) {
        if (certificate.getCertificateFile() == null) {
            throw new IOException(sm.getString("sslUtilBase.noCertFile"));
        }
        PEMFile privateKeyFile = new PEMFile(certificate.getCertificateKeyFile() != null ? certificate.getCertificateKeyFile() : certificate.getCertificateFile(), keyPass);
        PEMFile certificateFile = new PEMFile(certificate.getCertificateFile());
        Collection<Certificate> chain = new ArrayList<>(certificateFile.getCertificates());
        if (certificate.getCertificateChainFile() != null) {
            PEMFile certificateChainFile = new PEMFile(certificate.getCertificateChainFile());
            chain.addAll(certificateChainFile.getCertificates());
        }
        if (keyAlias == null) {
            keyAlias = "tomcat";
        }
        // Switch to in-memory key store
        ksUsed = KeyStore.getInstance("JKS");
        ksUsed.load(null, null);
        ksUsed.setKeyEntry(keyAlias, privateKeyFile.getPrivateKey(), keyPass.toCharArray(), chain.toArray(new Certificate[0]));
    } else {
        if (keyAlias != null && !ks.isKeyEntry(keyAlias)) {
            throw new IOException(sm.getString("sslUtilBase.alias_no_key_entry", keyAlias));
        } else if (keyAlias == null) {
            Enumeration<String> aliases = ks.aliases();
            if (!aliases.hasMoreElements()) {
                throw new IOException(sm.getString("sslUtilBase.noKeys"));
            }
            while (aliases.hasMoreElements() && keyAlias == null) {
                keyAlias = aliases.nextElement();
                if (!ks.isKeyEntry(keyAlias)) {
                    keyAlias = null;
                }
            }
            if (keyAlias == null) {
                throw new IOException(sm.getString("sslUtilBase.alias_no_key_entry", (Object) null));
            }
        }
        Key k = ks.getKey(keyAlias, keyPassArray);
        if (k != null && !"DKS".equalsIgnoreCase(certificate.getCertificateKeystoreType()) && "PKCS#8".equalsIgnoreCase(k.getFormat())) {
            // Switch to in-memory key store
            String provider = certificate.getCertificateKeystoreProvider();
            if (provider == null) {
                ksUsed = KeyStore.getInstance(certificate.getCertificateKeystoreType());
            } else {
                ksUsed = KeyStore.getInstance(certificate.getCertificateKeystoreType(), provider);
            }
            ksUsed.load(null, null);
            ksUsed.setKeyEntry(keyAlias, k, keyPassArray, ks.getCertificateChain(keyAlias));
        }
    // Non-PKCS#8 key stores will use the original key store
    }
    kmf.init(ksUsed, keyPassArray);
    KeyManager[] kms = kmf.getKeyManagers();
    // have a single key so don't need filtering
    if (kms != null && ksUsed == ks) {
        String alias = keyAlias;
        // JKS keystores always convert the alias name to lower case
        if ("JKS".equals(certificate.getCertificateKeystoreType())) {
            alias = alias.toLowerCase(Locale.ENGLISH);
        }
        for (int i = 0; i < kms.length; i++) {
            kms[i] = new JSSEKeyManager((X509KeyManager) kms[i], alias);
        }
    }
    return kms;
}
Also used : Enumeration(java.util.Enumeration) ArrayList(java.util.ArrayList) IOException(java.io.IOException) KeyStore(java.security.KeyStore) JSSEKeyManager(org.apache.tomcat.util.net.jsse.JSSEKeyManager) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) X509KeyManager(javax.net.ssl.X509KeyManager) PEMFile(org.apache.tomcat.util.net.jsse.PEMFile) X509KeyManager(javax.net.ssl.X509KeyManager) JSSEKeyManager(org.apache.tomcat.util.net.jsse.JSSEKeyManager) KeyManager(javax.net.ssl.KeyManager) Key(java.security.Key) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 74 with KeyManager

use of javax.net.ssl.KeyManager in project platformlayer by platformlayer.

the class PlatformLayerAuthenticationClient method authenticateWithCertificate.

public PlatformlayerAuthenticationToken authenticateWithCertificate(String username, X509Certificate[] certificateChain, PrivateKey privateKey) throws PlatformlayerAuthenticationClientException {
    if (username == null) {
        throw new IllegalArgumentException();
    }
    CertificateCredentials certificateCredentials = new CertificateCredentials();
    certificateCredentials.setUsername(username);
    Auth auth = new Auth();
    auth.setCertificateCredentials(certificateCredentials);
    AuthenticateRequest request = new AuthenticateRequest();
    request.setAuth(auth);
    final KeyManager keyManager = new SimpleClientCertificateKeyManager(privateKey, certificateChain);
    for (int i = 0; i < 2; i++) {
        AuthenticateResponse response;
        try {
            RestfulRequest<AuthenticateResponse> httpRequest = httpClient.buildRequest(HttpMethod.POST, "api/tokens", HttpPayload.asXml(request), AuthenticateResponse.class);
            httpRequest.setKeyManager(keyManager);
            response = httpRequest.execute();
        } catch (RestClientException e) {
            throw new PlatformlayerAuthenticationClientException("Error authenticating", e);
        }
        if (i == 0) {
            if (response == null || response.getChallenge() == null) {
                return null;
            }
            byte[] challenge = response.getChallenge();
            byte[] challengeResponse = decrypt(privateKey, challenge);
            certificateCredentials.setChallengeResponse(challengeResponse);
        } else {
            if (response == null || response.getAccess() == null) {
                return null;
            }
            return new PlatformlayerAuthenticationToken(response.getAccess());
        }
    }
    return null;
}
Also used : SimpleClientCertificateKeyManager(com.fathomdb.crypto.SimpleClientCertificateKeyManager) AuthenticateResponse(org.platformlayer.auth.v1.AuthenticateResponse) PlatformlayerAuthenticationToken(org.platformlayer.auth.PlatformlayerAuthenticationToken) PlatformlayerAuthenticationClientException(org.platformlayer.auth.PlatformlayerAuthenticationClientException) AuthenticateRequest(org.platformlayer.auth.v1.AuthenticateRequest) CertificateCredentials(org.platformlayer.auth.v1.CertificateCredentials) Auth(org.platformlayer.auth.v1.Auth) RestClientException(org.platformlayer.rest.RestClientException) SimpleClientCertificateKeyManager(com.fathomdb.crypto.SimpleClientCertificateKeyManager) KeyManager(javax.net.ssl.KeyManager)

Example 75 with KeyManager

use of javax.net.ssl.KeyManager in project platformlayer by platformlayer.

the class PlatformLayerAuthAdminClient method build.

public static AuthenticationTokenValidator build(HttpStrategy httpStrategy, Configuration configuration, EncryptionStore encryptionStore) throws OpsException {
    String keystoneServiceUrl = configuration.lookup("auth.system.url", "https://127.0.0.1:" + WellKnownPorts.PORT_PLATFORMLAYER_AUTH_ADMIN + "/");
    String cert = configuration.get("auth.system.tls.clientcert");
    CertificateAndKey certificateAndKey = encryptionStore.getCertificateAndKey(cert);
    HostnameVerifier hostnameVerifier = null;
    KeyManager keyManager = new SimpleClientCertificateKeyManager(certificateAndKey);
    TrustManager trustManager = null;
    String trustKeys = configuration.lookup("auth.system.ssl.keys", null);
    if (trustKeys != null) {
        trustManager = new PublicKeyTrustManager(Splitter.on(',').trimResults().split(trustKeys));
        hostnameVerifier = new AcceptAllHostnameVerifier();
    }
    if (log.isDebugEnabled() && certificateAndKey != null) {
        X509Certificate[] chain = certificateAndKey.getCertificateChain();
        log.debug("Using client cert for PL auth: " + Joiner.on(",").join(chain));
    }
    SslConfiguration sslConfiguration = new SslConfiguration(keyManager, trustManager, hostnameVerifier);
    RestfulClient restfulClient = new JreRestfulClient(httpStrategy, keystoneServiceUrl, sslConfiguration);
    AuthenticationTokenValidator tokenValidator = new PlatformLayerAuthAdminClient(restfulClient);
    tokenValidator = new CachingAuthenticationTokenValidator(tokenValidator);
    return tokenValidator;
}
Also used : SimpleClientCertificateKeyManager(com.fathomdb.crypto.SimpleClientCertificateKeyManager) PublicKeyTrustManager(com.fathomdb.crypto.ssl.PublicKeyTrustManager) AuthenticationTokenValidator(org.platformlayer.auth.AuthenticationTokenValidator) RestfulClient(org.platformlayer.rest.RestfulClient) JreRestfulClient(org.platformlayer.rest.JreRestfulClient) X509Certificate(java.security.cert.X509Certificate) AcceptAllHostnameVerifier(com.fathomdb.crypto.ssl.AcceptAllHostnameVerifier) HostnameVerifier(javax.net.ssl.HostnameVerifier) TrustManager(javax.net.ssl.TrustManager) PublicKeyTrustManager(com.fathomdb.crypto.ssl.PublicKeyTrustManager) AcceptAllHostnameVerifier(com.fathomdb.crypto.ssl.AcceptAllHostnameVerifier) JreRestfulClient(org.platformlayer.rest.JreRestfulClient) SslConfiguration(org.platformlayer.http.SslConfiguration) CertificateAndKey(com.fathomdb.crypto.CertificateAndKey) SimpleClientCertificateKeyManager(com.fathomdb.crypto.SimpleClientCertificateKeyManager) KeyManager(javax.net.ssl.KeyManager)

Aggregations

KeyManager (javax.net.ssl.KeyManager)210 SSLContext (javax.net.ssl.SSLContext)127 TrustManager (javax.net.ssl.TrustManager)127 KeyManagerFactory (javax.net.ssl.KeyManagerFactory)103 KeyStore (java.security.KeyStore)95 IOException (java.io.IOException)59 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)59 SecureRandom (java.security.SecureRandom)54 TrustManagerFactory (javax.net.ssl.TrustManagerFactory)54 KeyManagementException (java.security.KeyManagementException)46 X509TrustManager (javax.net.ssl.X509TrustManager)45 KeyStoreException (java.security.KeyStoreException)42 X509KeyManager (javax.net.ssl.X509KeyManager)40 InputStream (java.io.InputStream)33 UnrecoverableKeyException (java.security.UnrecoverableKeyException)32 FileInputStream (java.io.FileInputStream)31 CertificateException (java.security.cert.CertificateException)30 GeneralSecurityException (java.security.GeneralSecurityException)24 X509Certificate (java.security.cert.X509Certificate)23 File (java.io.File)15