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

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

Introduction

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

Prototype

AllowAllHostnameVerifier

Source Link

Usage

From source file:com.nookdevs.library.FictionwiseBooks.java

private boolean authenticate() {
    String url = AUTH_URL;
    try {//from   www .j av  a  2 s.  co  m
        nookLib.waitForNetwork(lock);
        SSLSocketFactory factory = SSLSocketFactory.getSocketFactory();
        X509HostnameVerifier orgVerifier = factory.getHostnameVerifier();
        factory.setHostnameVerifier(new AllowAllHostnameVerifier());
        HttpPost request = new HttpPost(url);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("loginid", m_User));
        nvps.add(new BasicNameValuePair("password", m_Pass));
        nvps.add(new BasicNameValuePair("login", "Login"));
        request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        HttpResponse response = httpClient.execute(request);
        m_BookShelfHtml = EntityUtils.toString(response.getEntity());
        factory.setHostnameVerifier(orgVerifier);
        m_Auth = true;
        return true;
    } catch (Exception ex) {
        Log.e("FictionwiseBooks", "exception during authentication", ex);
        return false;
    }
}

From source file:org.kontalk.client.KontalkConnection.java

@SuppressLint("AllowAllHostnameVerifier")
private static void setupSSL(XMPPTCPConnectionConfiguration.Builder builder, boolean direct,
        PrivateKey privateKey, X509Certificate bridgeCert, boolean acceptAnyCertificate, KeyStore trustStore) {
    try {/*from  ww  w . jav a  2s.c o m*/
        SSLContext ctx = SSLContext.getInstance("TLS");

        KeyManager[] km = null;
        if (privateKey != null && bridgeCert != null) {
            // in-memory keystore
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            keystore.load(null, null);
            keystore.setKeyEntry("private", privateKey, null, new Certificate[] { bridgeCert });

            // key managers
            KeyManagerFactory kmFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmFactory.init(keystore, null);

            km = kmFactory.getKeyManagers();

            // disable PLAIN mechanism if not upgrading from legacy
            if (!LegacyAuthentication.isUpgrading()) {
                // blacklist PLAIN mechanism
                SASLAuthentication.blacklistSASLMechanism("PLAIN");
            }
        }

        // trust managers
        TrustManager[] tm;

        if (acceptAnyCertificate) {
            tm = new TrustManager[] { new X509TrustManager() {
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

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

                @SuppressLint("TrustAllX509TrustManager")
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                }
            } };
            builder.setHostnameVerifier(new AllowAllHostnameVerifier());
        }

        else {
            // builtin keystore
            TrustManagerFactory tmFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmFactory.init(trustStore);

            tm = tmFactory.getTrustManagers();
        }

        ctx.init(km, tm, null);
        builder.setCustomSSLContext(ctx);
        if (direct)
            builder.setSocketFactory(ctx.getSocketFactory());

        // SASL EXTERNAL is already enabled in Smack
    } catch (Exception e) {
        Log.w(TAG, "unable to setup SSL connection", e);
    }
}

From source file:org.andstatus.app.net.http.TlsSniSocketFactory.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private void connectWithSNI(SSLSocket ssl, String host) throws SSLPeerUnverifiedException {
    // set reasonable SSL/TLS settings before the handshake:
    // - enable all supported protocols (enables TLSv1.1 and TLSv1.2 on Android <4.4.3, if available)
    ssl.setEnabledProtocols(ssl.getSupportedProtocols());

    // - set SNI host name
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        MyLog.d(this, "Using documented SNI with host name " + host);
        sslSocketFactory.setHostname(ssl, host);
    } else {/*from  w  w w  .j  a  v  a2 s  .c  o  m*/
        MyLog.d(this, "No documented SNI support on Android <4.2, trying with reflection");
        try {
            java.lang.reflect.Method setHostnameMethod = ssl.getClass().getMethod("setHostname", String.class);
            setHostnameMethod.invoke(ssl, host);
        } catch (Exception e) {
            MyLog.i(this, "SNI not useable", e);
        }
    }

    // verify hostname and certificate
    SSLSession session = ssl.getSession();
    if (!session.isValid()) {
        MyLog.i(this, "Invalid session to host:'" + host + "'");
    }

    HostnameVerifier hostnameVerifier = secure ? new BrowserCompatHostnameVerifier()
            : new AllowAllHostnameVerifier();
    if (!hostnameVerifier.verify(host, session)) {
        throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host);
    }

    MyLog.i(this, "Established " + session.getProtocol() + " connection with " + session.getPeerHost()
            + " using " + session.getCipherSuite());
}

