Example usage for javax.net.ssl HostnameVerifier HostnameVerifier

List of usage examples for javax.net.ssl HostnameVerifier HostnameVerifier

Introduction

In this page you can find the example usage for javax.net.ssl HostnameVerifier HostnameVerifier.

Prototype

HostnameVerifier

Source Link

Usage

From source file:com.spotify.helios.client.DefaultRequestDispatcher.java

private HttpURLConnection connect0(final URI ipUri, final String method, final byte[] entity,
        final Map<String, List<String>> headers, final String hostname, final AgentProxy agentProxy,
        final Identity identity) throws IOException {
    if (log.isTraceEnabled()) {
        log.trace("req: {} {} {} {} {} {}", method, ipUri, headers.size(),
                Joiner.on(',').withKeyValueSeparator("=").join(headers), entity.length,
                Json.asPrettyStringUnchecked(entity));
    } else {/*w w  w . j a  v a 2  s .c  o  m*/
        log.debug("req: {} {} {} {}", method, ipUri, headers.size(), entity.length);
    }

    final URLConnection urlConnection = ipUri.toURL().openConnection();
    final HttpURLConnection connection = (HttpURLConnection) urlConnection;

    // We verify the TLS certificate against the original hostname since verifying against the
    // IP address will fail
    if (urlConnection instanceof HttpsURLConnection) {
        System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
        connection.setRequestProperty("Host", hostname);

        final HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection;
        httpsConnection.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String ip, SSLSession sslSession) {
                final String tHostname = hostname.endsWith(".") ? hostname.substring(0, hostname.length() - 1)
                        : hostname;
                return new DefaultHostnameVerifier().verify(tHostname, sslSession);
            }
        });

        if (!isNullOrEmpty(user) && (agentProxy != null) && (identity != null)) {
            final SSLSocketFactory factory = new SshAgentSSLSocketFactory(agentProxy, identity, user);
            httpsConnection.setSSLSocketFactory(factory);
        }
    }

    connection.setRequestProperty("Accept-Encoding", "gzip");
    connection.setInstanceFollowRedirects(false);
    connection.setConnectTimeout((int) HTTP_TIMEOUT_MILLIS);
    connection.setReadTimeout((int) HTTP_TIMEOUT_MILLIS);
    for (Map.Entry<String, List<String>> header : headers.entrySet()) {
        for (final String value : header.getValue()) {
            connection.addRequestProperty(header.getKey(), value);
        }
    }
    if (entity.length > 0) {
        connection.setDoOutput(true);
        connection.getOutputStream().write(entity);
    }
    if (urlConnection instanceof HttpsURLConnection) {
        setRequestMethod(connection, method, true);
    } else {
        setRequestMethod(connection, method, false);
    }

    final int responseCode = connection.getResponseCode();
    if (responseCode == HTTP_BAD_GATEWAY) {
        throw new ConnectException("502 Bad Gateway");
    }

    return connection;
}

From source file:io.kodokojo.brick.gitlab.GitlabConfigurer.java

public static OkHttpClient provideDefaultOkHttpClient() {
    OkHttpClient httpClient = new OkHttpClient();
    final TrustManager[] certs = new TrustManager[] { new X509TrustManager() {

        @Override//from w ww. ja v a2s. com
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

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

    SSLContext ctx = null;
    try {
        ctx = SSLContext.getInstance("TLS");
        ctx.init(null, certs, new SecureRandom());
    } catch (final java.security.GeneralSecurityException ex) {
        //
    }
    httpClient.setHostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String s, SSLSession sslSession) {
            return true;
        }
    });
    httpClient.setSslSocketFactory(ctx.getSocketFactory());
    CookieManager cookieManager = new CookieManager(new GitlabCookieStore(), CookiePolicy.ACCEPT_ALL);
    httpClient.setCookieHandler(cookieManager);
    httpClient.setReadTimeout(2, TimeUnit.MINUTES);
    httpClient.setConnectTimeout(1, TimeUnit.MINUTES);
    httpClient.setWriteTimeout(1, TimeUnit.MINUTES);
    return httpClient;
}

From source file:org.opennms.protocols.vmware.VmwareConfigBuilder.java

