List of usage examples for javax.net.ssl SSLSocket getSession
public abstract SSLSession getSession();
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 v a 2s . 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:de.vanita5.twittnuker.util.net.ssl.AbstractCheckSignatureVerifier.java
@Override public final void verify(final String host, final SSLSocket ssl) throws IOException { if (host == null) throw new NullPointerException("host to verify is null"); SSLSession session = ssl.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 = ssl.getInputStream(); in.available();//from w w w . j av a 2s . co m /* * If you're looking at the 2 lines of code above because you're * running into a problem, you probably have two options: * * #1. Clean up the certificate chain that your server is presenting * (e.g. edit "/etc/apache2/server.crt" or wherever it is your * server's certificate chain is defined). * * OR * * #2. Upgrade to an IBM 1.5.x or greater JVM, or switch to a * non-IBM JVM. */ // If ssl.getInputStream().available() didn't cause an // exception, maybe at least now the session is available? session = ssl.getSession(); if (session == null) { // If it's still null, probably a startHandshake() will // unearth the real problem. ssl.startHandshake(); // Okay, if we still haven't managed to cause an exception, // might as well go for the NPE. Or maybe we're okay now? session = ssl.getSession(); } } final Certificate[] certs = session.getPeerCertificates(); final X509Certificate x509 = (X509Certificate) certs[0]; verify(host, x509); }
From source file:test.integ.be.fedict.commons.eid.client.SSLTest.java
@Test public void testTestEIDBelgiumBe() throws Exception { Security.addProvider(new BeIDProvider()); SSLContext sslContext = SSLContext.getInstance("TLS"); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("BeID"); keyManagerFactory.init(null);//from w w w . j ava 2s. c om SecureRandom secureRandom = new SecureRandom(); sslContext.init(keyManagerFactory.getKeyManagers(), new TrustManager[] { new ClientTestX509TrustManager() }, secureRandom); SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket("test.eid.belgium.be", 443); LOG.debug("socket created"); SSLSession sslSession = sslSocket.getSession(); Certificate[] peerCertificates = sslSession.getPeerCertificates(); for (Certificate peerCertificate : peerCertificates) { LOG.debug("peer certificate: " + ((X509Certificate) peerCertificate).getSubjectX500Principal()); } }
From source file:org.bombusim.networking.NetworkSocketDataStream.java
public void setTLS() throws IOException { LimeLog.i("Socket", "Switching to secure socket layer", null); //TODO: check on different devices: // !!! ENSURE TLS enabled in account settings before test // 1. emulator/2.2 - SSLPeerUnverifiedException (jabber.ru, google.com) - bug in emulator v2.2 // 2. cyanogen/2.3 - works (all hosts) // 3. emulator/ics - works // 4. Gratia/2.2 - works SSLSocketFactory sf =/*from w w w.j ava 2s . co m*/ //SSLCertificateSocketFactory.getDefault(20000, null); SSLCertificateSocketFactory.getInsecure(20000, null); //TODO: check on different devices: // 1. emulator/2.2 - works // 2. cyanogen/2.3 - works //KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); //trustStore.load(null, null); //SSLSocketFactory sf = new AndroidSSLSocketFactory(trustStore); //sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); final SSLSocket ssls = (SSLSocket) sf.createSocket(socket, host, port, true); ssls.addHandshakeCompletedListener(new HandshakeCompletedListener() { @Override public void handshakeCompleted(HandshakeCompletedEvent event) { X509Certificate[] certs; try { certs = ssls.getSession().getPeerCertificateChain(); } catch (SSLPeerUnverifiedException e) { return; } StringBuilder so = new StringBuilder(); for (X509Certificate cert : certs) { so.append("X509 Certificate:\n").append(" Subject:"); appendPrincipal(so, cert.getSubjectDN()); so.append("\n Issued by:"); appendPrincipal(so, cert.getIssuerDN()); so.append("\n Valid from: ").append(DateFormat.getInstance().format(cert.getNotBefore())); so.append("\n Expired after: ").append(DateFormat.getInstance().format(cert.getNotAfter())); so.append("\n\n"); } certificateInfo = so.toString(); LimeLog.i("Socket", "Certificate chain verified", certificateInfo); } private void appendPrincipal(StringBuilder so, Principal p) { String name = p.getName(); if (name == null) { so.append("<null>\n"); return; } String elements[] = name.split(","); for (String e : elements) { so.append("\n ").append(e); } so.append("\n"); } }); ssls.startHandshake(); socket = ssls; istream = socket.getInputStream(); ostream = socket.getOutputStream(); }
From source file:com.sonatype.nexus.ssl.plugin.internal.CertificateRetriever.java
/** * Retrieves certificate chain of specified host:port using direct socket connection. * * @param host to get certificate chain from (cannot be null) * @param port of host to connect to//w ww .ja va2 s. com * @return certificate chain * @throws Exception Re-thrown from accessing the remote host */ public Certificate[] retrieveCertificates(final String host, final int port) throws Exception { checkNotNull(host); log.info("Retrieving certificate from {}:{} using direct socket connection", host, port); SSLSocket socket = null; try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, new TrustManager[] { ACCEPT_ALL_TRUST_MANAGER }, null); javax.net.ssl.SSLSocketFactory sslSocketFactory = sc.getSocketFactory(); socket = (SSLSocket) sslSocketFactory.createSocket(host, port); socket.startHandshake(); SSLSession session = socket.getSession(); return session.getPeerCertificates(); } finally { if (socket != null) { socket.close(); } } }
From source file:com.epam.reportportal.apache.http.conn.ssl.AbstractVerifier.java
public final void verify(final String host, final SSLSocket ssl) throws IOException { if (host == null) { throw new NullPointerException("host to verify is null"); }//from w ww.j a v a 2 s . c o m SSLSession session = ssl.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 = ssl.getInputStream(); in.available(); /* If you're looking at the 2 lines of code above because you're running into a problem, you probably have two options: #1. Clean up the certificate chain that your server is presenting (e.g. edit "/etc/apache2/server.crt" or wherever it is your server's certificate chain is defined). OR #2. Upgrade to an IBM 1.5.x or greater JVM, or switch to a non-IBM JVM. */ // If ssl.getInputStream().available() didn't cause an // exception, maybe at least now the session is available? session = ssl.getSession(); if (session == null) { // If it's still null, probably a startHandshake() will // unearth the real problem. ssl.startHandshake(); // Okay, if we still haven't managed to cause an exception, // might as well go for the NPE. Or maybe we're okay now? session = ssl.getSession(); } } final Certificate[] certs = session.getPeerCertificates(); final X509Certificate x509 = (X509Certificate) certs[0]; verify(host, x509); }
From source file:gov.miamidade.open311.utilities.SslContextedSecureProtocolSocketFactory.java
/** * Describe <code>verifyHostname</code> method here. * * @param socket//w ww. ja v a2s . c o m * a <code>SSLSocket</code> value * @exception SSLPeerUnverifiedException * If there are problems obtaining the server certificates * from the SSL session, or the server host name does not * match with the "Common Name" in the server certificates * SubjectDN. * @exception UnknownHostException * If we are not able to resolve the SSL sessions returned * server host name. */ private void verifyHostname(SSLSocket socket) throws SSLPeerUnverifiedException, UnknownHostException { synchronized (this) { if (!verifyHostname) return; } SSLSession session = socket.getSession(); String hostname = session.getPeerHost(); try { InetAddress.getByName(hostname); } catch (UnknownHostException uhe) { throw new UnknownHostException("Could not resolve SSL sessions " + "server hostname: " + hostname); } X509Certificate[] certs = (X509Certificate[]) session.getPeerCertificates(); if (certs == null || certs.length == 0) throw new SSLPeerUnverifiedException("No server certificates found!"); X500Principal subjectDN = certs[0].getSubjectX500Principal(); // get the common names from the first cert List<String> cns = getCNs(subjectDN); boolean foundHostName = false; for (String cn : cns) { if (hostname.equalsIgnoreCase(cn)) { foundHostName = true; break; } } if (!foundHostName) { throw new SSLPeerUnverifiedException( "HTTPS hostname invalid: expected '" + hostname + "', received '" + cns + "'"); } }
From source file:nl.nn.adapterframework.http.AuthSSLProtocolSocketFactoryBase.java
/** * Describe <code>verifyHostname</code> method here. * * @param socket a <code>SSLSocket</code> value * @exception SSLPeerUnverifiedException If there are problems obtaining * the server certificates from the SSL session, or the server host name * does not match with the "Common Name" in the server certificates * SubjectDN./*from w w w .j av a 2 s. c om*/ * @exception UnknownHostException If we are not able to resolve * the SSL sessions returned server host name. */ protected void verifyHostname(SSLSocket socket) throws SSLPeerUnverifiedException, UnknownHostException { if (!verifyHostname) return; SSLSession session = socket.getSession(); if (session == null) { throw new UnknownHostException("could not obtain session from socket"); } String hostname = session.getPeerHost(); try { InetAddress.getByName(hostname); } catch (UnknownHostException uhe) { String msg = "Could not resolve SSL sessions server hostname: " + hostname; // Under WebSphere, hostname can be equal to proxy-hostname log.warn(msg, uhe); // throw new UnknownHostException(msg); } javax.security.cert.X509Certificate[] certs = session.getPeerCertificateChain(); if (certs == null || certs.length == 0) throw new SSLPeerUnverifiedException("No server certificates found!"); //get the servers DN in its string representation String dn = certs[0].getSubjectDN().getName(); //might be useful to print out all certificates we receive from the //server, in case one has to debug a problem with the installed certs. if (log.isInfoEnabled()) { log.info("Server certificate chain:"); for (int i = 0; i < certs.length; i++) { log.info("X509Certificate[" + i + "]=" + certs[i]); } } //get the common name from the first cert String cn = getCN(dn); if (hostname.equalsIgnoreCase(cn)) { if (log.isInfoEnabled()) { log.info("Target hostname valid: " + cn); } } else { throw new SSLPeerUnverifiedException( "HTTPS hostname invalid: expected '" + hostname + "', received '" + cn + "'"); } }
From source file:org.jsslutils.extra.apachehttpclient.SslContextedSecureProtocolSocketFactory.java
/** * Describe <code>verifyHostname</code> method here. * /*from w ww . j av a2 s . c o m*/ * @param socket * a <code>SSLSocket</code> value * @exception SSLPeerUnverifiedException * If there are problems obtaining the server certificates * from the SSL session, or the server host name does not * match with the "Common Name" in the server certificates * SubjectDN. * @exception UnknownHostException * If we are not able to resolve the SSL sessions returned * server host name. * @throws CertificateParsingException */ private void verifyHostname(SSLSocket socket) throws IOException, UnknownHostException { synchronized (this) { if (!verifyHostname) return; } SSLSession session = socket.getSession(); String hostname = session.getPeerHost(); try { InetAddress.getByName(hostname); } catch (UnknownHostException uhe) { throw new UnknownHostException("Could not resolve SSL sessions " + "server hostname: " + hostname); } X509Certificate[] certs = (X509Certificate[]) session.getPeerCertificates(); if (certs == null || certs.length == 0) throw new SSLPeerUnverifiedException("No server certificates found!"); try { List<String> cns = new ArrayList<String>(); boolean foundDnsSan = false; Collection<List<?>> subjectAltNames = certs[0].getSubjectAlternativeNames(); if (subjectAltNames != null) { for (List<?> san : subjectAltNames) { if (((Integer) san.get(0)).intValue() == 2) { foundDnsSan = true; String sanDns = (String) san.get(1); cns.add(sanDns); if (hostname.equalsIgnoreCase(sanDns)) { return; } } } } if (!foundDnsSan) { // get the common names from the first cert X500Principal subjectDN = certs[0].getSubjectX500Principal(); cns = getCNs(subjectDN); for (String cn : cns) { if (hostname.equalsIgnoreCase(cn)) { return; } } } throw new SSLPeerUnverifiedException( "HTTPS hostname invalid: expected '" + hostname + "', received '" + cns + "'"); } catch (CertificateParsingException e) { throw new IOException(e); } }
From source file:com.newrelic.agent.deps.org.apache.http.conn.ssl.SSLConnectionSocketFactory.java
private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException { try {// w w w. j a v a2 s . co m 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) { } } if (!this.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; } }