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());
}
}
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();
}
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());
}
});
}
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());
}
}
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()));
}
Aggregations