Example usage for io.netty.handler.ssl SslContextBuilder build

List of usage examples for io.netty.handler.ssl SslContextBuilder build

Introduction

In this page you can find the example usage for io.netty.handler.ssl SslContextBuilder build.

Prototype

public SslContext build() throws SSLException 

Source Link

Document

Create new SslContext instance with configured settings.

Usage

From source file:com.relayrides.pushy.apns.ApnsClientBuilder.java

License:Open Source License

/**
 * Constructs a new {@link ApnsClient} with the previously-set configuration.
 *
 * @return a new ApnsClient instance with the previously-set configuration
 *
 * @throws SSLException if an SSL context could not be created for the new client for any reason
 *
 * @since 0.8//from  w  w  w .j  ava  2 s . c o  m
 */
public ApnsClient build() throws SSLException {
    final SslContext sslContext;
    {
        final SslProvider sslProvider;

        if (this.preferredSslProvider != null) {
            sslProvider = this.preferredSslProvider;
        } else {
            if (OpenSsl.isAvailable()) {
                if (OpenSsl.isAlpnSupported()) {
                    log.info("Native SSL provider is available and supports ALPN; will use native provider.");
                    sslProvider = SslProvider.OPENSSL;
                } else {
                    log.info(
                            "Native SSL provider is available, but does not support ALPN; will use JDK SSL provider.");
                    sslProvider = SslProvider.JDK;
                }
            } else {
                log.info("Native SSL provider not available; will use JDK SSL provider.");
                sslProvider = SslProvider.JDK;
            }
        }

        final SslContextBuilder sslContextBuilder = SslContextBuilder.forClient().sslProvider(sslProvider)
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .applicationProtocolConfig(
                        new ApplicationProtocolConfig(Protocol.ALPN, SelectorFailureBehavior.NO_ADVERTISE,
                                SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2));

        if (this.trustedServerCertificatePemFile != null) {
            sslContextBuilder.trustManager(this.trustedServerCertificatePemFile);
        } else if (this.trustedServerCertificateInputStream != null) {
            sslContextBuilder.trustManager(this.trustedServerCertificateInputStream);
        } else if (this.trustedServerCertificates != null) {
            sslContextBuilder.trustManager(this.trustedServerCertificates);
        }

        sslContext = sslContextBuilder.build();
    }

    final ApnsClient apnsClient = new ApnsClient(sslContext, this.eventLoopGroup);

    apnsClient.setMetricsListener(this.metricsListener);
    apnsClient.setProxyHandlerFactory(this.proxyHandlerFactory);

    if (this.connectionTimeout != null) {
        apnsClient.setConnectionTimeout((int) this.connectionTimeoutUnit.toMillis(this.connectionTimeout));
    }

    if (this.writeTimeout != null) {
        apnsClient.setWriteTimeout(this.writeTimeoutUnit.toMillis(this.writeTimeout));
    }

    if (this.gracefulShutdownTimeout != null) {
        apnsClient.setGracefulShutdownTimeout(
                this.gracefulShutdownTimeoutUnit.toMillis(this.gracefulShutdownTimeout));
    }

    return apnsClient;
}

From source file:com.relayrides.pushy.apns.MockApnsServerBuilder.java

License:Open Source License

/**
 * Constructs a new {@link MockApnsServer} with the previously-set configuration.
 *
 * @return a new MockApnsServer instance with the previously-set configuration
 *
 * @throws SSLException if an SSL context could not be created for the new server for any reason
 *
 * @since 0.8//from  w w  w  .j a v a  2 s.  c  o  m
 */
