Example usage for javax.net.ssl SSLSocket getSession

List of usage examples for javax.net.ssl SSLSocket getSession

Introduction

In this page you can find the example usage for javax.net.ssl SSLSocket getSession.

Prototype

public abstract SSLSession getSession();

Source Link

Document

Returns the SSL Session in use by this connection.

Usage

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);
        }/*from  www.  j  a v a  2s .  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.dcache.srm.client.FlexibleCredentialSSLConnectionSocketFactory.java

private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException {
    try {/* ww  w  .  jav  a 2 s .com*/
        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 (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Secure session established");
            LOGGER.debug(" negotiated protocol: {}", session.getProtocol());
            LOGGER.debug(" negotiated cipher suite: {}", session.getCipherSuite());

            try {

                final Certificate[] certs = session.getPeerCertificates();
                final X509Certificate x509 = (X509Certificate) certs[0];
                final X500Principal peer = x509.getSubjectX500Principal();

                LOGGER.debug(" peer principal: {}", peer);
                final Collection<List<?>> altNames1 = x509.getSubjectAlternativeNames();
                if (altNames1 != null) {
                    final List<String> altNames = new ArrayList<>();
                    for (final List<?> aC : altNames1) {
                        if (!aC.isEmpty()) {
                            altNames.add((String) aC.get(1));
                        }
                    }
                    LOGGER.debug(" peer alternative names: {}", altNames);
                }

                final X500Principal issuer = x509.getIssuerX500Principal();
                LOGGER.debug(" issuer principal: {}", issuer);
                final Collection<List<?>> altNames2 = x509.getIssuerAlternativeNames();
                if (altNames2 != null) {
                    final List<String> altNames = new ArrayList<>();
                    for (final List<?> aC : altNames2) {
                        if (!aC.isEmpty()) {
                            altNames.add((String) aC.get(1));
                        }
                    }
                    LOGGER.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 (RuntimeException | IOException iox) {
        // close the socket before re-throwing the exception
        try {
            sslsock.close();
        } catch (final Exception x) {
            iox.addSuppressed(x);
        }
        throw iox;
    }
}

From source file:com.serphacker.serposcope.scraper.http.extensions.ScrapClientSSLConnectionFactory.java

private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException {
    try {/*ww  w .j  a  v  a  2  s .c o  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) {
            }
        }

        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:au.edu.monash.merc.capture.util.httpclient.ssl.StrictSSLProtocolSocketFactory.java

/**
 * Describe <code>verifyHostname</code> method here.
 * //from w  ww.ja v a2  s. com
 * @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.
 */
private void verifyHostname(SSLSocket socket) throws SSLPeerUnverifiedException, UnknownHostException {
    if (!verifyHostname)
        return;

    SSLSession session = socket.getSession();
    String hostname = session.getPeerHost();
    try {
        // InetAddress addr = InetAddress.getByName(hostname);
        InetAddress.getByName(hostname);
    } catch (UnknownHostException uhe) {
        throw new UnknownHostException("Could not resolve SSL sessions " + "server hostname: " + hostname);
    }

    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.isDebugEnabled()) {
        LOG.debug("Server certificate chain:");
        for (int i = 0; i < certs.length; i++) {
            LOG.debug("X509Certificate[" + i + "]=" + certs[i]);
        }
    }
    // get the common name from the first cert
    String cn = getCN(dn);
    if (hostname.equalsIgnoreCase(cn)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Target hostname valid: " + cn);
        }
    } else {
        throw new SSLPeerUnverifiedException(
                "HTTPS hostname invalid: expected '" + hostname + "', received '" + cn + "'");
    }
}

From source file:org.apache.commons.httpclient.contrib.ssl.StrictSSLProtocolSocketFactory.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.// w w w. j a  v a  2 s  .co  m
 * @exception UnknownHostException  If we are not able to resolve
 * the SSL sessions returned server host name. 
 */
private void verifyHostname(SSLSocket socket) throws SSLPeerUnverifiedException, UnknownHostException {
    if (!verifyHostname)
        return;

    SSLSession session = socket.getSession();
    String hostname = session.getPeerHost();
    try {
        InetAddress addr = InetAddress.getByName(hostname);
    } catch (UnknownHostException uhe) {
        throw new UnknownHostException("Could not resolve SSL sessions " + "server hostname: " + hostname);
    }

    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.isDebugEnabled()) {
        LOG.debug("Server certificate chain:");
        for (int i = 0; i < certs.length; i++) {
            LOG.debug("X509Certificate[" + i + "]=" + certs[i]);
        }
    }
    //get the common name from the first cert
    String cn = getCN(dn);
    if (hostname.equalsIgnoreCase(cn)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Target hostname valid: " + cn);
        }
    } else {
        throw new SSLPeerUnverifiedException(
                "HTTPS hostname invalid: expected '" + hostname + "', received '" + cn + "'");
    }
}

From source file:com.app.mvc.http.ext.StrictSSLProtocolSocketFactory.java

/**
 * Describe <code>verifyHostname</code> method here.
 *
 * @param socket a <code>SSLSocket</code> value
 * @throws 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.
 * @throws UnknownHostException       If we are not able to resolve
 *                                    the SSL sessions returned server host name.
 *//*from w ww. jav a  2 s . c om*/
