Java Code Examples for javax.net.ssl.SSLContext#getClientSessionContext()

The following examples show how to use javax.net.ssl.SSLContext#getClientSessionContext() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
public static void main(String[] args) throws Exception {
    SSLServerSocketFactory sssf =
            (SSLServerSocketFactory)SSLServerSocketFactory.getDefault();

    try (SSLServerSocket serverSocket =
                (SSLServerSocket)sssf.createServerSocket()) {

        String[] protocols = serverSocket.getSupportedProtocols();
        for (int i = 0; i < protocols.length; i++) {
            if (protocols[i].equals("SSLv2Hello")) {
                continue;
            }
            SSLContext sslContext = SSLContext.getInstance(protocols[i]);
            SSLSessionContext sessionContext =
                    sslContext.getServerSessionContext();
            if (sessionContext.getSessionCacheSize() == 0) {
                throw new Exception(
                    "the default server session cache size is infinite");
            }

            sessionContext = sslContext.getClientSessionContext();
            if (sessionContext.getSessionCacheSize() == 0) {
                throw new Exception(
                    "the default client session cache size is infinite");
            }
        }
    }
}
 
Example 2
private static SSLContext newSSLContext(Provider sslContextProvider,
                                        X509Certificate[] trustCertCollection,
                                        TrustManagerFactory trustManagerFactory, X509Certificate[] keyCertChain,
                                        PrivateKey key, String keyPassword, KeyManagerFactory keyManagerFactory,
                                        long sessionCacheSize, long sessionTimeout) throws SSLException {
    try {
        if (trustCertCollection != null) {
            trustManagerFactory = buildTrustManagerFactory(trustCertCollection, trustManagerFactory);
        }
        if (keyCertChain != null) {
            keyManagerFactory = buildKeyManagerFactory(keyCertChain, key, keyPassword, keyManagerFactory);
        }
        SSLContext ctx = sslContextProvider == null ? SSLContext.getInstance(PROTOCOL)
            : SSLContext.getInstance(PROTOCOL, sslContextProvider);
        ctx.init(keyManagerFactory == null ? null : keyManagerFactory.getKeyManagers(),
                 trustManagerFactory == null ? null : trustManagerFactory.getTrustManagers(),
                 null);

        SSLSessionContext sessCtx = ctx.getClientSessionContext();
        if (sessionCacheSize > 0) {
            sessCtx.setSessionCacheSize((int) Math.min(sessionCacheSize, Integer.MAX_VALUE));
        }
        if (sessionTimeout > 0) {
            sessCtx.setSessionTimeout((int) Math.min(sessionTimeout, Integer.MAX_VALUE));
        }
        return ctx;
    } catch (Exception e) {
        if (e instanceof SSLException) {
            throw (SSLException) e;
        }
        throw new SSLException("failed to initialize the client-side SSL context", e);
    }
}
 
Example 3
public static void main(String[] args) throws Exception {
    SSLServerSocketFactory sssf =
            (SSLServerSocketFactory)SSLServerSocketFactory.getDefault();

    try (SSLServerSocket serverSocket =
                (SSLServerSocket)sssf.createServerSocket()) {

        String[] protocols = serverSocket.getSupportedProtocols();
        for (int i = 0; i < protocols.length; i++) {
            if (protocols[i].equals("SSLv2Hello")) {
                continue;
            }
            SSLContext sslContext = SSLContext.getInstance(protocols[i]);
            SSLSessionContext sessionContext =
                    sslContext.getServerSessionContext();
            if (sessionContext.getSessionCacheSize() == 0) {
                throw new Exception(
                    "the default server session cache size is infinite");
            }

            sessionContext = sslContext.getClientSessionContext();
            if (sessionContext.getSessionCacheSize() == 0) {
                throw new Exception(
                    "the default client session cache size is infinite");
            }
        }
    }
}
 