public MockApnsServer build() throws SSLException {
    final SslContext sslContext;
    {
        final SslProvider sslProvider;

        if (this.preferredSslProvider != null) {
            sslProvider = this.preferredSslProvider;
        } else {
            if (OpenSsl.isAvailable()) {
                if (OpenSsl.isAlpnSupported()) {
                    log.info("Native SSL provider is available and supports ALPN; will use native provider.");
                    sslProvider = SslProvider.OPENSSL;
                } else {
                    log.info(
                            "Native SSL provider is available, but does not support ALPN; will use JDK SSL provider.");
                    sslProvider = SslProvider.JDK;
                }
            } else {
                log.info("Native SSL provider not available; will use JDK SSL provider.");
                sslProvider = SslProvider.JDK;
            }
        }

        final SslContextBuilder sslContextBuilder;

        if (this.certificateChain != null && this.privateKey != null) {
            sslContextBuilder = SslContextBuilder.forServer(this.privateKey, this.privateKeyPassword,
                    this.certificateChain);
        } else if (this.certificateChainPemFile != null && this.privateKeyPkcs8File != null) {
            sslContextBuilder = SslContextBuilder.forServer(this.certificateChainPemFile,
                    this.privateKeyPkcs8File, this.privateKeyPassword);
        } else if (this.certificateChainInputStream != null && this.privateKeyPkcs8InputStream != null) {
            sslContextBuilder = SslContextBuilder.forServer(this.certificateChainInputStream,
                    this.privateKeyPkcs8InputStream, this.privateKeyPassword);
        } else {
            throw new IllegalStateException("Must specify server credentials before building a mock server.");
        }

        sslContextBuilder.sslProvider(sslProvider)
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .clientAuth(ClientAuth.OPTIONAL).applicationProtocolConfig(
                        new ApplicationProtocolConfig(Protocol.ALPN, SelectorFailureBehavior.NO_ADVERTISE,
                                SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2));

        sslContext = sslContextBuilder.build();
    }

    final MockApnsServer server = new MockApnsServer(sslContext, this.eventLoopGroup);
    server.setEmulateInternalErrors(this.emulateInternalErrors);

    return server;
}

From source file:com.turo.pushy.apns.ApnsClientBuilder.java

License:Open Source License

/**
 * Constructs a new {@link ApnsClient} with the previously-set configuration.
 *
 * @return a new ApnsClient instance with the previously-set configuration
 *
 * @throws SSLException if an SSL context could not be created for the new client for any reason
 * @throws IllegalStateException if this method is called without specifying an APNs server address, if this method
 * is called without providing TLS credentials or a signing key, or if this method is called with both TLS
 * credentials and a signing key/*from w  w w  . j  av  a2  s.c  om*/
 *
 * @since 0.8
 */
public ApnsClient build() throws SSLException {
    if (this.apnsServerAddress == null) {
        throw new IllegalStateException("No APNs server address specified.");
    }

    if (this.clientCertificate == null && this.privateKey == null && this.signingKey == null) {
        throw new IllegalStateException("No client credentials specified; either TLS credentials (a "
                + "certificate/private key) or an APNs signing key must be provided before building a client.");
    } else if ((this.clientCertificate != null || this.privateKey != null) && this.signingKey != null) {
        throw new IllegalStateException("Clients may not have both a signing key and TLS credentials.");
    }

    final SslContext sslContext;
    {
        final SslProvider sslProvider;

        if (OpenSsl.isAvailable()) {
            log.info("Native SSL provider is available; will use native provider.");
            sslProvider = SslProvider.OPENSSL_REFCNT;
        } else {
            log.info("Native SSL provider not available; will use JDK SSL provider.");
            sslProvider = SslProvider.JDK;
        }

        final SslContextBuilder sslContextBuilder = SslContextBuilder.forClient().sslProvider(sslProvider)
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE);

        if (this.clientCertificate != null && this.privateKey != null) {
            sslContextBuilder.keyManager(this.privateKey, this.privateKeyPassword, this.clientCertificate);
        }

        if (this.trustedServerCertificatePemFile != null) {
            sslContextBuilder.trustManager(this.trustedServerCertificatePemFile);
        } else if (this.trustedServerCertificateInputStream != null) {
            sslContextBuilder.trustManager(this.trustedServerCertificateInputStream);
        } else if (this.trustedServerCertificates != null) {
            sslContextBuilder.trustManager(this.trustedServerCertificates);
        }

        sslContext = sslContextBuilder.build();
    }

    final ApnsClient client = new ApnsClient(this.apnsServerAddress, sslContext, this.signingKey,
            this.proxyHandlerFactory, this.connectionTimeoutMillis, this.idlePingIntervalMillis,
            this.gracefulShutdownTimeoutMillis, this.concurrentConnections, this.metricsListener,
            this.frameLogger, this.eventLoopGroup);

    if (sslContext instanceof ReferenceCounted) {
        ((ReferenceCounted) sslContext).release();
    }

    return client;
}

