List of usage examples for org.apache.http.conn.ssl DefaultHostnameVerifier DefaultHostnameVerifier
public DefaultHostnameVerifier(final PublicSuffixMatcher publicSuffixMatcher)
From source file:interoperabilite.webservice.client.ClientCustomPublicSuffixList.java
public final static void main(String[] args) throws Exception { // Use PublicSuffixMatcherLoader to load public suffix list from a file, // resource or from an arbitrary URL PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader .load(new URL("https://publicsuffix.org/list/effective_tld_names.dat")); // Please use the publicsuffix.org URL to download the list no more than once per day !!! // Please consider making a local copy !!! DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher); RFC6265CookieSpecProvider cookieSpecProvider = new RFC6265CookieSpecProvider(publicSuffixMatcher); Lookup<CookieSpecProvider> cookieSpecRegistry = RegistryBuilder.<CookieSpecProvider>create() .register(CookieSpecs.DEFAULT, cookieSpecProvider) .register(CookieSpecs.STANDARD, cookieSpecProvider) .register(CookieSpecs.STANDARD_STRICT, cookieSpecProvider).build(); CloseableHttpClient httpclient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier) .setDefaultCookieSpecRegistry(cookieSpecRegistry).build(); try {/*from ww w . j av a 2s . c o m*/ HttpGet httpget = new HttpGet("https://httpbin.org/"); System.out.println("executing request " + httpget.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpget); try { HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); EntityUtils.consume(entity); } finally { response.close(); } } finally { httpclient.close(); } }
From source file:org.aevans.goat.net.SSLStrategyGetter.java
public static SchemeIOSessionStrategy getSchemeIOSessionStrategy() { DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier( PublicSuffixMatcherLoader.getDefault()); SchemeIOSessionStrategy sioss = new SchemeIOSessionStrategy() { @Override/*from w ww . j a v a 2 s .c o m*/ public boolean isLayeringRequired() { return true; } @Override public IOSession upgrade(final HttpHost host, final IOSession iosession) throws IOException { SSLSetupHandler handler = new SSLSetupHandler() { @Override public void initalize(SSLEngine sslengine) throws SSLException { } @Override public void verify(IOSession iosession, SSLSession sslsession) throws SSLException { if (!hostnameVerifier.verify(host.getHostName(), sslsession)) { final java.security.cert.Certificate[] certs = sslsession.getPeerCertificates(); final X509Certificate x509 = (X509Certificate) certs[0]; final X500Principal x500Principal = x509.getSubjectX500Principal(); throw new SSLPeerUnverifiedException("Host name '" + host.getHostName() + "' does not match " + "the certificate subject provided by the peer (" + x500Principal.toString() + ")"); } } }; SSLBufferManagementStrategy sslbm = new ReleasableSSLBufferManagementStrategy(); SSLIOSession ssio = new SSLIOSession(iosession, SSLMode.CLIENT, host, SSLContexts.createDefault(), handler, sslbm); iosession.setAttribute(SSLIOSession.SESSION_KEY, ssio); ssio.initialize(); return ssio; } }; return sioss; }
From source file:net.i2p.util.I2PSSLSocketFactory.java
/** * Validate the hostname/* ww w. j a v a 2 s . c o m*/ * * ref: https://developer.android.com/training/articles/security-ssl.html * ref: http://op-co.de/blog/posts/java_sslsocket_mitm/ * ref: http://kevinlocke.name/bits/2012/10/03/ssl-certificate-verification-in-dispatch-and-asynchttpclient/ * * @throws SSLException on hostname verification failure * @since 0.9.20 */ public static void verifyHostname(I2PAppContext ctx, SSLSocket socket, String host) throws SSLException { Log log = ctx.logManager().getLog(I2PSSLSocketFactory.class); if (ctx.getBooleanProperty(PROP_DISABLE) || host.equals("localhost") || host.equals("127.0.0.1") || host.equals("::1") || host.equals("0:0:0:0:0:0:0:1")) { if (log.shouldWarn()) log.warn("Skipping hostname validation for " + host); return; } HostnameVerifier hv; if (SystemVersion.isAndroid()) { // https://developer.android.com/training/articles/security-ssl.html hv = HttpsURLConnection.getDefaultHostnameVerifier(); } else { // haha the above may work for Android but it doesn't in Oracle // // quote http://kevinlocke.name/bits/2012/10/03/ssl-certificate-verification-in-dispatch-and-asynchttpclient/ : // Unlike SSLContext, using the Java default (HttpsURLConnection.getDefaultHostnameVerifier) // is not a viable option because the default HostnameVerifier expects to only be called // in the case that there is a mismatch (and therefore always returns false) while some // of the AsyncHttpClient providers (e.g. Netty, the default) call it on all connections. // To make matters worse, the check is not trivial (consider SAN and wildcard matching) // and is implemented in sun.security.util.HostnameChecker (a Sun internal proprietary API). // This leaves the developer in the position of either depending on an internal API or // finding/copying/creating another implementation of this functionality. // hv = new DefaultHostnameVerifier(getDefaultMatcher(ctx)); } SSLSession sess = socket.getSession(); // Verify that the certicate hostname is for mail.google.com // This is due to lack of SNI support in the current SSLSocket. if (!hv.verify(host, sess)) { throw new SSLHandshakeException("SSL hostname verify failed, Expected " + host + // throws SSLPeerUnverifiedException //", found " + sess.getPeerPrincipal() + // returns null //", found " + sess.getPeerHost() + // enable logging for DefaultHostnameVerifier to find out the CN and SANs " - set " + PROP_DISABLE + "=true to disable verification (dangerous!)"); } // At this point SSLSocket performed certificate verificaiton and // we have performed hostname verification, so it is safe to proceed. }
From source file:org.apache.hive.jdbc.HiveConnection.java
private CloseableHttpClient getHttpClient(Boolean useSsl) throws SQLException { boolean isCookieEnabled = sessConfMap.get(JdbcConnectionParams.COOKIE_AUTH) == null || (!JdbcConnectionParams.COOKIE_AUTH_FALSE .equalsIgnoreCase(sessConfMap.get(JdbcConnectionParams.COOKIE_AUTH))); String cookieName = sessConfMap.get(JdbcConnectionParams.COOKIE_NAME) == null ? JdbcConnectionParams.DEFAULT_COOKIE_NAMES_HS2 : sessConfMap.get(JdbcConnectionParams.COOKIE_NAME); CookieStore cookieStore = isCookieEnabled ? new BasicCookieStore() : null; HttpClientBuilder httpClientBuilder; // Request interceptor for any request pre-processing logic HttpRequestInterceptor requestInterceptor; Map<String, String> additionalHttpHeaders = new HashMap<String, String>(); // Retrieve the additional HttpHeaders for (Map.Entry<String, String> entry : sessConfMap.entrySet()) { String key = entry.getKey(); if (key.startsWith(JdbcConnectionParams.HTTP_HEADER_PREFIX)) { additionalHttpHeaders.put(key.substring(JdbcConnectionParams.HTTP_HEADER_PREFIX.length()), entry.getValue());//from w w w .ja v a2 s. c om } } // Configure http client for kerberos/password based authentication if (isKerberosAuthMode()) { /** * Add an interceptor which sets the appropriate header in the request. * It does the kerberos authentication and get the final service ticket, * for sending to the server before every request. * In https mode, the entire information is encrypted */ requestInterceptor = new HttpKerberosRequestInterceptor( sessConfMap.get(JdbcConnectionParams.AUTH_PRINCIPAL), host, getServerHttpUrl(useSsl), assumeSubject, cookieStore, cookieName, useSsl, additionalHttpHeaders); } else { // Check for delegation token, if present add it in the header String tokenStr = getClientDelegationToken(sessConfMap); if (tokenStr != null) { requestInterceptor = new HttpTokenAuthInterceptor(tokenStr, cookieStore, cookieName, useSsl, additionalHttpHeaders); } else { /** * Add an interceptor to pass username/password in the header. * In https mode, the entire information is encrypted */ requestInterceptor = new HttpBasicAuthInterceptor(getUserName(), getPassword(), cookieStore, cookieName, useSsl, additionalHttpHeaders); } } // Configure http client for cookie based authentication if (isCookieEnabled) { // Create a http client with a retry mechanism when the server returns a status code of 401. httpClientBuilder = HttpClients.custom() .setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() { @Override public boolean retryRequest(final HttpResponse response, final int executionCount, final HttpContext context) { int statusCode = response.getStatusLine().getStatusCode(); boolean ret = statusCode == 401 && executionCount <= 1; // Set the context attribute to true which will be interpreted by the request // interceptor if (ret) { context.setAttribute(Utils.HIVE_SERVER2_RETRY_KEY, Utils.HIVE_SERVER2_RETRY_TRUE); } return ret; } @Override public long getRetryInterval() { // Immediate retry return 0; } }); } else { httpClientBuilder = HttpClientBuilder.create(); } // In case the server's idletimeout is set to a lower value, it might close it's side of // connection. However we retry one more time on NoHttpResponseException httpClientBuilder.setRetryHandler(new HttpRequestRetryHandler() { @Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount > 1) { LOG.info("Retry attempts to connect to server exceeded."); return false; } if (exception instanceof org.apache.http.NoHttpResponseException) { LOG.info("Could not connect to the server. Retrying one more time."); return true; } return false; } }); // Add the request interceptor to the client builder httpClientBuilder.addInterceptorFirst(requestInterceptor); // Add an interceptor to add in an XSRF header httpClientBuilder.addInterceptorLast(new XsrfHttpRequestInterceptor()); // Configure http client for SSL if (useSsl) { String useTwoWaySSL = sessConfMap.get(JdbcConnectionParams.USE_TWO_WAY_SSL); String sslTrustStorePath = sessConfMap.get(JdbcConnectionParams.SSL_TRUST_STORE); String sslTrustStorePassword = sessConfMap.get(JdbcConnectionParams.SSL_TRUST_STORE_PASSWORD); KeyStore sslTrustStore; SSLConnectionSocketFactory socketFactory; SSLContext sslContext; /** * The code within the try block throws: SSLInitializationException, KeyStoreException, * IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException & * UnrecoverableKeyException. We don't want the client to retry on any of these, * hence we catch all and throw a SQLException. */ try { if (useTwoWaySSL != null && useTwoWaySSL.equalsIgnoreCase(JdbcConnectionParams.TRUE)) { socketFactory = getTwoWaySSLSocketFactory(); } else if (sslTrustStorePath == null || sslTrustStorePath.isEmpty()) { // Create a default socket factory based on standard JSSE trust material socketFactory = SSLConnectionSocketFactory.getSocketFactory(); } else { // Pick trust store config from the given path sslTrustStore = KeyStore.getInstance(JdbcConnectionParams.SSL_TRUST_STORE_TYPE); try (FileInputStream fis = new FileInputStream(sslTrustStorePath)) { sslTrustStore.load(fis, sslTrustStorePassword.toCharArray()); } sslContext = SSLContexts.custom().loadTrustMaterial(sslTrustStore, null).build(); socketFactory = new SSLConnectionSocketFactory(sslContext, new DefaultHostnameVerifier(null)); } final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", socketFactory).build(); httpClientBuilder.setConnectionManager(new BasicHttpClientConnectionManager(registry)); } catch (Exception e) { String msg = "Could not create an https connection to " + jdbcUriString + ". " + e.getMessage(); throw new SQLException(msg, " 08S01", e); } } return httpClientBuilder.build(); }
From source file:org.apache.http.conn.ssl.SSLConnectionSocketFactory.java
/** * @since 4.4/* ww w.j a v a2 s. c o m*/ */ public static HostnameVerifier getDefaultHostnameVerifier() { return new DefaultHostnameVerifier(PublicSuffixMatcherLoader.getDefault()); }