List of usage examples for org.apache.http.conn.ssl SSLSocketFactory SSLSocketFactory
public SSLSocketFactory(final javax.net.ssl.SSLSocketFactory socketfactory, final X509HostnameVerifier hostnameVerifier)
From source file:com.waitwha.nessus.server.Server.java
/** * Constructor// www .j av a 2 s . c om * * @param url End-point URL of the Nessus Server. (i.e. https://localhost:8834) */ public Server(final String url) { this.url = url; /* * Configure XML parsing. */ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { this.builder = factory.newDocumentBuilder(); log.finest(String.format("Successfully configured XML parsing using builder: %s", this.builder.getClass().getName())); } catch (ParserConfigurationException e) { log.warning(String.format("Could not configure XML parsing: %s", e.getMessage())); } /* * Setup SSL for HttpClient configurations. Here we will configure SSL/TLS to * accept all hosts (no verification on certificates). This is because Nessus by * default used a self-generate CA and certificate for the servers. So, a simple * self-signed-strategy will not work as we are not dealing with strictly * self-signed certs, but ones generated and signed by a self-generated CA. * * TODO Perhaps the serial number of the CA is always the same so in the future we * could use a strategy to only accept certs by this one serial. * * See http://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientConfiguration.java. * * TODO We need to work on the code here to be more up-to-date. SSLSocketFactory is deprecated, but * finding up-to-date docs on how to use SSLContext with a custom TrustStrategy and not using a KeyStore is * not currently available. */ //SSLContext sslContext = SSLContexts.createSystemDefault(); Registry<ConnectionSocketFactory> socketFactoryRegistry = null; try { socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.INSTANCE) .register("https", new SSLSocketFactory(new MyTrustStrategy(), SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)) .build(); log.finest(String.format("Configured SSL/TLS connections for %s.", url)); } catch (Exception e) { log.warning( String.format("Could not configure SSL/TLS: %s %s", e.getClass().getName(), e.getMessage())); } SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build(); this.connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry); this.connectionManager.setSocketConfig(socketConfig); log.finest(String.format("Configured socket connections for %s.", url)); this.cookieStore = new BasicCookieStore() { private static final long serialVersionUID = 1L; /** * @see org.apache.http.impl.client.BasicCookieStore#addCookie(org.apache.http.cookie.Cookie) */ @Override public synchronized void addCookie(Cookie cookie) { log.finest(String.format("[%s] Cookie added: %s=%s", url, cookie.getName(), cookie.getValue())); super.addCookie(cookie); } }; log.finest(String.format("Configured default/basic cookie storage for connections to %s", url)); }
From source file:org.wso2.identity.sample.webapp.APIInvoker.java
private String callRESTep(String ep) throws Exception { PlatformUtils.setKeyStoreProperties(); PlatformUtils.setKeyStoreParams();//from w w w. ja v a2 s. c om DefaultHttpClient httpClient = new DefaultHttpClient(); try { SSLSocketFactory sf = null; SSLContext sslContext = null; StringWriter writer; try { sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, null, null); } catch (NoSuchAlgorithmException e) { //<YourErrorHandling> } catch (KeyManagementException e) { //<YourErrorHandling> } try { sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } catch (Exception e) { //<YourErrorHandling> } Scheme scheme = new Scheme("https", 8243, sf); httpClient.getConnectionManager().getSchemeRegistry().register(scheme); HttpGet get = new HttpGet(ep); // add header get.setHeader("Content-Type", "text/xml;charset=UTF-8"); get.setHeader("Authorization", "Bearer " + oauthToken); get.setHeader("x-saml-assertion", SamlConsumerManager.getEncodedAssertion()); CloseableHttpResponse response = httpClient.execute(get); try { String result = EntityUtils.toString(response.getEntity()); System.out.println("API RESULT" + result); return result; } finally { response.close(); } } finally { httpClient.close(); } }
From source file:no.kantega.kwashc.server.test.SSLProtocolTest.java
private HttpResponse checkClient(Site site, int httpsPort, HttpClient httpclient, String[] protocols, String[] ciphers) throws NoSuchAlgorithmException, KeyManagementException, IOException { SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, new TrustManager[] { allowAllTrustManager }, null); SSLSocketFactory sf = new SSLSocketFactory(sslcontext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000); params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 1000); SSLSocket socket = (SSLSocket) sf.createSocket(params); if (protocols != null) { socket.setEnabledProtocols(protocols); }/*from ww w . ja va2s. co m*/ if (ciphers != null) { socket.setEnabledCipherSuites(ciphers); } URL url = new URL(site.getAddress()); InetSocketAddress address = new InetSocketAddress(url.getHost(), httpsPort); sf.connectSocket(socket, address, null, params); Scheme sch = new Scheme("https", httpsPort, sf); httpclient.getConnectionManager().getSchemeRegistry().register(sch); HttpGet request = new HttpGet( "https://" + url.getHost() + ":" + site.getSecureport() + url.getPath() + "blog"); return httpclient.execute(request); }
From source file:gov.nih.nci.nbia.StandaloneDMV2.java
private static List<String> connectAndReadFromURL(URL url, String fileName, String userId, String passWd) { List<String> data = null; DefaultHttpClient httpClient = null; TrustStrategy easyStrategy = new TrustStrategy() { @Override/* w w w . j ava2 s .c om*/ public boolean isTrusted(X509Certificate[] certificate, String authType) throws CertificateException { return true; } }; try { // SSLContext sslContext = SSLContext.getInstance("SSL"); // set up a TrustManager that trusts everything // sslContext.init(null, new TrustManager[] { new // EasyX509TrustManager(null)}, null); SSLSocketFactory sslsf = new SSLSocketFactory(easyStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme httpsScheme = new Scheme("https", 443, sslsf); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(httpsScheme); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); ClientConnectionManager ccm = new ThreadSafeClientConnManager(schemeRegistry); HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 50000); HttpConnectionParams.setSoTimeout(httpParams, new Integer(12000)); httpClient = new DefaultHttpClient(ccm, httpParams); httpClient.setRoutePlanner(new ProxySelectorRoutePlanner(schemeRegistry, ProxySelector.getDefault())); // // Additions by lrt for tcia - // // attempt to reduce errors going through a Coyote Point // Equalizer load balance switch httpClient.getParams().setParameter("http.socket.timeout", new Integer(12000)); httpClient.getParams().setParameter("http.socket.receivebuffer", new Integer(16384)); httpClient.getParams().setParameter("http.tcp.nodelay", true); httpClient.getParams().setParameter("http.connection.stalecheck", false); // // end lrt additions HttpPost httpPostMethod = new HttpPost(url.toString()); List<BasicNameValuePair> postParams = new ArrayList<BasicNameValuePair>(); postParams.add(new BasicNameValuePair("serverManifestLoc", fileName)); if (userId != null && passWd != null) { postParams.add(new BasicNameValuePair("userId", userId)); httpPostMethod.addHeader("password", passWd); } UrlEncodedFormEntity query = new UrlEncodedFormEntity(postParams); httpPostMethod.setEntity(query); HttpResponse response = httpClient.execute(httpPostMethod); int responseCode = response.getStatusLine().getStatusCode(); // System.out.println("!!!!!Response code for requesting datda file: // " + responseCode); if (responseCode != HttpURLConnection.HTTP_OK) { return null; } else { InputStream inputStream = response.getEntity().getContent(); data = IOUtils.readLines(inputStream); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnrecoverableKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (httpClient != null) { httpClient.getConnectionManager().shutdown(); } } return data; }
From source file:us.mn.state.health.lims.common.externalLinks.ExternalPatientSearch.java
protected void doSearch() { HttpClient httpclient = new DefaultHttpClient(); setTimeout(httpclient);/*from www . j a v a 2 s . co m*/ HttpGet httpget = new HttpGet(connectionString); URI getUri = buildConnectionString(httpget.getURI()); httpget.setURI(getUri); try { // Ignore hostname mismatches and allow trust of self-signed certs SSLSocketFactory sslsf = new SSLSocketFactory(new TrustSelfSignedStrategy(), SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme https = new Scheme("https", 443, sslsf); ClientConnectionManager ccm = httpclient.getConnectionManager(); ccm.getSchemeRegistry().register(https); HttpResponse getResponse = httpclient.execute(httpget); returnStatus = getResponse.getStatusLine().getStatusCode(); setPossibleErrors(); setResults(IOUtils.toString(getResponse.getEntity().getContent(), "UTF-8")); } catch (SocketTimeoutException e) { errors.add("Response from patient information server took too long."); LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString()); // System.out.println("Tinny time out" + e); } catch (ConnectException e) { errors.add("Unable to connect to patient information form service. Service may not be running"); LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString()); // System.out.println("you no talks? " + e); } catch (IOException e) { errors.add("IO error trying to read input stream."); LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString()); // System.out.println("all else failed " + e); } catch (KeyManagementException e) { errors.add("Key management error trying to connect to external search service."); LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString()); } catch (UnrecoverableKeyException e) { errors.add("Unrecoverable key error trying to connect to external search service."); LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString()); } catch (NoSuchAlgorithmException e) { errors.add("No such encyrption algorithm error trying to connect to external search service."); LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString()); } catch (KeyStoreException e) { errors.add("Keystore error trying to connect to external search service."); LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString()); } catch (RuntimeException e) { errors.add("Runtime error trying to retrieve patient information."); LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString()); httpget.abort(); throw e; } finally { httpclient.getConnectionManager().shutdown(); } }
From source file:com.google.appengine.tck.endpoints.support.EndPointClient.java
/** * This ssl socket factory ignores validation. * * @return ssl socket factory//from w w w . j a v a 2s. c o m */ protected SchemeSocketFactory getSslFactory() { try { TrustManager trm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, new TrustManager[] { trm }, null); X509HostnameVerifier hostnameVerifier = new X509HostnameVerifier() { public void verify(String host, SSLSocket ssl) throws IOException { } public void verify(String host, X509Certificate cert) throws SSLException { } public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException { } public boolean verify(String s, SSLSession sslSession) { return true; } }; return new SSLSocketFactory(sc, hostnameVerifier); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:eu.europa.ec.markt.dss.validation102853.https.CommonsDataLoader.java
private RegistryBuilder<ConnectionSocketFactory> setConnectionManagerSchemeHttps( RegistryBuilder<ConnectionSocketFactory> socketFactoryRegistryBuilder) throws DSSException { try {// w ww. ja v a2s . com // TODO: (Bob: 2013 Dec 03) To be replaced: SSLSocketFactory deprecated!!! SSLSocketFactory sslSocketFactory = new SSLSocketFactory(new OptimistTrustStrategy(), new OptimistX509HostnameVerifier()); return socketFactoryRegistryBuilder.register("https", sslSocketFactory); } catch (Exception e) { throw new DSSException(e); } }
From source file:pt.lunacloud.http.AmazonHttpClient.java
/** * Disables the default strict hostname verification in this client and * instead uses a browser compatible hostname verification strategy (i.e. * cert hostname wildcards are evaulated more liberally). *///from w ww . j av a2 s .c o m public void disableStrictHostnameVerification() { try { SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry(); SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getDefault(), SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); Scheme https = new Scheme("https", 443, sf); schemeRegistry.register(https); } catch (NoSuchAlgorithmException e) { throw new LunacloudClientException( "Unable to access default SSL context to disable strict hostname verification"); } }
From source file:com.revo.deployr.client.core.impl.RClientImpl.java
public RClientImpl(String serverurl, int concurrentCallLimit, boolean allowSelfSignedSSLCert) throws RClientException, RSecurityException { log.debug("Creating client connection: serverurl=" + serverurl + ", concurrentCallLimit=" + concurrentCallLimit + ", allowSelfSignedSSLCert=" + allowSelfSignedSSLCert); this.serverurl = serverurl; // Create and initialize HTTP parameters HttpParams httpParams = new BasicHttpParams(); // Set Infinite Connection and Socket Timeouts. HttpConnectionParams.setConnectionTimeout(httpParams, 0); HttpConnectionParams.setSoTimeout(httpParams, 0); ConnManagerParams.setMaxTotalConnections(httpParams, concurrentCallLimit); ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(concurrentCallLimit)); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); // Create and initialize scheme registry SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); if (allowSelfSignedSSLCert) { /*/*from ww w . j a v a 2 s. co m*/ * Register scheme for "https" that bypasses * SSL cert trusted-origin verification check * which makes it possible to connect to a * DeployR server using a self-signed certificate. * * Recommended for prototyping and testing only, * not recommended for production environments. */ TrustStrategy blindTrust = new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] certificate, String authType) { return true; } }; try { sslSocketFactory = new SSLSocketFactory(blindTrust, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); schemeRegistry.register(new Scheme("https", 8443, sslSocketFactory)); } catch (GeneralSecurityException gsex) { String exMsg = "Self-signed SSL cert config failed, " + gsex.getMessage(); log.debug(exMsg); throw new RSecurityException(exMsg, 0); } } // Create a HttpClient with the ThreadSafeClientConnManager. // This connection manager must be used if more than one thread will // be using the HttpClient. ClientConnectionManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry); httpClient = new DefaultHttpClient(cm, httpParams); // Enable cookie handling by setting cookie policy on HttpClient. httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH); log.debug("Created client connection: httpClient=" + httpClient); eService = Executors.newCachedThreadPool(); }