From source file:com.turo.pushy.apns.MockApnsServerBuilder.java

License:Open Source License

/**
 * Constructs a new {@link MockApnsServer} with the previously-set configuration.
 *
 * @return a new MockApnsServer instance with the previously-set configuration
 *
 * @throws SSLException if an SSL context could not be created for the new server for any reason
 *
 * @since 0.8/*  w  w w  .  j  a v  a2s . c  o m*/
 */
public MockApnsServer build() throws SSLException {
    final SslContext sslContext;
    {
        final SslProvider sslProvider = SslUtil.getSslProvider();

        final SslContextBuilder sslContextBuilder;

        if (this.certificateChain != null && this.privateKey != null) {
            sslContextBuilder = SslContextBuilder.forServer(this.privateKey, this.privateKeyPassword,
                    this.certificateChain);
        } else if (this.certificateChainPemFile != null && this.privateKeyPkcs8File != null) {
            sslContextBuilder = SslContextBuilder.forServer(this.certificateChainPemFile,
                    this.privateKeyPkcs8File, this.privateKeyPassword);
        } else if (this.certificateChainInputStream != null && this.privateKeyPkcs8InputStream != null) {
            sslContextBuilder = SslContextBuilder.forServer(this.certificateChainInputStream,
                    this.privateKeyPkcs8InputStream, this.privateKeyPassword);
        } else {
            throw new IllegalStateException("Must specify server credentials before building a mock server.");
        }

        sslContextBuilder.sslProvider(sslProvider)
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .clientAuth(ClientAuth.OPTIONAL).applicationProtocolConfig(
                        new ApplicationProtocolConfig(Protocol.ALPN, SelectorFailureBehavior.NO_ADVERTISE,
                                SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2));

        if (this.trustedClientCertificatePemFile != null) {
            sslContextBuilder.trustManager(this.trustedClientCertificatePemFile);
        } else if (this.trustedClientCertificateInputStream != null) {
            sslContextBuilder.trustManager(this.trustedClientCertificateInputStream);
        } else if (this.trustedClientCertificates != null) {
            sslContextBuilder.trustManager(this.trustedClientCertificates);
        }

        sslContext = sslContextBuilder.build();
    }

    final MockApnsServer server = new MockApnsServer(sslContext, this.eventLoopGroup);
    server.setEmulateInternalErrors(this.emulateInternalErrors);
    server.setEmulateExpiredFirstToken(this.emulateExpiredFirstToken);

    return server;
}

From source file:com.turo.pushy.apns.server.BaseHttp2ServerBuilder.java

License:Open Source License

/**
 * Constructs a new server with the previously-set configuration.
 *
 * @return a new server instance with the previously-set configuration
 *
 * @throws SSLException if an SSL context could not be created for the new server for any reason
 *
 * @since 0.8/*from  w  w  w .j a v  a2s  . c om*/
 */
