Search in sources :

Example 86 with SslContext

use of io.netty.handler.ssl.SslContext in project grpc-java by grpc.

the class ProtocolNegotiators method from.

public static FromServerCredentialsResult from(ServerCredentials creds) {
    if (creds instanceof TlsServerCredentials) {
        TlsServerCredentials tlsCreds = (TlsServerCredentials) creds;
        Set<TlsServerCredentials.Feature> incomprehensible = tlsCreds.incomprehensible(understoodServerTlsFeatures);
        if (!incomprehensible.isEmpty()) {
            return FromServerCredentialsResult.error("TLS features not understood: " + incomprehensible);
        }
        SslContextBuilder builder;
        if (tlsCreds.getKeyManagers() != null) {
            builder = GrpcSslContexts.configure(SslContextBuilder.forServer(new FixedKeyManagerFactory(tlsCreds.getKeyManagers())));
        } else if (tlsCreds.getPrivateKey() != null) {
            builder = GrpcSslContexts.forServer(new ByteArrayInputStream(tlsCreds.getCertificateChain()), new ByteArrayInputStream(tlsCreds.getPrivateKey()), tlsCreds.getPrivateKeyPassword());
        } else {
            throw new AssertionError("BUG! No key");
        }
        if (tlsCreds.getTrustManagers() != null) {
            builder.trustManager(new FixedTrustManagerFactory(tlsCreds.getTrustManagers()));
        } else if (tlsCreds.getRootCertificates() != null) {
            builder.trustManager(new ByteArrayInputStream(tlsCreds.getRootCertificates()));
        }
        // else use system default
        switch(tlsCreds.getClientAuth()) {
            case OPTIONAL:
                builder.clientAuth(io.netty.handler.ssl.ClientAuth.OPTIONAL);
                break;
            case REQUIRE:
                builder.clientAuth(io.netty.handler.ssl.ClientAuth.REQUIRE);
                break;
            case NONE:
                builder.clientAuth(io.netty.handler.ssl.ClientAuth.NONE);
                break;
            default:
                return FromServerCredentialsResult.error("Unknown TlsServerCredentials.ClientAuth value: " + tlsCreds.getClientAuth());
        }
        SslContext sslContext;
        try {
            sslContext = builder.build();
        } catch (SSLException ex) {
            throw new IllegalArgumentException("Unexpected error converting ServerCredentials to Netty SslContext", ex);
        }
        return FromServerCredentialsResult.negotiator(serverTlsFactory(sslContext));
    } else if (creds instanceof InsecureServerCredentials) {
        return FromServerCredentialsResult.negotiator(serverPlaintextFactory());
    } else if (creds instanceof NettyServerCredentials) {
        NettyServerCredentials nettyCreds = (NettyServerCredentials) creds;
        return FromServerCredentialsResult.negotiator(nettyCreds.getNegotiator());
    } else if (creds instanceof ChoiceServerCredentials) {
        ChoiceServerCredentials choiceCreds = (ChoiceServerCredentials) creds;
        StringBuilder error = new StringBuilder();
        for (ServerCredentials innerCreds : choiceCreds.getCredentialsList()) {
            FromServerCredentialsResult result = from(innerCreds);
            if (result.error == null) {
                return result;
            }
            error.append(", ");
            error.append(result.error);
        }
        return FromServerCredentialsResult.error(error.substring(2));
    } else {
        return FromServerCredentialsResult.error("Unsupported credential type: " + creds.getClass().getName());
    }
}
Also used : ChoiceServerCredentials(io.grpc.ChoiceServerCredentials) ServerCredentials(io.grpc.ServerCredentials) InsecureServerCredentials(io.grpc.InsecureServerCredentials) TlsServerCredentials(io.grpc.TlsServerCredentials) ChoiceServerCredentials(io.grpc.ChoiceServerCredentials) SSLException(javax.net.ssl.SSLException) ByteArrayInputStream(java.io.ByteArrayInputStream) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) InsecureServerCredentials(io.grpc.InsecureServerCredentials) TlsServerCredentials(io.grpc.TlsServerCredentials) SslContext(io.netty.handler.ssl.SslContext)

