Example usage for org.apache.http.conn.ssl StrictHostnameVerifier StrictHostnameVerifier

List of usage examples for org.apache.http.conn.ssl StrictHostnameVerifier StrictHostnameVerifier

Introduction

In this page you can find the example usage for org.apache.http.conn.ssl StrictHostnameVerifier StrictHostnameVerifier.

Prototype

StrictHostnameVerifier

Source Link

Usage

From source file:org.opensaml.security.httpclient.impl.SecurityEnhancedTLSSocketFactoryTest.java

@Test(expectedExceptions = SSLPeerUnverifiedException.class)
public void testFailNoCertsInSession() throws IOException {
    X509Credential cred = getCredential("foo-1A1-good.crt");
    ExplicitKeyTrustEngine trustEngine = new ExplicitKeyTrustEngine(new StaticCredentialResolver(cred));
    httpContext.setAttribute(HttpClientSecurityConstants.CONTEXT_KEY_TRUST_ENGINE, trustEngine);

    // Pass an empty cert list, to simulate unlikely condition of SSLSession not having any peerCertificates
    securityEnhancedSocketFactory = new SecurityEnhancedTLSSocketFactory(
            buildInnerSSLFactory(new ArrayList<Certificate>(), hostname), new StrictHostnameVerifier());
    Socket socket = securityEnhancedSocketFactory.createSocket(httpContext);

    securityEnhancedSocketFactory.connectSocket(0, socket, new HttpHost(hostname, 443, "https"), null, null,
            httpContext);//  w ww  .  j ava  2  s.co  m
}

From source file:net.shibboleth.idp.profile.spring.relyingparty.metadata.impl.AbstractDynamicHTTPMetadataProviderParser.java

/**
 * Build the definition of the HTTPClientBuilder which contains all our configuration.
 * //from   w  w w. j a  va  2 s.  com
 * @param element the HTTPMetadataProvider parser.
 * @param parserContext thee context
 * @param haveTLSTrustEngine whether have a TLS TrustEngine configured
 * @return the bean definition with the parameters.
 */
