List of usage examples for javax.net.ssl SSLSocket setUseClientMode
public abstract void setUseClientMode(boolean mode);
From source file:org.beepcore.beep.profile.tls.jsse.TLSProfileJSSE.java
public void receiveMSG(MessageMSG msg) { Channel channel = msg.getChannel(); InputDataStreamAdapter is = msg.getDataStream().getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String data;/* w w w.j a v a2 s.c o m*/ try { try { data = reader.readLine(); } catch (IOException e) { msg.sendERR(BEEPError.CODE_PARAMETER_ERROR, "Error reading data"); return; } if (data.equals(READY1) == false && data.equals(READY2) == false) { msg.sendERR(BEEPError.CODE_PARAMETER_INVALID, "Expected READY element"); } this.begin(channel); msg.sendRPY(new StringOutputDataStream(PROCEED2)); } catch (BEEPException e1) { channel.getSession().terminate("unable to send ERR"); return; } try { Socket oldSocket = ((TCPSession) channel.getSession()).getSocket(); /** @TODO add support for serverName */ SSLSocket newSocket = (SSLSocket) socketFactory.createSocket(oldSocket, oldSocket.getInetAddress().getHostName(), oldSocket.getPort(), true); BeepListenerHCL l = new BeepListenerHCL(channel); newSocket.addHandshakeCompletedListener(l); newSocket.setUseClientMode(false); newSocket.setNeedClientAuth(needClientAuth); newSocket.setEnabledCipherSuites(newSocket.getSupportedCipherSuites()); if (sslProtocols != null) { newSocket.setEnabledProtocols(sslProtocols); } newSocket.startHandshake(); } catch (IOException e) { channel.getSession().terminate("TLS error: " + e.getMessage()); return; } }
From source file:org.beepcore.beep.profile.tls.jsse.TLSProfileJSSE.java
/** * start a channel for the TLS profile. Besides issuing the * channel start request, it also performs the initiator side * chores necessary to begin encrypted communication using TLS * over a session. Parameters regarding the type of encryption * and whether or not authentication is required are specified * using the profile configuration passed to the <code>init</code> * method Upon returning, all traffic over the session will be * entrusted as per these parameters.<p> * * @see #init init - profile configuration * @param session The session to encrypt communcation for * * @return new <code>Session</code> with TLS negotiated. * @throws BEEPException an error occurs during the channel start * request or the TLS handshake (such as trying to negotiate an * anonymous connection with a peer that doesn't support an * anonymous cipher suite).//from ww w . j a va 2 s . co m */ public TCPSession startTLS(TCPSession session) throws BEEPException { Channel ch = startChannel(session, uri, false, READY2, null); // See if we got start data back String data = ch.getStartData(); if (log.isDebugEnabled()) { log.debug("Got start data of " + data); } // Consider the data (see if it's proceed) if ((data == null) || (!data.equals(PROCEED1) && !data.equals(PROCEED2))) { log.error("Invalid reply: " + data); throw new BEEPException(ERR_EXPECTED_PROCEED); } // Freeze IO and get the socket and reset it to TLS Socket oldSocket = session.getSocket(); SSLSocket newSocket = null; TLSHandshake l = new TLSHandshake(); // create the SSL Socket try { newSocket = (SSLSocket) socketFactory.createSocket(oldSocket, oldSocket.getInetAddress().getHostName(), oldSocket.getPort(), true); newSocket.addHandshakeCompletedListener(l); newSocket.setUseClientMode(true); newSocket.setNeedClientAuth(needClientAuth); newSocket.setEnabledCipherSuites(newSocket.getSupportedCipherSuites()); if (this.sslProtocols != null) { newSocket.setEnabledProtocols(sslProtocols); } // set up so the handshake listeners will be called l.session = session; log.debug("Handshake starting"); newSocket.startHandshake(); log.debug("Handshake returned"); synchronized (l) { if (!l.notifiedHandshake) { l.waitingForHandshake = true; l.wait(); l.waitingForHandshake = false; } } log.debug("Handshake done waiting"); } catch (javax.net.ssl.SSLException e) { log.error(e); throw new BEEPException(e); } catch (java.io.IOException e) { log.error(e); throw new BEEPException(ERR_TLS_SOCKET); } catch (InterruptedException e) { log.error(e); throw new BEEPException(ERR_TLS_HANDSHAKE_WAIT); } // swap it out for the new one with TLS enabled. if (abortSession) { session.close(); throw new BEEPException(ERR_TLS_NO_AUTHENTICATION); } else { Hashtable hash = new Hashtable(); hash.put(SessionTuningProperties.ENCRYPTION, "true"); SessionTuningProperties tuning = new SessionTuningProperties(hash); return (TCPSession) reset(session, generateCredential(), l.cred, tuning, session.getProfileRegistry(), newSocket); } }
From source file:org.apache.geode.internal.net.SocketCreator.java
/** * When a socket is accepted from a server socket, it should be passed to this method for SSL * configuration.//ww w . j av a 2 s . c o m */ private void configureClientSSLSocket(Socket socket, int timeout) throws IOException { if (socket instanceof SSLSocket) { SSLSocket sslSocket = (SSLSocket) socket; sslSocket.setUseClientMode(true); sslSocket.setEnableSessionCreation(true); String[] protocols = this.sslConfig.getProtocolsAsStringArray(); // restrict cyphers if (protocols != null && !"any".equalsIgnoreCase(protocols[0])) { sslSocket.setEnabledProtocols(protocols); } String[] ciphers = this.sslConfig.getCiphersAsStringArray(); if (ciphers != null && !"any".equalsIgnoreCase(ciphers[0])) { sslSocket.setEnabledCipherSuites(ciphers); } try { if (timeout > 0) { sslSocket.setSoTimeout(timeout); } sslSocket.startHandshake(); SSLSession session = sslSocket.getSession(); Certificate[] peer = session.getPeerCertificates(); if (logger.isDebugEnabled()) { logger.debug(LocalizedMessage.create(LocalizedStrings.SocketCreator_SSL_CONNECTION_FROM_PEER_0, ((X509Certificate) peer[0]).getSubjectDN())); } } catch (SSLHandshakeException ex) { logger.fatal( LocalizedMessage.create(LocalizedStrings.SocketCreator_SSL_ERROR_IN_CONNECTING_TO_PEER_0_1, new Object[] { socket.getInetAddress(), Integer.valueOf(socket.getPort()) }), ex); throw ex; } catch (SSLPeerUnverifiedException ex) { if (this.sslConfig.isRequireAuth()) { logger.fatal(LocalizedMessage .create(LocalizedStrings.SocketCreator_SSL_ERROR_IN_AUTHENTICATING_PEER), ex); throw ex; } } catch (SSLException ex) { logger.fatal( LocalizedMessage.create(LocalizedStrings.SocketCreator_SSL_ERROR_IN_CONNECTING_TO_PEER_0_1, new Object[] { socket.getInetAddress(), Integer.valueOf(socket.getPort()) }), ex); throw ex; } } }
From source file:android.net.http.CertificateChainValidator.java
/** * Performs the handshake and server certificates validation * @param sslSocket The secure connection socket * @param domain The website domain//w w w. j a v a 2 s. c o m * @return An SSL error object if there is an error and null otherwise */ public SslError doHandshakeAndValidateServerCertificates(HttpsConnection connection, SSLSocket sslSocket, String domain) throws SSLHandshakeException, IOException { ++sTotal; SSLContext sslContext = HttpsConnection.getContext(); if (sslContext == null) { closeSocketThrowException(sslSocket, "SSL context is null"); } X509Certificate[] serverCertificates = null; long sessionBeforeHandshakeLastAccessedTime = 0; byte[] sessionBeforeHandshakeId = null; SSLSession sessionAfterHandshake = null; synchronized (sslContext) { // get SSL session before the handshake SSLSession sessionBeforeHandshake = getSSLSession(sslContext, connection.getHost()); if (sessionBeforeHandshake != null) { sessionBeforeHandshakeLastAccessedTime = sessionBeforeHandshake.getLastAccessedTime(); sessionBeforeHandshakeId = sessionBeforeHandshake.getId(); } // start handshake, close the socket if we fail try { sslSocket.setUseClientMode(true); sslSocket.startHandshake(); } catch (IOException e) { closeSocketThrowException(sslSocket, e.getMessage(), "failed to perform SSL handshake"); } // retrieve the chain of the server peer certificates Certificate[] peerCertificates = sslSocket.getSession().getPeerCertificates(); if (peerCertificates == null || peerCertificates.length <= 0) { closeSocketThrowException(sslSocket, "failed to retrieve peer certificates"); } else { serverCertificates = new X509Certificate[peerCertificates.length]; for (int i = 0; i < peerCertificates.length; ++i) { serverCertificates[i] = (X509Certificate) (peerCertificates[i]); } // update the SSL certificate associated with the connection if (connection != null) { if (serverCertificates[0] != null) { connection.setCertificate(new SslCertificate(serverCertificates[0])); } } } // get SSL session after the handshake sessionAfterHandshake = getSSLSession(sslContext, connection.getHost()); } if (sessionBeforeHandshakeLastAccessedTime != 0 && sessionAfterHandshake != null && Arrays.equals(sessionBeforeHandshakeId, sessionAfterHandshake.getId()) && sessionBeforeHandshakeLastAccessedTime < sessionAfterHandshake.getLastAccessedTime()) { if (HttpLog.LOGV) { HttpLog.v("SSL session was reused: total reused: " + sTotalReused + " out of total of: " + sTotal); ++sTotalReused; } // no errors!!! return null; } // check if the first certificate in the chain is for this site X509Certificate currCertificate = serverCertificates[0]; if (currCertificate == null) { closeSocketThrowException(sslSocket, "certificate for this site is null"); } else { if (!DomainNameChecker.match(currCertificate, domain)) { String errorMessage = "certificate not for this host: " + domain; if (HttpLog.LOGV) { HttpLog.v(errorMessage); } sslSocket.getSession().invalidate(); return new SslError(SslError.SSL_IDMISMATCH, currCertificate); } } // // first, we validate the chain using the standard validation // solution; if we do not find any errors, we are done; if we // fail the standard validation, we re-validate again below, // this time trying to retrieve any individual errors we can // report back to the user. // try { synchronized (mDefaultTrustManager) { mDefaultTrustManager.checkServerTrusted(serverCertificates, "RSA"); // no errors!!! return null; } } catch (CertificateException e) { if (HttpLog.LOGV) { HttpLog.v("failed to pre-validate the certificate chain, error: " + e.getMessage()); } } sslSocket.getSession().invalidate(); SslError error = null; // we check the root certificate separately from the rest of the // chain; this is because we need to know what certificate in // the chain resulted in an error if any currCertificate = serverCertificates[serverCertificates.length - 1]; if (currCertificate == null) { closeSocketThrowException(sslSocket, "root certificate is null"); } // check if the last certificate in the chain (root) is trusted X509Certificate[] rootCertificateChain = { currCertificate }; try { synchronized (mDefaultTrustManager) { mDefaultTrustManager.checkServerTrusted(rootCertificateChain, "RSA"); } } catch (CertificateExpiredException e) { String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "root certificate has expired"; } if (HttpLog.LOGV) { HttpLog.v(errorMessage); } error = new SslError(SslError.SSL_EXPIRED, currCertificate); } catch (CertificateNotYetValidException e) { String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "root certificate not valid yet"; } if (HttpLog.LOGV) { HttpLog.v(errorMessage); } error = new SslError(SslError.SSL_NOTYETVALID, currCertificate); } catch (CertificateException e) { String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "root certificate not trusted"; } if (HttpLog.LOGV) { HttpLog.v(errorMessage); } return new SslError(SslError.SSL_UNTRUSTED, currCertificate); } // Then go through the certificate chain checking that each // certificate trusts the next and that each certificate is // within its valid date range. Walk the chain in the order // from the CA to the end-user X509Certificate prevCertificate = serverCertificates[serverCertificates.length - 1]; for (int i = serverCertificates.length - 2; i >= 0; --i) { currCertificate = serverCertificates[i]; // if a certificate is null, we cannot verify the chain if (currCertificate == null) { closeSocketThrowException(sslSocket, "null certificate in the chain"); } // verify if trusted by chain if (!prevCertificate.getSubjectDN().equals(currCertificate.getIssuerDN())) { String errorMessage = "not trusted by chain"; if (HttpLog.LOGV) { HttpLog.v(errorMessage); } return new SslError(SslError.SSL_UNTRUSTED, currCertificate); } try { currCertificate.verify(prevCertificate.getPublicKey()); } catch (GeneralSecurityException e) { String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "not trusted by chain"; } if (HttpLog.LOGV) { HttpLog.v(errorMessage); } return new SslError(SslError.SSL_UNTRUSTED, currCertificate); } // verify if the dates are valid try { currCertificate.checkValidity(); } catch (CertificateExpiredException e) { String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "certificate expired"; } if (HttpLog.LOGV) { HttpLog.v(errorMessage); } if (error == null || error.getPrimaryError() < SslError.SSL_EXPIRED) { error = new SslError(SslError.SSL_EXPIRED, currCertificate); } } catch (CertificateNotYetValidException e) { String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "certificate not valid yet"; } if (HttpLog.LOGV) { HttpLog.v(errorMessage); } if (error == null || error.getPrimaryError() < SslError.SSL_NOTYETVALID) { error = new SslError(SslError.SSL_NOTYETVALID, currCertificate); } } prevCertificate = currCertificate; } // if we do not have an error to report back to the user, throw // an exception (a generic error will be reported instead) if (error == null) { closeSocketThrowException(sslSocket, "failed to pre-validate the certificate chain due to a non-standard error"); } return error; }