Example usage for io.netty.handler.ssl SslProvider OPENSSL

List of usage examples for io.netty.handler.ssl SslProvider OPENSSL

Introduction

In this page you can find the example usage for io.netty.handler.ssl SslProvider OPENSSL.

Prototype

SslProvider OPENSSL

To view the source code for io.netty.handler.ssl SslProvider OPENSSL.

Click Source Link

Document

OpenSSL-based implementation.

Usage

From source file:org.graylog2.inputs.transports.NettyTransportConfiguration.java

License:Open Source License

private SslProvider detectTlsProvider() {
    if (OpenSsl.isAvailable()) {
        LOG.debug("Using OpenSSL for Netty transports.");
        return SslProvider.OPENSSL;
    } else {//  w w w  .j  a v  a 2 s .  c o  m
        LOG.debug("Using default Java TLS provider for Netty transports.");
        return SslProvider.JDK;
    }
}

From source file:org.hyperledger.fabric.sdk.Endpoint.java

License:Open Source License

Endpoint(String url, Properties properties) {

    logger.trace(String.format("Creating endpoint for url %s", url));
    this.url = url;

    String pem = null;/*  ww w.ja  v a2s . c  o  m*/
    String cn = null;
    String sslp = null;
    String nt = null;

    Properties purl = parseGrpcUrl(url);
    String protocol = purl.getProperty("protocol");
    this.addr = purl.getProperty("host");
    this.port = Integer.parseInt(purl.getProperty("port"));

    if (properties != null) {
        if ("grpcs".equals(protocol)) {
            try {
                pem = properties.getProperty("pemFile");
                cn = properties.getProperty("hostnameOverride");

                if (cn == null && "true".equals(properties.getProperty("trustServerCertificate"))) {

                    File pemF = new File(pem);
                    final String cnKey = pemF.getAbsolutePath() + pemF.length() + pemF.lastModified();

                    cn = cnCache.get(cnKey);
                    if (cn == null) {
                        Path path = Paths.get(pem);
                        byte[] data = Files.readAllBytes(path);

                        CryptoPrimitives cp = new CryptoPrimitives();

                        X500Name x500name = new JcaX509CertificateHolder(
                                (X509Certificate) cp.bytesToCertificate(data)).getSubject();
                        RDN rdn = x500name.getRDNs(BCStyle.CN)[0];
                        //   cnn =  cn +"";
                        AttributeTypeAndValue f = rdn.getFirst();
                        cn = IETFUtils.valueToString(rdn.getFirst().getValue());
                        cnCache.put(cnKey, cn);
                    }

                }
            } catch (Exception e) {
                /// Mostly a development env. just log it.
                logger.error(
                        "Error getting Subject CN from certificate. Try setting it specifically with hostnameOverride property. "
                                + e.getMessage());

            }

            sslp = properties.getProperty("sslProvider");
            if (sslp == null) {
                throw new RuntimeException("Property of sslProvider expected");
            }
            if (!sslp.equals("openSSL") && !sslp.equals("JDK")) {
                throw new RuntimeException("Property of sslProvider has to be either openSSL or JDK");
            }

            nt = properties.getProperty("negotiationType");
            if (nt == null) {
                throw new RuntimeException("Property of negotiationType expected");
            }
            if (!nt.equals("TLS") && !sslp.equals("plainText")) {
                throw new RuntimeException("Property of negotiationType has to be either TLS or plainText");
            }
        }

    }

    try {
        if (protocol.equalsIgnoreCase("grpc")) {
            this.channelBuilder = ManagedChannelBuilder.forAddress(addr, port).usePlaintext(true);
            addNettyBuilderProps(channelBuilder, properties);
        } else if (protocol.equalsIgnoreCase("grpcs")) {
            if (Utils.isNullOrEmpty(pem)) {
                // use root certificate
                this.channelBuilder = ManagedChannelBuilder.forAddress(addr, port);
                addNettyBuilderProps(channelBuilder, properties);
            } else {
                try {

                    SslProvider sslprovider = sslp.equals("openSSL") ? SslProvider.OPENSSL : SslProvider.JDK;
                    NegotiationType ntype = nt.equals("TLS") ? NegotiationType.TLS : NegotiationType.PLAINTEXT;

                    SslContext sslContext = GrpcSslContexts.forClient().trustManager(new File(pem))
                            .sslProvider(sslprovider).build();
                    this.channelBuilder = NettyChannelBuilder.forAddress(addr, port).sslContext(sslContext)
                            .negotiationType(ntype);
                    if (cn != null) {
                        channelBuilder.overrideAuthority(cn);
                    }
                    addNettyBuilderProps(channelBuilder, properties);
                } catch (SSLException sslex) {
                    throw new RuntimeException(sslex);
                }
            }
        } else {
            throw new RuntimeException("invalid protocol: " + protocol);
        }
    } catch (RuntimeException e) {
        logger.error(e);
        throw e;
    } catch (Exception e) {
        logger.error(e);
        throw new RuntimeException(e);
    }

}

