Search in sources :

Example 21 with X509TrustManager

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

the class OpenSSLContext method init.

/**
     * Setup the SSL_CTX.
     *
     * @param kms Must contain a KeyManager of the type
     *            {@code OpenSSLKeyManager}
     * @param tms Must contain a TrustManager of the type
     *            {@code X509TrustManager}
     * @param sr Is not used for this implementation.
     */
@Override
public synchronized void init(KeyManager[] kms, TrustManager[] tms, SecureRandom sr) {
    if (initialized) {
        log.warn(sm.getString("openssl.doubleInit"));
        return;
    }
    try {
        if (sslHostConfig.getInsecureRenegotiation()) {
            SSLContext.setOptions(ctx, SSL.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
        } else {
            SSLContext.clearOptions(ctx, SSL.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
        }
        // client's)
        if (sslHostConfig.getHonorCipherOrder()) {
            SSLContext.setOptions(ctx, SSL.SSL_OP_CIPHER_SERVER_PREFERENCE);
        } else {
            SSLContext.clearOptions(ctx, SSL.SSL_OP_CIPHER_SERVER_PREFERENCE);
        }
        // Disable compression if requested
        if (sslHostConfig.getDisableCompression()) {
            SSLContext.setOptions(ctx, SSL.SSL_OP_NO_COMPRESSION);
        } else {
            SSLContext.clearOptions(ctx, SSL.SSL_OP_NO_COMPRESSION);
        }
        // Disable TLS Session Tickets (RFC4507) to protect perfect forward secrecy
        if (sslHostConfig.getDisableSessionTickets()) {
            SSLContext.setOptions(ctx, SSL.SSL_OP_NO_TICKET);
        } else {
            SSLContext.clearOptions(ctx, SSL.SSL_OP_NO_TICKET);
        }
        // Set session cache size, if specified
        if (sslHostConfig.getSessionCacheSize() > 0) {
            SSLContext.setSessionCacheSize(ctx, sslHostConfig.getSessionCacheSize());
        } else {
            // Get the default session cache size using SSLContext.setSessionCacheSize()
            long sessionCacheSize = SSLContext.setSessionCacheSize(ctx, 20480);
            // Revert the session cache size to the default value.
            SSLContext.setSessionCacheSize(ctx, sessionCacheSize);
        }
        // Set session timeout, if specified
        if (sslHostConfig.getSessionTimeout() > 0) {
            SSLContext.setSessionCacheTimeout(ctx, sslHostConfig.getSessionTimeout());
        } else {
            // Get the default session timeout using SSLContext.setSessionCacheTimeout()
            long sessionTimeout = SSLContext.setSessionCacheTimeout(ctx, 300);
            // Revert the session timeout to the default value.
            SSLContext.setSessionCacheTimeout(ctx, sessionTimeout);
        }
        // List the ciphers that the client is permitted to negotiate
        String opensslCipherConfig = sslHostConfig.getCiphers();
        this.jsseCipherNames = OpenSSLCipherConfigurationParser.parseExpression(opensslCipherConfig);
        SSLContext.setCipherSuite(ctx, opensslCipherConfig);
        // Load Server key and certificate
        if (certificate.getCertificateFile() != null) {
            // Set certificate
            SSLContext.setCertificate(ctx, SSLHostConfig.adjustRelativePath(certificate.getCertificateFile()), SSLHostConfig.adjustRelativePath(certificate.getCertificateKeyFile()), certificate.getCertificateKeyPassword(), SSL.SSL_AIDX_RSA);
            // Set certificate chain file
            SSLContext.setCertificateChainFile(ctx, SSLHostConfig.adjustRelativePath(certificate.getCertificateChainFile()), false);
            // Support Client Certificates
            SSLContext.setCACertificate(ctx, SSLHostConfig.adjustRelativePath(sslHostConfig.getCaCertificateFile()), SSLHostConfig.adjustRelativePath(sslHostConfig.getCaCertificatePath()));
            // Set revocation
            SSLContext.setCARevocation(ctx, SSLHostConfig.adjustRelativePath(sslHostConfig.getCertificateRevocationListFile()), SSLHostConfig.adjustRelativePath(sslHostConfig.getCertificateRevocationListPath()));
        } else {
            X509KeyManager keyManager = chooseKeyManager(kms);
            String alias = certificate.getCertificateKeyAlias();
            if (alias == null) {
                alias = "tomcat";
            }
            X509Certificate[] chain = keyManager.getCertificateChain(alias);
            if (chain == null) {
                alias = findAlias(keyManager, certificate);
                chain = keyManager.getCertificateChain(alias);
            }
            PrivateKey key = keyManager.getPrivateKey(alias);
            StringBuilder sb = new StringBuilder(BEGIN_KEY);
            sb.append(Base64.getMimeEncoder(64, new byte[] { '\n' }).encodeToString(key.getEncoded()));
            sb.append(END_KEY);
            SSLContext.setCertificateRaw(ctx, chain[0].getEncoded(), sb.toString().getBytes(StandardCharsets.US_ASCII), SSL.SSL_AIDX_RSA);
            for (int i = 1; i < chain.length; i++) {
                SSLContext.addChainCertificateRaw(ctx, chain[i].getEncoded());
            }
        }
        // Client certificate verification
        int value = 0;
        switch(sslHostConfig.getCertificateVerification()) {
            case NONE:
                value = SSL.SSL_CVERIFY_NONE;
                break;
            case OPTIONAL:
                value = SSL.SSL_CVERIFY_OPTIONAL;
                break;
            case OPTIONAL_NO_CA:
                value = SSL.SSL_CVERIFY_OPTIONAL_NO_CA;
                break;
            case REQUIRED:
                value = SSL.SSL_CVERIFY_REQUIRE;
                break;
        }
        SSLContext.setVerify(ctx, value, sslHostConfig.getCertificateVerificationDepth());
        if (tms != null) {
            final X509TrustManager manager = chooseTrustManager(tms);
            SSLContext.setCertVerifyCallback(ctx, new CertificateVerifier() {

                @Override
                public boolean verify(long ssl, byte[][] chain, String auth) {
                    X509Certificate[] peerCerts = certificates(chain);
                    try {
                        manager.checkClientTrusted(peerCerts, auth);
                        return true;
                    } catch (Exception e) {
                        log.debug(sm.getString("openssl.certificateVerificationFailed"), e);
                    }
                    return false;
                }
            });
        }
        if (negotiableProtocols != null && negotiableProtocols.size() > 0) {
            ArrayList<String> protocols = new ArrayList<>();
            protocols.addAll(negotiableProtocols);
            protocols.add("http/1.1");
            String[] protocolsArray = protocols.toArray(new String[0]);
            SSLContext.setAlpnProtos(ctx, protocolsArray, SSL.SSL_SELECTOR_FAILURE_NO_ADVERTISE);
            SSLContext.setNpnProtos(ctx, protocolsArray, SSL.SSL_SELECTOR_FAILURE_NO_ADVERTISE);
        }
        sessionContext = new OpenSSLSessionContext(ctx);
        sslHostConfig.setOpenSslContext(Long.valueOf(ctx));
        initialized = true;
    } catch (Exception e) {
        log.warn(sm.getString("openssl.errorSSLCtxInit"), e);
        destroy();
    }
}
Also used : PrivateKey(java.security.PrivateKey) ArrayList(java.util.ArrayList) X509Certificate(java.security.cert.X509Certificate) AbstractEndpoint(org.apache.tomcat.util.net.AbstractEndpoint) CertificateException(java.security.cert.CertificateException) SSLException(javax.net.ssl.SSLException) X509TrustManager(javax.net.ssl.X509TrustManager) CertificateVerifier(org.apache.tomcat.jni.CertificateVerifier) X509KeyManager(javax.net.ssl.X509KeyManager)

Example 22 with X509TrustManager

use of javax.net.ssl.X509TrustManager in project cas by apereo.

the class SimpleHttpClientTests method getFriendlyToAllSSLSocketFactory.

private static SSLConnectionSocketFactory getFriendlyToAllSSLSocketFactory() throws Exception {
    final TrustManager trm = new X509TrustManager() {

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(final X509Certificate[] certs, final String authType) {
        }

        @Override
        public void checkServerTrusted(final X509Certificate[] certs, final String authType) {
        }
    };
    final SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, new TrustManager[] { trm }, null);
    return new SSLConnectionSocketFactory(sc, new NoopHostnameVerifier());
}
Also used : NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) X509TrustManager(javax.net.ssl.X509TrustManager) SSLContext(javax.net.ssl.SSLContext) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) X509Certificate(java.security.cert.X509Certificate) X509TrustManager(javax.net.ssl.X509TrustManager) TrustManager(javax.net.ssl.TrustManager)

