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:org.apache.hadoop.security.Krb5AndCertsSslSocketConnector.java

@Override
public void customize(EndPoint endpoint, Request request) throws IOException {
    if (useKrb) { // Add Kerberos-specific info
        SSLSocket sslSocket = (SSLSocket) endpoint.getTransport();
        Principal remotePrincipal = sslSocket.getSession().getPeerPrincipal();
        logIfDebug("Remote principal = " + remotePrincipal);
        request.setScheme(HttpSchemes.HTTPS);
        request.setAttribute(REMOTE_PRINCIPAL, remotePrincipal);

        if (!useCerts) { // Add extra info that would have been added by super
            String cipherSuite = sslSocket.getSession().getCipherSuite();
            Integer keySize = Integer.valueOf(ServletSSL.deduceKeyLength(cipherSuite));
            ;/*  w  w  w  .ja v  a2 s . c  om*/

            request.setAttribute("javax.servlet.request.cipher_suite", cipherSuite);
            request.setAttribute("javax.servlet.request.key_size", keySize);
        }
    }

    if (useCerts)
        super.customize(endpoint, request);
}

From source file:test.integ.be.fedict.trust.XKMSTrustTest.java

@Test
public void testValidateUnilateralTLSTrust() throws Exception {
    LOG.debug("validate using unilateral TLS Trust.");

    // Retrieve server public key
    SSLTrustManager.initialize();/*from  w  w  w .jav  a 2 s .c o  m*/
    SSLSocketFactory factory = HttpsURLConnection.getDefaultSSLSocketFactory();
    SSLSocket socket = (SSLSocket) factory.createSocket(TestUtils.XKMS_WS_HOST, port);
    socket.startHandshake();
    Certificate[] serverCerts = socket.getSession().getPeerCertificates();
    PublicKey publicKey = serverCerts[0].getPublicKey();
    LOG.debug("server public key: " + publicKey);
    socket.close();

    /*
     * Override default verification that CN of server SSL certificate has
     * to be equal to the hostname.
     */
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return hostname.equals(TestUtils.XKMS_WS_HOST);
        }
    });

    // setup
    List<X509Certificate> signCertificateChain = TestUtils.getSignCertificateChain();
    XKMS2Client client = new XKMS2Client(
            "https://" + TestUtils.XKMS_WS_HOST + ":" + port + TestUtils.XKMS_WS_CONTEXT_PATH);
    client.setServicePublicKey(publicKey);

    /*
     * Operate: validate non repudiation
     */
    client.validate(TrustServiceDomains.BELGIAN_EID_NON_REPUDIATION_TRUST_DOMAIN, signCertificateChain);
}

From source file:test.integ.be.fedict.trust.SSLTrustValidatorTest.java

@Test
public void testTestEIDBelgiumBe() throws Exception {
    Security.addProvider(new BeIDProvider());

    SSLContext sslContext = SSLContext.getInstance("TLS");
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("BeID");

    keyManagerFactory.init(null);//www.j a  va 2  s  .co  m
    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());
    }

    MemoryCertificateRepository repository = new MemoryCertificateRepository();
    repository.addTrustPoint((X509Certificate) peerCertificates[peerCertificates.length - 1]);

    TrustValidator trustValidator = new TrustValidator(repository);
    TrustValidatorDecorator trustValidatorDecorator = new TrustValidatorDecorator();
    trustValidatorDecorator.addDefaultTrustLinkerConfig(trustValidator);
    trustValidator.isTrusted(peerCertificates);
}

From source file:org.apache.nifi.registry.security.util.CertificateUtils.java

/**
 * Returns the DN extracted from the client certificate.
 *
 * If the client auth setting is WANT or NONE and a certificate is not present (and {@code respectClientAuth} is {@code true}), this method will return {@code null}.
 * If the client auth is NEED, it will throw a {@link CertificateException}.
 *
 * @param sslSocket the SSL Socket/*w w w.j  a v a 2s . co  m*/
 * @return the extracted DN
 * @throws CertificateException if there is a problem parsing the certificate
 */
private static String extractPeerDNFromClientSSLSocket(SSLSocket sslSocket) throws CertificateException {
    String dn = null;

    /** The clientAuth value can be "need", "want", or "none"
     * A client must send client certificates for need, should for want, and will not for none.
     * This method should throw an exception if none are provided for need, return null if none are provided for want, and return null (without checking) for none.
     */

    ClientAuth clientAuth = getClientAuthStatus(sslSocket);
    logger.debug("SSL Socket client auth status: {}", clientAuth);

    if (clientAuth != ClientAuth.NONE) {
        try {
            final Certificate[] certChains = sslSocket.getSession().getPeerCertificates();
            if (certChains != null && certChains.length > 0) {
                X509Certificate x509Certificate = convertAbstractX509Certificate(certChains[0]);
                dn = x509Certificate.getSubjectDN().getName().trim();
                logger.debug("Extracted DN={} from client certificate", dn);
            }
        } catch (SSLPeerUnverifiedException e) {
            if (e.getMessage().equals(PEER_NOT_AUTHENTICATED_MSG)) {
                logger.error("The incoming request did not contain client certificates and thus the DN cannot"
                        + " be extracted. Check that the other endpoint is providing a complete client certificate chain");
            }
            if (clientAuth == ClientAuth.WANT) {
                logger.warn(
                        "Suppressing missing client certificate exception because client auth is set to 'want'");
                return dn;
            }
            throw new CertificateException(e);
        }
    }
    return dn;
}

