Example usage for org.apache.http.conn.ssl SSLSocketFactory STRICT_HOSTNAME_VERIFIER

List of usage examples for org.apache.http.conn.ssl SSLSocketFactory STRICT_HOSTNAME_VERIFIER

Introduction

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

Prototype

X509HostnameVerifier STRICT_HOSTNAME_VERIFIER

To view the source code for org.apache.http.conn.ssl SSLSocketFactory STRICT_HOSTNAME_VERIFIER.

Click Source Link

Usage

From source file:org.thoughtcrime.ssl.pinning.PinningSSLSocketFactory.java

@Override
public Socket createSocket(final Socket socket, final String host, int port, final boolean autoClose)
        throws IOException {
    if (port == -1) {
        port = 443;/*w w w  .  j ava  2s  . c o m*/
    }

    final SSLSocket sslSocket = (SSLSocket) pinningSocketFactory.createSocket(socket, host, port, autoClose);
    SSLSocketFactory.STRICT_HOSTNAME_VERIFIER.verify(host, sslSocket);
    return sslSocket;
}

From source file:org.thoughtcrime.ssl.pinning.PinningSSLSocketFactory.java

@Override
public X509HostnameVerifier getHostnameVerifier() {
    return SSLSocketFactory.STRICT_HOSTNAME_VERIFIER;
}

From source file:com.mindprotectionkit.freephone.signaling.SignalingSocket.java

private Socket constructSSLSocket(Context context, String host, int port) throws SignalingException {
    try {//from  ww w.  jav  a 2s.c  o  m
        AssetManager assetManager = context.getAssets();
        InputStream keyStoreInputStream = assetManager.open("whisper.store");
        KeyStore trustStore = KeyStore.getInstance("BKS");

        trustStore.load(keyStoreInputStream, "whisper".toCharArray());

        SSLSocketFactory sslSocketFactory = new SSLSocketFactory(trustStore);

        if (Release.SSL) {
            sslSocketFactory.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
        } else {
            Log.w("SignalingSocket", "Disabling hostname verification...");
            sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        }

        return timeoutHackConnect(sslSocketFactory, host, port);
    } catch (IOException ioe) {
        throw new SignalingException(ioe);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException(e);
    } catch (KeyStoreException e) {
        throw new IllegalArgumentException(e);
    } catch (CertificateException e) {
        throw new IllegalArgumentException(e);
    } catch (KeyManagementException e) {
        throw new IllegalArgumentException(e);
    } catch (UnrecoverableKeyException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:org.apache.marmotta.ldclient.services.ldclient.LDClient.java

public LDClient(ClientConfiguration config) {
    log.info("Initialising Linked Data Client Service ...");

    this.config = config;

    endpoints = new ArrayList<>();
    for (Endpoint endpoint : defaultEndpoints) {
        endpoints.add(endpoint);/*w  w w .j  av  a  2  s .c  om*/
    }
    endpoints.addAll(config.getEndpoints());

    Collections.sort(endpoints);
    if (log.isInfoEnabled()) {
        for (Endpoint endpoint : endpoints) {
            log.info("- LDClient Endpoint: {}", endpoint.getName());
        }
    }

    providers = new ArrayList<>();
    for (DataProvider provider : defaultProviders) {
        providers.add(provider);
    }
    providers.addAll(config.getProviders());
    if (log.isInfoEnabled()) {
        for (DataProvider provider : providers) {
            log.info("- LDClient Provider: {}", provider.getName());
        }
    }

    retrievalSemaphore = new Semaphore(config.getMaxParallelRequests());

    if (config.getHttpClient() != null) {
        log.debug("Using HttpClient provided in the configuration");
        this.client = config.getHttpClient();
    } else {
        log.debug("Creating default HttpClient based on the configuration");

        HttpParams httpParams = new BasicHttpParams();
        httpParams.setParameter(CoreProtocolPNames.USER_AGENT, "Apache Marmotta LDClient");

        httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeout());
        httpParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout());

        httpParams.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
        httpParams.setIntParameter(ClientPNames.MAX_REDIRECTS, 3);

        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));

        try {
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, null, null);
            SSLSocketFactory sf = new SSLSocketFactory(sslcontext, SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);

            schemeRegistry.register(new Scheme("https", 443, sf));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }

        PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
        cm.setMaxTotal(20);
        cm.setDefaultMaxPerRoute(10);

        DefaultHttpClient client = new DefaultHttpClient(cm, httpParams);
        client.setRedirectStrategy(new LMFRedirectStrategy());
        client.setHttpRequestRetryHandler(new LMFHttpRequestRetryHandler());
        idleConnectionMonitorThread = new IdleConnectionMonitorThread(client.getConnectionManager());
        idleConnectionMonitorThread.start();

        this.client = client;
    }
}