Example 4
public static void main(String[] args) throws Exception {
    SSLServerSocketFactory sssf =
            (SSLServerSocketFactory)SSLServerSocketFactory.getDefault();

    try (SSLServerSocket serverSocket =
                (SSLServerSocket)sssf.createServerSocket()) {

        String[] protocols = serverSocket.getSupportedProtocols();
        for (int i = 0; i < protocols.length; i++) {
            if (protocols[i].equals("SSLv2Hello")) {
                continue;
            }
            SSLContext sslContext = SSLContext.getInstance(protocols[i]);
            SSLSessionContext sessionContext =
                    sslContext.getServerSessionContext();
            if (sessionContext.getSessionCacheSize() == 0) {
                throw new Exception(
                    "the default server session cache size is infinite");
            }

            sessionContext = sslContext.getClientSessionContext();
            if (sessionContext.getSessionCacheSize() == 0) {
                throw new Exception(
                    "the default client session cache size is infinite");
            }
        }
    }
}
 
Example 5
public static void main(String[] args) throws Exception {
    SSLServerSocketFactory sssf =
            (SSLServerSocketFactory)SSLServerSocketFactory.getDefault();

    try (SSLServerSocket serverSocket =
                (SSLServerSocket)sssf.createServerSocket()) {

        String[] protocols = serverSocket.getSupportedProtocols();
        for (int i = 0; i < protocols.length; i++) {
            if (protocols[i].equals("SSLv2Hello")) {
                continue;
            }
            SSLContext sslContext = SSLContext.getInstance(protocols[i]);
            SSLSessionContext sessionContext =
                    sslContext.getServerSessionContext();
            if (sessionContext.getSessionCacheSize() == 0) {
                throw new Exception(
                    "the default server session cache size is infinite");
            }

            sessionContext = sslContext.getClientSessionContext();
            if (sessionContext.getSessionCacheSize() == 0) {
                throw new Exception(
                    "the default client session cache size is infinite");
            }
        }
    }
}
 
Example 6
@Test
public void testSessionTimeout() throws Exception {
    final int port1 = SSLTestUtils.PORT;
    final int port2 = SSLTestUtils.SECONDARY_PORT;

    try (
            ServerSocket serverSocket1 = SSLTestUtils.createServerSocket(port1);
            ServerSocket serverSocket2 = SSLTestUtils.createServerSocket(port2)
    ) {

        final Thread acceptThread1 = startServer(serverSocket1);
        final Thread acceptThread2 = startServer(serverSocket2);

        SSLContext clientContext = SSLTestUtils.createClientSSLContext("openssl.TLSv1");
        final SSLSessionContext clientSession = clientContext.getClientSessionContext();
        byte[] host1SessionId = connectAndWrite(clientContext, port1);
        byte[] host2SessionId = connectAndWrite(clientContext, port2);

        // No timeout was set, id's should be identical
        Assert.assertArrayEquals(host1SessionId, connectAndWrite(clientContext, port1));
        Assert.assertArrayEquals(host2SessionId, connectAndWrite(clientContext, port2));

        // Set the session timeout to 1 second and sleep for 2 to ensure the timeout works
        clientSession.setSessionTimeout(1);
        TimeUnit.SECONDS.sleep(2L);
        Assert.assertFalse(Arrays.equals(host1SessionId, connectAndWrite(clientContext, port1)));
        Assert.assertFalse(Arrays.equals(host1SessionId, connectAndWrite(clientContext, port2)));

        serverSocket1.close();
        serverSocket2.close();
        acceptThread1.join();
        acceptThread2.join();
    }
}
 
Example 7
@Override
public boolean hasChild(PathElement element) {
    SSLContext sslContext;
    if (ElytronDescriptionConstants.SSL_SESSION.equals(element.getKey()) && (sslContext = getSSLContext(sslContextServiceController)) != null) {
        byte[] sessionId = ByteIterator.ofBytes(element.getValue().getBytes(StandardCharsets.UTF_8)).asUtf8String().hexDecode().drain();
        SSLSessionContext sslSessionContext = server ? sslContext.getServerSessionContext() : sslContext.getClientSessionContext();
        return sslSessionContext.getSession(sessionId) != null;
    }
    return false;
}
 