From source file:android.net.http.AbstractProxyTest.java

private void testConnectViaHttpProxyToHttps(ProxyConfig proxyConfig) throws Exception {
    TestSSLContext testSSLContext = TestSSLContext.create();

    server.useHttps(testSSLContext.serverContext.getSocketFactory(), true);
    server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END).clearHeaders());
    server.enqueue(new MockResponse().setResponseCode(200).setBody("this response comes via a secure proxy"));
    server.play();//w ww  . j  a v  a 2s .c o  m

    HttpClient httpProxyClient = newHttpClient();
    SSLSocketFactory sslSocketFactory = newSslSocketFactory(testSSLContext);
    sslSocketFactory.setHostnameVerifier(new AllowAllHostnameVerifier());
    httpProxyClient.getConnectionManager().getSchemeRegistry()
            .register(new Scheme("https", sslSocketFactory, 443));

    HttpGet request = new HttpGet("https://android.com/foo");
    proxyConfig.configure(server, httpProxyClient, request);

    HttpResponse response = httpProxyClient.execute(request);
    assertEquals("this response comes via a secure proxy", contentToString(response));

    RecordedRequest connect = server.takeRequest();
    assertEquals("Connect line failure on proxy " + proxyConfig, "CONNECT android.com:443 HTTP/1.1",
            connect.getRequestLine());
    assertContains(connect.getHeaders(), "Host: android.com");

    RecordedRequest get = server.takeRequest();
    assertEquals("GET /foo HTTP/1.1", get.getRequestLine());
    assertContains(get.getHeaders(), "Host: android.com");
}

From source file:org.kontalk.upload.KontalkBoxUploadConnection.java

private void setupClient(HttpsURLConnection conn, String mime, boolean encrypted, boolean acceptAnyCertificate)
        throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException,
        KeyManagementException, NoSuchProviderException, IOException {

    conn.setSSLSocketFactory(ClientHTTPConnection.setupSSLSocketFactory(mContext, mPrivateKey, mCertificate,
            acceptAnyCertificate));//  w ww  .  jav a 2s .  c  o  m
    if (acceptAnyCertificate)
        conn.setHostnameVerifier(new AllowAllHostnameVerifier());
    conn.setRequestProperty("Content-Type", mime != null ? mime : "application/octet-stream");
    if (encrypted)
        conn.setRequestProperty(HEADER_MESSAGE_FLAGS, "encrypted");
    // bug caused by Lighttpd
    conn.setRequestProperty("Expect", "100-continue");

    conn.setConnectTimeout(CONNECT_TIMEOUT);
    conn.setReadTimeout(READ_TIMEOUT);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod("POST");
}

From source file:com.googlesource.gerrit.plugins.hooks.rtc.network.RTCClient.java

private void setSSLTrustStrategy(boolean sslVerify) throws IOException {
    try {//from   w  ww.ja va 2s.com
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }

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

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };
        SSLContext sc;

        if (sslVerify) {
            sc = SSLContext.getDefault();
        } else {
            sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new SecureRandom());
        }

        SSLSocketFactory sf = new SSLSocketFactory(sc);
        sf.setHostnameVerifier(new AllowAllHostnameVerifier());
        SchemeRegistry schemeRegistry = httpclient.getConnectionManager().getSchemeRegistry();
        schemeRegistry.register(new Scheme("https", sf, 443));
    } catch (Exception any) {
        throw new IOException(any);
    }
}

From source file:com.tremolosecurity.scale.config.ScaleCommonConfig.java

