List of usage examples for javax.net.ssl X509TrustManager X509TrustManager
X509TrustManager
From source file:org.opencastproject.kernel.http.impl.HttpClientImpl.java
/** * Returns a new trust manager which will be in charge of checking the SSL certificates that are being presented by * SSL enabled hosts.//from ww w .j av a 2 s.c om * * @return the trust manager */ private X509TrustManager createTrustManager() { X509TrustManager trustManager = new X509TrustManager() { /** * {@InheritDoc} * * @see javax.net.ssl.X509TrustManager#checkClientTrusted(java.security.cert.X509Certificate[], java.lang.String) */ public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { logger.trace("Skipping trust check on client certificate {}", string); } /** * {@InheritDoc} * * @see javax.net.ssl.X509TrustManager#checkServerTrusted(java.security.cert.X509Certificate[], java.lang.String) */ public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { logger.trace("Skipping trust check on server certificate {}", string); } /** * {@InheritDoc} * * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers() */ public X509Certificate[] getAcceptedIssuers() { logger.trace("Returning empty list of accepted issuers"); return null; } }; return trustManager; }
From source file:com.pipinan.githubcrawler.GithubCrawler.java
/** * Just to avoid the ssl exception when using HttpClient to access https url * * @return/*from w w w . java 2 s . com*/ */ private HttpClient getHttpClient() { try { SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }, new SecureRandom()); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpClient httpClient = HttpClientBuilder.create().setSSLSocketFactory(socketFactory).build(); return httpClient; } catch (Exception e) { e.printStackTrace(); return HttpClientBuilder.create().build(); } }
From source file:org.wso2.carbon.databridge.agent.thrift.internal.pool.client.secure.SecureClientPoolFactory.java
@Override public ThriftSecureEventTransmissionService.Client makeObject(Object key) throws AgentSecurityException, TTransportException { String[] keyElements = key.toString().split(AgentConstants.SEPARATOR); if (keyElements[2].equals(ReceiverConfiguration.Protocol.TCP.toString())) { if (params == null) { if (trustStore == null) { trustStore = System.getProperty("javax.net.ssl.trustStore"); if (trustStore == null) { throw new AgentSecurityException("No trustStore found"); }// www .ja v a 2s .c o m // trustStore = "/home/suho/projects/wso2/trunk/carbon/distribution/product/modules/distribution/target/wso2carbon-4.0.0-SNAPSHOT/repository/resources/security/client-truststore.jks"; } if (trustStorePassword == null) { trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword"); if (trustStorePassword == null) { throw new AgentSecurityException("No trustStore password found"); } //trustStorePassword = "wso2carbon"; } params = new TSSLTransportFactory.TSSLTransportParameters(); params.setTrustStore(trustStore, trustStorePassword); } String[] hostNameAndPort = keyElements[3].split(AgentConstants.HOSTNAME_AND_PORT_SEPARATOR); TTransport receiverTransport = null; try { receiverTransport = TSSLTransportFactory.getClientSocket( HostAddressFinder.findAddress(hostNameAndPort[0]), Integer.parseInt(hostNameAndPort[1]), 0, params); } catch (SocketException ignored) { //already checked } TProtocol protocol = new TBinaryProtocol(receiverTransport); return new ThriftSecureEventTransmissionService.Client(protocol); } else { try { TrustManager easyTrustManager = new X509TrustManager() { public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException { } public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException { } public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } }; String[] hostNameAndPort = keyElements[3].split(AgentConstants.HOSTNAME_AND_PORT_SEPARATOR); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[] { easyTrustManager }, null); SSLSocketFactory sf = new SSLSocketFactory(sslContext); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme httpsScheme = new Scheme("https", sf, Integer.parseInt(hostNameAndPort[1])); DefaultHttpClient client = new DefaultHttpClient(); client.getConnectionManager().getSchemeRegistry().register(httpsScheme); THttpClient tclient = new THttpClient("https://" + keyElements[3] + "/securedThriftReceiver", client); TProtocol protocol = new TCompactProtocol(tclient); ThriftSecureEventTransmissionService.Client authClient = new ThriftSecureEventTransmissionService.Client( protocol); tclient.open(); return authClient; } catch (Exception e) { throw new AgentSecurityException("Cannot create Secure client for " + keyElements[3], e); } } }
From source file:com.clustercontrol.winservice.util.RequestWinRM.java
/** * WinRM????Windows??Running??????/*from w ww . j av a 2 s . com*/ * * @param ipAddress * @param user * @param userPassword * @param port * @param protocol * @param timeout * @param retries * @return */ public boolean polling(String ipAddress, String user, String userPassword, int port, String protocol, int timeout, int retries) throws HinemosUnknown, WsmanException { m_log.debug("polling() " + "ipAddress = " + ipAddress + ",user = " + user + ",userPassword = " + userPassword + ",port = " + port + ",protocol = " + protocol + ",timeout = " + timeout + ",retries = " + retries); // XML?TransformerFactory? m_log.debug("polling() javax.xml.transform.TransformerFactory = " + System.getProperty("javax.xml.transform.TransformerFactory")); System.setProperty("javax.xml.transform.TransformerFactory", "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl"); // URL?? try { InetAddress address = InetAddress.getByName(ipAddress); if (address instanceof Inet6Address) { m_url = protocol + "://[" + ipAddress + "]:" + port + "/wsman"; } else { m_url = protocol + "://" + ipAddress + ":" + port + "/wsman"; } } catch (UnknownHostException e) { m_log.info("polling() ipAddress is not valid : " + ipAddress + e.getClass().getSimpleName() + ", " + e.getMessage()); throw new HinemosUnknown("ipAddress is not valid : " + ipAddress); } m_log.debug("polling() url = " + m_url); // ???? m_con = WsmanConnection.createConnection(m_url); m_con.setAuthenticationScheme("basic"); m_con.setUsername(user); m_con.setUserpassword(userPassword); m_con.setTimeout(timeout); boolean sslTrustall = HinemosPropertyUtil.getHinemosPropertyBool("monitor.winservice.ssl.trustall", true); if (sslTrustall) { X509TrustManager tm = new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } @Override public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } }; m_con.setTrustManager(tm); m_con.setHostnameVerifier(NoopHostnameVerifier.INSTANCE); } else { // HTTP???? common-httpclient ? HostnameVerifier ? m_con.setHostnameVerifier(SSLConnectionSocketFactory.getDefaultHostnameVerifier()); } // URI? ManagedReference ref = m_con.newReference(URI_WIN32_SERVICE); ref.addSelector("Name", m_serviceName); // int count = 0; WsmanException lastException = null; while (count < retries) { try { // ManagedInstance inst = ref.get(); if (m_log.isDebugEnabled()) { m_log.debug(WsmanUtils.getXML(inst)); } // ?? Object stateObj = inst.getProperty("State"); if (stateObj != null) { m_state = stateObj.toString(); } else { count++; continue; } // ? if (STATE_RUNNING.equalsIgnoreCase(m_state)) { // [OK] m_message = m_serviceName + " Service is " + STATE_RUNNING; m_messageOrg = m_serviceName + " Service is " + STATE_RUNNING; m_date = HinemosTime.currentTimeMillis(); break; } else { // [NG] m_message = m_serviceName + " Service is not " + STATE_RUNNING; m_messageOrg = m_serviceName + " Service is another state : " + m_state; m_date = HinemosTime.currentTimeMillis(); return false; } } catch (WsmanException e) { m_log.debug("polling() url=" + m_url + ", count=" + count + " " + e.getMessage() + ", " + e.getReason()); lastException = e; // ?? count++; continue; } finally { if (m_con != null) { m_con = null; } } } // ???NG if (count == retries) { // ? m_message = "WinRM Access Error . "; m_messageOrg = "WinRM Access Error . "; if (lastException != null) { m_messageOrg = m_messageOrg + " : " + lastException.getMessage(); } m_date = HinemosTime.currentTimeMillis(); if (lastException != null) { m_log.info("winservice url=" + m_url + ", message=" + lastException.getMessage() + ", reason=" + lastException.getReason()); if (lastException.getMessage() == null) { throw new HinemosUnknown( MessageConstant.MESSAGE_WINSERVICE_NAME_NOT_EXIST_OR_NOT_REFERENCE_AUTHORITY_TO_WINRM .getMessage() + " : " + lastException.getReason()); } else { if (lastException.getMessage().indexOf("HTTP response code: 401") != -1) { throw new HinemosUnknown( MessageConstant.MESSAGE_FAIL_AT_WINRM_ID_OR_PASSWORD_OR_LOGINAUTH_ERR.getMessage()); } } throw lastException; } else { // ?????????? throw new HinemosUnknown("winservice unknown"); } } // [OK]????? return true; }
From source file:software.betamax.util.DynamicSelfSignedSslEngineSource.java
private void initializeSSLContext() { String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm"); if (algorithm == null) { algorithm = "SunX509"; }/*from ww w . j a va 2s . c om*/ try { final KeyStore ks = KeyStore.getInstance("JKS"); // ks.load(new FileInputStream("keystore.jks"), // "changeit".toCharArray()); ks.load(new FileInputStream(keyStoreFile), PASSWORD.toCharArray()); // Set up key manager factory to use our key store final KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm); kmf.init(ks, PASSWORD.toCharArray()); // Set up a trust manager factory to use our key store TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm); tmf.init(ks); TrustManager[] trustManagers = new TrustManager[] { new X509TrustManager() { // TrustManager that trusts all servers @Override public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } } }; KeyManager[] keyManagers = kmf.getKeyManagers(); // Initialize the SSLContext to work with our key managers. sslContext = SSLContext.getInstance(PROTOCOL); sslContext.init(keyManagers, trustManagers, null); } catch (final Exception e) { throw new Error("Failed to initialize the server-side SSLContext", e); } }
From source file:org.ovirt.engine.core.uutils.net.HttpClientBuilder.java
public CloseableHttpClient build() throws IOException, GeneralSecurityException { // Prepare the default configuration for all requests: RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(connectTimeout != null ? connectTimeout : 0) .setSocketTimeout(readTimeout != null ? readTimeout : 0).build(); // Configure the trust manager: TrustManager[] trustManager = null; if (verifyChain) { if (trustStore != null) { try (InputStream is = new FileInputStream(trustStore)) { KeyStore ks = KeyStore.getInstance(trustStoreType); ks.load(is, StringUtils.isEmpty(trustStorePassword) ? null : trustStorePassword.toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance(trustManagerAlgorithm); tmf.init(ks);/* w ww.ja v a2 s . c o m*/ trustManager = tmf.getTrustManagers(); } } } else { trustManager = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[] {}; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; } // Create the SSL context: SSLContext sslContext = SSLContext.getInstance(tlsProtocol); sslContext.init(null, trustManager, null); // Create the SSL host name verifier: HostnameVerifier sslHostnameVerifier = null; if (!verifyHost) { sslHostnameVerifier = (hostname, session) -> true; } // Create the socket factory for HTTP: ConnectionSocketFactory httpSocketFactory = new PlainConnectionSocketFactory(); // Create the socket factory for HTTPS: ConnectionSocketFactory httpsSocketFactory = new SSLConnectionSocketFactory(sslContext, sslHostnameVerifier); // Create the socket factory registry: Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", httpSocketFactory).register("https", httpsSocketFactory).build(); // Create the connection manager: HttpClientConnectionManager connectionManager; if (poolSize != null) { PoolingHttpClientConnectionManager poolManager = new PoolingHttpClientConnectionManager( socketFactoryRegistry); poolManager.setDefaultMaxPerRoute(poolSize); poolManager.setMaxTotal(poolSize); connectionManager = poolManager; } else { connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry); } // Create the client: return org.apache.http.impl.client.HttpClientBuilder.create().setDefaultRequestConfig(requestConfig) .setSSLHostnameVerifier(sslHostnameVerifier).setConnectionManager(connectionManager).build(); }
From source file:com.telefonica.iot.tidoop.apiext.http.HttpClientFactory.java
/** * Gets a SchemeRegistry object accepting all the X509 certificates by default. * @return A SchemeRegistry object./*from ww w .ja va 2s.c o m*/ */ private SchemeRegistry getSchemeRegistry() { // http://stackoverflow.com/questions/2703161/how-to-ignore-ssl-certificate-errors-in-apache-httpclient-4-0 SSLContext sslContext = null; try { sslContext = SSLContext.getInstance("SSL"); } catch (NoSuchAlgorithmException e) { logger.fatal("Fatal error (SSL cannot be used, no such algorithm. Details=" + e.getMessage() + ")"); return null; } // try catch try { // set up a TrustManager that trusts everything sslContext.init(null, new TrustManager[] { new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } // getAcceptedIssuers @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { } // getAcceptedIssuers @Override public void checkServerTrusted(X509Certificate[] certs, String authType) { } // checkServerTrusted } }, new SecureRandom()); } catch (KeyManagementException e) { logger.fatal("Fatal error (Cannot ignore SSL certificates. Details=" + e.getMessage() + ")"); return null; } // try catch if (sslContext == null) { logger.fatal("Fatal error (Cannot ignore SSL certificates, SSL context is null)"); return null; } // if SSLSocketFactory sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme httpsScheme = new Scheme("https", 443, sf); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(httpsScheme); return schemeRegistry; }
From source file:com.telefonica.iot.cosmos.hive.authprovider.HttpClientFactory.java
/** * Gets a SSL SchemeRegistry object accepting all the X509 certificates by default. * @return A SSL SchemeRegistry object.//from w ww. j a v a 2 s.c om */ private SchemeRegistry getSSLSchemeRegistry() { // http://stackoverflow.com/questions/2703161/how-to-ignore-ssl-certificate-errors-in-apache-httpclient-4-0 SSLContext sslContext; try { sslContext = SSLContext.getInstance("SSL"); } catch (NoSuchAlgorithmException e) { LOGGER.fatal("Fatal error (SSL cannot be used, no such algorithm. Details=" + e.getMessage() + ")"); return null; } // try catch // try catch try { // set up a TrustManager that trusts everything sslContext.init(null, new TrustManager[] { new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } // getAcceptedIssuers @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { } // getAcceptedIssuers @Override public void checkServerTrusted(X509Certificate[] certs, String authType) { } // checkServerTrusted } }, new SecureRandom()); } catch (KeyManagementException e) { LOGGER.fatal("Fatal error (Cannot ignore SSL certificates. Details=" + e.getMessage() + ")"); return null; } // try catch // try catch if (sslContext == null) { LOGGER.fatal("Fatal error (Cannot ignore SSL certificates, SSL context is null)"); return null; } // if SSLSocketFactory sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme httpsScheme = new Scheme("https", 443, sf); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(httpsScheme); return schemeRegistry; }
From source file:com.github.lpezet.antiope.dao.DefaultHttpClientFactory.java
@Override public HttpClient createHttpClient(APIConfiguration pConfiguration) { // Use a custom connection factory to customize the process of // initialization of outgoing HTTP connections. Beside standard connection // configuration parameters HTTP connection factory can define message // parser / writer routines to be employed by individual connections. HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> oConnFactory = new ManagedHttpClientConnectionFactory( new DefaultHttpRequestWriterFactory(), new DefaultHttpResponseParserFactory()); SSLContext oSslContext = null; X509HostnameVerifier oHostnameVerifier = null; if (pConfiguration.isCheckSSLCertificates()) { oSslContext = SSLContexts.createSystemDefault(); oHostnameVerifier = new BrowserCompatHostnameVerifier(); } else {// w ww. j av a 2 s .c o m final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(final X509Certificate[] chain, final String authType) { } @Override public void checkServerTrusted(final X509Certificate[] chain, final String authType) { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } } }; // Install the all-trusting trust manager try { final SSLContext sslContext = SSLContext.getInstance(SSL); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); // Create an ssl socket factory with our all-trusting manager //final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); oSslContext = sslContext; } catch (NoSuchAlgorithmException e) { throw new APIClientException(e); } catch (KeyManagementException e) { throw new APIClientException(e); } oHostnameVerifier = new AllowAllHostnameVerifier(); } // Create a registry of custom connection socket factories for supported // protocol schemes. Registry<ConnectionSocketFactory> oSocketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register(HTTP, PlainConnectionSocketFactory.INSTANCE) .register(HTTPS, new SSLConnectionSocketFactory(oSslContext, oHostnameVerifier)).build(); // Use custom DNS resolver to override the system DNS resolution. DnsResolver oDnsResolver = new SystemDefaultDnsResolver(); /* { @Override public InetAddress[] resolve(final String host) throws UnknownHostException { if (host.equalsIgnoreCase("myhost")) { return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) }; } else { return super.resolve(host); } } };*/ // Create a connection manager with custom configuration. PoolingHttpClientConnectionManager oConnManager = new PoolingHttpClientConnectionManager( oSocketFactoryRegistry, oConnFactory, oDnsResolver); // Create socket configuration SocketConfig oSocketConfig = SocketConfig.custom().setTcpNoDelay(true) .setSoTimeout(pConfiguration.getSocketTimeout()).build(); // Configure the connection manager to use socket configuration either // by default or for a specific host. oConnManager.setDefaultSocketConfig(oSocketConfig); // connManager.setSocketConfig(new HttpHost("somehost", 80), oSocketConfig); // Create message constraints MessageConstraints oMessageConstraints = MessageConstraints.custom().setMaxHeaderCount(200) .setMaxLineLength(2000).build(); // Create connection configuration ConnectionConfig oConnectionConfig = ConnectionConfig.custom() .setMalformedInputAction(CodingErrorAction.IGNORE) .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8) .setMessageConstraints(oMessageConstraints).build(); // Configure the connection manager to use connection configuration either // by default or for a specific host. oConnManager.setDefaultConnectionConfig(oConnectionConfig); // connManager.setConnectionConfig(new HttpHost("somehost", 80), ConnectionConfig.DEFAULT); // Configure total max or per route limits for persistent connections // that can be kept in the pool or leased by the connection manager. oConnManager.setMaxTotal(100); oConnManager.setDefaultMaxPerRoute(10); //oConnManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20); // Use custom cookie store if necessary. CookieStore oCookieStore = new BasicCookieStore(); // Use custom credentials provider if necessary. // // Create global request configuration RequestConfig oDefaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH) //.setExpectContinueEnabled(true) // WARNING: setting it to true slows things down by 4s!!!! .setStaleConnectionCheckEnabled(true) .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)) .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)) .setConnectTimeout(pConfiguration.getConnectionTimeout()).build(); CredentialsProvider oCredentialsProvider = new BasicCredentialsProvider(); HttpHost oProxy = null; if (pConfiguration.getProxyHost() != null && pConfiguration.getProxyPort() > 0) { String proxyHost = pConfiguration.getProxyHost(); int proxyPort = pConfiguration.getProxyPort(); String proxyUsername = pConfiguration.getProxyUsername(); String proxyPassword = pConfiguration.getProxyPassword(); String proxyDomain = pConfiguration.getProxyDomain(); String proxyWorkstation = pConfiguration.getProxyWorkstation(); oProxy = new HttpHost(proxyHost, proxyPort); if (proxyUsername != null && proxyPassword != null) { oCredentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain)); } } // Create an HttpClient with the given custom dependencies and configuration. CloseableHttpClient oHttpClient = HttpClients.custom().setConnectionManager(oConnManager) .setDefaultCookieStore(oCookieStore).setDefaultCredentialsProvider(oCredentialsProvider) .setProxy(oProxy).setDefaultRequestConfig(oDefaultRequestConfig).build(); return oHttpClient; /* RequestConfig oRequestConfig = RequestConfig.custom() .setConnectTimeout(pConfiguration.getConnectionTimeout()) .setSocketTimeout(pConfiguration.getSocketTimeout()) .setStaleConnectionCheckEnabled(true) .build(); */ }