public T build() throws SSLException {
    final SslContext sslContext;
    {
        final SslProvider sslProvider;

        if (OpenSsl.isAvailable()) {
            log.info("Native SSL provider is available; will use native provider.");
            sslProvider = SslProvider.OPENSSL;
        } else {
            log.info("Native SSL provider not available; will use JDK SSL provider.");
            sslProvider = SslProvider.JDK;
        }

        final SslContextBuilder sslContextBuilder;

        if (this.certificateChain != null && this.privateKey != null) {
            sslContextBuilder = SslContextBuilder.forServer(this.privateKey, this.privateKeyPassword,
                    this.certificateChain);
        } else if (this.certificateChainPemFile != null && this.privateKeyPkcs8File != null) {
            sslContextBuilder = SslContextBuilder.forServer(this.certificateChainPemFile,
                    this.privateKeyPkcs8File, this.privateKeyPassword);
        } else if (this.certificateChainInputStream != null && this.privateKeyPkcs8InputStream != null) {
            sslContextBuilder = SslContextBuilder.forServer(this.certificateChainInputStream,
                    this.privateKeyPkcs8InputStream, this.privateKeyPassword);
        } else {
            throw new IllegalStateException("Must specify server credentials before building a mock server.");
        }

        sslContextBuilder.sslProvider(sslProvider)
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .clientAuth(ClientAuth.OPTIONAL);

        if (this.trustedClientCertificatePemFile != null) {
            sslContextBuilder.trustManager(this.trustedClientCertificatePemFile);
        } else if (this.trustedClientCertificateInputStream != null) {
            sslContextBuilder.trustManager(this.trustedClientCertificateInputStream);
        } else if (this.trustedClientCertificates != null) {
            sslContextBuilder.trustManager(this.trustedClientCertificates);
        }

        if (this.useAlpn) {
            sslContextBuilder.applicationProtocolConfig(
                    new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN,
                            ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                            ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
                            ApplicationProtocolNames.HTTP_2));
        }

        sslContext = sslContextBuilder.build();
    }

    final T server = this.constructServer(sslContext);

    if (sslContext instanceof ReferenceCounted) {
        ((ReferenceCounted) sslContext).release();
    }

    return server;
}

From source file:com.vmware.xenon.host.XenonHostWithPeerListener.java

License:Open Source License

private int startPeerListener() throws Throwable {
    if (this.hostArgs.nodeGroupPublicUri == null) {
        return ServiceHost.PORT_VALUE_LISTENER_DISABLED;
    }/*w  w w .ja  va2 s.  com*/

    URI uri = URI.create(this.hostArgs.nodeGroupPublicUri);
    NettyHttpListener peerListener = new NettyHttpListener(this);

    boolean isHttps = uri.getScheme().equals("https");
    if (isHttps) {
        SslContextBuilder builder;
        if (this.hostArgs.peerCertificateFile != null && this.hostArgs.peerKeyFile != null) {
            builder = SslContextBuilder.forServer(this.hostArgs.peerCertificateFile.toFile(),
                    this.hostArgs.peerKeyFile.toFile(), this.hostArgs.peerKeyPassphrase);
        } else {
            builder = SslContextBuilder.forServer(this.hostArgs.certificateFile.toFile(),
                    this.hostArgs.keyFile.toFile(), this.hostArgs.keyPassphrase);
        }

        if (OpenSsl.isAlpnSupported()) {
            builder.ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                    .applicationProtocolConfig(
                            new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN,
                                    ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                                    ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
                                    ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1));
        }

        peerListener.setSSLContext(builder.build());
    }

    peerListener.start(uri.getPort(), uri.getHost());
    int assignedPort = peerListener.getPort();
    log(Level.INFO, "Started peer listener on %s",
            UriUtils.buildUri(uri.getScheme(), uri.getHost(), assignedPort, null, null));
    return assignedPort;
}

From source file:com.yahoo.pulsar.client.impl.ConnectionPool.java

License:Apache License