From source file:com.example.bbbbbb.http.sample.util.SecureSocketFactory.java

/**
 * Instantiate a new secured factory pertaining to the passed store. Be sure to initialize the
 * store with the password using {@link KeyStore#load(InputStream,
 * char[])} method.//  w  w w  .j  a  v  a  2s.  c  om
 *
 * @param store The key store holding the certificate details
 * @param alias The alias of the certificate to use
 */
public SecureSocketFactory(KeyStore store, String alias) throws CertificateException, NoSuchAlgorithmException,
        KeyManagementException, KeyStoreException, UnrecoverableKeyException {

    super(store);

    // Loading the CA certificate from store.
    final Certificate rootca = store.getCertificate(alias);

    // Turn it to X509 format.
    InputStream is = new ByteArrayInputStream(rootca.getEncoded());
    X509Certificate x509ca = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(is);
    AsyncHttpClient.silentCloseInputStream(is);

    if (null == x509ca) {
        throw new CertificateException("Embedded SSL certificate has expired.");
    }

    // Check the CA's validity.
    x509ca.checkValidity();

    // Accepted CA is only the one installed in the store.
    acceptedIssuers = new X509Certificate[] { x509ca };

    sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(null, new TrustManager[] { new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            Exception error = null;

            if (null == chain || 0 == chain.length) {
                error = new CertificateException("Certificate chain is invalid.");
            } else if (null == authType || 0 == authType.length()) {
                error = new CertificateException("Authentication type is invalid.");
            } else {
                Log.i(LOG_TAG, "Chain includes " + chain.length + " certificates.");
                try {
                    for (X509Certificate cert : chain) {
                        Log.i(LOG_TAG, "Server Certificate Details:");
                        Log.i(LOG_TAG, "---------------------------");
                        Log.i(LOG_TAG, "IssuerDN: " + cert.getIssuerDN().toString());
                        Log.i(LOG_TAG, "SubjectDN: " + cert.getSubjectDN().toString());
                        Log.i(LOG_TAG, "Serial Number: " + cert.getSerialNumber());
                        Log.i(LOG_TAG, "Version: " + cert.getVersion());
                        Log.i(LOG_TAG, "Not before: " + cert.getNotBefore().toString());
                        Log.i(LOG_TAG, "Not after: " + cert.getNotAfter().toString());
                        Log.i(LOG_TAG, "---------------------------");

                        // Make sure that it hasn't expired.
                        cert.checkValidity();

                        // Verify the certificate's public key chain.
                        cert.verify(rootca.getPublicKey());
                    }
                } catch (InvalidKeyException e) {
                    error = e;
                } catch (NoSuchAlgorithmException e) {
                    error = e;
                } catch (NoSuchProviderException e) {
                    error = e;
                } catch (SignatureException e) {
                    error = e;
                }
            }
            if (null != error) {
                Log.e(LOG_TAG, "Certificate error", error);
                throw new CertificateException(error);
            }
        }

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

    setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
}

From source file:com.fine47.http.SecureSocketFactory.java

private SecureSocketFactory(String factoryId, KeyStore store, String alias) throws CertificateException,
        NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    super(store);

    // Loading the CA certificate from store.
    Certificate rootca = store.getCertificate(alias);

    // Turn it to X509 format.
    InputStream is = new ByteArrayInputStream(rootca.getEncoded());
    X509Certificate x509ca = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(is);
    ActivityHttpClient.silentCloseInputStream(is);

    if (null == x509ca) {
        throw new CertificateException("Found expired SSL certificate in this store: " + factoryId);
    }/* w  ww  . j  av a  2  s .  c  o m*/

    // Check the CA's validity.
    x509ca.checkValidity();

    // Accepted CA is only the one installed in the store.
    acceptedIssuers = new X509Certificate[] { x509ca };

    // Get the public key.
    publicKey = rootca.getPublicKey();

    sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(null, new TrustManager[] { new X509TrustManager() {

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

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            Exception error = null;

            if (null == chain || 0 == chain.length) {
                error = new CertificateException("Certificate chain is invalid");
            } else if (null == authType || 0 == authType.length()) {
                error = new CertificateException("Authentication type is invalid");
            } else
                try {
                    for (X509Certificate cert : chain) {
                        if (ActivityHttpClient.isDebugging()) {
                            Log.d(ActivityHttpClient.LOG_TAG, "Server Certificate Details:");
                            Log.d(ActivityHttpClient.LOG_TAG, "---------------------------");
                            Log.d(ActivityHttpClient.LOG_TAG, "IssuerDN: " + cert.getIssuerDN().toString());
                            Log.d(ActivityHttpClient.LOG_TAG, "SubjectDN: " + cert.getSubjectDN().toString());
                            Log.d(ActivityHttpClient.LOG_TAG, "Serial Number: " + cert.getSerialNumber());
                            Log.d(ActivityHttpClient.LOG_TAG, "Version: " + cert.getVersion());
                            Log.d(ActivityHttpClient.LOG_TAG, "Not before: " + cert.getNotBefore().toString());
                            Log.d(ActivityHttpClient.LOG_TAG, "Not after: " + cert.getNotAfter().toString());
                            Log.d(ActivityHttpClient.LOG_TAG, "---------------------------");
                        }

                        // Make sure that it hasn't expired.
                        cert.checkValidity();

                        // Verify the certificate's chain.
                        cert.verify(publicKey);
                    }
                } catch (InvalidKeyException ex) {
                    error = ex;
                } catch (NoSuchAlgorithmException ex) {
                    error = ex;
                } catch (NoSuchProviderException ex) {
                    error = ex;
                } catch (SignatureException ex) {
                    error = ex;
                }
            if (null != error && ActivityHttpClient.isDebugging()) {
                Log.e(ActivityHttpClient.LOG_TAG, "Error while setting up a secure socket factory.", error);
                throw new CertificateException(error);
            }
        }

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

    setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
}

From source file:com.enjoy.nerd.http.AsyncHttpClient.java

/**
 * Returns default instance of SchemeRegistry
 *
 * @param fixNoHttpResponseException Whether to fix or not issue, by ommiting SSL verification
 * @param httpPort                   HTTP port to be used, must be greater than 0
 * @param httpsPort                  HTTPS port to be used, must be greater than 0
 *///from  w  ww .  ja  v  a  2  s . co m
private static SchemeRegistry getDefaultSchemeRegistry(boolean fixNoHttpResponseException, int httpPort,
        int httpsPort) {
    if (fixNoHttpResponseException) {
        Log.d(LOG_TAG, "Beware! Using the fix is insecure, as it doesn't verify SSL certificates.");
    }

    if (httpPort < 1) {
        httpPort = 80;
        Log.d(LOG_TAG, "Invalid HTTP port number specified, defaulting to 80");
    }

    if (httpsPort < 1) {
        httpsPort = 443;
        Log.d(LOG_TAG, "Invalid HTTPS port number specified, defaulting to 443");
    }

    // Fix to SSL flaw in API < ICS
    // See https://code.google.com/p/android/issues/detail?id=13117
    SSLSocketFactory sslSocketFactory;
    if (fixNoHttpResponseException)
        sslSocketFactory = MySSLSocketFactory.getFixedSocketFactory();
    else
        sslSocketFactory = SSLSocketFactory.getSocketFactory();

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), httpPort));
    if (sslSocketFactory != null) {
        sslSocketFactory.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
        schemeRegistry.register(new Scheme("https", sslSocketFactory, httpsPort));
    }

    return schemeRegistry;
}

