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:me.melchor9000.net.SSLSocket.java

License:Open Source License

/**
 * <p>Creates a SSL socket using the Java implementation and the system's keychain
 * certificates.</p>// ww w  .  ja va 2 s . co m
 * <p>In HTTPS, the host identification is not done. If you need this
 * security extra, you should use {@link #SSLSocket(IOService, SSLSocketConfigurator)}.</p>
 * @param service {@link IOService} to attach this socket
 */
public SSLSocket(@NotNull IOService service) {
    super(service);
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            SslContextBuilder ctx = SslContextBuilder.forClient();
            SslContext ctx2 = ctx.build();
            ch.pipeline().addLast("readManager", readManager);
            ch.pipeline().addBefore("readManager", "ssl", ctx2.newHandler(ch.alloc()));
        }
    });
}

From source file:me.melchor9000.net.SSLSocket.java

License:Open Source License

/**
 * <p>Creates a SSL socket using the Java implementation and the provided certificate
 * chain in {@code .pem} format.</p>
 * <p>In HTTPS, the host identification is not done. If you need this extra of security,
 * you should use {@link #SSLSocket(IOService, SSLSocketConfigurator)} and use the
 * option {@link SslContextBuilder#trustManager(File)}.</p>
 * @param service {@link IOService} to attach this socket
 * @param certificate Certificate chain in {@code .pem} format
 *//*from  w  w w .  j a v a 2 s. c  o  m*/
public SSLSocket(@NotNull IOService service, @NotNull final File certificate) {
    super(service);
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            SslContextBuilder ctx = SslContextBuilder.forClient();
            ctx.trustManager(certificate.getAbsoluteFile());
            ch.pipeline().addLast("readManager", readManager);
            ch.pipeline().addBefore("readManager", "ssl", ctx.build().newHandler(ch.alloc()));
        }
    });
}

From source file:me.melchor9000.net.SSLSocket.java

License:Open Source License

/**
 * <p>Creates a SSL socket using the Java implementation and the provided certificate
 * chain in {@code .pem} format.</p>
 * <p>In HTTPS, the host identification is not done. If you need this extra of security,
 * you should use {@link #SSLSocket(IOService, SSLSocketConfigurator)} and use the
 * option {@link SslContextBuilder#trustManager(InputStream)}.</p>
 * @param service {@link IOService} to attach this socket
 * @param certificate Certificate chain in {@code .pem} format
 *//*from   ww w.ja v a2  s .c  om*/
public SSLSocket(@NotNull IOService service, @NotNull final InputStream certificate) {
    super(service);
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            SslContextBuilder ctx = SslContextBuilder.forClient();
            ctx.trustManager(certificate);
            ch.pipeline().addLast("readManager", readManager);
            ch.pipeline().addBefore("readManager", "ssl", ctx.build().newHandler(ch.alloc()));
        }
    });
}

From source file:me.melchor9000.net.SSLSocket.java

License:Open Source License

/**
 * <p>Creates a SSL socket using the custom options you set in the
 * {@link SSLSocketConfigurator#configure(SslContextBuilder)} method.
 * All methods available can be found in <a href="https://netty.io/4.1/api/io/netty/handler/ssl/SslContextBuilder.html">
 * SslContextBuilder</a>.</p>
 * <p>For enable host identification for HTTPS, you should override
 * {@link SSLSocketConfigurator#changeParameters(SSLParameters)} and set the option
 * {@link SSLParameters#setEndpointIdentificationAlgorithm(String)} to {@code "HTTPS"}</p>
 * @param service {@link IOService} to attach this socket
 * @param conf Custom configuration set in {@link SSLSocketConfigurator}
 *//*from w  ww .  j  ava2 s  .co m*/
public SSLSocket(@NotNull IOService service, @NotNull final SSLSocketConfigurator conf) {
    super(service);
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            SslContextBuilder ctx = SslContextBuilder.forClient();
            conf.configure(ctx);
            SslHandler handler = ctx.build().newHandler(ch.alloc());
            SSLParameters p = handler.engine().getSSLParameters();
            SSLParameters np = conf.changeParameters(p);
            if (np != null)
                handler.engine().setSSLParameters(np);
            ch.pipeline().addLast("readManager", readManager);
            ch.pipeline().addBefore("readManager", "ssl", handler);
        }
    });
}

From source file:me.melchor9000.net.SSLSocket.java

License:Open Source License

SSLSocket(SSLAcceptor acceptor, SocketChannel socket, SSLAcceptorConfigurator configurator)
        throws SSLException {
    super(acceptor, socket);
    SslContextBuilder builder = SslContextBuilder.forServer(configurator.getFactory());
    configurator.configure(builder);// ww w. j a  v  a 2s  .  c  o m
    SslHandler handler = builder.build().newHandler(socket.alloc());
    SSLParameters p = handler.engine().getSSLParameters();
    SSLParameters np = configurator.changeParameters(p);
    if (np != null)
        handler.engine().setSSLParameters(np);
    socket.pipeline().addBefore("readManager", "ssl", handler);
}

