Search in sources :

Example 56 with SSLSocketFactory

use of javax.net.ssl.SSLSocketFactory in project qpid-broker-j by apache.

the class SNITest method performTest.

private void performTest(final boolean useMatching, final String defaultAlias, final String sniHostName, final KeyCertPair expectedCert) throws Exception {
    if (SSLUtil.canGenerateCerts()) {
        doBrokerStartup(useMatching, defaultAlias);
        SSLContext context = SSLUtil.tryGetSSLContext();
        context.init(null, new TrustManager[] { new X509TrustManager() {

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

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

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } }, null);
        SSLSocketFactory socketFactory = context.getSocketFactory();
        try (SSLSocket socket = (SSLSocket) socketFactory.createSocket()) {
            SSLParameters parameters = socket.getSSLParameters();
            if (sniHostName != null) {
                parameters.setServerNames(Collections.singletonList(new SNIHostName(sniHostName)));
            }
            socket.setSSLParameters(parameters);
            InetSocketAddress address = new InetSocketAddress("localhost", _boundPort);
            socket.connect(address, SOCKET_TIMEOUT);
            final Certificate[] certs = socket.getSession().getPeerCertificates();
            assertEquals(1, certs.length);
            assertEquals(expectedCert.getCertificate(), certs[0]);
        }
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) SSLSocket(javax.net.ssl.SSLSocket) SSLContext(javax.net.ssl.SSLContext) X509Certificate(java.security.cert.X509Certificate) SSLParameters(javax.net.ssl.SSLParameters) X509TrustManager(javax.net.ssl.X509TrustManager) SNIHostName(javax.net.ssl.SNIHostName) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 57 with SSLSocketFactory

use of javax.net.ssl.SSLSocketFactory in project nifi by apache.

the class InvokeHTTP method setSslSocketFactory.

/*
        Overall, this method is based off of examples from OkHttp3 documentation:
            https://square.github.io/okhttp/3.x/okhttp/okhttp3/OkHttpClient.Builder.html#sslSocketFactory-javax.net.ssl.SSLSocketFactory-javax.net.ssl.X509TrustManager-
            https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/CustomTrust.java#L156

        In-depth documentation on Java Secure Socket Extension (JSSE) Classes and interfaces:
            https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html#JSSEClasses
     */
private void setSslSocketFactory(OkHttpClient.Builder okHttpClientBuilder, SSLContextService sslService, SSLContext sslContext, boolean setAsSocketFactory) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException {
    final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509");
    // initialize the KeyManager array to null and we will overwrite later if a keystore is loaded
    KeyManager[] keyManagers = null;
    // we will only initialize the keystore if properties have been supplied by the SSLContextService
    if (sslService.isKeyStoreConfigured()) {
        final String keystoreLocation = sslService.getKeyStoreFile();
        final String keystorePass = sslService.getKeyStorePassword();
        final String keystoreType = sslService.getKeyStoreType();
        // prepare the keystore
        final KeyStore keyStore = KeyStore.getInstance(keystoreType);
        try (FileInputStream keyStoreStream = new FileInputStream(keystoreLocation)) {
            keyStore.load(keyStoreStream, keystorePass.toCharArray());
        }
        keyManagerFactory.init(keyStore, keystorePass.toCharArray());
        keyManagers = keyManagerFactory.getKeyManagers();
    }
    // we will only initialize the truststure if properties have been supplied by the SSLContextService
    if (sslService.isTrustStoreConfigured()) {
        // load truststore
        final String truststoreLocation = sslService.getTrustStoreFile();
        final String truststorePass = sslService.getTrustStorePassword();
        final String truststoreType = sslService.getTrustStoreType();
        KeyStore truststore = KeyStore.getInstance(truststoreType);
        truststore.load(new FileInputStream(truststoreLocation), truststorePass.toCharArray());
        trustManagerFactory.init(truststore);
    }
    /*
            TrustManagerFactory.getTrustManagers returns a trust manager for each type of trust material. Since we are getting a trust manager factory that uses "X509"
            as it's trust management algorithm, we are able to grab the first (and thus the most preferred) and use it as our x509 Trust Manager

            https://docs.oracle.com/javase/8/docs/api/javax/net/ssl/TrustManagerFactory.html#getTrustManagers--
         */
    final X509TrustManager x509TrustManager;
    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
    if (trustManagers[0] != null) {
        x509TrustManager = (X509TrustManager) trustManagers[0];
    } else {
        throw new IllegalStateException("List of trust managers is null");
    }
    // if keystore properties were not supplied, the keyManagers array will be null
    sslContext.init(keyManagers, trustManagerFactory.getTrustManagers(), null);
    final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    okHttpClientBuilder.sslSocketFactory(sslSocketFactory, x509TrustManager);
    if (setAsSocketFactory) {
        okHttpClientBuilder.socketFactory(sslSocketFactory);
    }
}
Also used : X509TrustManager(javax.net.ssl.X509TrustManager) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) KeyManager(javax.net.ssl.KeyManager) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager)