// Checkstyle: CyclomaticComplexity OFF
// Checkstyle: MethodLength OFF
private BeanDefinition buildHttpClient(Element element, ParserContext parserContext,
        boolean haveTLSTrustEngine) {
    String caching = DEFAULT_CACHING;
    if (element.hasAttributeNS(null, "httpCaching")) {
        caching = StringSupport.trimOrNull(element.getAttributeNS(null, "httpCaching"));
    }

    BeanDefinitionBuilder clientBuilder = null;
    switch (caching) {
    case "none":
        clientBuilder = BeanDefinitionBuilder.genericBeanDefinition(HttpClientFactoryBean.class);
        break;
    case "file":
        clientBuilder = BeanDefinitionBuilder.genericBeanDefinition(FileCachingHttpClientFactoryBean.class);
        if (element.hasAttributeNS(null, "httpCacheDirectory")) {
            clientBuilder.addPropertyValue("cacheDirectory",
                    StringSupport.trimOrNull(element.getAttributeNS(null, "httpCacheDirectory")));
        }
        if (element.hasAttributeNS(null, "httpMaxCacheEntries")) {
            clientBuilder.addPropertyValue("maxCacheEntries",
                    StringSupport.trimOrNull(element.getAttributeNS(null, "httpMaxCacheEntries")));
        }
        if (element.hasAttributeNS(null, "httpMaxCacheEntrySize")) {
            clientBuilder.addPropertyValue("maxCacheEntrySize",
                    StringSupport.trimOrNull(element.getAttributeNS(null, "httpMaxCacheEntrySize")));
        }
        break;
    case "memory":
        clientBuilder = BeanDefinitionBuilder.genericBeanDefinition(InMemoryCachingHttpClientFactoryBean.class);
        if (element.hasAttributeNS(null, "httpMaxCacheEntries")) {
            clientBuilder.addPropertyValue("maxCacheEntries",
                    StringSupport.trimOrNull(element.getAttributeNS(null, "httpMaxCacheEntries")));
        }
        if (element.hasAttributeNS(null, "httpMaxCacheEntrySize")) {
            clientBuilder.addPropertyValue("maxCacheEntrySize",
                    StringSupport.trimOrNull(element.getAttributeNS(null, "httpMaxCacheEntrySize")));
        }
        break;
    default:
        throw new BeanDefinitionParsingException(
                new Problem(String.format("Caching value '%s' is unsupported", caching),
                        new Location(parserContext.getReaderContext().getResource())));
    }

    clientBuilder.setLazyInit(true);

    if (element.hasAttributeNS(null, "requestTimeout")) {
        clientBuilder.addPropertyValue("connectionTimeout",
                StringSupport.trimOrNull(element.getAttributeNS(null, "requestTimeout")));
    }

    if (haveTLSTrustEngine) {
        clientBuilder.addPropertyValue("tLSSocketFactory", new SecurityEnhancedTLSSocketFactory(
                HttpClientSupport.buildNoTrustTLSSocketFactory(), new StrictHostnameVerifier()));
    }

    if (element.hasAttributeNS(null, "disregardTLSCertificate")) {
        clientBuilder.addPropertyValue("connectionDisregardTLSCertificate",
                StringSupport.trimOrNull(element.getAttributeNS(null, "disregardTLSCertificate")));
    } else if (element.hasAttributeNS(null, "disregardSslCertificate")) {
        log.warn("disregardSslCertificate is deprecated, please switch to disregardTLSCertificate");
        clientBuilder.addPropertyValue("connectionDisregardTLSCertificate",
                StringSupport.trimOrNull(element.getAttributeNS(null, "disregardSslCertificate")));
    }

    if (element.hasAttributeNS(null, "proxyHost")) {
        clientBuilder.addPropertyValue("connectionProxyHost",
                StringSupport.trimOrNull(element.getAttributeNS(null, "proxyHost")));
    }

    if (element.hasAttributeNS(null, "proxyPort")) {
        clientBuilder.addPropertyValue("connectionProxyPort",
                StringSupport.trimOrNull(element.getAttributeNS(null, "proxyPort")));
    }

    if (element.hasAttributeNS(null, "proxyUser")) {
        clientBuilder.addPropertyValue("connectionProxyUsername",
                StringSupport.trimOrNull(element.getAttributeNS(null, "proxyUser")));
    }

    if (element.hasAttributeNS(null, "proxyPassword")) {
        clientBuilder.addPropertyValue("connectionProxyPassword",
                element.getAttributeNS(null, "proxyPassword"));
    }

    return clientBuilder.getBeanDefinition();
}

From source file:com.irccloud.android.HTTPFetcher.java