From source file:net.devh.boot.grpc.client.channelfactory.NettyChannelFactory.java

License:Open Source License

@Override
// Keep this in sync with ShadedNettyChannelFactory#configureSecurity
protected void configureSecurity(final NettyChannelBuilder builder, final String name) {
    final GrpcChannelProperties properties = getPropertiesFor(name);

    final NegotiationType negotiationType = properties.getNegotiationType();
    builder.negotiationType(of(negotiationType));

    if (negotiationType == NegotiationType.TLS) {
        final Security security = properties.getSecurity();

        final String authorityOverwrite = security.getAuthorityOverride();
        if (authorityOverwrite != null && !authorityOverwrite.isEmpty()) {
            builder.overrideAuthority(authorityOverwrite);
        }//from w  w w  .  java  2  s  .  co m

        final SslContextBuilder sslContextBuilder = GrpcSslContexts.forClient();

        if (security.isClientAuthEnabled()) {
            final File keyCertChainFile = toCheckedFile("keyCertChain", security.getCertificateChainPath());
            final File privateKeyFile = toCheckedFile("privateKey", security.getPrivateKeyPath());
            sslContextBuilder.keyManager(keyCertChainFile, privateKeyFile);
        }

        final String trustCertCollectionPath = security.getTrustCertCollectionPath();
        if (trustCertCollectionPath != null && !trustCertCollectionPath.isEmpty()) {
            final File trustCertCollectionFile = toCheckedFile("trustCertCollection", trustCertCollectionPath);
            sslContextBuilder.trustManager(trustCertCollectionFile);
        }

        try {
            builder.sslContext(sslContextBuilder.build());
        } catch (final SSLException e) {
            throw new IllegalStateException("Failed to create ssl context for grpc client", e);
        }
    }
}

From source file:net.devh.boot.grpc.server.serverfactory.NettyGrpcServerFactory.java

License:Open Source License

@Override
// Keep this in sync with ShadedNettyGrpcServerFactory#configureSecurity
protected void configureSecurity(final NettyServerBuilder builder) {
    final Security security = this.properties.getSecurity();
    if (security.isEnabled()) {
        final File certificateChainFile = toCheckedFile("certificateChain", security.getCertificateChainPath());
        final File privateKeyFile = toCheckedFile("privateKey", security.getPrivateKeyPath());
        final SslContextBuilder sslContextBuilder = GrpcSslContexts.forServer(certificateChainFile,
                privateKeyFile);/*w  ww .  j a v  a2s .c om*/

        if (security.getClientAuth() != ClientAuth.NONE) {
            sslContextBuilder.clientAuth(of(security.getClientAuth()));

            final String trustCertCollectionPath = security.getTrustCertCollectionPath();
            if (trustCertCollectionPath != null && !trustCertCollectionPath.isEmpty()) {
                final File trustCertCollectionFile = toCheckedFile("trustCertCollection",
                        trustCertCollectionPath);
                sslContextBuilder.trustManager(trustCertCollectionFile);
            }
        }

        try {
            builder.sslContext(sslContextBuilder.build());
        } catch (final SSLException e) {
            throw new IllegalStateException("Failed to create ssl context for grpc server", e);
        }
    }
}

From source file:org.apache.bookkeeper.tls.TLSContextFactory.java

License:Apache License