Example 87 with SslContext

use of io.netty.handler.ssl.SslContext in project grpc-java by grpc.

the class SdsProtocolNegotiatorsTest method serverSdsHandler_addLast.

@Test
public void serverSdsHandler_addLast() throws InterruptedException, TimeoutException, ExecutionException {
    FakeClock executor = new FakeClock();
    CommonCertProviderTestUtils.register(executor);
    // we need InetSocketAddress instead of EmbeddedSocketAddress as localAddress for this test
    channel = new EmbeddedChannel() {

        @Override
        public SocketAddress localAddress() {
            return new InetSocketAddress("172.168.1.1", 80);
        }

        @Override
        public SocketAddress remoteAddress() {
            return new InetSocketAddress("172.168.2.2", 90);
        }
    };
    pipeline = channel.pipeline();
    Bootstrapper.BootstrapInfo bootstrapInfoForServer = CommonBootstrapperTestUtils.buildBootstrapInfo("google_cloud_private_spiffe-server", SERVER_1_KEY_FILE, SERVER_1_PEM_FILE, CA_PEM_FILE, null, null, null, null);
    DownstreamTlsContext downstreamTlsContext = CommonTlsContextTestsUtil.buildDownstreamTlsContext("google_cloud_private_spiffe-server", true, true);
    TlsContextManagerImpl tlsContextManager = new TlsContextManagerImpl(bootstrapInfoForServer);
    SdsProtocolNegotiators.HandlerPickerHandler handlerPickerHandler = new SdsProtocolNegotiators.HandlerPickerHandler(grpcHandler, InternalProtocolNegotiators.serverPlaintext());
    pipeline.addLast(handlerPickerHandler);
    channelHandlerCtx = pipeline.context(handlerPickerHandler);
    // should find HandlerPickerHandler
    assertThat(channelHandlerCtx).isNotNull();
    // kick off protocol negotiation: should replace HandlerPickerHandler with ServerSdsHandler
    ProtocolNegotiationEvent event = InternalProtocolNegotiationEvent.getDefault();
    Attributes attr = InternalProtocolNegotiationEvent.getAttributes(event).toBuilder().set(ATTR_SERVER_SSL_CONTEXT_PROVIDER_SUPPLIER, new SslContextProviderSupplier(downstreamTlsContext, tlsContextManager)).build();
    pipeline.fireUserEventTriggered(InternalProtocolNegotiationEvent.withAttributes(event, attr));
    channelHandlerCtx = pipeline.context(handlerPickerHandler);
    assertThat(channelHandlerCtx).isNull();
    channelHandlerCtx = pipeline.context(SdsProtocolNegotiators.ServerSdsHandler.class);
    assertThat(channelHandlerCtx).isNotNull();
    SslContextProviderSupplier sslContextProviderSupplier = new SslContextProviderSupplier(downstreamTlsContext, tlsContextManager);
    final SettableFuture<Object> future = SettableFuture.create();
    sslContextProviderSupplier.updateSslContext(new SslContextProvider.Callback(MoreExecutors.directExecutor()) {

        @Override
        public void updateSecret(SslContext sslContext) {
            future.set(sslContext);
        }

        @Override
        protected void onException(Throwable throwable) {
            future.set(throwable);
        }
    });
    // need this for tasks to execute on eventLoop
    channel.runPendingTasks();
    assertThat(executor.runDueTasks()).isEqualTo(1);
    Object fromFuture = future.get(2, TimeUnit.SECONDS);
    assertThat(fromFuture).isInstanceOf(SslContext.class);
    channel.runPendingTasks();
    channelHandlerCtx = pipeline.context(SdsProtocolNegotiators.ServerSdsHandler.class);
    assertThat(channelHandlerCtx).isNull();
    // pipeline should only have SslHandler and ServerTlsHandler
    Iterator<Map.Entry<String, ChannelHandler>> iterator = pipeline.iterator();
    assertThat(iterator.next().getValue()).isInstanceOf(SslHandler.class);
    // ProtocolNegotiators.ServerTlsHandler.class is not accessible, get canonical name
    assertThat(iterator.next().getValue().getClass().getCanonicalName()).contains("ProtocolNegotiators.ServerTlsHandler");
    CommonCertProviderTestUtils.register0();
}
Also used : ProtocolNegotiationEvent(io.grpc.netty.ProtocolNegotiationEvent) InternalProtocolNegotiationEvent(io.grpc.netty.InternalProtocolNegotiationEvent) FakeClock(io.grpc.internal.FakeClock) InetSocketAddress(java.net.InetSocketAddress) DownstreamTlsContext(io.grpc.xds.EnvoyServerProtoData.DownstreamTlsContext) Attributes(io.grpc.Attributes) InternalXdsAttributes(io.grpc.xds.InternalXdsAttributes) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Bootstrapper(io.grpc.xds.Bootstrapper) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) SslContext(io.netty.handler.ssl.SslContext) Test(org.junit.Test)