private void http_thread() {
    try {/* w w w.j  a va2  s.  c  o m*/
        mThread.setName("http-stream-thread");
        int port = (mURI.getPort() != -1) ? mURI.getPort() : (mURI.getProtocol().equals("https") ? 443 : 80);

        String path = TextUtils.isEmpty(mURI.getPath()) ? "/" : mURI.getPath();
        if (!TextUtils.isEmpty(mURI.getQuery())) {
            path += "?" + mURI.getQuery();
        }

        PrintWriter out = new PrintWriter(mSocket.getOutputStream());

        if (mProxyHost != null && mProxyHost.length() > 0 && mProxyPort > 0) {
            out.print("CONNECT " + mURI.getHost() + ":" + port + " HTTP/1.0\r\n");
            out.print("\r\n");
            out.flush();
            HybiParser.HappyDataInputStream stream = new HybiParser.HappyDataInputStream(
                    mSocket.getInputStream());

            // Read HTTP response status line.
            StatusLine statusLine = parseStatusLine(readLine(stream));
            if (statusLine == null) {
                throw new HttpException("Received no reply from server.");
            } else if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
                throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
            }

            // Read HTTP response headers.
            while (!TextUtils.isEmpty(readLine(stream)))
                ;
            if (mURI.getProtocol().equals("https")) {
                mSocket = getSSLSocketFactory().createSocket(mSocket, mURI.getHost(), port, false);
                SSLSocket s = (SSLSocket) mSocket;
                try {
                    s.setEnabledProtocols(ENABLED_PROTOCOLS);
                } catch (IllegalArgumentException e) {
                    //Not supported on older Android versions
                }
                try {
                    s.setEnabledCipherSuites(ENABLED_CIPHERS);
                } catch (IllegalArgumentException e) {
                    //Not supported on older Android versions
                }
                out = new PrintWriter(mSocket.getOutputStream());
            }
        }

        if (mURI.getProtocol().equals("https")) {
            SSLSocket s = (SSLSocket) mSocket;
            StrictHostnameVerifier verifier = new StrictHostnameVerifier();
            if (!verifier.verify(mURI.getHost(), s.getSession()))
                throw new SSLException("Hostname mismatch");
        }

        Crashlytics.log(Log.DEBUG, TAG, "Sending HTTP request");

        out.print("GET " + path + " HTTP/1.0\r\n");
        out.print("Host: " + mURI.getHost() + "\r\n");
        if (mURI.getHost().equals(NetworkConnection.IRCCLOUD_HOST)
                && NetworkConnection.getInstance().session != null
                && NetworkConnection.getInstance().session.length() > 0)
            out.print("Cookie: session=" + NetworkConnection.getInstance().session + "\r\n");
        out.print("Connection: close\r\n");
        out.print("Accept-Encoding: gzip\r\n");
        out.print("User-Agent: " + NetworkConnection.getInstance().useragent + "\r\n");
        out.print("\r\n");
        out.flush();

        HybiParser.HappyDataInputStream stream = new HybiParser.HappyDataInputStream(mSocket.getInputStream());

        // Read HTTP response status line.
        StatusLine statusLine = parseStatusLine(readLine(stream));
        if (statusLine != null)
            Crashlytics.log(Log.DEBUG, TAG, "Got HTTP response: " + statusLine);

        if (statusLine == null) {
            throw new HttpException("Received no reply from server.");
        } else if (statusLine.getStatusCode() != HttpStatus.SC_OK
                && statusLine.getStatusCode() != HttpStatus.SC_MOVED_PERMANENTLY) {
            Crashlytics.log(Log.ERROR, TAG, "Failure: " + mURI + ": " + statusLine.getStatusCode() + " "
                    + statusLine.getReasonPhrase());
            throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
        }

        // Read HTTP response headers.
        String line;

        boolean gzipped = false;
        while (!TextUtils.isEmpty(line = readLine(stream))) {
            Header header = parseHeader(line);
            if (header.getName().equalsIgnoreCase("content-encoding")
                    && header.getValue().equalsIgnoreCase("gzip"))
                gzipped = true;
            if (statusLine.getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY
                    && header.getName().equalsIgnoreCase("location")) {
                Crashlytics.log(Log.INFO, TAG, "Redirecting to: " + header.getValue());
                mURI = new URL(header.getValue());
                mSocket.close();
                mSocket = null;
                mThread = null;
                connect();
                return;
            }
        }

        if (gzipped)
            onStreamConnected(new GZIPInputStream(mSocket.getInputStream()));
        else
            onStreamConnected(mSocket.getInputStream());

        onFetchComplete();
    } catch (Exception ex) {
        NetworkConnection.printStackTraceToCrashlytics(ex);
        onFetchFailed();
    }
}

From source file:org.switchyard.component.resteasy.util.ClientInvoker.java