From source file:org.opensaml.security.httpclient.impl.SecurityEnhancedTLSSocketFactory.java

/**
 * Extract the server TLS {@link X509Credential} from the supplied {@link SSLSocket}.
 * /* w w w. j  a  v a 2  s . com*/
 * @param sslSocket the SSL socket instance to process
 * @return an X509Credential representing the server TLS entity certificate as well as the 
 *          supplied supporting intermediate certificate chain (if any)
 * @throws IOException if credential data can not be extracted from the socket
 */
@Nonnull
protected X509Credential extractCredential(@Nonnull final SSLSocket sslSocket) throws IOException {
    SSLSession session = sslSocket.getSession();
    final Certificate[] peerCertificates = session.getPeerCertificates();
    if (peerCertificates == null || peerCertificates.length < 1) {
        throw new SSLPeerUnverifiedException("SSLSession peer certificates array was null or empty");
    }

    ArrayList<X509Certificate> certChain = new ArrayList<>();
    for (Certificate cert : peerCertificates) {
        certChain.add((X509Certificate) cert);
    }

    final X509Certificate entityCert = certChain.get(0);

    BasicX509Credential credential = new BasicX509Credential(entityCert);
    credential.setEntityCertificateChain(certChain);

    return credential;
}

From source file:net.lightbody.bmp.proxy.jetty.http.JsseListener.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>/*from w w w . j a v a2  s.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);
    }
}

From source file:com.rastating.droidbeard.net.TlsSocketFactory.java

@Override
public Socket createSocket(Socket plainSocket, String host, int port, boolean autoClose)
        throws IOException, UnknownHostException {
    // Create and connect SSL socket, but don't do hostname/certificate verification yet
    SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory
            .getDefault(0);//from   www  .ja  v  a2s.co  m

    // Setup custom trust manager if we are trusting all certificates
    if (mTrustAllCertificates) {
        TrustManager tm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sslSocketFactory.setTrustManagers(new TrustManager[] { tm });
    }

    SSLSocket ssl = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port);

    // Enable TLSv1.1/1.2 if available
    // (see https://github.com/rfc2822/davdroid/issues/229)
    ssl.setEnabledProtocols(ssl.getSupportedProtocols());
    SSLSession session = ssl.getSession();

    // Verify hostname and certificate if we aren't trusting all certificates
    if (!mTrustAllCertificates) {
        if (!hostnameVerifier.verify(host, session))
            throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host);
    }

    Log.i("droidbeard", "Established " + session.getProtocol() + " connection with " + session.getPeerHost()
            + " using " + session.getCipherSuite());
    return ssl;
}

From source file:ee.ria.xroad.proxy.clientproxy.FastestConnectionSelectingSSLSocketFactory.java

private void prepareAndVerify(SSLSocket sslSocket, URI selectedAddress, HttpContext context)
        throws IOException {
    prepareSocket(sslSocket);/*  www.  ja  v a  2 s . c  o m*/

    sslSocket.getSession().putValue(ID_SELECTED_TARGET, selectedAddress);

    verify(context, sslSocket.getSession(), selectedAddress);
}

From source file:org.apache.http.HC4.conn.ssl.AbstractVerifier.java

@Override
public final void verify(final String host, final SSLSocket ssl) throws IOException {
    Args.notNull(host, "Host");
    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();/*  w ww  . ja  v  a  2s . c om*/
        /*
          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:org.jasig.portal.security.provider.saml.PublicKeyVerifyingSSLSocketFactory.java

/**
 * This method makes a connection to the server by utilizing the base class
 * method, but it adds a validation of the server's public key if one was
 * supplied previously./*from   ww w .j av a  2  s. c  om*/
 * 
 * @see org.apache.http.conn.ssl.SSLSocketFactory#connectSocket(java.net.Socket, java.lang.String, int, java.net.InetAddress, int, org.apache.http.params.HttpParams)
 */
@Override
public Socket connectSocket(final Socket sock, final String host, final int port,
        final InetAddress localAddress, int localPort, final HttpParams params) throws IOException {
    SSLSocket newSocket = (SSLSocket) super.connectSocket(sock, host, port, localAddress, localPort, params);

    if (publicKey != null) {
        logger.debug("Verifying SSL Socket to {}:{} against configured public key {}",
                new Object[] { host, port, publicKey });

        SSLSession session = newSocket.getSession();
        Certificate[] certs = session.getPeerCertificates();
        boolean matchFound = false;

        for (int i = 0; i < certs.length; i++) {
            X509Certificate x509 = (X509Certificate) certs[i];
            PublicKey certKey = x509.getPublicKey();

            if (certKey.equals(publicKey)) {
                logger.debug("Validated public key against server key: {}", certKey);
                matchFound = true;
                break;
            }
            logger.debug("server key doesn't match public key: {} ", certKey);
        }
        if (!matchFound) {
            newSocket.close();
            throw new IOException("Unable to verify the server's public key");
        }
    }
    return newSocket;
}