Example 88 with SslContext

use of io.netty.handler.ssl.SslContext in project Glowstone by GlowstoneMC.

the class HttpClient method connect.

/**
 * Opens a URL.
 *
 * @param url       the URL to download
 * @param eventLoop an {@link EventLoop} that will receive the response body
 * @param callback  a callback to handle the response or any error
 */
public void connect(String url, EventLoop eventLoop, HttpCallback callback) {
    URI uri = URI.create(url);
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    int port = uri.getPort();
    SslContext sslCtx = null;
    if ("https".equalsIgnoreCase(scheme)) {
        if (port == -1) {
            port = 443;
        }
        try {
            sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
        } catch (SSLException e) {
            callback.error(e);
            return;
        }
    } else if ("http".equalsIgnoreCase(scheme)) {
        if (port == -1) {
            port = 80;
        }
    } else {
        throw new IllegalArgumentException("Only http(s) is supported!");
    }
    new Bootstrap().group(eventLoop).resolver(resolverGroup).channel(Networking.bestSocketChannel()).handler(new HttpChannelInitializer(sslCtx, callback)).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000).connect(InetSocketAddress.createUnresolved(host, port)).addListener((ChannelFutureListener) future -> {
        if (future.isSuccess()) {
            String path = uri.getRawPath() + (uri.getRawQuery() == null ? "" : "?" + uri.getRawQuery());
            HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path);
            request.headers().set(HttpHeaderNames.HOST, host);
            future.channel().writeAndFlush(request);
        } else {
            callback.error(future.cause());
        }
    });
}
Also used : HttpVersion(io.netty.handler.codec.http.HttpVersion) ChannelOption(io.netty.channel.ChannelOption) DnsServerAddressStreamProvider(io.netty.resolver.dns.DnsServerAddressStreamProvider) SequentialDnsServerAddressStreamProvider(io.netty.resolver.dns.SequentialDnsServerAddressStreamProvider) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) ChannelFutureListener(io.netty.channel.ChannelFutureListener) SocketUtils(io.netty.util.internal.SocketUtils) URI(java.net.URI) HttpRequest(io.netty.handler.codec.http.HttpRequest) ChannelInitializer(io.netty.channel.ChannelInitializer) SslContext(io.netty.handler.ssl.SslContext) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler) HttpMethod(io.netty.handler.codec.http.HttpMethod) EventLoop(io.netty.channel.EventLoop) DnsServerAddressStreamProviders(io.netty.resolver.dns.DnsServerAddressStreamProviders) InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) TimeUnit(java.util.concurrent.TimeUnit) Bootstrap(io.netty.bootstrap.Bootstrap) Networking(net.glowstone.net.Networking) SSLException(javax.net.ssl.SSLException) List(java.util.List) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) DnsEndpoint(net.glowstone.net.config.DnsEndpoint) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) AllArgsConstructor(lombok.AllArgsConstructor) DnsAddressResolverGroup(io.netty.resolver.dns.DnsAddressResolverGroup) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) Bootstrap(io.netty.bootstrap.Bootstrap) URI(java.net.URI) SSLException(javax.net.ssl.SSLException) DnsEndpoint(net.glowstone.net.config.DnsEndpoint) SslContext(io.netty.handler.ssl.SslContext)

