List of usage examples for org.apache.http.conn.ssl BrowserCompatHostnameVerifier BrowserCompatHostnameVerifier
BrowserCompatHostnameVerifier
From source file:com.owncloud.android.lib.common.network.NetworkUtils.java
public static AdvancedSslSocketFactory getAdvancedSslSocketFactory(Context context) throws GeneralSecurityException, IOException { if (mAdvancedSslSocketFactory == null) { KeyStore trustStore = getKnownServersStore(context); AdvancedX509TrustManager trustMgr = new AdvancedX509TrustManager(trustStore); TrustManager[] tms = new TrustManager[] { trustMgr }; SSLContext sslContext;// w ww . java 2s .co m try { sslContext = SSLContext.getInstance("TLSv1.2"); } catch (NoSuchAlgorithmException e) { Log_OC.w(TAG, "TLSv1.2 is not supported in this device; falling through TLSv1.0"); sslContext = SSLContext.getInstance("TLSv1"); // should be available in any device; see reference of supported protocols in // http://developer.android.com/reference/javax/net/ssl/SSLSocket.html } sslContext.init(null, tms, null); mHostnameVerifier = new BrowserCompatHostnameVerifier(); mAdvancedSslSocketFactory = new AdvancedSslSocketFactory(sslContext, trustMgr, mHostnameVerifier); } return mAdvancedSslSocketFactory; }
From source file:sk.datalan.solr.impl.HttpClientUtil.java
public static HttpClientBuilder configureClient(final HttpClientConfiguration config) { HttpClientBuilder clientBuilder = HttpClientBuilder.create(); // max total connections if (config.isSetMaxConnections()) { clientBuilder.setMaxConnTotal(config.getMaxConnections()); }/*from w ww .j a v a2 s. c o m*/ // max connections per route if (config.isSetMaxConnectionsPerRoute()) { clientBuilder.setMaxConnPerRoute(config.getMaxConnectionsPerRoute()); } RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH) .setExpectContinueEnabled(true).setStaleConnectionCheckEnabled(true); // connection timeout if (config.isSetConnectionTimeout()) { requestConfigBuilder.setConnectTimeout(config.getConnectionTimeout()); } // soucket timeout if (config.isSetSocketTimeout()) { requestConfigBuilder.setSocketTimeout(config.getSocketTimeout()); } // soucket timeout if (config.isSetFollowRedirects()) { requestConfigBuilder.setRedirectsEnabled(config.getFollowRedirects()); } clientBuilder.setDefaultRequestConfig(requestConfigBuilder.build()); if (config.isSetUseRetry()) { if (config.getUseRetry()) { clientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler()); } else { clientBuilder.setRetryHandler(NO_RETRY); } } // basic authentication if (config.isSetBasicAuthUsername() && config.isSetBasicAuthPassword()) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(config.getBasicAuthUsername(), config.getBasicAuthPassword())); } if (config.isSetAllowCompression()) { clientBuilder.addInterceptorFirst(new UseCompressionRequestInterceptor()); clientBuilder.addInterceptorFirst(new UseCompressionResponseInterceptor()); } // SSL context for secure connections can be created either based on // system or application specific properties. SSLContext sslcontext = SSLContexts.createSystemDefault(); // Use custom hostname verifier to customize SSL hostname verification. X509HostnameVerifier hostnameVerifier = new BrowserCompatHostnameVerifier(); // Create a registry of custom connection socket factories for supported // protocol schemes. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.INSTANCE) .register("https", new SSLConnectionSocketFactory(sslcontext, hostnameVerifier)).build(); clientBuilder.setConnectionManager(new PoolingHttpClientConnectionManager(socketFactoryRegistry)); return clientBuilder; }
From source file:org.apache.zeppelin.notebook.repo.zeppelinhub.rest.HttpProxyClient.java
private PoolingNHttpClientConnectionManager getAsyncConnectionManager() { ConnectingIOReactor ioReactor = null; PoolingNHttpClientConnectionManager cm = null; try {/*from w w w .j a v a2s .com*/ ioReactor = new DefaultConnectingIOReactor(); // ssl setup SSLContext sslcontext = SSLContexts.createSystemDefault(); X509HostnameVerifier hostnameVerifier = new BrowserCompatHostnameVerifier(); @SuppressWarnings("deprecation") Registry<SchemeIOSessionStrategy> sessionStrategyRegistry = RegistryBuilder .<SchemeIOSessionStrategy>create().register("http", NoopIOSessionStrategy.INSTANCE) .register("https", new SSLIOSessionStrategy(sslcontext, hostnameVerifier)).build(); cm = new PoolingNHttpClientConnectionManager(ioReactor, sessionStrategyRegistry); } catch (IOReactorException e) { LOG.error("Couldn't initialize multi-threaded async client ", e); return null; } return cm; }
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 {// ww w . ja va2s . co 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(); */ }
From source file:org.apache.chemistry.opencmis.client.bindings.spi.http.ApacheClientHttpInvoker.java
/** * Builds a SSL Socket Factory for the Apache HTTP Client. *//* w w w . j a v a 2 s.c om*/ private SchemeLayeredSocketFactory getSSLSocketFactory(final UrlBuilder url, final BindingSession session) { // get authentication provider AuthenticationProvider authProvider = CmisBindingsHelper.getAuthenticationProvider(session); // check SSL Socket Factory final SSLSocketFactory sf = authProvider.getSSLSocketFactory(); if (sf == null) { // no custom factory -> return default factory return org.apache.http.conn.ssl.SSLSocketFactory.getSocketFactory(); } // check hostame verifier and use default if not set final HostnameVerifier hv = (authProvider.getHostnameVerifier() == null ? new BrowserCompatHostnameVerifier() : authProvider.getHostnameVerifier()); if (hv instanceof X509HostnameVerifier) { return new org.apache.http.conn.ssl.SSLSocketFactory(sf, (X509HostnameVerifier) hv); } // build new socket factory return new SchemeLayeredSocketFactory() { @Override public boolean isSecure(Socket sock) { return true; } @Override public Socket createSocket(HttpParams params) throws IOException { return sf.createSocket(); } @Override public Socket connectSocket(final Socket socket, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpParams params) throws IOException { Socket sock = socket != null ? socket : createSocket(params); if (localAddress != null) { sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params)); sock.bind(localAddress); } int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); try { sock.setSoTimeout(soTimeout); sock.connect(remoteAddress, connTimeout); } catch (SocketTimeoutException ex) { closeSocket(sock); throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out!"); } String host; if (remoteAddress instanceof HttpInetSocketAddress) { host = ((HttpInetSocketAddress) remoteAddress).getHttpHost().getHostName(); } else { host = remoteAddress.getHostName(); } SSLSocket sslSocket; if (sock instanceof SSLSocket) { sslSocket = (SSLSocket) sock; } else { int port = remoteAddress.getPort(); sslSocket = (SSLSocket) sf.createSocket(sock, host, port, true); } verify(hv, host, sslSocket); return sslSocket; } @Override public Socket createLayeredSocket(final Socket socket, final String host, final int port, final HttpParams params) throws IOException { SSLSocket sslSocket = (SSLSocket) sf.createSocket(socket, host, port, true); verify(hv, host, sslSocket); return sslSocket; } }; }
From source file:com.ea.core.bridge.ws.rest.client.AbstractRestClient.java
public AbstractRestClient(URL httpUrl) { super(httpUrl); HttpMessageParserFactory<HttpResponse> responseParserFactory = new DefaultHttpResponseParserFactory() { @Override/*from w w w. jav a 2s . c om*/ public HttpMessageParser<HttpResponse> create(SessionInputBuffer buffer, MessageConstraints constraints) { LineParser lineParser = new BasicLineParser() { @Override public Header parseHeader(final CharArrayBuffer buffer) { try { return super.parseHeader(buffer); } catch (ParseException ex) { return new BasicHeader(buffer.toString(), null); } } }; return new DefaultHttpResponseParser(buffer, lineParser, DefaultHttpResponseFactory.INSTANCE, constraints) { @Override protected boolean reject(final CharArrayBuffer line, int count) { // try to ignore all garbage preceding a status line infinitely return false; } }; } }; HttpMessageWriterFactory<HttpRequest> requestWriterFactory = new DefaultHttpRequestWriterFactory(); HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory = new ManagedHttpClientConnectionFactory( requestWriterFactory, responseParserFactory); SSLContext sslcontext = SSLContexts.createSystemDefault(); X509HostnameVerifier hostnameVerifier = new BrowserCompatHostnameVerifier(); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.INSTANCE) .register("https", new SSLConnectionSocketFactory(sslcontext, hostnameVerifier)).build(); DnsResolver dnsResolver = new SystemDefaultDnsResolver() { @Override public InetAddress[] resolve(final String host) throws UnknownHostException { if (host.equalsIgnoreCase("myhost") || host.equalsIgnoreCase("localhost")) { return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) }; } else { return super.resolve(host); } } }; PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager( socketFactoryRegistry, connFactory, dnsResolver); SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build(); connManager.setDefaultSocketConfig(socketConfig); connManager.setSocketConfig(new HttpHost("somehost", 80), socketConfig); MessageConstraints messageConstraints = MessageConstraints.custom().setMaxHeaderCount(200) .setMaxLineLength(2000).build(); ConnectionConfig connectionConfig = ConnectionConfig.custom() .setMalformedInputAction(CodingErrorAction.IGNORE) .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8) .setMessageConstraints(messageConstraints).build(); connManager.setDefaultConnectionConfig(connectionConfig); connManager.setConnectionConfig(new HttpHost("somehost", 80), ConnectionConfig.DEFAULT); connManager.setMaxTotal(100); connManager.setDefaultMaxPerRoute(10); connManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20); CookieStore cookieStore = new BasicCookieStore(); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH) .setExpectContinueEnabled(true).setStaleConnectionCheckEnabled(true) .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)) .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).setConnectionRequestTimeout(3000) .setConnectTimeout(3000).setSocketTimeout(3000).build(); client = HttpClients.custom().setConnectionManager(connManager).setDefaultCookieStore(cookieStore) .setDefaultCredentialsProvider(credentialsProvider) // .setProxy(new HttpHost("myproxy", 8080)) .setDefaultRequestConfig(defaultRequestConfig).build(); }
From source file:org.apache.directory.studio.connection.core.io.StudioTrustManager.java
/** * {@inheritDoc}//from w w w. jav a2 s.c om */ public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { // check permanent trusted certificates, return on success try { X509TrustManager permanentTrustManager = getPermanentTrustManager(); if (permanentTrustManager != null) { permanentTrustManager.checkServerTrusted(chain, authType); return; } } catch (CertificateException ce) { } // check temporary trusted certificates, return on success try { X509TrustManager sessionTrustManager = getSessionTrustManager(); if (sessionTrustManager != null) { sessionTrustManager.checkServerTrusted(chain, authType); return; } } catch (CertificateException ce) { } // below here no manually trusted certificate (either permanent or temporary) matched List<ICertificateHandler.FailCause> failCauses = new ArrayList<ICertificateHandler.FailCause>(); // perform trust check of JVM trust manager try { jvmTrustManager.checkServerTrusted(chain, authType); } catch (CertificateException ce) { if (ce instanceof CertificateExpiredException) { failCauses.add(FailCause.CertificateExpired); } else if (ce instanceof CertificateNotYetValidException) { failCauses.add(FailCause.CertificateNotYetValid); } else { X500Principal issuerX500Principal = chain[0].getIssuerX500Principal(); X500Principal subjectX500Principal = chain[0].getSubjectX500Principal(); if (issuerX500Principal.equals(subjectX500Principal)) { failCauses.add(FailCause.SelfSignedCertificate); } else { failCauses.add(FailCause.NoValidCertificationPath); } try { chain[0].checkValidity(); } catch (CertificateException ve) { if (ve instanceof CertificateExpiredException) { failCauses.add(FailCause.CertificateExpired); } else if (ve instanceof CertificateNotYetValidException) { failCauses.add(FailCause.CertificateNotYetValid); } } } } // perform host name verification try { BrowserCompatHostnameVerifier hostnameVerifier = new BrowserCompatHostnameVerifier(); hostnameVerifier.verify(host, chain[0]); } catch (SSLException ce) { failCauses.add(FailCause.HostnameVerificationFailed); } if (!failCauses.isEmpty()) { // either trust check or host name verification // ask for confirmation ICertificateHandler ch = ConnectionCorePlugin.getDefault().getCertificateHandler(); ICertificateHandler.TrustLevel trustLevel = ch.verifyTrustLevel(host, chain, failCauses); switch (trustLevel) { case Permanent: ConnectionCorePlugin.getDefault().getPermanentTrustStoreManager().addCertificate(chain[0]); break; case Session: ConnectionCorePlugin.getDefault().getSessionTrustStoreManager().addCertificate(chain[0]); break; case Not: throw new CertificateException(Messages.error__untrusted_certificate); } } }
From source file:com.alphabetbloc.accessmrs.utilities.NetworkUtils.java
public static HttpClient getHttpClient() { HttpClient client = null;//from w w w. j av a 2 s. c om try { if (App.DEBUG) Log.v(TAG, "httpClient is null, download is creating a new client"); SSLContext sslContext = createSslContext(); MySSLSocketFactory socketFactory = new MySSLSocketFactory(sslContext, new BrowserCompatHostnameVerifier()); client = createHttpClient(socketFactory); } catch (GeneralSecurityException e) { Log.e(TAG, "Could not load the trust manager"); e.printStackTrace(); } catch (IOException e) { Log.e(TAG, "Could not load the trust manager. Ensure credential storage is available"); e.printStackTrace(); } return client; }
From source file:com.owncloud.android.network.OwnCloudClientUtils.java
public static AdvancedSslSocketFactory getAdvancedSslSocketFactory(Context context) throws GeneralSecurityException, IOException { if (mAdvancedSslSocketFactory == null) { KeyStore trustStore = getKnownServersStore(context); AdvancedX509TrustManager trustMgr = new AdvancedX509TrustManager(trustStore); TrustManager[] tms = new TrustManager[] { trustMgr }; SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tms, null); mHostnameVerifier = new BrowserCompatHostnameVerifier(); mAdvancedSslSocketFactory = new AdvancedSslSocketFactory(sslContext, trustMgr, mHostnameVerifier); }//from ww w . j a v a 2 s . com return mAdvancedSslSocketFactory; }
From source file:org.andstatus.app.net.http.TlsSniSocketFactory.java
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) private void connectWithSNI(SSLSocket ssl, String host) throws SSLPeerUnverifiedException { // set reasonable SSL/TLS settings before the handshake: // - enable all supported protocols (enables TLSv1.1 and TLSv1.2 on Android <4.4.3, if available) ssl.setEnabledProtocols(ssl.getSupportedProtocols()); // - set SNI host name if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { MyLog.d(this, "Using documented SNI with host name " + host); sslSocketFactory.setHostname(ssl, host); } else {//from w ww .j a va 2 s . c o m MyLog.d(this, "No documented SNI support on Android <4.2, trying with reflection"); try { java.lang.reflect.Method setHostnameMethod = ssl.getClass().getMethod("setHostname", String.class); setHostnameMethod.invoke(ssl, host); } catch (Exception e) { MyLog.i(this, "SNI not useable", e); } } // verify hostname and certificate SSLSession session = ssl.getSession(); if (!session.isValid()) { MyLog.i(this, "Invalid session to host:'" + host + "'"); } HostnameVerifier hostnameVerifier = secure ? new BrowserCompatHostnameVerifier() : new AllowAllHostnameVerifier(); if (!hostnameVerifier.verify(host, session)) { throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host); } MyLog.i(this, "Established " + session.getProtocol() + " connection with " + session.getPeerHost() + " using " + session.getCipherSuite()); }