Search in sources :

Example 1 with X509ExtendedTrustManager

use of javax.net.ssl.X509ExtendedTrustManager in project java-chassis by ServiceComb.

the class SSLManager method createSSLContext.

public static SSLContext createSSLContext(SSLOption option, SSLCustom custom) {
    try {
        String keyStoreName = custom.getFullPath(option.getKeyStore());
        KeyManager[] keymanager;
        if (keyStoreName != null && new File(keyStoreName).exists()) {
            char[] keyStoreValue = custom.decode(option.getKeyStoreValue().toCharArray());
            KeyStore keyStore = KeyStoreUtil.createKeyStore(keyStoreName, option.getKeyStoreType(), keyStoreValue);
            keymanager = KeyStoreUtil.createKeyManagers(keyStore, keyStoreValue);
        } else {
            keymanager = null;
        }
        String trustStoreName = custom.getFullPath(option.getTrustStore());
        TrustManager[] trustManager;
        if (trustStoreName != null && new File(trustStoreName).exists()) {
            char[] trustStoreValue = custom.decode(option.getTrustStoreValue().toCharArray());
            KeyStore trustStore = KeyStoreUtil.createKeyStore(trustStoreName, option.getTrustStoreType(), trustStoreValue);
            trustManager = KeyStoreUtil.createTrustManagers(trustStore);
        } else {
            trustManager = new TrustManager[] { new TrustAllManager() };
        }
        TrustManager[] wrapped = new TrustManager[trustManager.length];
        for (int i = 0; i < trustManager.length; i++) {
            wrapped[i] = new TrustManagerExt((X509ExtendedTrustManager) trustManager[i], option, custom);
        }
        // ?: ssl context version
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keymanager, wrapped, new SecureRandom());
        return context;
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("NoSuchAlgorithmException." + e.getMessage());
    } catch (KeyManagementException e) {
        throw new IllegalArgumentException("KeyManagementException." + e.getMessage());
    }
}
Also used : X509ExtendedTrustManager(javax.net.ssl.X509ExtendedTrustManager) SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStore(java.security.KeyStore) KeyManagementException(java.security.KeyManagementException) TrustManager(javax.net.ssl.TrustManager) X509ExtendedTrustManager(javax.net.ssl.X509ExtendedTrustManager) KeyManager(javax.net.ssl.KeyManager) File(java.io.File)

Example 2 with X509ExtendedTrustManager

use of javax.net.ssl.X509ExtendedTrustManager in project incubator-servicecomb-java-chassis by apache.

the class TrustManagerExtTest method testConstructor.

@SuppressWarnings("unused")
@Test
public void testConstructor() {
    String keyStoreName = custom.getFullPath(option.getKeyStore());
    char[] keyStoreValue = custom.decode(option.getKeyStoreValue().toCharArray());
    String trustStoreName = custom.getFullPath(option.getTrustStore());
    char[] trustStoreValue = custom.decode(option.getTrustStoreValue().toCharArray());
    KeyStore trustStore = KeyStoreUtil.createKeyStore(trustStoreName, option.getTrustStoreType(), trustStoreValue);
    TrustManager[] trustManager = KeyStoreUtil.createTrustManagers(trustStore);
    TrustManagerExt trustManagerExt = new TrustManagerExt((X509ExtendedTrustManager) trustManager[0], option, custom);
    Assert.assertEquals(3, trustManagerExt.getAcceptedIssuers()[0].getVersion());
    Assert.assertNotNull(trustManagerExt);
}
Also used : KeyStore(java.security.KeyStore) TrustManager(javax.net.ssl.TrustManager) X509ExtendedTrustManager(javax.net.ssl.X509ExtendedTrustManager) Test(org.junit.Test)

Example 3 with X509ExtendedTrustManager

use of javax.net.ssl.X509ExtendedTrustManager in project netty by netty.

the class SslHandlerTest method testHandshakeFailureOnlyFireExceptionOnce.