Example 58 with SSLSocketFactory

use of javax.net.ssl.SSLSocketFactory in project nifi by apache.

the class HttpNotificationService method init.

@Override
protected void init(final NotificationInitializationContext context) {
    final String url = context.getProperty(PROP_URL).evaluateAttributeExpressions().getValue();
    if (url == null || url.isEmpty()) {
        throw new IllegalArgumentException("Property, \"" + PROP_URL.getDisplayName() + "\", for the URL to POST notifications to must be set.");
    }
    urlReference.set(url);
    httpClientReference.set(null);
    final OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
    Long connectTimeout = context.getProperty(PROP_CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS);
    Long writeTimeout = context.getProperty(PROP_WRITE_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS);
    // Set timeouts
    okHttpClientBuilder.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS);
    okHttpClientBuilder.writeTimeout(writeTimeout, TimeUnit.MILLISECONDS);
    // check if the keystore is set and add the factory if so
    if (url.toLowerCase().startsWith("https")) {
        try {
            SSLSocketFactory sslSocketFactory = getSslSocketFactory(context);
            okHttpClientBuilder.sslSocketFactory(sslSocketFactory);
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }
    httpClientReference.set(okHttpClientBuilder.build());
}
Also used : OkHttpClient(okhttp3.OkHttpClient) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) NotificationFailedException(org.apache.nifi.bootstrap.notification.NotificationFailedException) ProcessException(org.apache.nifi.processor.exception.ProcessException)

Example 59 with SSLSocketFactory

use of javax.net.ssl.SSLSocketFactory in project couchbase-lite-android by couchbase.

the class CBLWebSocket method setupTrustedCertificate.

private void setupTrustedCertificate(OkHttpClient.Builder builder) throws GeneralSecurityException {
    if (options != null && options.containsKey(kC4ReplicatorOptionPinnedServerCert)) {
        byte[] pin = (byte[]) options.get(kC4ReplicatorOptionPinnedServerCert);
        if (pin != null) {
            X509TrustManager trustManager = trustManagerForCertificates(toStream(pin));
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[] { trustManager }, null);
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            if (trustManager != null && sslSocketFactory != null)
                builder.sslSocketFactory(sslSocketFactory, trustManager);
            // custom hostname verifier - allow IP address and empty Common Name (CN).
            builder.hostnameVerifier(CustomHostnameVerifier.getInstance());
        }
    }
}
Also used : X509TrustManager(javax.net.ssl.X509TrustManager) SSLContext(javax.net.ssl.SSLContext) SSLSocketFactory(javax.net.ssl.SSLSocketFactory)

Example 60 with SSLSocketFactory

use of javax.net.ssl.SSLSocketFactory in project bnd by bndtools.

the class HttpsUtil method disableServerVerification.

static void disableServerVerification(URLConnection connection) throws GeneralSecurityException {
    if (!(connection instanceof HttpsURLConnection))
        return;
    HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

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

        public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
        }
    } };
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, trustAllCerts, new SecureRandom());
    SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    httpsConnection.setSSLSocketFactory(sslSocketFactory);
    HostnameVerifier trustAnyHost = new HostnameVerifier() {

        public boolean verify(String string, SSLSession session) {
            return true;
        }
    };
    httpsConnection.setHostnameVerifier(trustAnyHost);
}
Also used : X509TrustManager(javax.net.ssl.X509TrustManager) SSLSession(javax.net.ssl.SSLSession) SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) X509Certificate(java.security.cert.X509Certificate) X509TrustManager(javax.net.ssl.X509TrustManager) TrustManager(javax.net.ssl.TrustManager) HostnameVerifier(javax.net.ssl.HostnameVerifier)

Aggregations

SSLSocketFactory (javax.net.ssl.SSLSocketFactory)403 SSLContext (javax.net.ssl.SSLContext)150 SSLSocket (javax.net.ssl.SSLSocket)134 IOException (java.io.IOException)106 X509TrustManager (javax.net.ssl.X509TrustManager)69 Socket (java.net.Socket)63 TrustManager (javax.net.ssl.TrustManager)56 HostnameVerifier (javax.net.ssl.HostnameVerifier)49 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)48 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)48 Test (org.junit.Test)46 KeyManagementException (java.security.KeyManagementException)45 URL (java.net.URL)41 CertificateException (java.security.cert.CertificateException)39 OkHttpClient (okhttp3.OkHttpClient)39 OutputStream (java.io.OutputStream)35 InputStream (java.io.InputStream)34 X509Certificate (java.security.cert.X509Certificate)34 SSLSession (javax.net.ssl.SSLSession)30 InetSocketAddress (java.net.InetSocketAddress)29