Search in sources :

Example 76 with SSLSocketFactory

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

the class HttpConnector method get.

public HttpURLConnection get(String endpointPath, Map<String, List<String>> headers) throws ConfigurationProviderException {
    String endpointUrl = baseUrl + endpointPath;
    if (logger.isDebugEnabled()) {
        logger.debug("Connecting to endpoint: " + endpointUrl);
    }
    URL url;
    try {
        url = new URL(endpointUrl);
    } catch (MalformedURLException e) {
        throw new ConfigurationProviderException("Malformed url " + endpointUrl, e);
    }
    HttpURLConnection httpURLConnection;
    try {
        if (proxy == null) {
            httpURLConnection = (HttpURLConnection) url.openConnection();
        } else {
            httpURLConnection = (HttpURLConnection) url.openConnection(proxy);
        }
        if (sslContextFactory != null) {
            HttpsURLConnection httpsURLConnection = (HttpsURLConnection) httpURLConnection;
            SSLContext sslContext = sslContextFactory.getSslContext();
            SSLSocketFactory socketFactory = sslContext.getSocketFactory();
            httpsURLConnection.setSSLSocketFactory(socketFactory);
        }
    } catch (IOException e) {
        throw new ConfigurationProviderException("Unable to connect to " + url, e);
    }
    if (proxyAuthorization != null) {
        httpURLConnection.setRequestProperty("Proxy-Authorization", proxyAuthorization);
    }
    headers.forEach((s, strings) -> httpURLConnection.setRequestProperty(s, strings.stream().collect(Collectors.joining(","))));
    return httpURLConnection;
}
Also used : ConfigurationProviderException(org.apache.nifi.minifi.c2.api.ConfigurationProviderException) MalformedURLException(java.net.MalformedURLException) HttpURLConnection(java.net.HttpURLConnection) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) URL(java.net.URL) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 77 with SSLSocketFactory

use of javax.net.ssl.SSLSocketFactory in project BestPracticeApp by pop1234o.

the class Https method getSSLSocketFactory.

public static SSLSocketFactory getSSLSocketFactory() {
    // 创建一个不验证证书的 “信任证书管理器”
    TrustManager[] manager = new TrustManager[] { new X509TrustManager() {

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    } };
    try {
        SSLContext tls = SSLContext.getInstance("TLS");
        tls.init(null, manager, new SecureRandom());
        SSLSocketFactory socketFactory = tls.getSocketFactory();
        return socketFactory;
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return null;
}
Also used : X509TrustManager(javax.net.ssl.X509TrustManager) SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) X509Certificate(java.security.cert.X509Certificate) KeyManagementException(java.security.KeyManagementException) X509TrustManager(javax.net.ssl.X509TrustManager) TrustManager(javax.net.ssl.TrustManager)

Example 78 with SSLSocketFactory

use of javax.net.ssl.SSLSocketFactory in project apm-agent-java by elastic.

the class ReporterFactory method disableCertificateValidation.

// based on https://gist.github.com/mefarazath/c9b588044d6bffd26aac3c520660bf40
private void disableCertificateValidation(OkHttpClient.Builder builder) {
    // Create a trust manager that does not validate certificate chains
    final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

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

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    } };
    try {
        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]).hostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
    } catch (KeyManagementException | NoSuchAlgorithmException e) {
        logger.warn(e.getMessage(), e);
    }
}
Also used : SSLSession(javax.net.ssl.SSLSession) SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) X509Certificate(java.security.cert.X509Certificate) KeyManagementException(java.security.KeyManagementException) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) HostnameVerifier(javax.net.ssl.HostnameVerifier) X509TrustManager(javax.net.ssl.X509TrustManager) SSLSocketFactory(javax.net.ssl.SSLSocketFactory)

Example 79 with SSLSocketFactory

use of javax.net.ssl.SSLSocketFactory in project photon-model by vmware.

the class CertificateUtil method resolveCertificate.