private void createClientContext(AbstractConfiguration conf)
        throws SecurityException, KeyStoreException, NoSuchAlgorithmException, CertificateException,
        IOException, UnrecoverableKeyException, InvalidKeySpecException, NoSuchProviderException {
    final SslContextBuilder sslContextBuilder;
    final ClientConfiguration clientConf;
    final SslProvider provider;
    final boolean clientAuthentication;

    // get key-file and trust-file locations and passwords
    if (!(conf instanceof ClientConfiguration)) {
        throw new SecurityException("Client configruation not provided");
    }//from   w w  w  . jav a 2  s  . c  o  m

    clientConf = (ClientConfiguration) conf;
    provider = getTLSProvider(clientConf.getTLSProvider());
    clientAuthentication = clientConf.getTLSClientAuthentication();

    switch (KeyStoreType.valueOf(clientConf.getTLSTrustStoreType())) {
    case PEM:
        if (Strings.isNullOrEmpty(clientConf.getTLSTrustStore())) {
            throw new SecurityException("CA Certificate required");
        }

        sslContextBuilder = SslContextBuilder.forClient().trustManager(new File(clientConf.getTLSTrustStore()))
                .ciphers(null).sessionCacheSize(0).sessionTimeout(0).sslProvider(provider)
                .clientAuth(ClientAuth.REQUIRE);

        break;
    case JKS:
        // falling thru, same as PKCS12
    case PKCS12:
        TrustManagerFactory tmf = initTrustManagerFactory(clientConf.getTLSTrustStoreType(),
                clientConf.getTLSTrustStore(), clientConf.getTLSTrustStorePasswordPath());

        sslContextBuilder = SslContextBuilder.forClient().trustManager(tmf).ciphers(null).sessionCacheSize(0)
                .sessionTimeout(0).sslProvider(provider).clientAuth(ClientAuth.REQUIRE);

        break;
    default:
        throw new SecurityException("Invalid Truststore type: " + clientConf.getTLSTrustStoreType());
    }

    if (clientAuthentication) {
        switch (KeyStoreType.valueOf(clientConf.getTLSKeyStoreType())) {
        case PEM:
            final String keyPassword;

            if (Strings.isNullOrEmpty(clientConf.getTLSCertificatePath())) {
                throw new SecurityException("Valid Certificate is missing");
            }

            if (Strings.isNullOrEmpty(clientConf.getTLSKeyStore())) {
                throw new SecurityException("Valid Key is missing");
            }

            if (!Strings.isNullOrEmpty(clientConf.getTLSKeyStorePasswordPath())) {
                keyPassword = getPasswordFromFile(clientConf.getTLSKeyStorePasswordPath());
            } else {
                keyPassword = null;
            }

            sslContextBuilder.keyManager(new File(clientConf.getTLSCertificatePath()),
                    new File(clientConf.getTLSKeyStore()), keyPassword);
            break;
        case JKS:
            // falling thru, same as PKCS12
        case PKCS12:
            KeyManagerFactory kmf = initKeyManagerFactory(clientConf.getTLSKeyStoreType(),
                    clientConf.getTLSKeyStore(), clientConf.getTLSKeyStorePasswordPath());

            sslContextBuilder.keyManager(kmf);
            break;
        default:
            throw new SecurityException("Invalid Keyfile type" + clientConf.getTLSKeyStoreType());
        }
    }

    sslContext = sslContextBuilder.build();
}

From source file:org.apache.bookkeeper.tls.TLSContextFactory.java

License:Apache License

private void createServerContext(AbstractConfiguration conf)
        throws SecurityException, KeyStoreException, NoSuchAlgorithmException, CertificateException,
        IOException, UnrecoverableKeyException, InvalidKeySpecException, IllegalArgumentException {
    final SslContextBuilder sslContextBuilder;
    final ServerConfiguration serverConf;
    final SslProvider provider;
    final boolean clientAuthentication;

    // get key-file and trust-file locations and passwords
    if (!(conf instanceof ServerConfiguration)) {
        throw new SecurityException("Server configruation not provided");
    }//from w w  w  .  j a v a  2  s.co m

    serverConf = (ServerConfiguration) conf;
    provider = getTLSProvider(serverConf.getTLSProvider());
    clientAuthentication = serverConf.getTLSClientAuthentication();

    switch (KeyStoreType.valueOf(serverConf.getTLSKeyStoreType())) {
    case PEM:
        final String keyPassword;

        if (Strings.isNullOrEmpty(serverConf.getTLSKeyStore())) {
            throw new SecurityException("Key path is required");
        }

        if (Strings.isNullOrEmpty(serverConf.getTLSCertificatePath())) {
            throw new SecurityException("Certificate path is required");
        }

        if (!Strings.isNullOrEmpty(serverConf.getTLSKeyStorePasswordPath())) {
            keyPassword = getPasswordFromFile(serverConf.getTLSKeyStorePasswordPath());
        } else {
            keyPassword = null;
        }

        sslContextBuilder = SslContextBuilder
                .forServer(new File(serverConf.getTLSCertificatePath()), new File(serverConf.getTLSKeyStore()),
                        keyPassword)
                .ciphers(null).sessionCacheSize(0).sessionTimeout(0).sslProvider(provider).startTls(true);

        break;
    case JKS:
        // falling thru, same as PKCS12
    case PKCS12:
        KeyManagerFactory kmf = initKeyManagerFactory(serverConf.getTLSKeyStoreType(),
                serverConf.getTLSKeyStore(), serverConf.getTLSKeyStorePasswordPath());

        sslContextBuilder = SslContextBuilder.forServer(kmf).ciphers(null).sessionCacheSize(0).sessionTimeout(0)
                .sslProvider(provider).startTls(true);

        break;
    default:
        throw new SecurityException("Invalid Keyfile type" + serverConf.getTLSKeyStoreType());
    }

    if (clientAuthentication) {
        sslContextBuilder.clientAuth(ClientAuth.REQUIRE);

        switch (KeyStoreType.valueOf(serverConf.getTLSTrustStoreType())) {
        case PEM:
            if (Strings.isNullOrEmpty(serverConf.getTLSTrustStore())) {
                throw new SecurityException("CA Certificate chain is required");
            }
            sslContextBuilder.trustManager(new File(serverConf.getTLSTrustStore()));
            break;
        case JKS:
            // falling thru, same as PKCS12
        case PKCS12:
            TrustManagerFactory tmf = initTrustManagerFactory(serverConf.getTLSTrustStoreType(),
                    serverConf.getTLSTrustStore(), serverConf.getTLSTrustStorePasswordPath());
            sslContextBuilder.trustManager(tmf);
            break;
        default:
            throw new SecurityException("Invalid Truststore type" + serverConf.getTLSTrustStoreType());
        }
    }

    sslContext = sslContextBuilder.build();
}

