List of usage examples for javax.net.ssl HostnameVerifier HostnameVerifier
HostnameVerifier
From source file:com.nubits.nubot.utils.Utils.java
/** * Install a trust manager that does not validate certificate chains for https calls * * @throws Exception// w w w . ja va2 s. c o m */ private static void installTrustAllManager() throws Exception { // 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) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager 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) { return true; } }; // Install the all-trusting host verifier HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); }
From source file:org.wso2.carbon.identity.application.authentication.endpoint.util.MutualSSLManager.java
/** * Create basic SSL connection factory/*from ww w. j a va 2 s . c o m*/ * * @throws AuthenticationException */ public static void initMutualSSLConnection(boolean hostNameVerificationEnabled) throws AuthenticationException { try { KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(keyManagerType); keyManagerFactory.init(keyStore, keyStorePassword); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(trustManagerType); trustManagerFactory.init(trustStore); // Create and initialize SSLContext for HTTPS communication SSLContext sslContext = SSLContext.getInstance(protocol); if (hostNameVerificationEnabled) { sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); sslSocketFactory = sslContext.getSocketFactory(); if (log.isDebugEnabled()) { log.debug("Mutual SSL Client initialized with Hostname Verification enabled"); } } else { // All the code below is to overcome host name verification failure we get in certificate // validation due to self signed certificate. // Create empty HostnameVerifier HostnameVerifier hv = new HostnameVerifier() { @Override public boolean verify(String urlHostName, SSLSession session) { return true; } }; // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[0]; } @Override public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { /* skipped implementation */ } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { /* skipped implementation */ } } }; sslContext.init(keyManagerFactory.getKeyManagers(), trustAllCerts, new java.security.SecureRandom()); if (log.isDebugEnabled()) { log.debug("SSL Context is initialized with trust manager for excluding certificate validation"); } SSLContext.setDefault(sslContext); sslSocketFactory = sslContext.getSocketFactory(); HttpsURLConnection.setDefaultHostnameVerifier(hv); if (log.isDebugEnabled()) { log.debug("Mutual SSL Client initialized with Hostname Verification disabled"); } } } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { throw new AuthenticationException("Error while trying to load Trust Store.", e); } }
From source file:com.sitewhere.wso2.identity.scim.Wso2ScimAssetModule.java
protected SSLContext createContext() { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; }/*from w ww. j a v a 2s .c o m*/ public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { } } }; try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, null); SSLContext.setDefault(sc); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); return sc; } catch (Exception e) { } return null; }
From source file:org.apache.stratos.cli.RestCommandLineService.java
/** * Authenticate and login to stratos server. * * @param serverURL URL of the server * @param username username/*from w w w. j a va 2s. c om*/ * @param password password * @param validateLogin validate login * @return boolean * @throws Exception */ public boolean login(String serverURL, String username, String password, boolean validateLogin) throws Exception { try { // Avoid validating SSL certificate SSLContext sc = SSLContext.getInstance("SSL"); // Create empty HostnameVerifier HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { return true; } }; // 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(java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { } } }; sc.init(null, trustAllCerts, new java.security.SecureRandom()); SSLContext.setDefault(sc); HttpsURLConnection.setDefaultHostnameVerifier(hv); } catch (Exception e) { throw new RuntimeException("Error while authentication process!", e); } // Initialize client try { initializeRestClient(serverURL, username, password); if (log.isDebugEnabled()) { log.debug("Initialized REST Client for user {}", username); } } catch (AxisFault e) { String message = "Error connecting to the stratos server"; printError(message, e); throw new CommandException(e); } DefaultHttpClient httpClient = new DefaultHttpClient(); try { if (validateLogin) { HttpResponse response = restClient.doGet(httpClient, restClient.getBaseURL() + ENDPOINT_INIT); if (response != null) { int responseCode = response.getStatusLine().getStatusCode(); if (responseCode == 200) { return true; } else { System.out.println("Invalid value is set for STRATOS_URL"); } } return false; } else { // Just return true as we don't need to validate return true; } } catch (ConnectException e) { String message = "Could not connect to stratos manager"; printError(message, e); return false; } catch (java.lang.NoSuchMethodError e) { String message = "Authentication failed!"; printError(message, e); return false; } catch (Exception e) { if (e.getCause() instanceof MalformedChallengeException) { String message = "Authentication failed. Please check your username/password"; printError(message, e); return false; } String message = "An unknown error occurred: " + e.getMessage(); printError(message, e); return false; } finally { httpClient.getConnectionManager().shutdown(); } }
From source file:org.apache.ranger.admin.client.RangerAdminJersey2RESTClient.java
Client buildClient() { if (_isSSL) { if (_sslContext == null) { RangerSslHelper sslHelper = new RangerSslHelper(_sslConfigFileName); _sslContext = sslHelper.createContext(); }/*from w ww .j a v a2 s . co m*/ if (_hv == null) { _hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { return session.getPeerHost().equals(urlHostName); } }; } _client = ClientBuilder.newBuilder().sslContext(_sslContext).hostnameVerifier(_hv).build(); } if (_client == null) { _client = ClientBuilder.newClient(); } return _client; }
From source file:org.openecomp.sdnc.sli.aai.AAIService.java
public AAIService(URL propURL) { LOG.info("Entered AAIService.ctor"); String runtime = System.getProperty("aaiclient.runtime"); if (runtime != null && runtime.equals("OSGI")) { runtimeOSGI = true;/*from w w w . j ava2s . co m*/ } else { runtimeOSGI = false; } Properties props = null; try { props = initialize(propURL); AAIRequest.setProperties(props, this); } catch (Exception exc) { LOG.error("AicAAIResource.static", exc); } executor = new AAIRequestExecutor(); user_name = props.getProperty(CLIENT_NAME); user_password = props.getProperty(CLIENT_PWWD); if (user_name == null || user_name.isEmpty()) { LOG.debug("Basic user name is not set"); } if (user_password == null || user_password.isEmpty()) { LOG.debug("Basic password is not set"); } truststore_path = props.getProperty(TRUSTSTORE_PATH); truststore_password = props.getProperty(TRUSTSTORE_PSSWD); keystore_path = props.getProperty(KEYSTORE_PATH); keystore_password = props.getProperty(KEYSTORE_PSSWD); target_uri = props.getProperty(TARGET_URI); query_path = props.getProperty(QUERY_PATH); update_path = props.getProperty(UPDATE_PATH); String applicationId = props.getProperty(APPLICATION_ID); if (applicationId == null || applicationId.isEmpty()) { applicationId = "SDNC"; } application_id = applicationId; // connection timeout int tmpConnectionTimeout = 30000; int tmpReadTimeout = 30000; try { String tmpValue = null; tmpValue = props.getProperty(CONNECTION_TIMEOUT, "30000"); tmpConnectionTimeout = Integer.parseInt(tmpValue); tmpValue = props.getProperty(READ_TIMEOUT, "30000"); tmpReadTimeout = Integer.parseInt(tmpValue); } catch (Exception exc) { LOG.error("Failed setting connection timeout", exc); tmpConnectionTimeout = 30000; tmpReadTimeout = 30000; } connection_timeout = tmpConnectionTimeout; read_timeout = tmpReadTimeout; network_vserver_path = props.getProperty(NETWORK_VSERVER_PATH); svc_instance_path = props.getProperty(SVC_INSTANCE_PATH); // "/aai/v1/business/customers/customer/{customer-id}/service-subscriptions/service-subscription/{service-type}/service-instances"); // "/aai/v1/business/customers/customer/ma9181-203-customerid/service-subscriptions/service-subscription/ma9181%20Hosted%20Voice/service-instances"; // svc_inst_qry_path = props.getProperty(SVC_INST_QRY_PATH, "/aai/v1/search/generic-query?key=service-instance.service-instance-id:ma9181-204-instance&start-node-type=service-instance&include=service-instance"); svc_inst_qry_path = props.getProperty(SVC_INST_QRY_PATH); // "/aai/v1/search/generic-query?key=service-instance.service-instance-id:{svc-instance-id}&start-node-type=service-instance&include=service-instance"); param_service_type = props.getProperty(PARAM_SERVICE_TYPE, "service-type"); // P-Interfaces p_interface_path = props.getProperty(P_INTERFACE_PATH); vnf_image_query_path = props.getProperty(VNF_IMAGE_QUERY_PATH); ubb_notify_path = props.getProperty(UBB_NOTIFY_PATH); selflink_avpn = props.getProperty(SELFLINK_AVPN); selflink_fqdn = props.getProperty(SELFLINK_FQDN); service_path = props.getProperty(SERVICE_PATH); site_pair_set_path = props.getProperty(SITE_PAIR_SET_PATH); query_nodes_path = props.getProperty(QUERY_NODES_PATH); String iche = props.getProperty(CERTIFICATE_HOST_ERROR); boolean host_error = false; if (iche != null && !iche.isEmpty()) { host_error = Boolean.valueOf(iche); } ignore_certificate_host_error = host_error; HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { public boolean verify(String string, SSLSession ssls) { return ignore_certificate_host_error; } }); if (truststore_path != null && truststore_password != null && (new File(truststore_path)).exists()) { System.setProperty("javax.net.ssl.trustStore", truststore_path); System.setProperty("javax.net.ssl.trustStorePassword", truststore_password); } if (keystore_path != null && keystore_password != null && (new File(keystore_path)).exists()) { DefaultClientConfig config = new DefaultClientConfig(); //both jersey and HttpURLConnection can use this SSLContext ctx = null; try { ctx = SSLContext.getInstance("TLS"); KeyManagerFactory kmf = null; try { String def = "SunX509"; String storeType = "PKCS12"; def = KeyStore.getDefaultType(); kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); FileInputStream fin = new FileInputStream(keystore_path); // KeyStore ks = KeyStore.getInstance("PKCS12"); String extension = keystore_path.substring(keystore_path.lastIndexOf(".") + 1); if (extension != null && !extension.isEmpty() && extension.equalsIgnoreCase("JKS")) { storeType = "JKS"; } KeyStore ks = KeyStore.getInstance(storeType); char[] pwd = keystore_password.toCharArray(); ks.load(fin, pwd); kmf.init(ks, pwd); } catch (Exception ex) { LOG.error("AAIResource", ex); } ctx.init(kmf.getKeyManagers(), null, null); config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return ignore_certificate_host_error; } }, ctx)); CTX = ctx; LOG.debug("SSLContext created"); } catch (KeyManagementException | NoSuchAlgorithmException exc) { LOG.error("AAIResource", exc); } } LOG.info("AAIResource.ctor initialized."); try { Field methodsField = HttpURLConnection.class.getDeclaredField("methods"); methodsField.setAccessible(true); // get the methods field modifiers Field modifiersField = Field.class.getDeclaredField("modifiers"); // bypass the "private" modifier modifiersField.setAccessible(true); // remove the "final" modifier modifiersField.setInt(methodsField, methodsField.getModifiers() & ~Modifier.FINAL); /* valid HTTP methods */ String[] methods = { "GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE", "PATCH" }; // set the new methods - including patch methodsField.set(null, methods); } catch (SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException e) { e.printStackTrace(); } }
From source file:org.kurento.test.base.BrowserTest.java
public void waitForHostIsReachable(URL url, int timeout) { long timeoutMillis = TimeUnit.MILLISECONDS.convert(timeout, TimeUnit.SECONDS); long endTimeMillis = System.currentTimeMillis() + timeoutMillis; log.debug("Waiting for {} to be reachable (timeout {} seconds)", url, timeout); try {/*from www.jav a2 s .co m*/ TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { } @Override public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HostnameVerifier allHostsValid = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); int responseCode = 0; while (true) { try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout((int) timeoutMillis); connection.setReadTimeout((int) timeoutMillis); connection.setRequestMethod("HEAD"); responseCode = connection.getResponseCode(); break; } catch (SSLHandshakeException | SocketException e) { log.warn("Error {} waiting URL {}, trying again in 1 second", e.getMessage(), url); // Polling to wait a consistent SSL state Thread.sleep(1000); } if (System.currentTimeMillis() > endTimeMillis) { break; } } if (responseCode != HttpURLConnection.HTTP_OK) { log.warn("URL " + url + " not reachable. Response code=" + responseCode); } } catch (Exception e) { e.printStackTrace(); Assert.fail("URL " + url + " not reachable in " + timeout + " seconds (" + e.getClass().getName() + ", " + e.getMessage() + ")"); } log.debug("URL {} already reachable", url); }
From source file:com.createtank.payments.coinbase.RequestClient.java
public static void disableCertificateValidation() { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }/*from www . j a va2 s .c om*/ public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; // Ignore differences between given hostname and certificate hostname HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier(hv); } catch (Exception e) { //Ignore } }
From source file:org.talend.core.nexus.NexusServerUtils.java
private static HttpURLConnection getHttpURLConnection(String nexusUrl, String restService, String userName, String password) throws Exception { if (!nexusUrl.endsWith(NexusConstants.SLASH)) { nexusUrl = nexusUrl + NexusConstants.SLASH; }//from w w w . ja v a2 s . co m URL url = new URL(nexusUrl + restService); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); if (urlConnection instanceof HttpsURLConnection) { String userDir = Platform.getInstallLocation().getURL().getPath(); final SSLSocketFactory socketFactory = SSLUtils.getSSLContext(userDir).getSocketFactory(); HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection; httpsConnection.setSSLSocketFactory(socketFactory); httpsConnection.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String arg0, SSLSession arg1) { return true; } }); } IEclipsePreferences node = InstanceScope.INSTANCE.getNode(ORG_TALEND_DESIGNER_CORE); int timeout = node.getInt(ITalendCorePrefConstants.NEXUS_TIMEOUT, 10000); urlConnection.setConnectTimeout(timeout); return urlConnection; }
From source file:ch.cyberduck.core.gdocs.GDSession.java
protected HttpURLConnection getConnection(URL url) throws IOException { URLConnection c = null;/* ww w .j a v a2 s.c om*/ if (Preferences.instance().getBoolean("connection.proxy.enable")) { final Proxy proxy = ProxyFactory.instance(); if (proxy.isHTTPSProxyEnabled(new Host(Protocol.GDOCS_SSL, url.getHost(), url.getPort()))) { c = url.openConnection(new java.net.Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress(proxy.getHTTPSProxyHost(host), proxy.getHTTPSProxyPort(host)))); } } if (null == c) { log.debug("Direct connection"); c = url.openConnection(); } c.setConnectTimeout(timeout()); c.setReadTimeout(timeout()); if (c instanceof HttpsURLConnection) { ((HttpsURLConnection) c).setSSLSocketFactory( new CustomTrustSSLProtocolSocketFactory(this.getTrustManager(url.getHost()))); ((HttpsURLConnection) c).setHostnameVerifier(new HostnameVerifier() { public boolean verify(String s, javax.net.ssl.SSLSession sslSession) { return true; } }); } if (c instanceof HttpURLConnection) { return (HttpURLConnection) c; } throw new ConnectionCanceledException("Invalid URL connection:" + c); }