private void verifyHostname(SSLSocket socket) throws SSLPeerUnverifiedException, UnknownHostException {
    if (!verifyHostname)
        return;

    SSLSession session = socket.getSession();
    String hostname = session.getPeerHost();
    try {
        InetAddress addr = InetAddress.getByName(hostname);
    } catch (UnknownHostException uhe) {
        throw new UnknownHostException("Could not resolve SSL sessions " + "server hostname: " + hostname);
    }

    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 (logger.isDebugEnabled()) {
        logger.debug("Server certificate chain:");
        for (int i = 0; i < certs.length; i++) {
            logger.debug("X509Certificate[" + i + "]=" + certs[i]);
        }
    }
    //get the common name from the first cert
    String cn = getCN(dn);
    if (hostname.equalsIgnoreCase(cn)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Target hostname valid: " + cn);
        }
    } else {
        throw new SSLPeerUnverifiedException(
                "HTTPS hostname invalid: expected '" + hostname + "', received '" + cn + "'");
    }
}

From source file:it.anyplace.sync.core.security.KeystoreHandler.java

public void checkSocketCerificate(SSLSocket socket, String deviceId)
        throws SSLPeerUnverifiedException, CertificateException {
    SSLSession session = socket.getSession();
    List<Certificate> certs = Arrays.asList(session.getPeerCertificates());
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    CertPath certPath = certificateFactory.generateCertPath(certs);
    Certificate certificate = certPath.getCertificates().get(0);
    checkArgument(certificate instanceof X509Certificate);
    byte[] derData = certificate.getEncoded();
    String deviceIdFromCertificate = derDataToDeviceIdString(derData);
    logger.trace("remote pem certificate =\n{}", derToPem(derData));
    checkArgument(equal(deviceIdFromCertificate, deviceId), "device id mismatch! expected = %s, got = %s",
            deviceId, deviceIdFromCertificate);
    logger.debug("remote ssl certificate match deviceId = {}", deviceId);
}

From source file:eu.eidas.auth.engine.metadata.impl.BaseMetadataFetcher.java

/**
 * Override this method to plug your own SSLSocketFactory.
 * <p>//from  w w w.j a  va 2  s  . c  o m
 * This default implementation relies on the default one from the JVM, i.e. using the default trustStore
 * ($JRE/lib/security/cacerts).
 *
 * @return the SecureProtocolSocketFactory instance to be used to connect to https metadata URLs.
 */
@Nonnull
protected SecureProtocolSocketFactory newSslSocketFactory() {

    HostnameVerifier hostnameVerifier;

    if (!Boolean.getBoolean(DefaultBootstrap.SYSPROP_HTTPCLIENT_HTTPS_DISABLE_HOSTNAME_VERIFICATION)) {
        hostnameVerifier = new StrictHostnameVerifier();
    } else {
        hostnameVerifier = org.apache.commons.ssl.HostnameVerifier.ALLOW_ALL;
    }

    TLSProtocolSocketFactory tlsProtocolSocketFactory = new TLSProtocolSocketFactory(null, null,
            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.SslListener.java

/**
 * Allow the Listener a chance to customise the request. before the server does its stuff. <br>
 * This allows the required attributes to be set for SSL requests. <br>
 * The requirements of the Servlet specs are:
 * <ul>/*w  w w. j a  v  a 2s. co  m*/
 * <li>an attribute named "javax.servlet.request.cipher_suite" of type String.</li>
 * <li>an attribute named "javax.servlet.request.key_size" of type Integer.</li>
 * <li>an attribute named "javax.servlet.request.X509Certificate" of type
 * java.security.cert.X509Certificate[]. This is an array of objects of type X509Certificate,
 * the order of this array is defined as being in ascending order of trust. The first
 * certificate in the chain is the one set by the client, the next is the one used to
 * authenticate the first, and so on.</li>
 * </ul>
 * 
 * @param socket The Socket the request arrived on. This should be a javax.net.ssl.SSLSocket.
 * @param request HttpRequest to be customised.
 */
protected void customizeRequest(Socket socket, HttpRequest request) {
    super.customizeRequest(socket, request);

    if (!(socket instanceof javax.net.ssl.SSLSocket))
        return; // I'm tempted to let it throw an
                // exception...

    try {
        SSLSocket sslSocket = (SSLSocket) socket;
        SSLSession sslSession = sslSocket.getSession();
        String cipherSuite = sslSession.getCipherSuite();
        Integer keySize;
        X509Certificate[] certs;

        CachedInfo cachedInfo = (CachedInfo) sslSession.getValue(CACHED_INFO_ATTR);
        if (cachedInfo != null) {
            keySize = cachedInfo.getKeySize();
            certs = cachedInfo.getCerts();
        } else {
            keySize = new Integer(ServletSSL.deduceKeyLength(cipherSuite));
            certs = getCertChain(sslSession);
            cachedInfo = new CachedInfo(keySize, certs);
            sslSession.putValue(CACHED_INFO_ATTR, cachedInfo);
        }

        if (certs != null)
            request.setAttribute("javax.servlet.request.X509Certificate", certs);
        else if (_needClientAuth) // Sanity check
            throw new HttpException(HttpResponse.__403_Forbidden);

        request.setAttribute("javax.servlet.request.cipher_suite", cipherSuite);
        request.setAttribute("javax.servlet.request.key_size", keySize);
    } catch (Exception e) {
        log.warn(LogSupport.EXCEPTION, e);
    }
}