Example 23 with X509TrustManager

use of javax.net.ssl.X509TrustManager in project OpenAttestation by OpenAttestation.

the class X509Util method createX509TrustManagerWithKeystore.

/**
     * @deprecated use TlsPolicy instead
     * @param keystore
     * @return
     * @throws KeyManagementException 
     */
public static X509TrustManager createX509TrustManagerWithKeystore(SimpleKeystore keystore) throws KeyManagementException {
    try {
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(KeyStoreUtil.createTrustedSslKeystore(keystore));
        TrustManager[] tms = tmf.getTrustManagers();
        for (TrustManager tm : tms) {
            if (tm instanceof X509TrustManager) {
                return (X509TrustManager) tm;
            }
        }
    } catch (NoSuchAlgorithmException | IOException | CertificateException | UnrecoverableEntryException | KeyStoreException e) {
        throw new KeyManagementException("Cannot create X509TrustManager", e);
    }
    throw new IllegalArgumentException("TrustManagerFactory did not return an X509TrustManager instance");
}
Also used : X509TrustManager(javax.net.ssl.X509TrustManager) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) UnrecoverableEntryException(java.security.UnrecoverableEntryException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException) KeyManagementException(java.security.KeyManagementException) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager)

Example 24 with X509TrustManager

use of javax.net.ssl.X509TrustManager in project OpenAttestation by OpenAttestation.