private SSLSocketFactory getSSLSocketFactory(SSLContextModel sslContextConfig) {
    SSLSocketFactory sslFactory = null;
    if (sslContextConfig != null) {
        X509HostnameVerifier verifier = null;
        if (sslContextConfig.getVerifier() != null) {
            if (sslContextConfig.getVerifier().equals(ANY)) {
                verifier = new AllowAllHostnameVerifier();
            } else if (sslContextConfig.getVerifier().equals(BROWSER)) {
                verifier = new BrowserCompatHostnameVerifier();
            } else if (sslContextConfig.getVerifier().equals(STRICT)) {
                verifier = new StrictHostnameVerifier();
            }//from  ww  w .  ja va  2 s.co m
        }
        KeyStore truststore = null;
        KeyStore keystore = null;
        if (sslContextConfig.getTruststore() != null) {
            FileInputStream instream = null;
            try {
                truststore = KeyStore.getInstance(KeyStore.getDefaultType());
                instream = new FileInputStream(new File(sslContextConfig.getTruststore()));
                truststore.load(instream, sslContextConfig.getTruststorePass().toCharArray());
            } catch (Exception e) {
                throw RestEasyMessages.MESSAGES.unexpectedExceptionLoadingTruststore(e);
            } finally {
                if (instream != null) {
                    try {
                        instream.close();
                    } catch (IOException ioe) {
                        throw RestEasyMessages.MESSAGES.unexpectedExceptionClosingTruststore(ioe);
                    }
                }
            }
        }
        if (sslContextConfig.getKeystore() != null) {
            FileInputStream instream = null;
            try {
                keystore = KeyStore.getInstance(KeyStore.getDefaultType());
                instream = new FileInputStream(new File(sslContextConfig.getKeystore()));
                keystore.load(instream, sslContextConfig.getKeystorePass().toCharArray());
            } catch (Exception e) {
                throw RestEasyMessages.MESSAGES.unexpectedExceptionLoadingKeystore(e);
            } finally {
                if (instream != null) {
                    try {
                        instream.close();
                    } catch (IOException ioe) {
                        throw RestEasyMessages.MESSAGES.unexpectedExceptionClosingKeystore(ioe);
                    }
                }
            }
        }
        try {
            sslFactory = new SSLSocketFactory(SSLSocketFactory.TLS, keystore,
                    sslContextConfig.getKeystorePass(), truststore, null, verifier);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    return sslFactory;
}

From source file:nl.esciencecenter.ptk.web.WebClient.java

protected void initHTTPS() throws CertificateStoreException {
    // Create SSL Socket factory with custom Certificate Store.
    // Default protocol is TLS (newer when SSL).
    // SSLContext sslContext = certStore.createSSLContext("SSLv3");
    SSLContext sslContext = certStore.createSSLContext(SslConst.PROTOCOL_TLS);
    AbstractVerifier verifier;/*  w  ww. ja v a 2  s  .com*/

    if (config.sslOptions.disable_strict_hostname_checking) {
        verifier = new AllowAllHostnameVerifier();
    } else {
        verifier = new StrictHostnameVerifier();
    }

    // Create and register HTTPS socket factory
    SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext, verifier);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("https", config.getPort(), socketFactory));
    ClientConnectionManager manager = this.httpClient.getConnectionManager();
    manager.getSchemeRegistry().register(new Scheme("https", config.getPort(), socketFactory));
}

From source file:com.centurylink.cloud.sdk.core.client.SdkClientBuilder.java

private X509HostnameVerifier initHostnameVerifier() {
    X509HostnameVerifier verifier = null;
    if (this.verifier != null) {
        verifier = new VerifierWrapper(this.verifier);
    } else {/*from   w ww  .j  a v a 2s . c o m*/
        switch (policy) {
        case ANY:
            verifier = new AllowAllHostnameVerifier();
            break;
        case WILDCARD:
            verifier = new BrowserCompatHostnameVerifier();
            break;
        case STRICT:
            verifier = new StrictHostnameVerifier();
            break;
        }
    }

    return verifier;
}

From source file:org.whispersystems.textsecure.push.PushServiceSocket.java

