List of usage examples for javax.net.ssl SSLSocket startHandshake
public abstract void startHandshake() throws IOException;
From source file:davmail.util.ClientCertificateTest.java
public void testClientSocket() throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, KeyManagementException, UnrecoverableKeyException { //System.setProperty("javax.net.ssl.trustStoreProvider", "SunMSCAPI"); //System.setProperty("javax.net.ssl.trustStoreType", "Windows-ROOT"); System.setProperty("javax.net.ssl.trustStore", "cacerts"); System.setProperty("javax.net.ssl.trustStorePassword", "changeit"); System.setProperty("javax.net.ssl.trustStoreType", "JKS"); String algorithm = KeyManagerFactory.getDefaultAlgorithm(); if ("SunX509".equals(algorithm)) { algorithm = "NewSunX509"; } else if ("IbmX509".equals(algorithm)) { algorithm = "NewIbmX509"; }/*from w w w . j a v a 2 s . c om*/ Provider sunMSCAPI = new sun.security.mscapi.SunMSCAPI(); //Security.insertProviderAt(sunMSCAPI, 1); KeyStore keyStore = KeyStore.getInstance("Windows-MY", sunMSCAPI); keyStore.load(null, null); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm); keyManagerFactory.init(keyStore, null); // Get a list of key managers KeyManager[] keyManagers = keyManagerFactory.getKeyManagers(); // Walk through the key managers and replace all X509 Key Managers with // a specialized wrapped DavMail X509 Key Manager for (int i = 0; i < keyManagers.length; i++) { KeyManager keyManager = keyManagers[i]; if (keyManager instanceof X509KeyManager) { keyManagers[i] = new DavMailX509KeyManager((X509KeyManager) keyManager); } } SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagers, null, null); SSLSocketFactory sockFactory = sslContext.getSocketFactory(); SSLSocket sslSock = (SSLSocket) sockFactory.createSocket("localhost", 443); sslSock.startHandshake(); }
From source file:org.dcache.srm.client.FlexibleCredentialSSLConnectionSocketFactory.java
@Override public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context) throws IOException { Args.notNull(host, "HTTP host"); Args.notNull(remoteAddress, "Remote address"); final Socket sock = socket != null ? socket : createSocket(context); if (localAddress != null) { sock.bind(localAddress);//ww w .j a v a 2s .c om } try { if (connectTimeout > 0 && sock.getSoTimeout() == 0) { sock.setSoTimeout(connectTimeout); } LOGGER.debug("Connecting socket to {} with timeout {}", remoteAddress, connectTimeout); sock.connect(remoteAddress, connectTimeout); } catch (final IOException ex) { try { sock.close(); } catch (final IOException ignore) { } throw ex; } // Setup SSL layering if necessary if (sock instanceof SSLSocket) { final SSLSocket sslsock = (SSLSocket) sock; LOGGER.debug("Starting handshake"); sslsock.startHandshake(); verifyHostname(sslsock, host.getHostName()); return sock; } else { return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context); } }
From source file:com.owncloud.android.network.AdvancedSslSocketFactory.java
/** * Verifies the identity of the server. * /*from ww w.j a v a2s. com*/ * The server certificate is verified first. * * Then, the host name is compared with the content of the server certificate using the current host name verifier, if any. * @param socket */ private void verifyPeerIdentity(String host, int port, Socket socket) throws IOException { try { CertificateCombinedException failInHandshake = null; /// 1. VERIFY THE SERVER CERTIFICATE through the registered TrustManager (that should be an instance of AdvancedX509TrustManager) try { SSLSocket sock = (SSLSocket) socket; // a new SSLSession instance is created as a "side effect" sock.startHandshake(); } catch (RuntimeException e) { if (e instanceof CertificateCombinedException) { failInHandshake = (CertificateCombinedException) e; } else { Throwable cause = e.getCause(); Throwable previousCause = null; while (cause != null && cause != previousCause && !(cause instanceof CertificateCombinedException)) { previousCause = cause; cause = cause.getCause(); } if (cause != null && cause instanceof CertificateCombinedException) { failInHandshake = (CertificateCombinedException) cause; } } if (failInHandshake == null) { throw e; } failInHandshake.setHostInUrl(host); } /// 2. VERIFY HOSTNAME SSLSession newSession = null; boolean verifiedHostname = true; if (mHostnameVerifier != null) { if (failInHandshake != null) { /// 2.1 : a new SSLSession instance was NOT created in the handshake X509Certificate serverCert = failInHandshake.getServerCertificate(); try { mHostnameVerifier.verify(host, serverCert); } catch (SSLException e) { verifiedHostname = false; } } else { /// 2.2 : a new SSLSession instance was created in the handshake newSession = ((SSLSocket) socket).getSession(); if (!mTrustManager.isKnownServer((X509Certificate) (newSession.getPeerCertificates()[0]))) { verifiedHostname = mHostnameVerifier.verify(host, newSession); } } } /// 3. Combine the exceptions to throw, if any if (!verifiedHostname) { SSLPeerUnverifiedException pue = new SSLPeerUnverifiedException( "Names in the server certificate do not match to " + host + " in the URL"); if (failInHandshake == null) { failInHandshake = new CertificateCombinedException( (X509Certificate) newSession.getPeerCertificates()[0]); failInHandshake.setHostInUrl(host); } failInHandshake.setSslPeerUnverifiedException(pue); pue.initCause(failInHandshake); throw pue; } else if (failInHandshake != null) { SSLHandshakeException hse = new SSLHandshakeException("Server certificate could not be verified"); hse.initCause(failInHandshake); throw hse; } } catch (IOException io) { try { socket.close(); } catch (Exception x) { // NOTHING - irrelevant exception for the caller } throw io; } }
From source file:com.serphacker.serposcope.scraper.http.extensions.ScrapClientSSLConnectionFactory.java
@Override public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context) throws IOException { Args.notNull(host, "HTTP host"); Args.notNull(remoteAddress, "Remote address"); final Socket sock = socket != null ? socket : createSocket(context); if (localAddress != null) { sock.bind(localAddress);// w w w .ja v a2 s . c o m } try { if (connectTimeout > 0 && sock.getSoTimeout() == 0) { sock.setSoTimeout(connectTimeout); } if (this.log.isDebugEnabled()) { this.log.debug("Connecting socket to " + remoteAddress + " with timeout " + connectTimeout); } sock.connect(remoteAddress, connectTimeout); } catch (final IOException ex) { try { sock.close(); } catch (final IOException ignore) { } throw ex; } // Setup SSL layering if necessary if (sock instanceof SSLSocket) { final SSLSocket sslsock = (SSLSocket) sock; this.log.debug("Starting handshake"); sslsock.startHandshake(); verifyHostname(sslsock, host.getHostName()); return sock; } else { return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context); } }
From source file:org.apache.tomcat.util.net.jsse.JSSE14Support.java
/** * JSSE in JDK 1.4 has an issue/feature that requires us to do a * read() to get the client-cert. As suggested by Andreas * Sterbenz//from w ww.j a v a 2 s .c o m */ private void synchronousHandshake(SSLSocket socket) throws IOException { InputStream in = socket.getInputStream(); int oldTimeout = socket.getSoTimeout(); socket.setSoTimeout(1000); byte[] b = new byte[0]; listener.reset(); socket.startHandshake(); int maxTries = 60; // 60 * 1000 = example 1 minute time out for (int i = 0; i < maxTries; i++) { if (logger.isTraceEnabled()) logger.trace("Reading for try #" + i); try { int x = in.read(b); } catch (SSLException sslex) { logger.info("SSL Error getting client Certs", sslex); throw sslex; } catch (IOException e) { // ignore - presumably the timeout } if (listener.completed) { break; } } socket.setSoTimeout(oldTimeout); if (listener.completed == false) { throw new SocketException("SSL Cert handshake timeout"); } }
From source file:eu.eidas.node.auth.metadata.NodeMetadataFetcher.java
protected SecureProtocolSocketFactory hubLocalSslSocketFactory() { HostnameVerifier hostnameVerifier; if (!Boolean.getBoolean(DefaultBootstrap.SYSPROP_HTTPCLIENT_HTTPS_DISABLE_HOSTNAME_VERIFICATION)) { hostnameVerifier = new StrictHostnameVerifier(); } else {/* ww w . j a v a 2s .co m*/ hostnameVerifier = org.apache.commons.ssl.HostnameVerifier.ALLOW_ALL; } X509TrustManager trustedCertManager = new X509TrustManager() { @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { try { return new X509Certificate[] { CertificateUtil.toCertificate(hubSslCertificateString) }; } catch (EIDASSAMLEngineException e) { throw new RuntimeException("Unable to load trusted certificate: ", e); } } @Override public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { } }; TLSProtocolSocketFactory tlsProtocolSocketFactory = new TLSProtocolSocketFactory(null, trustedCertManager, hostnameVerifier) { @Override protected void verifyHostname(Socket socket) throws SSLException { if (socket instanceof SSLSocket) { SSLSocket sslSocket = (SSLSocket) socket; try { sslSocket.startHandshake(); } catch (IOException e) { throw new SSLException(e); } SSLSession sslSession = sslSocket.getSession(); if (!sslSession.isValid()) { throw new SSLException("SSLSession was invalid: Likely implicit handshake failure: " + "Set system property javax.net.debug=all for details"); } super.verifyHostname(sslSocket); } } }; Protocol.registerProtocol("https", new Protocol("https", tlsProtocolSocketFactory, 443)); return tlsProtocolSocketFactory; }
From source file:net.lightbody.bmp.proxy.jetty.http.JsseListener.java
/** * @param p_serverSocket//w ww. j a va2 s . c om * @return * @exception IOException */ protected Socket accept(ServerSocket p_serverSocket) throws IOException { try { SSLSocket s = (SSLSocket) p_serverSocket.accept(); if (getMaxIdleTimeMs() > 0) s.setSoTimeout(getMaxIdleTimeMs()); s.startHandshake(); // block until SSL handshaking is done return s; } catch (SSLException e) { log.warn(LogSupport.EXCEPTION, e); throw new IOException(e.getMessage()); } }
From source file:com.zimbra.cs.mailclient.MailConnection.java
protected void startTls() throws IOException { checkState(State.NOT_AUTHENTICATED); sendStartTls();//from w w w . j a va 2s . c om SSLSocket sock = newSSLSocket(socket); sock.startHandshake(); initStreams(sock.getInputStream(), sock.getOutputStream()); }
From source file:client.ui.Container.java
private JSONObject getCert(SocketFactory factory, URL url) { JSONObject json = new JSONObject(); json.put("host", url.getHost()); json.put("port", url.getPort()); try {/*from w ww . j a va2 s. c om*/ log("Get Certs: " + url.getHost() + ":" + url.getPort()); SSLSocket socket = (SSLSocket) factory.createSocket(url.getHost(), url.getPort()); socket.startHandshake(); Certificate[] certs = socket.getSession().getPeerCertificates(); String result = ""; for (Certificate cert : certs) { if (cert instanceof X509Certificate) { try { ((X509Certificate) cert).checkValidity(); result += "OK "; } catch (CertificateExpiredException cee) { result += "Expired "; } catch (CertificateNotYetValidException ex) { result += "NotYetValid "; } } } log("Result: " + result.trim()); json.put("result", result.trim()); } catch (SSLException se) { log("Error: SSLException (" + se.getMessage() + ")"); json.put("result", "SSLException: " + se.getMessage()); } catch (ConnectException ce) { log("Error: ConnectException (" + ce.getMessage() + ")"); json.put("result", "ConnectException: " + ce.getMessage()); } catch (IOException ioe) { log("Error: IOException (" + ioe.getMessage() + ")"); json.put("result", "IOException: " + ioe.getMessage()); } return json; }
From source file:com.cerema.cloud2.lib.common.network.AdvancedSslSocketFactory.java
/** * Verifies the identity of the server. * /* w ww .j ava2 s.c om*/ * The server certificate is verified first. * * Then, the host name is compared with the content of the server certificate using the current host name verifier, * if any. * @param socket */ private void verifyPeerIdentity(String host, int port, Socket socket) throws IOException { try { CertificateCombinedException failInHandshake = null; /// 1. VERIFY THE SERVER CERTIFICATE through the registered TrustManager /// (that should be an instance of AdvancedX509TrustManager) try { SSLSocket sock = (SSLSocket) socket; // a new SSLSession instance is created as a "side effect" sock.startHandshake(); } catch (RuntimeException e) { if (e instanceof CertificateCombinedException) { failInHandshake = (CertificateCombinedException) e; } else { Throwable cause = e.getCause(); Throwable previousCause = null; while (cause != null && cause != previousCause && !(cause instanceof CertificateCombinedException)) { previousCause = cause; cause = cause.getCause(); } if (cause != null && cause instanceof CertificateCombinedException) { failInHandshake = (CertificateCombinedException) cause; } } if (failInHandshake == null) { throw e; } failInHandshake.setHostInUrl(host); } /// 2. VERIFY HOSTNAME SSLSession newSession = null; boolean verifiedHostname = true; if (mHostnameVerifier != null) { if (failInHandshake != null) { /// 2.1 : a new SSLSession instance was NOT created in the handshake X509Certificate serverCert = failInHandshake.getServerCertificate(); try { mHostnameVerifier.verify(host, serverCert); } catch (SSLException e) { verifiedHostname = false; } } else { /// 2.2 : a new SSLSession instance was created in the handshake newSession = ((SSLSocket) socket).getSession(); if (!mTrustManager.isKnownServer((X509Certificate) (newSession.getPeerCertificates()[0]))) { verifiedHostname = mHostnameVerifier.verify(host, newSession); } } } /// 3. Combine the exceptions to throw, if any if (!verifiedHostname) { SSLPeerUnverifiedException pue = new SSLPeerUnverifiedException( "Names in the server certificate do not match to " + host + " in the URL"); if (failInHandshake == null) { failInHandshake = new CertificateCombinedException( (X509Certificate) newSession.getPeerCertificates()[0]); failInHandshake.setHostInUrl(host); } failInHandshake.setSslPeerUnverifiedException(pue); pue.initCause(failInHandshake); throw pue; } else if (failInHandshake != null) { SSLHandshakeException hse = new SSLHandshakeException("Server certificate could not be verified"); hse.initCause(failInHandshake); throw hse; } } catch (IOException io) { try { socket.close(); } catch (Exception x) { // NOTHING - irrelevant exception for the caller } throw io; } }