public static void main(String[] args) throws ParseException {
    String hostname = null;/*from   w  w w .jav  a 2 s .c o m*/
    String username = null;
    String password = null;
    String rrdRepository = null;

    final Options options = new Options();

    options.addOption("rrdRepository", true,
            "set rrdRepository path for generated config files, default: '/opt/opennms/share/rrd/snmp/'");

    final CommandLineParser parser = new PosixParser();
    final CommandLine cmd = parser.parse(options, args);

    @SuppressWarnings("unchecked")
    List<String> arguments = (List<String>) cmd.getArgList();

    if (arguments.size() < 3) {
        usage(options, cmd);
        System.exit(1);
    }

    hostname = arguments.remove(0);
    username = arguments.remove(0);
    password = arguments.remove(0);

    if (cmd.hasOption("rrdRepository")) {
        rrdRepository = cmd.getOptionValue("rrdRepository");
    } else {
        rrdRepository = "/opt/opennms/share/rrd/snmp/";
    }

    TrustManager[] trustAllCerts = new TrustManager[1];

    trustAllCerts[0] = new TrustAllManager();

    SSLContext sc = null;
    try {
        sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    HostnameVerifier hv = new HostnameVerifier() {
        @Override
        public boolean verify(String urlHostName, SSLSession session) {
            return true;
        }
    };

    HttpsURLConnection.setDefaultHostnameVerifier(hv);

    VmwareConfigBuilder vmwareConfigBuilder;

    vmwareConfigBuilder = new VmwareConfigBuilder(hostname, username, password);

    try {
        vmwareConfigBuilder.generateData(rrdRepository);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.eclipse.emf.emfstore.client.model.connectionmanager.KeyStoreManager.java

/**
 * Returns a SSL Context. This is need for encryption, used by the
 * SSLSocketFactory./*from   w  w w .j a  v a  2  s . co m*/
 * 
 * @return SSL Context
 * @throws CertificateStoreException
 *             in case of failure retrieving the context
 */
public SSLContext getSSLContext() throws CertificateStoreException {
    try {
        loadKeyStore();
        KeyManagerFactory managerFactory = KeyManagerFactory.getInstance("SunX509");
        managerFactory.init(keyStore, KEYSTOREPASSWORD.toCharArray());
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
        trustManagerFactory.init(keyStore);
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(managerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        return sslContext;
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateStoreException("Loading certificate failed!", e);
    } catch (UnrecoverableKeyException e) {
        throw new CertificateStoreException("Loading certificate failed!", e);
    } catch (KeyStoreException e) {
        throw new CertificateStoreException("Loading certificate failed!", e);
    } catch (KeyManagementException e) {
        throw new CertificateStoreException("Loading certificate failed!", e);
    }
}

From source file:TestHTTPSource.java

public void doTestHttps(String protocol) throws Exception {
    Type listType = new TypeToken<List<JSONEvent>>() {
    }.getType();/*from   w  ww . j  a v a2 s  . c om*/
    List<JSONEvent> events = Lists.newArrayList();
    Random rand = new Random();
    for (int i = 0; i < 10; i++) {
        Map<String, String> input = Maps.newHashMap();
        for (int j = 0; j < 10; j++) {
            input.put(String.valueOf(i) + String.valueOf(j), String.valueOf(i));
        }
        input.put("MsgNum", String.valueOf(i));
        JSONEvent e = new JSONEvent();
        e.setHeaders(input);
        e.setBody(String.valueOf(rand.nextGaussian()).getBytes("UTF-8"));
        events.add(e);
    }
    Gson gson = new Gson();
    String json = gson.toJson(events, listType);
    HttpsURLConnection httpsURLConnection = null;
    try {
        TrustManager[] trustAllCerts = { new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                    throws CertificateException {
                // noop
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                    throws CertificateException {
                // noop
            }

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };

        SSLContext sc = null;
        javax.net.ssl.SSLSocketFactory factory = null;
        if (System.getProperty("java.vendor").contains("IBM")) {
            sc = SSLContext.getInstance("SSL_TLS");
        } else {
            sc = SSLContext.getInstance("SSL");
        }

        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        };
        sc.init(null, trustAllCerts, new SecureRandom());

        if (protocol != null) {
            factory = new DisabledProtocolsSocketFactory(sc.getSocketFactory(), protocol);
        } else {
            factory = sc.getSocketFactory();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(factory);
        HttpsURLConnection.setDefaultHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        URL sslUrl = new URL("https://0.0.0.0:" + sslPort);
        httpsURLConnection = (HttpsURLConnection) sslUrl.openConnection();
        httpsURLConnection.setDoInput(true);
        httpsURLConnection.setDoOutput(true);
        httpsURLConnection.setRequestMethod("POST");
        httpsURLConnection.getOutputStream().write(json.getBytes());

        int statusCode = httpsURLConnection.getResponseCode();
        Assert.assertEquals(200, statusCode);

        Transaction transaction = channel.getTransaction();
        transaction.begin();
        for (int i = 0; i < 10; i++) {
            Event e = channel.take();
            Assert.assertNotNull(e);
            Assert.assertEquals(String.valueOf(i), e.getHeaders().get("MsgNum"));
        }

        transaction.commit();
        transaction.close();
    } finally {
        httpsURLConnection.disconnect();
    }
}

From source file:com.njlabs.amrita.aid.gpms.ui.GpmsActivity.java

public Picasso getUnsecuredPicassoDownloader() {
    try {//  ww w .  j  a v  a  2 s.c o m
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

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

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

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

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());

        Picasso.Builder builder = new Picasso.Builder(baseContext).listener(new Picasso.Listener() {

            @Override
            public void onImageLoadFailed(Picasso arg0, Uri arg1, Exception ex) {
                ex.printStackTrace();

            }
        });

        OkHttpClient client = new OkHttpClient.Builder().sslSocketFactory(sc.getSocketFactory())
                .hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                }).build();

        Downloader downloader = new OkHttp3Downloader(client);
        return builder.downloader(downloader).build();
    } catch (Exception ignored) {
        Picasso.Builder builder = new Picasso.Builder(baseContext).listener(new Picasso.Listener() {
            @Override
            public void onImageLoadFailed(Picasso arg0, Uri arg1, Exception ex) {
                ex.printStackTrace();
            }
        });
        return builder.build();
    }

}

From source file:it.greenvulcano.gvesb.virtual.rest.RestCallOperation.java

private HttpsURLConnection openSecureConnection(URL url) throws Exception {

    InputStream keyStream = new FileInputStream(truststorePath);

    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(keyStream, Optional.ofNullable(truststorePassword).orElse("").toCharArray());

    TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(
            Optional.ofNullable(truststoreAlgorithm).orElseGet(TrustManagerFactory::getDefaultAlgorithm));
    trustFactory.init(keystore);/*w w  w .  j  a  va 2  s.com*/

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

    HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();

    httpsURLConnection.setSSLSocketFactory(context.getSocketFactory());

    httpsURLConnection.setHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    });

    return httpsURLConnection;
}