public static X509TrustManagerResolver resolveCertificate(URI uri, Proxy proxy, String proxyUsername, String proxyPassword, long timeoutMillis) {
    logger.entering(logger.getName(), "resolveCertificate");
    X509TrustManagerResolver trustManagerResolver = new X509TrustManagerResolver();
    SSLContext sslContext;
    try {
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[] { trustManagerResolver }, null);
    } catch (KeyManagementException | NoSuchAlgorithmException e) {
        logger.throwing(logger.getName(), "connect", e);
        throw new LocalizableValidationException(e, "Failed to initialize SSL context.", "security.certificate.context.init.error");
    }
    String hostAddress = uri.getHost();
    int port = uri.getPort() == -1 ? DEFAULT_SECURE_CONNECTION_PORT : uri.getPort();
    String uriScheme = uri.getScheme();
    String host = String.format("%s://%s:%d", uriScheme, hostAddress, port);
    try {
        SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        if (proxy != null && proxy.type() == Type.HTTP && proxyUsername != null && UriUtils.HTTPS_SCHEME.equalsIgnoreCase(uriScheme)) {
            URL url = uri.toURL();
            handleCertForHttpsThroughHttpProxyWithAuth(url, proxy, proxyUsername, proxyPassword, timeoutMillis, sslSocketFactory);
        } else {
            SSLSocket sslSocket;
            if (proxy != null) {
                if (proxyUsername != null) {
                    throw new LocalizableValidationException("Proxy authentication supported " + "for HTTPS URI through HTTP Proxy only." + " URI: " + uri.toASCIIString() + ", Proxy: " + proxy.toString(), "security.certificate.proxy.authentication.not.supported.error", uri.toASCIIString(), proxy.toString());
                }
                Socket tunnel = new Socket(proxy);
                tunnel.connect(new InetSocketAddress(hostAddress, port), (int) timeoutMillis);
                sslSocket = (SSLSocket) sslSocketFactory.createSocket(tunnel, hostAddress, port, true);
            } else {
                sslSocket = (SSLSocket) sslSocketFactory.createSocket();
                if (SSL_CONNECT_USE_SNI) {
                    SNIHostName serverName = new SNIHostName(hostAddress);
                    List<SNIServerName> serverNames = new ArrayList<>(1);
                    serverNames.add(serverName);
                    SSLParameters params = sslSocket.getSSLParameters();
                    params.setServerNames(serverNames);
                    sslSocket.setSSLParameters(params);
                }
                sslSocket.connect(new InetSocketAddress(hostAddress, port), (int) timeoutMillis);
            }
            SSLSession session = sslSocket.getSession();
            session.invalidate();
        }
    } catch (IOException e) {
        try {
            if (trustManagerResolver.isCertsTrusted() || trustManagerResolver.getCertificateChain().length == 0) {
                Utils.logWarning("Exception while resolving certificate for host: [%s]. Error: %s ", host, e.getMessage());
            } else {
                logger.throwing(logger.getName(), "connect", e);
                throw new IllegalArgumentException(e.getMessage(), e);
            }
        } catch (IllegalStateException ise) {
            throw new LocalizableValidationException(e, String.format("Cannot connect to host: [%s]. Error: %s", host, e.getMessage()), "security.certificate.connection.error", host, e.getMessage());
        }
    }
    if (trustManagerResolver.getCertificateChain().length == 0) {
        LocalizableValidationException e = new LocalizableValidationException("Check ssl certificate failed for server: " + host, "security.certificate.check.error", host);
        logger.throwing(logger.getName(), "connect", e);
        throw e;
    }
    logger.exiting(logger.getName(), "resolveCertificate");
    return trustManagerResolver;
}
Also used : LocalizableValidationException(com.vmware.xenon.common.LocalizableValidationException) InetSocketAddress(java.net.InetSocketAddress) SSLSocket(javax.net.ssl.SSLSocket) ArrayList(java.util.ArrayList) SSLSession(javax.net.ssl.SSLSession) SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) DEROctetString(org.bouncycastle.asn1.DEROctetString) IOException(java.io.IOException) CertIOException(org.bouncycastle.cert.CertIOException) KeyManagementException(java.security.KeyManagementException) URL(java.net.URL) SNIServerName(javax.net.ssl.SNIServerName) SSLParameters(javax.net.ssl.SSLParameters) SNIHostName(javax.net.ssl.SNIHostName) X509TrustManagerResolver(com.vmware.photon.controller.model.security.ssl.X509TrustManagerResolver) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) SSLSocket(javax.net.ssl.SSLSocket) Socket(java.net.Socket)

Example 80 with SSLSocketFactory

use of javax.net.ssl.SSLSocketFactory in project box-android-sdk by box.

the class BoxRequest method onSend.

/**
 * Synchronously make the request to Box and handle the response appropriately.
 * @return the expected BoxObject if the request is successful.
 * @throws BoxException thrown if there was a problem with handling the request.
 */
protected T onSend() throws BoxException {
    BoxRequest.BoxRequestHandler requestHandler = getRequestHandler();
    BoxHttpResponse response = null;
    HttpURLConnection connection = null;
    try {
        // Create the HTTP request and send it
        BoxHttpRequest request = createHttpRequest();
        connection = request.getUrlConnection();
        if (mRequiresSocket && connection instanceof HttpsURLConnection) {
            final SSLSocketFactory factory = ((HttpsURLConnection) connection).getSSLSocketFactory();
            SSLSocketFactoryWrapper wrappedFactory = new SSLSocketFactoryWrapper(factory);
            mSocketFactoryRef = new WeakReference<SSLSocketFactoryWrapper>(wrappedFactory);
            ((HttpsURLConnection) connection).setSSLSocketFactory(wrappedFactory);
        }
        if (mTimeout > 0) {
            connection.setConnectTimeout(mTimeout);
            connection.setReadTimeout(mTimeout);
        }
        response = sendRequest(request, connection);
        logDebug(response);
        // Process the response through the provided handler
        if (requestHandler.isResponseSuccess(response)) {
            T result = (T) requestHandler.onResponse(mClazz, response);
            return result;
        }
        throw new BoxException("An error occurred while sending the request", response);
    } catch (IOException e) {
        return handleSendException(requestHandler, response, e);
    } catch (InstantiationException e) {
        return handleSendException(requestHandler, response, e);
    } catch (IllegalAccessException e) {
        return handleSendException(requestHandler, response, e);
    } catch (BoxException e) {
        return handleSendException(requestHandler, response, e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}
Also used : BoxException(com.box.androidsdk.content.BoxException) IOException(java.io.IOException) HttpURLConnection(java.net.HttpURLConnection) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

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