From source file:org.hyperledger.fabric.sdk.security.TLSCertGenTest.java

License:Open Source License

private SslContextBuilder getSslContextBuilder(File clientCertFile, File clientKeyFile, File serverCertFile) {
    SslProvider sslprovider = SslProvider.OPENSSL;
    SslContextBuilder ctxBuilder = SslContextBuilder.forClient().protocols(TLS_PROTOCOL)
            .trustManager(serverCertFile);
    SslContextBuilder clientContextBuilder = GrpcSslContexts.configure(ctxBuilder, sslprovider);
    clientContextBuilder = clientContextBuilder.keyManager(clientCertFile, clientKeyFile);
    return clientContextBuilder;
}

From source file:org.jooby.internal.netty.NettySslContext.java

License:Apache License

static SslContext build(final Config conf) throws IOException, CertificateException {
    String tmpdir = conf.getString("application.tmpdir");
    boolean http2 = conf.getBoolean("server.http2.enabled");
    File keyStoreCert = toFile(conf.getString("ssl.keystore.cert"), tmpdir);
    File keyStoreKey = toFile(conf.getString("ssl.keystore.key"), tmpdir);
    String keyStorePass = conf.hasPath("ssl.keystore.password") ? conf.getString("ssl.keystore.password")
            : null;/*w  w w . ja  v  a  2  s .c o m*/
    SslContextBuilder scb = SslContextBuilder.forServer(keyStoreCert, keyStoreKey, keyStorePass);
    if (conf.hasPath("ssl.trust.cert")) {
        scb.trustManager(toFile(conf.getString("ssl.trust.cert"), tmpdir));
    }
    if (http2) {
        SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
        return scb.sslProvider(provider).ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN,
                        SelectorFailureBehavior.NO_ADVERTISE, SelectedListenerFailureBehavior.ACCEPT,
                        Arrays.asList(ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1)))
                .build();
    }
    return scb.build();
}

From source file:org.wso2.carbon.http2.transport.util.Http2ConnectionFactory.java

License:Open Source License

/**
 * Create new connection and return client handler
 *
 * @param uri/*w ww.  j  a  v a2 s . c o m*/
 * @return Http2ClientHandler
 * @throws AxisFault
 */
private Http2ClientHandler cacheNewConnection(HttpHost uri) throws AxisFault {

    final SslContext sslCtx;
    final boolean SSL;
    if (uri.getSchemeName().equalsIgnoreCase("https")) {
        SSL = true;
    } else
        SSL = false;
    try {
        // Handling SSL
        if (SSL) {
            Parameter trustParam = trasportOut.getParameter(Http2Constants.TRUST_STORE_CONFIG_ELEMENT);
            OMElement tsEle = null;
            if (trustParam != null) {
                tsEle = trustParam.getParameterElement();
            }
            final String location = tsEle.getFirstChildWithName(new QName(Http2Constants.TRUST_STORE_LOCATION))
                    .getText();
            final String storePassword = tsEle
                    .getFirstChildWithName(new QName(Http2Constants.TRUST_STORE_PASSWORD)).getText();

            SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
            sslCtx = SslContextBuilder.forClient()
                    .trustManager(SSLUtil.createTrustmanager(location, storePassword)).sslProvider(provider)
                    .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                    .trustManager(InsecureTrustManagerFactory.INSTANCE)
                    .applicationProtocolConfig(
                            new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN,
                                    ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                                    ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
                                    ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1))
                    .build();
        } else {
            sslCtx = null;
        }
        Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx, Integer.MAX_VALUE);

        String HOST = uri.getHostName();
        Integer PORT = uri.getPort();
        // Configure the client.
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.remoteAddress(HOST, PORT);
        b.handler(initializer);
        // Start the client.
        Channel channel = b.connect().syncUninterruptibly().channel();

        log.debug("Connected to [" + HOST + ':' + PORT + ']');

        Http2SettingsHandler http2SettingsHandler = initializer.settingsHandler();
        http2SettingsHandler.awaitSettings(5, TimeUnit.SECONDS);

        final String key = generateKey(URI.create(uri.toURI()));
        Http2ClientHandler handler = initializer.responseHandler();

        clientConnections.put(key, handler);

        channel.closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() {
            @Override
            public void operationComplete(Future<? super Void> future) throws Exception {
                clientConnections.remove(key);
            }
        });
        return initializer.responseHandler();
    } catch (SSLException e) {
        throw new AxisFault("Error while connection establishment:", e);
    } catch (Exception e) {
        throw new AxisFault("Error while connection establishment:" + e);
    }
}

From source file:org.wso2.carbon.inbound.endpoint.protocol.http2.management.Http2EndpointManager.java

License:Open Source License