From source file:org.bremersee.sms.GoyyaSmsService.java

/**
 * Creates a host name verifier that does not verify the host name.
 *//* w w w . java 2 s .c  o m*/
protected HostnameVerifier createAllHostnamesVerifier() {

    return new HostnameVerifier() {

        /*
         * (non-Javadoc)
         * 
         * @see javax.net.ssl.HostnameVerifier#verify(java.lang.String,
         * javax.net.ssl.SSLSession)
         */
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };
}

From source file:gov.nih.nci.nbia.StandaloneDMDispatcher.java

private void downloadInstaller(String downloadUrl) {
    String fileName = getInstallerName(downloadUrl);
    InputStream in;//from w  ww.  j  a va2 s . c om

    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
            // here is the place to check client certs and throw an
            // exception if certs are wrong. When there is nothing all certs
            // accepted.
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
            // here is the place to check server certs and throw an
            // exception if certs are wrong. When there is nothing all certs
            // accepted.
        }
    } };
    // Install the all-trusting trust manager
    try {
        final SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                // Here is the palce to check host name against to
                // certificate owner
                return true;
            }
        };
        // Install the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    } catch (KeyManagementException | NoSuchAlgorithmException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } finally {
    }

    try {
        URL url = new URL(downloadUrl);
        in = url.openStream();
        FileOutputStream fos = new FileOutputStream(new File(fileName));

        int length = -1;
        ProgressMonitorInputStream pmis;
        pmis = new ProgressMonitorInputStream(null,
                "Downloading new version of installer for NBIA Data Retriever...", in);

        ProgressMonitor monitor = pmis.getProgressMonitor();
        monitor.setMillisToPopup(0);
        monitor.setMinimum(0);
        monitor.setMaximum((int) 200000000); // The actual size is much
        // smaller,
        // but we have no way to
        // know
        // the actual size so picked
        // this big number

        byte[] buffer = new byte[1024];// buffer for portion of data from
        // connection

        while ((length = pmis.read(buffer)) > 0) {
            fos.write(buffer, 0, length);
        }
        pmis.close();
        fos.flush();
        fos.close();
        in.close();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.hybris.mobile.app.commerce.CommerceApplicationBase.java

public void onCreate() {
    super.onCreate();
    mInstance = this;

    String urlBackend = getStringFromSharedPreferences(getString(R.string.preference_key_value_base_url), "");
    String catalogStore = getStringFromSharedPreferences(getString(R.string.preference_key_value_catalog_store),
            "");/* www . j  a va2s . c  o m*/
    String catalogId = getStringFromSharedPreferences(getString(R.string.preference_key_value_catalog_id), "");
    String catalogMainCategory = getStringFromSharedPreferences(
            getString(R.string.preference_key_value_catalog_main_category_id), "");

    // Setting the default backend url
    if (StringUtils.isBlank(urlBackend)) {
        urlBackend = getString(R.string.url_backend);

        int index = ArrayUtils.indexOf(getResources().getStringArray(R.array.backend_url_values), urlBackend);

        // Update the settings
        setStringToSharedPreferences(getString(R.string.preference_key_value_base_url), urlBackend);
        setStringToSharedPreferences(getString(R.string.preference_key_key_base_url),
                getResources().getStringArray(R.array.backend_url_keys)[index]);
    }

    // Setting the default catalog
    if (StringUtils.isBlank(catalogStore)) {
        catalogStore = getString(R.string.url_path_catalog);
        setStringToSharedPreferences(getString(R.string.preference_key_value_catalog_store), catalogStore);
    }

    if (StringUtils.isBlank(catalogId)) {
        catalogId = getString(R.string.url_path_catalog_id);
        setStringToSharedPreferences(getString(R.string.preference_key_value_catalog_id), catalogId);
    }

    if (StringUtils.isBlank(catalogMainCategory)) {
        catalogMainCategory = getString(R.string.id_category_main);
        setStringToSharedPreferences(getString(R.string.preference_key_value_catalog_main_category_id),
                catalogMainCategory);
    }

    // Updating the pre-defined catalog key
    String catalogKey = catalogStore + "|" + catalogId + "|" + catalogMainCategory;
    int index = ArrayUtils.indexOf(getResources().getStringArray(R.array.backend_catalog_values), catalogKey);
    setStringToSharedPreferences(getString(R.string.preference_key_key_catalog),
            getResources().getStringArray(R.array.backend_catalog_keys)[index]);

    // Configuration for the backend url
    com.hybris.mobile.lib.commerce.Configuration configuration = new com.hybris.mobile.lib.commerce.Configuration();
    configuration.setBackendUrl(urlBackend);
    configuration.setCatalogId(catalogId);
    configuration.setCatalog(catalogStore);
    configuration.setCatalogVersionId(mInstance.getString(R.string.url_path_catalog_version_id));
    configuration.setCatalogAuthority(getString(R.string.provider_authority));
    configuration.setCatalogIdMainCategory(catalogMainCategory);

    // Bypassing SSLHelperSyncService
    TrustManager[] trustManager = new TrustManager[] { new X509TrustManager() {
        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
        }

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

        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    } };

    SSLContext sslContext = null;

    try {
        sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustManager, new java.security.SecureRandom());
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        Log.e(TAG, "Error with SSLHelperSyncService. Details: " + e.getLocalizedMessage());
    }

    if (sslContext == null) {
        throw new IllegalStateException("Unable to get an instance of SSLContext");
    }

    // Creating the content service helper
    mInstance.mContentServiceHelper = buildContentServiceHelper(configuration, sslContext.getSocketFactory(),
            new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });

    // Build the configuration for the app
    mConfiguration = Configuration.buildConfiguration(this);

    // Barcode scanner instance
    mScannerHelper = new ScannerHelper(new CommerceBarcodeCheckerFactory());

    // Register local broadcast to Logout
    LocalBroadcastManager.getInstance(this).registerReceiver(new LogoutBroadcastReceiver(),
            new IntentFilter(getString(R.string.intent_action_logout)));

    // Register local broadcast to update cache on the content service helper
    LocalBroadcastManager.getInstance(this).registerReceiver(new UpdateCacheBroadcastReceiver(),
            new IntentFilter(getString(R.string.intent_action_update_cache)));

    // Default account for the sync adapter
    addCatalogSyncAdapterDefaultAccount();

    // We sync in advance the main category of the catalog to create the sync adapter and accelerate the process
    Bundle bundle = new Bundle();
    bundle.putString(CatalogSyncConstants.SYNC_PARAM_GROUP_ID, catalogMainCategory);
    bundle.putInt(CatalogSyncConstants.SYNC_PARAM_CURRENT_PAGE, 0);
    bundle.putInt(CatalogSyncConstants.SYNC_PARAM_PAGE_SIZE, mConfiguration.getDefaultPageSize());
    requestCatalogSyncAdapter(bundle);
}