@Test
@Timeout(value = 10000, unit = TimeUnit.MILLISECONDS)
public void testHandshakeFailureOnlyFireExceptionOnce() throws Exception {
    final SslContext sslClientCtx = SslContextBuilder.forClient().trustManager(new X509ExtendedTrustManager() {

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {
            failVerification();
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {
            failVerification();
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException {
            failVerification();
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException {
            failVerification();
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            failVerification();
        }

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

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return EmptyArrays.EMPTY_X509_CERTIFICATES;
        }

        private void failVerification() throws CertificateException {
            throw new CertificateException();
        }
    }).sslProvider(SslProvider.JDK).build();
    final SelfSignedCertificate cert = new SelfSignedCertificate();
    final SslContext sslServerCtx = SslContextBuilder.forServer(cert.key(), cert.cert()).sslProvider(SslProvider.JDK).build();
    EventLoopGroup group = new NioEventLoopGroup();
    Channel sc = null;
    final SslHandler clientSslHandler = sslClientCtx.newHandler(UnpooledByteBufAllocator.DEFAULT);
    final SslHandler serverSslHandler = sslServerCtx.newHandler(UnpooledByteBufAllocator.DEFAULT);
    try {
        final Object terminalEvent = new Object();
        final BlockingQueue<Object> errorQueue = new LinkedBlockingQueue<Object>();
        sc = new ServerBootstrap().group(group).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) {
                ch.pipeline().addLast(serverSslHandler);
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void exceptionCaught(final ChannelHandlerContext ctx, Throwable cause) {
                        errorQueue.add(cause);
                    }

                    @Override
                    public void channelInactive(ChannelHandlerContext ctx) {
                        errorQueue.add(terminalEvent);
                    }
                });
            }
        }).bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
        final ChannelFuture future = new Bootstrap().group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) {
                ch.pipeline().addLast(clientSslHandler);
            }
        }).connect(sc.localAddress());
        future.syncUninterruptibly();
        clientSslHandler.handshakeFuture().addListener(new FutureListener<Channel>() {

            @Override
            public void operationComplete(Future<Channel> f) {
                future.channel().close();
            }
        });
        assertFalse(clientSslHandler.handshakeFuture().await().isSuccess());
        assertFalse(serverSslHandler.handshakeFuture().await().isSuccess());
        Object error = errorQueue.take();
        assertThat(error, Matchers.instanceOf(DecoderException.class));
        assertThat(((Throwable) error).getCause(), Matchers.<Throwable>instanceOf(SSLException.class));
        Object terminal = errorQueue.take();
        assertSame(terminalEvent, terminal);
        assertNull(errorQueue.poll(1, TimeUnit.MILLISECONDS));
    } finally {
        if (sc != null) {
            sc.close().syncUninterruptibly();
        }
        group.shutdownGracefully();
    }
}
Also used : X509ExtendedTrustManager(javax.net.ssl.X509ExtendedTrustManager) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) SSLEngine(javax.net.ssl.SSLEngine) InetSocketAddress(java.net.InetSocketAddress) CertificateException(java.security.cert.CertificateException) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) SSLException(javax.net.ssl.SSLException) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelFuture(io.netty.channel.ChannelFuture) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Channel(io.netty.channel.Channel) X509Certificate(java.security.cert.X509Certificate) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) DecoderException(io.netty.handler.codec.DecoderException) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) Socket(java.net.Socket) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test) Timeout(org.junit.jupiter.api.Timeout)

Example 4 with X509ExtendedTrustManager

use of javax.net.ssl.X509ExtendedTrustManager in project druid by druid-io.

the class TLSUtils method createSSLContext.