public ConnectionPool(final PulsarClientImpl client, EventLoopGroup eventLoopGroup) {
    this.eventLoopGroup = eventLoopGroup;
    this.maxConnectionsPerHosts = client.getConfiguration().getConnectionsPerBroker();

    pool = new ConcurrentHashMap<>();
    bootstrap = new Bootstrap();
    bootstrap.group(eventLoopGroup);//from   w  w w .  j a  v  a  2s.  com
    if (SystemUtils.IS_OS_LINUX && eventLoopGroup instanceof EpollEventLoopGroup) {
        bootstrap.channel(EpollSocketChannel.class);
    } else {
        bootstrap.channel(NioSocketChannel.class);
    }

    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
    bootstrap.option(ChannelOption.TCP_NODELAY, client.getConfiguration().isUseTcpNoDelay());
    bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        public void initChannel(SocketChannel ch) throws Exception {
            ClientConfiguration clientConfig = client.getConfiguration();
            if (clientConfig.isUseTls()) {
                SslContextBuilder builder = SslContextBuilder.forClient();
                if (clientConfig.isTlsAllowInsecureConnection()) {
                    builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
                } else {
                    if (clientConfig.getTlsTrustCertsFilePath().isEmpty()) {
                        // Use system default
                        builder.trustManager((File) null);
                    } else {
                        File trustCertCollection = new File(clientConfig.getTlsTrustCertsFilePath());
                        builder.trustManager(trustCertCollection);
                    }
                }

                // Set client certificate if available
                AuthenticationDataProvider authData = clientConfig.getAuthentication().getAuthData();
                if (authData.hasDataForTls()) {
                    builder.keyManager(authData.getTlsPrivateKey(),
                            (X509Certificate[]) authData.getTlsCertificates());
                }

                SslContext sslCtx = builder.build();
                ch.pipeline().addLast(TLS_HANDLER, sslCtx.newHandler(ch.alloc()));
            }
            ch.pipeline().addLast("frameDecoder",
                    new PulsarLengthFieldFrameDecoder(MaxMessageSize, 0, 4, 0, 4));
            ch.pipeline().addLast("handler", new ClientCnx(client));
        }
    });
}

From source file:com.yahoo.pulsar.common.util.SecurityUtility.java

License:Apache License

public static SslContext createNettySslContext(boolean allowInsecureConnection, String trustCertsFilePath,
        Certificate[] certificates, PrivateKey privateKey)
        throws GeneralSecurityException, SSLException, FileNotFoundException {
    SslContextBuilder builder = SslContextBuilder.forClient();
    if (allowInsecureConnection) {
        builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
    } else {//from w ww  .  ja va2s .co  m
        if (trustCertsFilePath != null && trustCertsFilePath.length() != 0) {
            builder.trustManager(new FileInputStream(trustCertsFilePath));
        }
    }
    builder.keyManager(privateKey, (X509Certificate[]) certificates);
    return builder.build();
}

From source file:com.yahoo.pulsar.discovery.service.DiscoveryServiceTest.java

License:Apache License

/**
 * creates ClientHandler channel to connect and communicate with server
 * //from  ww w  . j a  v  a 2 s  .  com
 * @param serviceUrl
 * @param latch
 * @return
 * @throws URISyntaxException
 */
public static NioEventLoopGroup connectToService(String serviceUrl, CountDownLatch latch, boolean tls)
        throws URISyntaxException {
    NioEventLoopGroup workerGroup = new NioEventLoopGroup();
    Bootstrap b = new Bootstrap();
    b.group(workerGroup);
    b.channel(NioSocketChannel.class);

    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            if (tls) {
                SslContextBuilder builder = SslContextBuilder.forClient();
                builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
                X509Certificate[] certificates = SecurityUtility
                        .loadCertificatesFromPemFile(TLS_CLIENT_CERT_FILE_PATH);
                PrivateKey privateKey = SecurityUtility.loadPrivateKeyFromPemFile(TLS_CLIENT_KEY_FILE_PATH);
                builder.keyManager(privateKey, (X509Certificate[]) certificates);
                SslContext sslCtx = builder.build();
                ch.pipeline().addLast("tls", sslCtx.newHandler(ch.alloc()));
            }
            ch.pipeline().addLast(new ClientHandler(latch));
        }
    });
    URI uri = new URI(serviceUrl);
    InetSocketAddress serviceAddress = new InetSocketAddress(uri.getHost(), uri.getPort());
    b.connect(serviceAddress).addListener((ChannelFuture future) -> {
        if (!future.isSuccess()) {
            throw new IllegalStateException(future.cause());
        }
    });
    return workerGroup;
}