public SslContext getSSLContext(InboundWebsocketSSLConfiguration sslconfig) {
    SslContext sslContext = null;//from  w w w . j av a  2 s.c  o m
    SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
    try {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        SSLHandlerFactory handlerFactory = new SSLHandlerFactory(sslconfig);
        sslContext = SslContextBuilder.forServer(handlerFactory.getKeyStoreFactory())
                .trustManager(handlerFactory.getTrustStoreFactory()).sslProvider(provider)
                /* NOTE: the cipher filter may not include all ciphers required by the HTTP/2 specification.
                 * Please refer to the HTTP/2 specification for cipher requirements. */
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .applicationProtocolConfig(
                        new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN,
                                // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
                                ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                                // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
                                ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
                                ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1))
                .build();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (SSLException e) {
        e.printStackTrace();
    }
    return sslContext;
}

From source file:org.wso2.carbon.transport.http.netty.common.ssl.SSLHandlerFactory.java

License:Open Source License

/**
 * This method will provide netty ssl context which supports HTTP2 over TLS using
 * Application Layer Protocol Negotiation (ALPN)
 *
 * @return instance of {@link SslContext}
 * @throws SSLException if any error occurred during building SSL context.
 *//*w  w  w . j av  a 2s  . co  m*/
public SslContext createHttp2TLSContext() throws SSLException {

    // If listener configuration does not include cipher suites , default ciphers required by the HTTP/2
    // specification will be added.
    List<String> ciphers = sslConfig.getCipherSuites() != null && sslConfig.getCipherSuites().length > 0
            ? Arrays.asList(sslConfig.getCipherSuites())
            : Http2SecurityUtil.CIPHERS;
    SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
    return SslContextBuilder.forServer(this.getKeyManagerFactory()).trustManager(this.getTrustStoreFactory())
            .sslProvider(provider).ciphers(ciphers, SupportedCipherSuiteFilter.INSTANCE)
            .clientAuth(needClientAuth ? ClientAuth.REQUIRE : ClientAuth.NONE)
            .applicationProtocolConfig(new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN,
                    // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
                    ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                    // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
                    ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
                    ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1))
            .build();
}

From source file:org.wso2.carbon.transport.http.netty.util.client.http2.HTTP2Client.java

License:Open Source License

public HTTP2Client(boolean ssl, String host, int port) throws Exception {

    try {/*from w ww. j  av  a 2  s.  com*/

        final SslContext sslCtx;
        if (ssl) {
            SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
            sslCtx = SslContextBuilder.forClient().sslProvider(provider)
                    .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                    .trustManager(InsecureTrustManagerFactory.INSTANCE)
                    .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN,
                            // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
                            SelectorFailureBehavior.NO_ADVERTISE,
                            // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
                            SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2,
                            ApplicationProtocolNames.HTTP_1_1))
                    .build();
        } else {
            sslCtx = null;
        }
        workerGroup = new NioEventLoopGroup();
        HTTP2ClientInitializer initializer = new HTTP2ClientInitializer(sslCtx, Integer.MAX_VALUE);

        // Configure the client.
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.remoteAddress(host, port);
        b.handler(initializer);

        // Start the client.
        channel = b.connect().syncUninterruptibly().channel();
        log.info("Connected to [" + host + ':' + port + ']');

        // Wait for the HTTP/2 upgrade to occur.
        HTTP2SettingsHandler http2SettingsHandler = initializer.settingsHandler();
        http2SettingsHandler.awaitSettings(TestUtil.HTTP2_RESPONSE_TIME_OUT, TestUtil.HTTP2_RESPONSE_TIME_UNIT);
        responseHandler = initializer.responseHandler();
        scheme = ssl ? HttpScheme.HTTPS : HttpScheme.HTTP;
        hostName = new AsciiString(host + ':' + port);

    } catch (Exception ex) {
        log.error("Error while initializing http2 client " + ex);
        this.close();
    }

}

From source file:org.wso2.esb.integration.common.utils.clients.Http2Client.java

License:Open Source License

private SslContext generateSSLContext(TrustManagerFactory trustManager) throws SSLException {
    SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
    return SslContextBuilder.forClient().sslProvider(provider).trustManager(trustManager)
            .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
            .trustManager(InsecureTrustManagerFactory.INSTANCE)
            .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN,
                    SelectorFailureBehavior.NO_ADVERTISE, SelectedListenerFailureBehavior.ACCEPT,
                    ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1))
            .build();/*w ww.  ja v  a  2 s . com*/

}

From source file:org.wso2.esb.integration.common.utils.servers.Http2Server.java

License:Open Source License

public void startServer() throws Exception {
    final SslContext sslCtx;
    if (SSL) {/*from  w  w w .j av  a  2s  .co m*/
        SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).sslProvider(provider)
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN,
                        SelectorFailureBehavior.NO_ADVERTISE, SelectedListenerFailureBehavior.ACCEPT,
                        ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1))
                .build();
    } else {
        sslCtx = null;
    }
    group = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.option(ChannelOption.SO_BACKLOG, 1024);
    b.group(group).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new Http2ServerInitializer(sslCtx));

    b.bind("127.0.0.5", PORT).sync().channel();

}