public static SSLContext createSSLContext(@Nullable String protocol, @Nullable String trustStoreType, String trustStorePath, @Nullable String trustStoreAlgorithm, @Nullable PasswordProvider trustStorePasswordProvider, @Nullable String keyStoreType, @Nullable String keyStorePath, @Nullable String keyStoreAlgorithm, @Nullable String certAlias, @Nullable PasswordProvider keyStorePasswordProvider, @Nullable PasswordProvider keyManagerFactoryPasswordProvider, @Nullable Boolean validateHostnames, TLSCertificateChecker tlsCertificateChecker) {
    SSLContext sslContext;
    try {
        sslContext = SSLContext.getInstance(protocol == null ? "TLSv1.2" : protocol);
        KeyStore trustStore = KeyStore.getInstance(trustStoreType == null ? KeyStore.getDefaultType() : trustStoreType);
        try (final InputStream trustStoreFileStream = Files.newInputStream(Paths.get(trustStorePath))) {
            trustStore.load(trustStoreFileStream, trustStorePasswordProvider == null ? null : trustStorePasswordProvider.getPassword().toCharArray());
        }
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(trustStoreAlgorithm == null ? TrustManagerFactory.getDefaultAlgorithm() : trustStoreAlgorithm);
        trustManagerFactory.init(trustStore);
        KeyManager[] keyManagers;
        if (keyStorePath != null) {
            KeyStore keyStore = KeyStore.getInstance(keyStoreType == null ? KeyStore.getDefaultType() : keyStoreType);
            try (final InputStream keyStoreFileStream = Files.newInputStream(Paths.get(keyStorePath))) {
                keyStore.load(keyStoreFileStream, keyStorePasswordProvider == null ? null : keyStorePasswordProvider.getPassword().toCharArray());
                KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(keyStoreAlgorithm == null ? KeyManagerFactory.getDefaultAlgorithm() : keyStoreAlgorithm);
                keyManagerFactory.init(keyStore, keyManagerFactoryPasswordProvider == null ? null : keyManagerFactoryPasswordProvider.getPassword().toCharArray());
                keyManagers = createAliasedKeyManagers(keyManagerFactory.getKeyManagers(), certAlias);
            }
        } else {
            keyManagers = null;
        }
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        TrustManager[] newTrustManagers = new TrustManager[trustManagers.length];
        for (int i = 0; i < trustManagers.length; i++) {
            if (trustManagers[i] instanceof X509ExtendedTrustManager) {
                newTrustManagers[i] = new CustomCheckX509TrustManager((X509ExtendedTrustManager) trustManagers[i], tlsCertificateChecker, validateHostnames == null ? true : validateHostnames);
            } else {
                newTrustManagers[i] = trustManagers[i];
                log.info("Encountered non-X509ExtendedTrustManager: " + trustManagers[i].getClass());
            }
        }
        sslContext.init(keyManagers, newTrustManagers, null);
    } catch (CertificateException | KeyManagementException | IOException | KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) {
        throw new RuntimeException(e);
    }
    return sslContext;
}
Also used : X509ExtendedTrustManager(javax.net.ssl.X509ExtendedTrustManager) InputStream(java.io.InputStream) CertificateException(java.security.cert.CertificateException) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStore(java.security.KeyStore) KeyManagementException(java.security.KeyManagementException) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) TrustManager(javax.net.ssl.TrustManager) X509ExtendedTrustManager(javax.net.ssl.X509ExtendedTrustManager) UnrecoverableKeyException(java.security.UnrecoverableKeyException) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) KeyManager(javax.net.ssl.KeyManager) AliasedX509ExtendedKeyManager(org.eclipse.jetty.util.ssl.AliasedX509ExtendedKeyManager) X509ExtendedKeyManager(javax.net.ssl.X509ExtendedKeyManager)

Example 5 with X509ExtendedTrustManager

use of javax.net.ssl.X509ExtendedTrustManager in project grpc-java by grpc.

the class AdvancedTlsX509TrustManager method updateTrustCredentials.

/**
 * Updates the current cached trust certificates as well as the key store.
 *
 * @param trustCerts the trust certificates that are going to be used
 */
public void updateTrustCredentials(X509Certificate[] trustCerts) throws IOException, GeneralSecurityException {
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(null, null);
    int i = 1;
    for (X509Certificate cert : trustCerts) {
        String alias = Integer.toString(i);
        keyStore.setCertificateEntry(alias, cert);
        i++;
    }
    X509ExtendedTrustManager newDelegateManager = createDelegateTrustManager(keyStore);
    this.delegateManager = newDelegateManager;
}
Also used : X509ExtendedTrustManager(javax.net.ssl.X509ExtendedTrustManager) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate)

Aggregations

X509ExtendedTrustManager (javax.net.ssl.X509ExtendedTrustManager)17 TrustManager (javax.net.ssl.TrustManager)13 KeyStore (java.security.KeyStore)10 X509Certificate (java.security.cert.X509Certificate)7 CertificateException (java.security.cert.CertificateException)6 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)5 KeyManager (javax.net.ssl.KeyManager)5 SSLContext (javax.net.ssl.SSLContext)5 SSLEngine (javax.net.ssl.SSLEngine)5 Test (org.junit.Test)5 IOException (java.io.IOException)4 Socket (java.net.Socket)4 KeyManagementException (java.security.KeyManagementException)4 TrustManagerFactory (javax.net.ssl.TrustManagerFactory)4 SecureRandom (java.security.SecureRandom)3 SelfSignedCertificate (io.netty.handler.ssl.util.SelfSignedCertificate)2 File (java.io.File)2 KeyStoreException (java.security.KeyStoreException)2 VisibleForTesting (com.google.common.annotations.VisibleForTesting)1 Bootstrap (io.netty.bootstrap.Bootstrap)1