the class X509Util method createX509TrustManagerWithCertificates.

/**
     * 
     * @deprecated use TlsPolicy instead
     * @param certificates
     * @return
     * @throws KeyManagementException 
     */
public static X509TrustManager createX509TrustManagerWithCertificates(X509Certificate[] certificates) throws KeyManagementException {
    try {
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(KeyStoreUtil.createTrustedSslKeystore(certificates));
        TrustManager[] tms = tmf.getTrustManagers();
        for (TrustManager tm : tms) {
            if (tm instanceof X509TrustManager) {
                return (X509TrustManager) tm;
            }
        }
    } catch (NoSuchAlgorithmException | IOException | CertificateException | UnrecoverableEntryException | KeyStoreException e) {
        throw new KeyManagementException("Cannot create X509TrustManager", e);
    }
    throw new IllegalArgumentException("TrustManagerFactory did not return an X509TrustManager instance");
}
Also used : X509TrustManager(javax.net.ssl.X509TrustManager) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) UnrecoverableEntryException(java.security.UnrecoverableEntryException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException) KeyManagementException(java.security.KeyManagementException) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager)

Example 25 with X509TrustManager

use of javax.net.ssl.X509TrustManager in project OpenGrok by OpenGrok.

the class Query method createHttpsUrlConnection.

private HttpsURLConnection createHttpsUrlConnection(URL url) {
    try {
        System.setProperty("jsse.enableSNIExtension", "false");
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }
        } };
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
        return (HttpsURLConnection) url.openConnection();
    } catch (Exception ex) {
        handleException(ex);
    }
    return null;
}
Also used : SSLSession(javax.net.ssl.SSLSession) SSLContext(javax.net.ssl.SSLContext) ParseException(org.json.simple.parser.ParseException) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) HostnameVerifier(javax.net.ssl.HostnameVerifier) X509TrustManager(javax.net.ssl.X509TrustManager) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Aggregations

X509TrustManager (javax.net.ssl.X509TrustManager)183 TrustManager (javax.net.ssl.TrustManager)114 X509Certificate (java.security.cert.X509Certificate)96 SSLContext (javax.net.ssl.SSLContext)88 CertificateException (java.security.cert.CertificateException)54 IOException (java.io.IOException)50 TrustManagerFactory (javax.net.ssl.TrustManagerFactory)45 SecureRandom (java.security.SecureRandom)44 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)32 KeyManagementException (java.security.KeyManagementException)28 Test (org.junit.Test)21 HostnameVerifier (javax.net.ssl.HostnameVerifier)19 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)19 KeyStore (java.security.KeyStore)17 GeneralSecurityException (java.security.GeneralSecurityException)15 SSLSession (javax.net.ssl.SSLSession)15 KeyStoreException (java.security.KeyStoreException)14 SSLException (javax.net.ssl.SSLException)14 URL (java.net.URL)11 OkHttpClient (okhttp3.OkHttpClient)10