Example 8
@Override
public Set<String> getChildrenNames(String childType) {
    SSLContext sslContext;
    if (ElytronDescriptionConstants.SSL_SESSION.equals(childType) && (sslContext = getSSLContext(sslContextServiceController)) != null) {
        SSLSessionContext sslSessionContext = server ? sslContext.getServerSessionContext() : sslContext.getClientSessionContext();
        Set<String> set = new HashSet<>();
        for (byte[] b : Collections.list(sslSessionContext.getIds())) {
            String s = ByteIterator.ofBytes(b).hexEncode(true).drainToString();
            set.add(s);
        }
        return set;
    }
    return Collections.emptySet();
}
 
Example 9
/**
 * Check if the {@link SSLContext} has any active sessions.
 *
 * @return {@code true} if the {@link SSLContext} is available and has at least one session, {@code false} otherwise.
 */
private boolean hasActiveSessions() {
    final SSLContext sslContext = getSSLContext(sslContextServiceController);
    if (sslContext == null) return false;
    SSLSessionContext sslSessionContext = server ? sslContext.getServerSessionContext() : sslContext.getClientSessionContext();
    return sslSessionContext.getIds().hasMoreElements();
}
 
Example 10
@Override
protected void performRuntime(ModelNode result, ModelNode operation, SSLContext sslContext) throws OperationFailedException {
    SSLSessionContext sslSessionContext = server ? sslContext.getServerSessionContext() : sslContext.getClientSessionContext();
    SSLSession sslSession = sslSessionContext.getSession(sessionId(operation));
    if (sslSession != null) {
        performRuntime(result, operation, sslSession);
    }
}
 
Example 11
Source Project: cxf   File: SSLUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static SSLContext getSSLContext(TLSParameterBase parameters) throws GeneralSecurityException {
    // TODO do we need to cache the context
    String provider = parameters.getJsseProvider();

    String protocol = parameters.getSecureSocketProtocol() != null ? parameters
        .getSecureSocketProtocol() : "TLS";

    SSLContext ctx = provider == null ? SSLContext.getInstance(protocol) : SSLContext
        .getInstance(protocol, provider);

    KeyManager[] keyManagers = parameters.getKeyManagers();
    if (keyManagers == null && parameters instanceof TLSClientParameters) {
        keyManagers = org.apache.cxf.configuration.jsse.SSLUtils.getDefaultKeyStoreManagers(LOG);
    }
    KeyManager[] configuredKeyManagers = configureKeyManagersWithCertAlias(parameters, keyManagers);

    TrustManager[] trustManagers = parameters.getTrustManagers();
    if (trustManagers == null && parameters instanceof TLSClientParameters) {
        trustManagers = org.apache.cxf.configuration.jsse.SSLUtils.getDefaultTrustStoreManagers(LOG);
    }

    ctx.init(configuredKeyManagers, trustManagers, parameters.getSecureRandom());

    if (parameters instanceof TLSClientParameters && ctx.getClientSessionContext() != null) {
        ctx.getClientSessionContext().setSessionTimeout(((TLSClientParameters)parameters).getSslCacheTimeout());
    }

    return ctx;
}
 