private HttpURLConnection getConnection(String urlFragment, String method, String body)
        throws PushNetworkException {
    try {//from   w  w  w  .  j a  v a 2 s  . c o m
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, trustManagers, null);

        URL url = new URL(String.format("%s%s", serviceUrl, urlFragment));
        Log.w("PushServiceSocket", "Push service URL: " + serviceUrl);
        Log.w("PushServiceSocket", "Opening URL: " + url);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        if (ENFORCE_SSL) {
            ((HttpsURLConnection) connection).setSSLSocketFactory(context.getSocketFactory());
            ((HttpsURLConnection) connection).setHostnameVerifier(new StrictHostnameVerifier());
        }

        connection.setRequestMethod(method);
        connection.setRequestProperty("Content-Type", "application/json");

        if (password != null) {
            connection.setRequestProperty("Authorization", getAuthorizationHeader());
        }

        if (body != null) {
            connection.setDoOutput(true);
        }

        connection.connect();

        if (body != null) {
            Log.w("PushServiceSocket", method + "  --  " + body);
            OutputStream out = connection.getOutputStream();
            out.write(body.getBytes());
            out.close();
        }

        return connection;
    } catch (IOException e) {
        throw new PushNetworkException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new AssertionError(e);
    } catch (KeyManagementException e) {
        throw new AssertionError(e);
    }
}

From source file:org.whispersystems.signalservice.internal.push.PushServiceSocket.java

private Response getConnection(String urlFragment, String method, String body) throws PushNetworkException {
    try {//from w w  w  .  j  av  a  2  s  .c om
        Log.w(TAG, "Push service URL: " + serviceUrl.getUrl());
        Log.w(TAG, "Opening URL: " + String.format("%s%s", serviceUrl.getUrl(), urlFragment));

        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, trustManagers, null);

        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setSslSocketFactory(context.getSocketFactory());
        okHttpClient.setHostnameVerifier(new StrictHostnameVerifier());

        Request.Builder request = new Request.Builder();
        request.url(String.format("%s%s", serviceUrl.getUrl(), urlFragment));

        if (body != null) {
            request.method(method, RequestBody.create(MediaType.parse("application/json"), body));
        } else {
            request.method(method, null);
        }

        if (credentialsProvider.getPassword() != null) {
            request.addHeader("Authorization", getAuthorizationHeader());
        }

        if (userAgent != null) {
            request.addHeader("X-Signal-Agent", userAgent);
        }

        if (serviceUrl.getHostHeader().isPresent()) {
            okHttpClient.networkInterceptors().add(new HostInterceptor(serviceUrl.getHostHeader().get()));
        }

        return okHttpClient.newCall(request.build()).execute();
    } catch (IOException e) {
        throw new PushNetworkException(e);
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        throw new AssertionError(e);
    }
}

From source file:org.whispersystems.textsecure.internal.push.PushServiceSocket.java

private HttpURLConnection getConnection(String urlFragment, String method, String body)
        throws PushNetworkException {
    try {/*from www. j  ava  2s  . c o  m*/
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, trustManagers, null);

        URL url = new URL(String.format("%s%s", serviceUrl, urlFragment));
        Log.w(TAG, "Push service URL: " + serviceUrl);
        Log.w(TAG, "Opening URL: " + url);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        if (ENFORCE_SSL) {
            ((HttpsURLConnection) connection).setSSLSocketFactory(context.getSocketFactory());
            ((HttpsURLConnection) connection).setHostnameVerifier(new StrictHostnameVerifier());
        }

        connection.setRequestMethod(method);
        connection.setRequestProperty("Content-Type", "application/json");

        if (credentialsProvider.getPassword() != null) {
            connection.setRequestProperty("Authorization", getAuthorizationHeader());
        }

        if (userAgent != null) {
            connection.setRequestProperty("X-Signal-Agent", userAgent);
        }

        if (body != null) {
            connection.setDoOutput(true);
        }

        connection.connect();

        if (body != null) {
            Log.w(TAG, method + "  --  " + body);
            OutputStream out = connection.getOutputStream();
            out.write(body.getBytes());
            out.close();
        }

        return connection;
    } catch (IOException e) {
        throw new PushNetworkException(e);
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        throw new AssertionError(e);
    }
}