From source file:org.apache.nifi.processors.grpc.InvokeGRPC.java

License:Apache License

/**
 * Whenever this processor is triggered, we need to construct a client in order to communicate
 * with the configured gRPC service.//www.  j ava2  s  . c o m
 *
 * @param context the processor context
 */
@OnScheduled
public void initializeClient(final ProcessContext context) throws Exception {

    channelReference.set(null);
    blockingStubReference.set(null);
    final ComponentLog logger = getLogger();

    final String host = context.getProperty(PROP_SERVICE_HOST).getValue();
    final int port = context.getProperty(PROP_SERVICE_PORT).asInteger();
    final Integer maxMessageSize = context.getProperty(PROP_MAX_MESSAGE_SIZE).asDataSize(DataUnit.B).intValue();
    String userAgent = USER_AGENT_PREFIX;
    try {
        userAgent += "_" + InetAddress.getLocalHost().getHostName();
    } catch (final UnknownHostException e) {
        logger.warn("Unable to determine local hostname. Defaulting gRPC user agent to {}.",
                new Object[] { USER_AGENT_PREFIX }, e);
    }

    final NettyChannelBuilder nettyChannelBuilder = NettyChannelBuilder.forAddress(host, port)
            // supports both gzip and plaintext, but will compress by default.
            .compressorRegistry(CompressorRegistry.getDefaultInstance())
            .decompressorRegistry(DecompressorRegistry.getDefaultInstance())
            .maxInboundMessageSize(maxMessageSize).userAgent(userAgent);

    // configure whether or not we're using secure comms
    final boolean useSecure = context.getProperty(PROP_USE_SECURE).asBoolean();
    final SSLContextService sslContextService = context.getProperty(PROP_SSL_CONTEXT_SERVICE)
            .asControllerService(SSLContextService.class);
    final SSLContext sslContext = sslContextService == null ? null
            : sslContextService.createSSLContext(SSLContextService.ClientAuth.NONE);

    if (useSecure && sslContext != null) {
        SslContextBuilder sslContextBuilder = GrpcSslContexts.forClient();
        if (StringUtils.isNotBlank(sslContextService.getKeyStoreFile())) {
            final KeyManagerFactory keyManagerFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm(), sslContext.getProvider());
            final KeyStore keyStore = KeyStore.getInstance(sslContextService.getKeyStoreType());
            try (final InputStream is = new FileInputStream(sslContextService.getKeyStoreFile())) {
                keyStore.load(is, sslContextService.getKeyStorePassword().toCharArray());
            }
            keyManagerFactory.init(keyStore, sslContextService.getKeyStorePassword().toCharArray());
            sslContextBuilder.keyManager(keyManagerFactory);
        }

        if (StringUtils.isNotBlank(sslContextService.getTrustStoreFile())) {
            final TrustManagerFactory trustManagerFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm(), sslContext.getProvider());
            final KeyStore trustStore = KeyStore.getInstance(sslContextService.getTrustStoreType());
            try (final InputStream is = new FileInputStream(sslContextService.getTrustStoreFile())) {
                trustStore.load(is, sslContextService.getTrustStorePassword().toCharArray());
            }
            trustManagerFactory.init(trustStore);
            sslContextBuilder.trustManager(trustManagerFactory);
        }
        nettyChannelBuilder.sslContext(sslContextBuilder.build());

    } else {
        nettyChannelBuilder.usePlaintext(true);
    }

    final ManagedChannel channel = nettyChannelBuilder.build();
    final FlowFileServiceGrpc.FlowFileServiceBlockingStub blockingStub = FlowFileServiceGrpc
            .newBlockingStub(channel);
    channelReference.set(channel);
    blockingStubReference.set(blockingStub);
}