Example 12
@Test
public void testSessionSize() throws Exception {
    final int port1 = SSLTestUtils.PORT;
    final int port2 = SSLTestUtils.SECONDARY_PORT;

    try (
            ServerSocket serverSocket1 = SSLTestUtils.createServerSocket(port1);
            ServerSocket serverSocket2 = SSLTestUtils.createServerSocket(port2)
    ) {

        final Thread acceptThread1 = startServer(serverSocket1);
        final Thread acceptThread2 = startServer(serverSocket2);
        SSLContext clientContext = SSLTestUtils.createClientSSLContext("openssl.TLSv1");

        final SSLSessionContext clientSession = clientContext.getClientSessionContext();

        byte[] host1SessionId = connectAndWrite(clientContext, port1);
        byte[] host2SessionId = connectAndWrite(clientContext, port2);

        // No cache limit was set, id's should be identical
        Assert.assertArrayEquals(host1SessionId, connectAndWrite(clientContext, port1));
        Assert.assertArrayEquals(host2SessionId, connectAndWrite(clientContext, port2));

        // Set the cache size to 1
        clientSession.setSessionCacheSize(1);
        // The second session id should be the one kept as it was the last one used
        Assert.assertArrayEquals(host2SessionId, connectAndWrite(clientContext, port2));
        // Connect again to the first host, this should not match the initial session id for the first host
        byte[] nextId = connectAndWrite(clientContext, port1);
        Assert.assertFalse(Arrays.equals(host1SessionId, nextId));
        // Once more connect to the first host and this should match the previous session id
        Assert.assertArrayEquals(nextId, connectAndWrite(clientContext, port1));
        // Connect to the second host which should be purged at this point
        Assert.assertFalse(Arrays.equals(nextId, connectAndWrite(clientContext, port2)));

        // Reset the cache limit and ensure both sessions are cached
        clientSession.setSessionCacheSize(0);
        host1SessionId = connectAndWrite(clientContext, port1);
        host2SessionId = connectAndWrite(clientContext, port2);

        // No cache limit was set, id's should be identical
        Assert.assertArrayEquals(host1SessionId, connectAndWrite(clientContext, port1));
        Assert.assertArrayEquals(host2SessionId, connectAndWrite(clientContext, port2));

        serverSocket1.close();
        serverSocket2.close();
        acceptThread1.join();
        acceptThread2.join();
    }
}
 
Example 13
Source Project: cxf   File: AsyncHTTPConduit.java    License: Apache License 2.0 4 votes vote down vote up
public synchronized SSLContext getSSLContext(TLSClientParameters tlsClientParameters)
    throws GeneralSecurityException {

    int hash = tlsClientParameters.hashCode();
    if (hash == lastTlsHash && sslContext != null) {
        return sslContext;
    }

    SSLContext ctx = null;
    if (tlsClientParameters.getSslContext() != null) {
        ctx = tlsClientParameters.getSslContext();
    } else {
        String provider = tlsClientParameters.getJsseProvider();

        String protocol = tlsClientParameters.getSecureSocketProtocol() != null ? tlsClientParameters
            .getSecureSocketProtocol() : "TLS";

        ctx = provider == null ? SSLContext.getInstance(protocol) : SSLContext
            .getInstance(protocol, provider);

        KeyManager[] keyManagers = tlsClientParameters.getKeyManagers();
        if (keyManagers == null) {
            keyManagers = org.apache.cxf.configuration.jsse.SSLUtils.getDefaultKeyStoreManagers(LOG);
        }
        KeyManager[] configuredKeyManagers =
            org.apache.cxf.transport.https.SSLUtils.configureKeyManagersWithCertAlias(
                tlsClientParameters, keyManagers);

        TrustManager[] trustManagers = tlsClientParameters.getTrustManagers();
        if (trustManagers == null) {
            trustManagers = org.apache.cxf.configuration.jsse.SSLUtils.getDefaultTrustStoreManagers(LOG);
        }

        ctx.init(configuredKeyManagers, trustManagers, tlsClientParameters.getSecureRandom());

        if (ctx.getClientSessionContext() != null) {
            ctx.getClientSessionContext().setSessionTimeout(tlsClientParameters.getSslCacheTimeout());
        }
    }

    sslContext = ctx;
    lastTlsHash = hash;
    sslState = null;
    sslURL = null;
    session = null;
    return ctx;
}
 
Example 14
/**
 * Installs a {@link SSLSessionCache} on a {@link SSLContext}. The cache will
 * be used on all socket factories created by this context (including factories
 * created before this call).
 *
 * @param cache the cache instance to install, or {@code null} to uninstall any
 *         existing cache.
 * @param context the context to install it on.
 * @throws IllegalArgumentException if the context does not support a session
 *         cache.
 *
 * @hide candidate for public API
 */
public static void install(SSLSessionCache cache, SSLContext context) {
    SSLSessionContext clientContext = context.getClientSessionContext();
    if (clientContext instanceof ClientSessionContext) {
        ((ClientSessionContext) clientContext).setPersistentCache(
                cache == null ? null : cache.mSessionCache);
    } else {
        throw new IllegalArgumentException("Incompatible SSLContext: " + context);
    }
}