From source file:org.ovirt.engine.sdk.web.ConnectionsPoolBuilder.java

/**
 * Creates SchemeRegistry//from www  .  j av  a 2s .  com
 *
 * @param url
 * @param port
 *
 * @return {@link SchemeRegistry}
 */
private SchemeRegistry createSchemeRegistry(String url, int port) {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    String protocol = getProtocol(url);
    SSLSocketFactory sf;

    if (HTTP_PROTOCOL.equals(protocol)) {
        schemeRegistry.register(new Scheme(HTTP_PROTOCOL, port, PlainSocketFactory.getSocketFactory()));
    } else if (HTTPS_PROTOCOL.equals(protocol)) {
        try {
            if (this.noHostVerification) {
                SSLContext sslcontext = SSLContext.getInstance("TLS");
                sslcontext.init(null, new TrustManager[] { noCaTrustManager }, null);
                sf = new SSLSocketFactory(sslcontext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            } else {
                KeyStore truststore = null;
                InputStream in = null;

                if (this.keyStorePath != null) {
                    truststore = KeyStore.getInstance(KeyStore.getDefaultType());
                    try {
                        in = new FileInputStream(this.keyStorePath);
                        truststore.load(in,
                                this.keyStorePassword != null ? this.keyStorePassword.toCharArray() : null);

                    } finally {
                        if (in != null) {
                            in.close();
                        }
                    }
                }
                sf = new SSLSocketFactory(SSLSocketFactory.TLS, null, null, truststore, null, null,
                        SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
            }

            schemeRegistry.register(new Scheme(HTTPS_PROTOCOL, port, sf));

        } catch (NoSuchAlgorithmException e) {
            throw new SocketFactoryException(NO_TLS_ERROR, e);
        } catch (KeyManagementException e) {
            throw new SocketFactoryException(BAD_KEY_ERROR, e);
        } catch (KeyStoreException e) {
            throw new SocketFactoryException(KEY_STORE_ERROR, e);
        } catch (FileNotFoundException e) {
            throw new SocketFactoryException(KEY_STORE_FILE_NOT_FOUND_ERROR, e);
        } catch (CertificateException e) {
            throw new SocketFactoryException(CERTEFICATE_ERROR, e);
        } catch (IOException e) {
            throw new SocketFactoryException(IO_ERROR, e);
        } catch (UnrecoverableKeyException e) {
            throw new SocketFactoryException(UNRECOVERABLE_KEY_ERROR, e);
        }
    } else {
        throw new ProtocolException(BAD_PROTOCOL_ERROR + protocol);
    }

    return schemeRegistry;
}

From source file:com.marklogic.client.impl.JerseyServices.java

@Override
public void connect(String host, int port, String database, String user, String password,
        Authentication authenType, SSLContext context, SSLHostnameVerifier verifier) {
    X509HostnameVerifier x509Verifier = null;
    if (verifier == null) {
        if (context != null)
            x509Verifier = SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
    } else if (verifier == SSLHostnameVerifier.ANY)
        x509Verifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    else if (verifier == SSLHostnameVerifier.COMMON)
        x509Verifier = SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
    else if (verifier == SSLHostnameVerifier.STRICT)
        x509Verifier = SSLSocketFactory.STRICT_HOSTNAME_VERIFIER;
    else if (context != null)
        x509Verifier = new HostnameVerifierAdapter(verifier);
    else/* w  ww. ja va 2 s.  c  o m*/
        throw new IllegalArgumentException("Null SSLContent but non-null SSLHostnameVerifier for client");

    connect(host, port, database, user, password, authenType, context, x509Verifier);
}