List of usage examples for io.netty.handler.ssl SslContextBuilder trustManager
public SslContextBuilder trustManager(TrustManager trustManager)
From source file:io.viewserver.network.netty.tcp.NettyTcpEndpoint.java
License:Apache License
@Override public IClient getClient(EventLoopGroup eventLoopGroup, ChannelHandler handler) { SslContext sslContext;//from www . ja v a 2 s . c o m if (this.uri.getScheme().equals("tcps")) { try { SslContextBuilder builder = SslContextBuilder.forClient(); if (bypassCertificateChecks || usingSelfSignedCertificate) { builder.trustManager(InsecureTrustManagerFactory.INSTANCE); } sslContext = builder.build(); } catch (SSLException e) { throw new RuntimeException(e); } } else { sslContext = null; } Bootstrap bootstrap = new Bootstrap(); bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (sslContext != null) { pipeline.addLast(sslContext.newHandler(ch.alloc(), uri.getHost(), uri.getPort())); } pipeline.addLast(handler); } }); return () -> bootstrap.connect(uri.getHost(), uri.getPort()); }
From source file:io.viewserver.network.netty.websocket.NettyWebSocketEndpoint.java
License:Apache License
@Override public IClient getClient(EventLoopGroup eventLoopGroup, ChannelHandler handler) { SslContext sslContext;//from w ww .ja va2 s. c om if (this.uri.getScheme().equals("wss")) { try { SslContextBuilder builder = SslContextBuilder.forClient(); if (bypassCertificateChecks || usingSelfSignedCertificate) { builder.trustManager(InsecureTrustManagerFactory.INSTANCE); } sslContext = builder.build(); } catch (SSLException e) { throw new RuntimeException(e); } } else { sslContext = null; } Bootstrap bootstrap = new Bootstrap(); WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders()); bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (sslContext != null) { pipeline.addLast(sslContext.newHandler(ch.alloc(), uri.getHost(), uri.getPort())); } pipeline.addLast(new HttpClientCodec()); pipeline.addLast(new HttpObjectAggregator(1 << 30)); pipeline.addLast("websocket", new WebSocketClientProtocolHandler(handshaker)); pipeline.addLast(new ChannelInboundHandlerAdapter() { @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt == WebSocketClientProtocolHandler.ClientHandshakeStateEvent.HANDSHAKE_COMPLETE) { ChannelPipeline pipeline = ctx.channel().pipeline(); pipeline.addAfter("websocket", "ws-decoder-xx", new MessageToMessageDecoder<BinaryWebSocketFrame>() { @Override protected void decode(ChannelHandlerContext ctx, BinaryWebSocketFrame msg, List<Object> out) throws Exception { out.add(msg.content().retain()); } }); pipeline.addAfter("websocket", "ws-encoder-xx", new MessageToMessageEncoder<ByteBuf>() { @Override protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception { out.add(new BinaryWebSocketFrame(msg).retain()); } }); } super.userEventTriggered(ctx, evt); } }); pipeline.addLast("frameDecoder", new ChannelInboundHandlerAdapter()); pipeline.addLast("frameEncoder", new ChannelOutboundHandlerAdapter()); pipeline.addLast(handler); } }); return () -> bootstrap.connect(uri.getHost(), uri.getPort()); }
From source file:io.vitess.client.grpc.GrpcClientFactory.java
License:Apache License
/** * <p>Factory method to construct a gRPC client connection with transport-layer security.</p> * * <p>Within the <code>tlsOptions</code> parameter value, the <code>trustStore</code> field * should/* w ww . j a v a2 s . com*/ * always be populated. All other fields are optional.</p> * * @param ctx TODO: This parameter is not actually used, but probably SHOULD be so that * timeout duration and caller ID settings aren't discarded * @param target target is passed to NettyChannelBuilder which will resolve based on scheme, * by default dns. */ @Override public RpcClient createTls(Context ctx, String target, TlsOptions tlsOptions) { final SslContextBuilder sslContextBuilder = GrpcSslContexts.forClient(); // trustManager should always be set final KeyStore trustStore = loadKeyStore(tlsOptions.getTrustStore(), tlsOptions.getTrustStorePassword()); if (trustStore == null) { throw new RuntimeException("Could not load trustStore"); } final X509Certificate[] trustCertCollection = tlsOptions.getTrustAlias() == null ? loadCertCollection(trustStore) : loadCertCollectionForAlias(trustStore, tlsOptions.getTrustAlias()); sslContextBuilder.trustManager(trustCertCollection); // keyManager should only be set if a keyStore is specified (meaning that client authentication // is enabled) final KeyStore keyStore = loadKeyStore(tlsOptions.getKeyStore(), tlsOptions.getKeyStorePassword()); if (keyStore != null) { final PrivateKeyWrapper privateKeyWrapper = tlsOptions.getKeyAlias() == null ? loadPrivateKeyEntry(keyStore, tlsOptions.getKeyStorePassword(), tlsOptions.getKeyPassword()) : loadPrivateKeyEntryForAlias(keyStore, tlsOptions.getKeyAlias(), tlsOptions.getKeyStorePassword(), tlsOptions.getKeyPassword()); if (privateKeyWrapper == null) { throw new RuntimeException("Could not retrieve private key and certificate chain from keyStore"); } sslContextBuilder.keyManager(privateKeyWrapper.getPrivateKey(), privateKeyWrapper.getPassword(), privateKeyWrapper.getCertificateChain()); } final SslContext sslContext; try { sslContext = sslContextBuilder.build(); } catch (SSLException exc) { throw new RuntimeException(exc); } ClientInterceptor[] interceptors = getClientInterceptors(); return new GrpcClient(channelBuilder(target).negotiationType(NegotiationType.TLS).sslContext(sslContext) .intercept(interceptors).build(), ctx); }
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 */// www . j a v a 2s . c om 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 . j a v a 2 s .com*/ 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: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 ww w. j a va2s . c om*/ 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 w w . j a va2 s .co m*/ 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 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"); }//ww w . j a v a 2s. 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.//from w ww . j a va 2 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); }
From source file:org.apache.nifi.processors.grpc.ListenGRPC.java
License:Apache License
@OnScheduled public void startServer(final ProcessContext context) throws NoSuchAlgorithmException, IOException, KeyStoreException, CertificateException, UnrecoverableKeyException { final ComponentLog logger = getLogger(); // gather configured properties final Integer port = context.getProperty(PROP_SERVICE_PORT).asInteger(); final Boolean useSecure = context.getProperty(PROP_USE_SECURE).asBoolean(); final Integer flowControlWindow = context.getProperty(PROP_FLOW_CONTROL_WINDOW).asDataSize(DataUnit.B) .intValue();//from w w w. jav a 2s .c om final Integer maxMessageSize = context.getProperty(PROP_MAX_MESSAGE_SIZE).asDataSize(DataUnit.B).intValue(); final SSLContextService sslContextService = context.getProperty(PROP_SSL_CONTEXT_SERVICE) .asControllerService(SSLContextService.class); final SSLContext sslContext = sslContextService == null ? null : sslContextService.createSSLContext(SSLContextService.ClientAuth.NONE); final Pattern authorizedDnPattern = Pattern .compile(context.getProperty(PROP_AUTHORIZED_DN_PATTERN).getValue()); final FlowFileIngestServiceInterceptor callInterceptor = new FlowFileIngestServiceInterceptor(getLogger()); callInterceptor.enforceDNPattern(authorizedDnPattern); final FlowFileIngestService flowFileIngestService = new FlowFileIngestService(getLogger(), sessionFactoryReference, context); NettyServerBuilder serverBuilder = NettyServerBuilder.forPort(port) .addService(ServerInterceptors.intercept(flowFileIngestService, callInterceptor)) // default (de)compressor registries handle both plaintext and gzip compressed messages .compressorRegistry(CompressorRegistry.getDefaultInstance()) .decompressorRegistry(DecompressorRegistry.getDefaultInstance()) .flowControlWindow(flowControlWindow).maxMessageSize(maxMessageSize); if (useSecure && sslContext != null) { // construct key manager if (StringUtils.isBlank(sslContextService.getKeyStoreFile())) { throw new IllegalStateException( "SSL is enabled, but no keystore has been configured. You must configure a keystore."); } 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 sslContextBuilder = SslContextBuilder.forServer(keyManagerFactory); // if the trust store is configured, then client auth is required. 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 = sslContextBuilder.trustManager(trustManagerFactory); sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.REQUIRE); } else { sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.NONE); } sslContextBuilder = GrpcSslContexts.configure(sslContextBuilder); serverBuilder = serverBuilder.sslContext(sslContextBuilder.build()); } logger.info("Starting gRPC server on port: {}", new Object[] { port.toString() }); this.server = serverBuilder.build().start(); }