public HttpClientInfo createHttpClientInfo() {

    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslctx, new AllowAllHostnameVerifier());
    PlainConnectionSocketFactory sf = PlainConnectionSocketFactory.getSocketFactory();
    Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create().register("http", sf)
            .register("https", sslsf).build();

    RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY)
            .setRedirectsEnabled(true).build();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r);

    return new HttpClientInfo(cm, globalConfig);
}

From source file:com.googlesource.gerrit.plugins.its.rtc.network.RTCClient.java

private void setSSLTrustStrategy(boolean sslVerify) throws IOException {
    try {//from  ww w .  j  ava 2  s . c om
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }

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

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };
        SSLContext sc;

        if (sslVerify) {
            sc = SSLContext.getDefault();
        } else {
            sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new SecureRandom());
        }

        SSLSocketFactory sf = new SSLSocketFactory(sc);
        sf.setHostnameVerifier(new AllowAllHostnameVerifier());
        SchemeRegistry schemeRegistry = httpclient.getConnectionManager().getSchemeRegistry();
        schemeRegistry.register(new Scheme("https", sf, 443));
    } catch (Exception any) {
        throw new IOException(any);
    }
}

From source file:ru.anr.base.facade.web.api.RestClient.java

/**
 * Configuring an apache client to support untrusted ssl connections. This
 * can be useful for test purposes only.
 * /*from  w w  w.ja v  a2 s.  com*/
 * @return Apache {@link HttpClient}
 */
private HttpClient buildSSLClient() {

    TrustStrategy acceptingTrustStrategy = new TrustStrategy() {

        @Override
        public boolean isTrusted(X509Certificate[] certificate, String authType) {

            return true;
        }
    };

    try {

        SSLContextBuilder sslBuilder = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy);
        SSLContext sslContext = sslBuilder.useTLS().build();

        SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext,
                new AllowAllHostnameVerifier());
        return HttpClients.custom().setSSLSocketFactory(sf).build();

    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException ex) {
        throw new ApplicationException(ex);
    }
}

From source file:org.votingsystem.util.HttpHelper.java

private HttpHelper() {
    try {/*  w  ww  .  j a v  a 2  s.  com*/
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        SSLContext sslcontext = null;
        SSLConnectionSocketFactory sslsf = null;
        if (ContextVS.getInstance().getVotingSystemSSLCerts() != null) {
            log.info("loading SSLContext with app certificates");
            X509Certificate sslServerCert = ContextVS.getInstance().getVotingSystemSSLCerts().iterator().next();
            trustStore.setCertificateEntry(sslServerCert.getSubjectDN().toString(), sslServerCert);
            sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore).build();
            X509HostnameVerifier hostnameVerifier = (X509HostnameVerifier) new AllowAllHostnameVerifier();
            sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
                    hostnameVerifier);
        } else {
            sslcontext = SSLContexts.createSystemDefault();
            sslsf = new SSLConnectionSocketFactory(sslcontext);
            log.info("loading default SSLContext");
        }
        // Create a registry of custom connection socket factories for supported protocol schemes.
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", sslsf).build();
        //Create socket configuration
        //SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
        //Configure the connection manager to use socket configuration either by default or for a specific host.
        //connManager.setDefaultSocketConfig(socketConfig);
        connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry, connFactory, dnsResolver);
        connManager.setMaxTotal(200);
        connManager.setDefaultMaxPerRoute(100);
        connEvictor = new IdleConnectionEvictor(connManager);
        connEvictor.start();
        HttpRoute httpRouteVS = new HttpRoute(new HttpHost("www.sistemavotacion.org", 80));
        connManager.setMaxPerRoute(httpRouteVS, 200);
        /* timeouts with large simulations ->
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(REQUEST_TIME_OUT)
            .setConnectionRequestTimeout(REQUEST_TIME_OUT).setSocketTimeout(REQUEST_TIME_OUT).build();
        httpClient = HttpClients.custom().setConnectionManager(connManager).setDefaultRequestConfig(
            requestConfig).build();*/
        httpClient = HttpClients.custom().setConnectionManager(connManager).build();
    } catch (Exception ex) {
        log.log(Level.SEVERE, ex.getMessage(), ex);
    }
}