List of usage examples for javax.net.ssl SSLContext setDefault
public static void setDefault(SSLContext context)
From source file:it.jnrpe.plugin.CheckHttp.java
private void checkCertificateExpiryDate(URL url, List<Metric> metrics) throws Exception { SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom()); SSLContext.setDefault(ctx); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setHostnameVerifier(new HostnameVerifier() { public boolean verify(final String arg0, final SSLSession arg1) { return true; }/*from w w w .j a va 2 s . c o m*/ }); List<Date> expiryDates = new ArrayList<Date>(); conn.getResponseCode(); Certificate[] certs = conn.getServerCertificates(); for (Certificate cert : certs) { X509Certificate x509 = (X509Certificate) cert; Date expiry = x509.getNotAfter(); expiryDates.add(expiry); } conn.disconnect(); Date today = new Date(); for (Date date : expiryDates) { int diffInDays = (int) ((date.getTime() - today.getTime()) / (1000 * 60 * 60 * 24)); metrics.add(new Metric("certificate", "", new BigDecimal(diffInDays), null, null)); } }
From source file:com.cisco.oss.foundation.http.netlifx.apache.ApacheNetflixHttpClient.java
protected void configureClient() { clientConfig = new DefaultClientConfigImpl(); clientConfig.loadProperties(getApiName()); setLoadBalancer(loadBalancer);/*from w w w . j ava2s. c o m*/ // clientConfig.set(CommonClientConfigKey.NIWSServerListClassName, DiscoveryEnabledNIWSServerList.class.getName()); // clientConfig.set(IClientConfigKey.Keys.DeploymentContextBasedVipAddresses, metadata.getServiceName()); // clientConfig.set(CommonClientConfigKey.NFLoadBalancerRuleClassName, RoundRobinRule.class.getName()); // clientConfig.set(CommonClientConfigKey.NFLoadBalancerPingClassName, NIWSDiscoveryPing.class.getName()); // clientConfig.set(CommonClientConfigKey.VipAddressResolverClassName, SimpleVipAddressResolver.class.getName()); if (DiscoveryManager.getInstance().getDiscoveryClient() == null && startEurekaClient) { EurekaInstanceConfig eurekaInstanceConfig = new MyDataCenterInstanceConfig(getApiName()); EurekaClientConfig eurekaClientConfig = new DefaultEurekaClientConfig(getApiName() + "."); DiscoveryManager.getInstance().initComponent(eurekaInstanceConfig, eurekaClientConfig); } loadBalancer.initWithNiwsConfig(clientConfig); // if (HystrixPlugins.getInstance().getMetricsPublisher() == null) { // HystrixPlugins.getInstance().registerMetricsPublisher(HystrixMetricsPublisherDefault.getInstance()); // } RequestConfig.Builder requestBuilder = RequestConfig.custom(); requestBuilder = requestBuilder.setConnectTimeout(metadata.getConnectTimeout()); requestBuilder = requestBuilder.setSocketTimeout(metadata.getReadTimeout()); requestBuilder = requestBuilder.setStaleConnectionCheckEnabled(metadata.isStaleConnectionCheckEnabled()); RequestConfig requestConfig = requestBuilder.build(); boolean addSslSupport = StringUtils.isNotEmpty(metadata.getKeyStorePath()) && StringUtils.isNotEmpty(metadata.getKeyStorePassword()); boolean addTrustSupport = StringUtils.isNotEmpty(metadata.getTrustStorePath()) && StringUtils.isNotEmpty(metadata.getTrustStorePassword()); autoCloseable = metadata.isAutoCloseable(); autoEncodeUri = metadata.isAutoEncodeUri(); followRedirects = metadata.isFollowRedirects(); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); SSLContext sslContext = null; try { String keystoreType = "JKS"; if (addSslSupport && addTrustSupport) { KeyStore keyStore = KeyStore.getInstance(keystoreType); keyStore.load(new FileInputStream(metadata.getKeyStorePath()), metadata.getKeyStorePassword().toCharArray()); KeyStore trustStore = KeyStore.getInstance(keystoreType); trustStore.load(new FileInputStream(metadata.getTrustStorePath()), metadata.getTrustStorePassword().toCharArray()); sslContext = SSLContexts.custom().useProtocol("TLS") .loadKeyMaterial(keyStore, metadata.getKeyStorePassword().toCharArray()) .loadTrustMaterial(trustStore, null).build(); } else if (addSslSupport) { TrustManagerFactory tmf = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); KeyStore keyStore = KeyStore.getInstance(keystoreType); keyStore.load(new FileInputStream(metadata.getKeyStorePath()), metadata.getKeyStorePassword().toCharArray()); tmf.init(keyStore); sslContext = SSLContexts.custom().useProtocol("SSL") .loadKeyMaterial(keyStore, metadata.getKeyStorePassword().toCharArray()).build(); sslContext.init(null, tmf.getTrustManagers(), null); SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); httpClientBuilder.setSSLSocketFactory(sf); } else if (addTrustSupport) { KeyStore trustStore = KeyStore.getInstance(keystoreType); trustStore.load(new FileInputStream(metadata.getTrustStorePath()), metadata.getTrustStorePassword().toCharArray()); sslContext = SSLContexts.custom().useProtocol("TLS").loadTrustMaterial(trustStore, null).build(); } if (addSslSupport | addTrustSupport) { SSLContext.setDefault(sslContext); httpClientBuilder.setSslcontext(sslContext); } } catch (Exception e) { LOGGER.error("can't set TLS Support. Error is: {}", e, e); } httpClientBuilder.setMaxConnPerRoute(metadata.getMaxConnectionsPerAddress()) .setMaxConnTotal(metadata.getMaxConnectionsTotal()).setDefaultRequestConfig(requestConfig) .evictExpiredConnections().evictIdleConnections(metadata.getIdleTimeout(), TimeUnit.MILLISECONDS) .setKeepAliveStrategy(new InfraConnectionKeepAliveStrategy(metadata.getIdleTimeout())); HttpAsyncClientBuilder httpAsyncClientBuilder = HttpAsyncClients.custom(); httpAsyncClientBuilder.setDefaultRequestConfig(requestConfig) .setMaxConnPerRoute(metadata.getMaxConnectionsPerAddress()) .setMaxConnTotal(metadata.getMaxConnectionsTotal()) .setKeepAliveStrategy(new InfraConnectionKeepAliveStrategy(metadata.getIdleTimeout())) .setSSLContext(sslContext); if (metadata.isDisableCookies()) { httpClientBuilder.disableCookieManagement(); httpAsyncClientBuilder.disableCookieManagement(); } if (hostnameVerifier != null) { httpClientBuilder.setSSLHostnameVerifier(hostnameVerifier); httpAsyncClientBuilder.setSSLHostnameVerifier(hostnameVerifier); } if (!followRedirects) { httpClientBuilder.disableRedirectHandling(); } httpClient = httpClientBuilder.build(); httpAsyncClient = httpAsyncClientBuilder.build(); httpAsyncClient.start(); }
From source file:test.integ.be.agiv.security.IPSTSTest.java
@Test public void testSTS_JAXWS_Client() throws Exception { ServletTester servletTester = new ServletTester(); servletTester.addServlet(MyTestServlet.class, "/"); Security.addProvider(new BouncyCastleProvider()); KeyPair keyPair = generateKeyPair(); DateTime notBefore = new DateTime(); DateTime notAfter = notBefore.plusMonths(1); X509Certificate certificate = generateSelfSignedCertificate(keyPair, "CN=localhost", notBefore, notAfter); File tmpP12File = File.createTempFile("ssl-", ".p12"); LOG.debug("p12 file: " + tmpP12File.getAbsolutePath()); persistKey(tmpP12File, keyPair.getPrivate(), certificate, "secret".toCharArray(), "secret".toCharArray()); SslSocketConnector sslSocketConnector = new SslSocketConnector(); sslSocketConnector.setKeystore(tmpP12File.getAbsolutePath()); sslSocketConnector.setTruststore(tmpP12File.getAbsolutePath()); sslSocketConnector.setTruststoreType("pkcs12"); sslSocketConnector.setKeystoreType("pkcs12"); sslSocketConnector.setPassword("secret"); sslSocketConnector.setKeyPassword("secret"); sslSocketConnector.setTrustPassword("secret"); sslSocketConnector.setMaxIdleTime(30000); int sslPort = getFreePort(); sslSocketConnector.setPort(sslPort); servletTester.getContext().getServer().addConnector(sslSocketConnector); String sslLocation = "https://localhost:" + sslPort + "/"; servletTester.start();/*from www . j a va 2 s . co m*/ String location = servletTester.createSocketConnector(true); SSLContext sslContext = SSLContext.getInstance("TLS"); TrustManager trustManager = new TestTrustManager(certificate); sslContext.init(null, new TrustManager[] { trustManager }, null); SSLContext.setDefault(sslContext); try { LOG.debug("running IP-STS test..."); IPSTSClient client = new IPSTSClient(sslLocation, AGIVSecurity.BETA_REALM); client.getSecurityToken("username", "password"); } finally { servletTester.stop(); } }
From source file:test.integ.be.agiv.security.IPSTSTest.java
@Test public void testRSTS_JAXWS_Client() throws Exception { ServletTester servletTester = new ServletTester(); servletTester.addServlet(MyTestServlet.class, "/"); Security.addProvider(new BouncyCastleProvider()); KeyPair keyPair = generateKeyPair(); DateTime notBefore = new DateTime(); DateTime notAfter = notBefore.plusMonths(1); X509Certificate certificate = generateSelfSignedCertificate(keyPair, "CN=localhost", notBefore, notAfter); File tmpP12File = File.createTempFile("ssl-", ".p12"); LOG.debug("p12 file: " + tmpP12File.getAbsolutePath()); persistKey(tmpP12File, keyPair.getPrivate(), certificate, "secret".toCharArray(), "secret".toCharArray()); SslSocketConnector sslSocketConnector = new SslSocketConnector(); sslSocketConnector.setKeystore(tmpP12File.getAbsolutePath()); sslSocketConnector.setTruststore(tmpP12File.getAbsolutePath()); sslSocketConnector.setTruststoreType("pkcs12"); sslSocketConnector.setKeystoreType("pkcs12"); sslSocketConnector.setPassword("secret"); sslSocketConnector.setKeyPassword("secret"); sslSocketConnector.setTrustPassword("secret"); sslSocketConnector.setMaxIdleTime(30000); int sslPort = getFreePort(); sslSocketConnector.setPort(sslPort); servletTester.getContext().getServer().addConnector(sslSocketConnector); String sslLocation = "https://localhost:" + sslPort + "/"; servletTester.start();//from ww w .j a v a2 s .com String location = servletTester.createSocketConnector(true); SSLContext sslContext = SSLContext.getInstance("TLS"); TrustManager trustManager = new TestTrustManager(certificate); sslContext.init(null, new TrustManager[] { trustManager }, null); SSLContext.setDefault(sslContext); try { LOG.debug("running R-STS test..."); RSTSClient client = new RSTSClient(sslLocation); SecurityToken inputSecurityToken = new SecurityToken(); byte[] key = new byte[256 / 8]; SecureRandom random = new SecureRandom(); random.nextBytes(key); inputSecurityToken.setKey(key); inputSecurityToken.setAttachedReference("_" + UUID.randomUUID().toString()); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element tokenElement = document.createElement("Token"); tokenElement.setTextContent("hello world"); inputSecurityToken.setToken(tokenElement); client.getSecurityToken(inputSecurityToken, "https://auth.beta.agiv.be/ClaimsAwareService/Service.svc"); } finally { servletTester.stop(); } }
From source file:org.sharegov.cirm.StartUp.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]; }/* w w w . ja v a 2 s.c o m*/ public void checkClientTrusted(X509Certificate[] certs, String authType) { // System.out.println("Check client trusted"); } public void checkServerTrusted(X509Certificate[] certs, String authType) { // System.out.println("Check server trusted"); } } }; // Ignore differences between given hostname and certificate hostname HostnameVerifier hv = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { // TODO Auto-generated method stub return true; } }; // Install the all-trusting trust manager try { // SSLContext sc = SSLContext.getInstance("SSL"); // sc.init(null, trustAllCerts, new SecureRandom()); SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(new KeyManager[0], trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier(hv); // see:http://stackoverflow.com/questions/1828775/how-to-handle-invalid-ssl-certificates-with-apache-httpclient // see:https://code.google.com/p/jsslutils/wiki/ApacheHttpClientUsage org.apache.commons.httpclient.protocol.Protocol.registerProtocol("https", new org.apache.commons.httpclient.protocol.Protocol("https", (ProtocolSocketFactory) new SslContextedSecureProtocolSocketFactory(ctx, false), 443)); SSLContext.setDefault(ctx); } catch (Exception e) { } }
From source file:com.microfocus.application.automation.tools.srf.run.RunFromSrfBuilder.java
private void initSrfEventListener() throws IOException, IllegalArgumentException, SrfException, AuthorizationException { // !!! Important Notice !!! // by using 'level=session' in the sse request we're ensuring that we'll get only events related // to this run since we're creating a new session (token) for each run String urlSSe = _ftaasServerAddress.concat("/rest/test-manager/events").concat( "?level=session&types=test-run-started,test-run-ended,test-run-count,script-step-updated,script-step-created,script-run-started,script-run-ended"); urlSSe = urlSSe.concat("&access-token=").concat(_token); ClientBuilder sslBuilder = ClientBuilder.newBuilder(); SSLContext sslContext;/*from w ww. j a v a2 s.c om*/ try { sslContext = SSLContext.getInstance("TLS"); _trustMgr = new SrfTrustManager(); sslContext.init(null, new SrfTrustManager[] { _trustMgr }, null); SSLContext.setDefault(sslContext); } catch (NoSuchAlgorithmException | KeyManagementException e1) { return; } sslBuilder.register(SSLContext.class); Client client = sslBuilder.register(SseFeature.class).build(); client.register(sslContext); try { client.getSslContext().init(null, new SrfTrustManager[] { _trustMgr }, null); } catch (KeyManagementException e) { e.printStackTrace(); } WebTarget target = client.target(urlSSe); eventSrc = openAsynch(target, addAuthentication(null)); if (eventSrc == null) { throw new SrfException("Failed to initiate open event source for SRF SSE"); } eventSrc.register(this.sseEventListener); }
From source file:org.wso2.carbon.device.mgt.jaxrs.service.impl.admin.DeviceAnalyticsArtifactUploaderAdminServiceImpl.java
/** * Initializes the SSL Context// w ww . j a va 2s. c o m */ private void initSSLConnection() throws NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, KeyManagementException { KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KEY_MANAGER_TYPE); keyManagerFactory.init(keyStore, keyStorePassword); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TRUST_MANAGER_TYPE); trustManagerFactory.init(trustStore); // Create and initialize SSLContext for HTTPS communication sslContext = SSLContext.getInstance(SSLV3); sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); SSLContext.setDefault(sslContext); }
From source file:com.microfocus.application.automation.tools.srf.run.RunFromSrfBuilder.java
@Override public boolean perform(final AbstractBuild<?, ?> build, final Launcher launcher, BuildListener _listener) throws InterruptedException, IOException { this.logger = _listener.getLogger(); Dispatcher.TRACE = true;// w ww. j a v a 2 s.c o m Dispatcher.TRACE_PER_REQUEST = true; this._token = null; // Important in order to get only this run events this.build = build; this.sseEventListener = new SseEventListener(this.logger); this.sseEventListener.addObserver(this); this.srfExecutionFuture = new CompletableFuture<>(); this.runningCount = new HashSet<>(); JSONObject conData = getSrfConnectionData(build, logger); if (conData == null) return false; _app = conData.getString("app"); _secret = conData.getString("secret"); _ftaasServerAddress = conData.getString("server"); _https = conData.getBoolean("https"); _tenant = conData.getString("tenant"); String srfProxy = conData.getString("proxy"); URL proxy = null; if ((srfProxy != null) && (srfProxy.length() != 0)) { proxy = new URL(srfProxy); String proxyHost = proxy.getHost(); String proxyPort = String.format("%d", proxy.getPort()); Properties systemProperties = System.getProperties(); systemProperties.setProperty("https.proxyHost", proxyHost); systemProperties.setProperty("http.proxyHost", proxyHost); systemProperties.setProperty("https.proxyPort", proxyPort); systemProperties.setProperty("http.proxyPort", proxyPort); } try { SSLContext sslContext = SSLContext.getInstance("TLS"); _trustMgr = new SrfTrustManager(); sslContext.init(null, new SrfTrustManager[] { _trustMgr }, null); SSLContext.setDefault(sslContext); _factory = sslContext.getSocketFactory(); this.srfClient = new SrfClient(_ftaasServerAddress, _tenant, _factory, proxy); } catch (NoSuchAlgorithmException | KeyManagementException e) { logger.print(e.getMessage()); logger.print("\n\r"); } jobIds = null; try { srfClient.login(_app, _secret); this._token = srfClient.getAccessToken(); initSrfEventListener(); jobIds = executeTestsSet(); } catch (UnknownHostException | ConnectException | SSLHandshakeException | IllegalArgumentException | AuthorizationException | AuthenticationException e) { cleanUp(); logger.println( String.format("ERROR: Failed logging into SRF server: %s %s", this._ftaasServerAddress, e)); return false; } catch (IOException | SrfException e) { cleanUp(); logger.println(String.format("ERROR: Failed executing test, %s", e)); return false; } try { boolean buildResult = this.srfExecutionFuture.get(); return buildResult; } catch (ExecutionException e) { e.printStackTrace(); return false; } catch (InterruptedException e) { e.printStackTrace(); build.setResult(Result.ABORTED); // TODO: Optimization instead of testrunid set maintain testrunid map with job info, in order to avoid already finished job cancellation if (!jobIds.isEmpty()) { for (int i = 0; i < jobIds.size(); i++) { String jobId = jobIds.get(i).toString(); try { srfClient.cancelJob(jobId); } catch (SrfException e1) { e1.printStackTrace(); } } } return false; } finally { cleanUp(); } }
From source file:com.hpe.application.automation.tools.srf.run.RunFromSrfBuilder.java
private void initSrfEventListener() throws IOException, ConnectException, UnknownHostException, SSLHandshakeException, IllegalArgumentException { if (this._token != null) return;/* w ww .j a va2 s.c om*/ // !!! Important Notice !!! // by using 'level=session' in the sse request we're ensuring that we'll get only events related // to this run since we're creating a new session (token) for each run this._token = loginToSrf(); String urlSSe = _ftaasServerAddress.concat("/rest/test-manager/events").concat( "?level=session&types=test-run-started,test-run-ended,test-run-count,script-step-updated,script-step-created,script-run-started,script-run-ended"); urlSSe = urlSSe.concat("&access-token=").concat(_token); ClientBuilder sslBuilder = ClientBuilder.newBuilder(); SSLContext sslContext; try { sslContext = SSLContext.getInstance("TLS"); _trustMgr = new SrfTrustManager(); sslContext.init(null, new SrfTrustManager[] { _trustMgr }, null); SSLContext.setDefault(sslContext); } catch (NoSuchAlgorithmException | KeyManagementException e1) { return; } sslBuilder.register(SSLContext.class); Client client = sslBuilder.register(SseFeature.class).build(); client.register(sslContext); try { client.getSslContext().init(null, new SrfTrustManager[] { _trustMgr }, null); } catch (KeyManagementException e) { e.printStackTrace(); } WebTarget target = client.target(urlSSe); eventSrc = openAsynch(target, addAuthentication(null)); eventSrc.register(this.sseEventListener); }
From source file:com.hpe.application.automation.tools.srf.run.RunFromSrfBuilder.java
@Override public boolean perform(final AbstractBuild<?, ?> build, final Launcher launcher, BuildListener _listener) throws InterruptedException, IOException { this.logger = _listener.getLogger(); Dispatcher.TRACE = true;// ww w . java2 s. co m Dispatcher.TRACE_PER_REQUEST = true; this._token = null; // Important in order to get only this run events this.build = build; this.sseEventListener = new SseEventListener(this.logger); this.sseEventListener.addObserver(this); this.srfExecutionFuture = new CompletableFuture<>(); this.runningCount = new HashSet<>(); JSONObject conData = getSrfConnectionData(build, logger); if (conData == null) return false; _app = conData.getString("app"); _secret = conData.getString("secret"); _ftaasServerAddress = conData.getString("server"); _https = conData.getBoolean("https"); _tenant = conData.getString("tenant"); String srfProxy = conData.getString("proxy"); try { SSLContext sslContext = SSLContext.getInstance("TLS"); _trustMgr = new SrfTrustManager(); sslContext.init(null, new SrfTrustManager[] { _trustMgr }, null); SSLContext.setDefault(sslContext); _factory = sslContext.getSocketFactory(); } catch (NoSuchAlgorithmException | KeyManagementException e) { logger.print(e.getMessage()); logger.print("\n\r"); } if ((srfProxy != null) && (srfProxy.length() != 0)) { URL proxy = new URL(srfProxy); String proxyHost = proxy.getHost(); String proxyPort = String.format("%d", proxy.getPort()); Properties systemProperties = System.getProperties(); systemProperties.setProperty("https.proxyHost", proxyHost); systemProperties.setProperty("http.proxyHost", proxyHost); systemProperties.setProperty("https.proxyPort", proxyPort); systemProperties.setProperty("http.proxyPort", proxyPort); } jobIds = null; try { initSrfEventListener(); _secretApplied = false; try { jobIds = executeTestsSet(); if (jobIds.size() > 0 && eventSrc == null) initSrfEventListener(); } catch (AuthenticationException e) { initSrfEventListener(); if (_token == null) _token = loginToSrf(); _secretApplied = true; } } catch (UnknownHostException | ConnectException | SSLHandshakeException | IllegalArgumentException e) { cleanUp(); logger.println( String.format("ERROR: Failed logging in to SRF server: %s %s", this._ftaasServerAddress, e)); return false; } catch (IOException | SrfException e) { cleanUp(); logger.println(String.format("ERROR: Failed executing test, %s", e)); return false; } try { boolean buildResult = this.srfExecutionFuture.get(); return buildResult; } catch (ExecutionException e) { e.printStackTrace(); return false; } catch (InterruptedException e) { e.printStackTrace(); build.setResult(Result.ABORTED); // postSrfJobCancellation(); return false; } finally { cleanUp(); } }