Example 89 with SslContext

use of io.netty.handler.ssl.SslContext in project vert.x by eclipse.

the class SSLHelperTest method testOpenSslServerSessionContext.

private void testOpenSslServerSessionContext(boolean testDefault) {
    HttpServerOptions httpServerOptions = new HttpServerOptions().setOpenSslEngineOptions(new OpenSSLEngineOptions());
    if (!testDefault) {
        httpServerOptions.setOpenSslEngineOptions(new OpenSSLEngineOptions().setSessionCacheEnabled(false));
    }
    SSLHelper defaultHelper = new SSLHelper(httpServerOptions, Cert.SERVER_PEM.get(), Trust.SERVER_PEM.get());
    SslContext ctx = defaultHelper.getContext((VertxInternal) vertx);
    assertTrue(ctx instanceof OpenSslServerContext);
    SSLSessionContext sslSessionContext = ctx.sessionContext();
    assertTrue(sslSessionContext instanceof OpenSslServerSessionContext);
    if (sslSessionContext instanceof OpenSslServerSessionContext) {
        assertEquals(testDefault, ((OpenSslServerSessionContext) sslSessionContext).isSessionCacheEnabled());
    }
}
Also used : SSLHelper(io.vertx.core.net.impl.SSLHelper) SSLSessionContext(javax.net.ssl.SSLSessionContext) OpenSslServerContext(io.netty.handler.ssl.OpenSslServerContext) HttpServerOptions(io.vertx.core.http.HttpServerOptions) OpenSslServerSessionContext(io.netty.handler.ssl.OpenSslServerSessionContext) SslContext(io.netty.handler.ssl.SslContext)

Example 90 with SslContext

use of io.netty.handler.ssl.SslContext in project vert.x by eclipse.

the class SSLHelperTest method testUseJdkCiphersWhenNotSpecified.

@Test
public void testUseJdkCiphersWhenNotSpecified() throws Exception {
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, null, null);
    SSLEngine engine = context.createSSLEngine();
    String[] expected = engine.getEnabledCipherSuites();
    SSLHelper helper = new SSLHelper(new HttpClientOptions(), Cert.CLIENT_JKS.get(), Trust.SERVER_JKS.get());
    SslContext ctx = helper.getContext((VertxInternal) vertx);
    assertEquals(new HashSet<>(Arrays.asList(expected)), new HashSet<>(ctx.cipherSuites()));
}
Also used : SSLHelper(io.vertx.core.net.impl.SSLHelper) SSLEngine(javax.net.ssl.SSLEngine) SSLContext(javax.net.ssl.SSLContext) HttpClientOptions(io.vertx.core.http.HttpClientOptions) SslContext(io.netty.handler.ssl.SslContext) Test(org.junit.Test)

Aggregations

SslContext (io.netty.handler.ssl.SslContext)200 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)63 EventLoopGroup (io.netty.channel.EventLoopGroup)52 SelfSignedCertificate (io.netty.handler.ssl.util.SelfSignedCertificate)50 Test (org.junit.Test)48 Channel (io.netty.channel.Channel)43 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)41 SSLException (javax.net.ssl.SSLException)40 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)36 Bootstrap (io.netty.bootstrap.Bootstrap)35 LoggingHandler (io.netty.handler.logging.LoggingHandler)35 SocketChannel (io.netty.channel.socket.SocketChannel)34 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)33 SslHandler (io.netty.handler.ssl.SslHandler)26 SslContextBuilder (io.netty.handler.ssl.SslContextBuilder)25 ChannelPipeline (io.netty.channel.ChannelPipeline)23 InetSocketAddress (java.net.InetSocketAddress)23 ChannelFuture (io.netty.channel.ChannelFuture)21 File (java.io.File)21 CertificateException (java.security.cert.CertificateException)20