From source file:io.airlift.drift.transport.netty.DriftNettyMethodInvokerFactory.java

License:Apache License

@Override
public MethodInvoker createMethodInvoker(AddressSelector addressSelector, I clientIdentity) {
    DriftNettyClientConfig clientConfig = clientConfigurationProvider.apply(clientIdentity);

    TProtocolFactory protocolFactory;//from   w w w  .  j a va  2  s .c o m
    switch (clientConfig.getProtocol()) {
    case BINARY:
        protocolFactory = new TBinaryProtocol.Factory(false, true, -1,
                clientConfig.getMaxFrameSize().toBytes());
        break;
    case COMPACT:
        // Header transport uses the FB fork of the compact protocol
        if (clientConfig.getTransport() == Transport.HEADER) {
            protocolFactory = new TFacebookCompactProtocol.Factory(
                    toIntExact(clientConfig.getMaxFrameSize().toBytes()));
        } else {
            protocolFactory = new TCompactProtocol.Factory(-1, clientConfig.getMaxFrameSize().toBytes());
        }
        break;
    default:
        throw new IllegalArgumentException("Unknown protocol: " + clientConfig.getProtocol());
    }

    MessageFraming messageFraming;
    MessageEncoding messageEncoding;
    switch (clientConfig.getTransport()) {
    case UNFRAMED:
        messageFraming = new NoMessageFraming(protocolFactory, clientConfig.getMaxFrameSize());
        messageEncoding = new SimpleMessageEncoding(protocolFactory);
        break;
    case FRAMED:
        messageFraming = new LengthPrefixedMessageFraming(clientConfig.getMaxFrameSize());
        messageEncoding = new SimpleMessageEncoding(protocolFactory);
        break;
    case HEADER:
        messageFraming = new LengthPrefixedMessageFraming(clientConfig.getMaxFrameSize());
        messageEncoding = new HeaderMessageEncoding(protocolFactory);
        break;
    default:
        throw new IllegalArgumentException("Unknown transport: " + clientConfig.getTransport());
    }

    Optional<SslContext> sslContext;
    if (clientConfig.isSslEnabled()) {
        try {
            SslContextBuilder sslContextBuilder = SslContextBuilder.forClient()
                    .trustManager(clientConfig.getTrustCertificate())
                    .keyManager(clientConfig.getKey(), null, clientConfig.getKeyPassword())
                    .sessionCacheSize(clientConfig.getSessionCacheSize())
                    .sessionTimeout(clientConfig.getSessionTimeout().roundTo(SECONDS));
            if (!clientConfig.getCiphers().isEmpty()) {
                sslContextBuilder.ciphers(clientConfig.getCiphers());
            }
            sslContext = Optional.of(sslContextBuilder.build());
        } catch (SSLException e) {
            throw new RuntimeException("Invalid SSL configuration", e);
        }
    } else {
        sslContext = Optional.empty();
    }

    ConnectionManager connectionManager = new ConnectionFactory(group, messageFraming, messageEncoding,
            sslContext, clientConfig);
    if (clientConfig.isPoolEnabled()) {
        connectionManager = new ConnectionPool(connectionManager, group, clientConfig);
    }
    return new DriftNettyMethodInvoker(connectionManager, addressSelector);
}