List of usage examples for javax.net.ssl HostnameVerifier verify
public boolean verify(String hostname, SSLSession session);
From source file:com.fuzhouxiu.coretransfer.net.core.TcpSocket.java
/** Creates a new UdpSocket */ public TcpSocket(IpAddress ipaddr, int port, String host) throws java.io.IOException { // socket = new Socket(ipaddr.getInetAddress(), port); modified SSLSocketFactory f = (SSLSocketFactory) SSLSocketFactory.getSocketFactory(); if (host == null) socket = new Socket(); else/*w w w.j a v a 2 s. co m*/ socket = f.createSocket(); if (lock) throw new java.io.IOException(); lock = true; try { socket.connect(new InetSocketAddress(ipaddr.toString(), port), Thread.currentThread().getName().equals("main") ? 1000 : 10000); } catch (java.io.IOException e) { lock = false; throw e; } if (host != null) { HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier(); SSLSession s = ((SSLSocket) socket).getSession(); if (!hv.verify(host, s)) { lock = false; throw new java.io.IOException(); } } lock = false; }
From source file:co.elastic.tealess.SSLChecker.java
private void checkHostnameVerification(SSLReport sslReport) { HostnameVerifier hv = new DefaultHostnameVerifier(); sslReport.setHostnameVerified(hv.verify(sslReport.getHostname(), sslReport.getSSLSession())); }
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 w w. ja v a 2s. co 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()); }
From source file:com.serphacker.serposcope.scraper.http.extensions.ScrapClientSSLConnectionFactory.java
private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException { try {/*from w ww.java 2 s . c om*/ SSLSession session = sslsock.getSession(); if (session == null) { // In our experience this only happens under IBM 1.4.x when // spurious (unrelated) certificates show up in the server' // chain. Hopefully this will unearth the real problem: final InputStream in = sslsock.getInputStream(); in.available(); // If ssl.getInputStream().available() didn't cause an // exception, maybe at least now the session is available? session = sslsock.getSession(); if (session == null) { // If it's still null, probably a startHandshake() will // unearth the real problem. sslsock.startHandshake(); session = sslsock.getSession(); } } if (session == null) { throw new SSLHandshakeException("SSL session not available"); } if (this.log.isDebugEnabled()) { this.log.debug("Secure session established"); this.log.debug(" negotiated protocol: " + session.getProtocol()); this.log.debug(" negotiated cipher suite: " + session.getCipherSuite()); try { final Certificate[] certs = session.getPeerCertificates(); final X509Certificate x509 = (X509Certificate) certs[0]; final X500Principal peer = x509.getSubjectX500Principal(); this.log.debug(" peer principal: " + peer.toString()); final Collection<List<?>> altNames1 = x509.getSubjectAlternativeNames(); if (altNames1 != null) { final List<String> altNames = new ArrayList<String>(); for (final List<?> aC : altNames1) { if (!aC.isEmpty()) { altNames.add((String) aC.get(1)); } } this.log.debug(" peer alternative names: " + altNames); } final X500Principal issuer = x509.getIssuerX500Principal(); this.log.debug(" issuer principal: " + issuer.toString()); final Collection<List<?>> altNames2 = x509.getIssuerAlternativeNames(); if (altNames2 != null) { final List<String> altNames = new ArrayList<String>(); for (final List<?> aC : altNames2) { if (!aC.isEmpty()) { altNames.add((String) aC.get(1)); } } this.log.debug(" issuer alternative names: " + altNames); } } catch (Exception ignore) { } } HostnameVerifier hostnameVerifier = insecure ? insecureHostnameVerifier : defaultHostnameVerifier; if (!hostnameVerifier.verify(hostname, session)) { final Certificate[] certs = session.getPeerCertificates(); final X509Certificate x509 = (X509Certificate) certs[0]; final X500Principal x500Principal = x509.getSubjectX500Principal(); throw new SSLPeerUnverifiedException("Host name '" + hostname + "' does not match " + "the certificate subject provided by the peer (" + x500Principal.toString() + ")"); } // verifyHostName() didn't blowup - good! } catch (final IOException iox) { // close the socket before re-throwing the exception try { sslsock.close(); } catch (final Exception x) { /*ignore*/ } throw iox; } }
From source file:jetbrains.buildServer.buildTriggers.vcs.git.SNIHttpClientConnection.java
public void setHostnameVerifier(final HostnameVerifier hostnameverifier) { this.hostnameverifier = new X509HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return hostnameverifier.verify(hostname, session); }/*w w w .j av a 2 s .co m*/ public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException { throw new UnsupportedOperationException(); // TODO message } public void verify(String host, X509Certificate cert) throws SSLException { throw new UnsupportedOperationException(); // TODO message } public void verify(String host, SSLSocket ssl) throws IOException { hostnameverifier.verify(host, ssl.getSession()); } }; }
From source file:org.apache.chemistry.opencmis.client.bindings.spi.http.AbstractApacheClientHttpInvoker.java
/** * Verifies a hostname with the given verifier. *///ww w .j a va 2s . c o m protected void verify(HostnameVerifier verifier, String host, SSLSocket sslSocket) throws IOException { try { if (verifier instanceof X509HostnameVerifier) { ((X509HostnameVerifier) verifier).verify(host, sslSocket); } else { if (!verifier.verify(host, sslSocket.getSession())) { throw new SSLException("Hostname in certificate didn't match: <" + host + ">"); } } } catch (IOException ioe) { closeSocket(sslSocket); throw ioe; } }
From source file:net.i2p.util.I2PSSLSocketFactory.java
/** * Validate the hostname/*from w ww . j av a 2 s. c om*/ * * 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:net.myrrix.client.ClientRecommender.java
private SSLSocketFactory buildSSLSocketFactory() throws IOException { final HostnameVerifier defaultVerifier = HttpsURLConnection.getDefaultHostnameVerifier(); HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { @Override//from www . ja va 2s. co m public boolean verify(String hostname, SSLSession sslSession) { return ignoreHTTPSHost || "localhost".equals(hostname) || "127.0.0.1".equals(hostname) || defaultVerifier.verify(hostname, sslSession); } }); try { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); File trustStoreFile = config.getKeystoreFile().getAbsoluteFile(); String password = config.getKeystorePassword(); Preconditions.checkNotNull(password); InputStream in = new FileInputStream(trustStoreFile); try { keyStore.load(in, password.toCharArray()); } finally { in.close(); } TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(keyStore); SSLContext ctx; try { ctx = SSLContext.getInstance("TLSv1.1"); // Java 7 only } catch (NoSuchAlgorithmException ignored) { log.info("TLSv1.1 unavailable, falling back to TLSv1"); ctx = SSLContext.getInstance("TLSv1"); // Java 6 // This also seems to be necessary: if (System.getProperty("https.protocols") == null) { System.setProperty("https.protocols", "TLSv1"); } } ctx.init(null, tmf.getTrustManagers(), null); return ctx.getSocketFactory(); } catch (NoSuchAlgorithmException nsae) { // can't happen? throw new IllegalStateException(nsae); } catch (KeyStoreException kse) { throw new IOException(kse); } catch (KeyManagementException kme) { throw new IOException(kme); } catch (CertificateException ce) { throw new IOException(ce); } }
From source file:org.dcm4chee.xds2.src.tool.pnrsnd.PnRSnd.java
private void configTLS() { final HostnameVerifier origHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier(); final String allowedUrlHost = props.getProperty("allowedUrlHost"); HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { if (!origHostnameVerifier.verify(urlHostName, session)) { if (isAllowedUrlHost(urlHostName)) { log.warn("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost()); } else { return false; }//from w ww .j a va 2 s .c om } return true; } private boolean isAllowedUrlHost(String urlHostName) { if (allowedUrlHost == null || "CERT".equals(allowedUrlHost)) return false; if (allowedUrlHost.equals("*")) return true; return allowedUrlHost.equals(urlHostName); } }; HttpsURLConnection.setDefaultHostnameVerifier(hv); }