io.netty.handler.ssl.ApplicationProtocolConfig Java Examples

The following examples show how to use io.netty.handler.ssl.ApplicationProtocolConfig. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ServerSSLContextManager.java    From cute-proxy with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private SslContext getNettySslContextInner(String host, boolean useH2) throws Exception {
        long start = System.currentTimeMillis();
        PrivateKeyAndCertChain keyAndCertChain = keyStoreGenerator.generateCertChain(host, Settings.certValidityDays);
        logger.debug("Create certificate for {}, cost {} ms", host, System.currentTimeMillis() - start);
        SslContextBuilder builder = SslContextBuilder
                .forServer(keyAndCertChain.privateKey(), keyAndCertChain.certificateChain());
        if (useH2) {
//                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
            builder.applicationProtocolConfig(new ApplicationProtocolConfig(
                    ApplicationProtocolConfig.Protocol.ALPN,
                    SelectorFailureBehavior.NO_ADVERTISE,
                    SelectedListenerFailureBehavior.ACCEPT,
                    ApplicationProtocolNames.HTTP_2,
                    ApplicationProtocolNames.HTTP_1_1));
        }
        return builder.build();
    }
 
Example #2
Source File: NettySubstitutions.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Substitute
static SslContext newClientContextInternal(
        SslProvider provider,
        Provider sslContextProvider,
        X509Certificate[] trustCert, TrustManagerFactory trustManagerFactory,
        X509Certificate[] keyCertChain, PrivateKey key, String keyPassword, KeyManagerFactory keyManagerFactory,
        Iterable<String> ciphers, CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn, String[] protocols,
        long sessionCacheSize, long sessionTimeout, boolean enableOcsp, String keyStoreType) throws SSLException {
    if (enableOcsp) {
        throw new IllegalArgumentException("OCSP is not supported with this SslProvider: " + provider);
    }
    return (SslContext) (Object) new Target_io_netty_handler_ssl_JdkSslClientContext(sslContextProvider,
            trustCert, trustManagerFactory, keyCertChain, key, keyPassword,
            keyManagerFactory, ciphers, cipherFilter, apn, protocols, sessionCacheSize,
            sessionTimeout, keyStoreType);
}
 
Example #3
Source File: NettySubstitutions.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Substitute
static SslContext newServerContextInternal(SslProvider provider,
        Provider sslContextProvider,
        X509Certificate[] trustCertCollection, TrustManagerFactory trustManagerFactory,
        X509Certificate[] keyCertChain, PrivateKey key, String keyPassword, KeyManagerFactory keyManagerFactory,
        Iterable<String> ciphers, CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn,
        long sessionCacheSize, long sessionTimeout, ClientAuth clientAuth, String[] protocols, boolean startTls,
        boolean enableOcsp, String keyStoreType)
        throws SSLException {

    if (enableOcsp) {
        throw new IllegalArgumentException("OCSP is not supported with this SslProvider: " + provider);
    }
    return (SslContext) (Object) new Target_io_netty_handler_ssl_JdkSslServerContext(sslContextProvider,
            trustCertCollection, trustManagerFactory, keyCertChain, key, keyPassword,
            keyManagerFactory, ciphers, cipherFilter, apn, sessionCacheSize, sessionTimeout,
            clientAuth, protocols, startTls, keyStoreType);
}
 
Example #4
Source File: NettyHttp2Client.java    From jmeter-http2-plugin with Apache License 2.0 6 votes vote down vote up
private SslContext getSslContext() {
    SslContext sslCtx = null;

    final SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;

    try {
        sslCtx = SslContextBuilder.forClient()
            .sslProvider(provider)
            .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
            .trustManager(InsecureTrustManagerFactory.INSTANCE)
            .applicationProtocolConfig(new ApplicationProtocolConfig(
                Protocol.ALPN,
                SelectorFailureBehavior.NO_ADVERTISE,
                SelectedListenerFailureBehavior.ACCEPT,
                ApplicationProtocolNames.HTTP_2))
            .build();
    } catch(SSLException exception) {
        return null;
    }

    return sslCtx;
}
 
Example #5
Source File: XConfigTest.java    From xrpc with Apache License 2.0 6 votes vote down vote up
@Test
void buildTlsConfig_shouldUseCorrectTlsConfigValues() {
  TlsConfig tlsConfig =
      XConfig.buildTlsConfig(
          ConfigFactory.parseResources(XConfig.class, "xrpc.conf").getConfig("tls"));

  List<String> defaultSupportedProtocols = tlsConfig.getCiphers();
  assertEquals(6, defaultSupportedProtocols.size());
  for (String protocol : defaultSupportedProtocols) {
    assertTrue(SUPPORTED_PROTOCOLS.contains(protocol));
  }

  ApplicationProtocolConfig applicationProtocolConfig = tlsConfig.getAlpnConfig();
  assertEquals(
      SUPPORTED_PROTOCOLS_IN_PREFERENCE_ORDER, applicationProtocolConfig.supportedProtocols());
  assertEquals(NO_ADVERTISE, applicationProtocolConfig.selectorFailureBehavior());
  assertEquals(ACCEPT, applicationProtocolConfig.selectedListenerFailureBehavior());
  assertEquals(ALPN, applicationProtocolConfig.protocol());
  assertTrue(tlsConfig.isLogInsecureConfig());
  assertTrue(tlsConfig.isUseSsl());
  assertEquals(ClientAuth.OPTIONAL, tlsConfig.getClientAuth());
  assertFalse(tlsConfig.isEnableOcsp());
  assertEquals(0, tlsConfig.getSessionTimeout());
  assertEquals(0, tlsConfig.getSessionCacheSize());
  assertEquals(SslProvider.OPENSSL, tlsConfig.getSslProvider());
}
 
Example #6
Source File: HttpServerSPDY.java    From netty-cookbook with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	String ip = "127.0.0.1";
	int port = 8080;
	// Configure SSL.
	SelfSignedCertificate ssc = new SelfSignedCertificate();
	final SslContext sslCtx = SslContext.newServerContext(
			ssc.certificate(), ssc.privateKey(), null, null,
			IdentityCipherSuiteFilter.INSTANCE,
			new ApplicationProtocolConfig(Protocol.ALPN,
					SelectorFailureBehavior.FATAL_ALERT,
					SelectedListenerFailureBehavior.FATAL_ALERT,
					SelectedProtocol.SPDY_3_1.protocolName(),
					SelectedProtocol.HTTP_1_1.protocolName()), 0, 0);

	ChannelInitializer<SocketChannel> channelInit = new ChannelInitializer<SocketChannel>() {
		@Override
		protected void initChannel(SocketChannel ch) throws Exception {
			ChannelPipeline p = ch.pipeline();
			p.addLast(sslCtx.newHandler(ch.alloc()));				
			p.addLast(new SpdyOrHttpHandler());
		}
	};
	NettyServerUtil.newHttpServerBootstrap(ip, port, channelInit);
}
 
Example #7
Source File: TlsUtil.java    From nitmproxy with MIT License 6 votes vote down vote up
private static ApplicationProtocolConfig applicationProtocolConfig(NitmProxyConfig config, boolean http2) {
    if (http2) {
        return new ApplicationProtocolConfig(
                Protocol.ALPN,
                SelectorFailureBehavior.NO_ADVERTISE,
                SelectedListenerFailureBehavior.ACCEPT,
                ApplicationProtocolNames.HTTP_2,
                ApplicationProtocolNames.HTTP_1_1);
    } else {
        return new ApplicationProtocolConfig(
                Protocol.ALPN,
                SelectorFailureBehavior.NO_ADVERTISE,
                SelectedListenerFailureBehavior.ACCEPT,
                ApplicationProtocolNames.HTTP_1_1);
    }
}
 
Example #8
Source File: SdsSslContextProvider.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private void updateSslContext() {
  try {
    CertificateValidationContext localCertValidationContext = mergeStaticAndDynamicCertContexts();
    SslContextBuilder sslContextBuilder = getSslContextBuilder(localCertValidationContext);
    CommonTlsContext commonTlsContext = getCommonTlsContext();
    if (commonTlsContext != null && commonTlsContext.getAlpnProtocolsCount() > 0) {
      List<String> alpnList = commonTlsContext.getAlpnProtocolsList();
      ApplicationProtocolConfig apn = new ApplicationProtocolConfig(
          ApplicationProtocolConfig.Protocol.ALPN,
          ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
          ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
          alpnList);
      sslContextBuilder.applicationProtocolConfig(apn);
    }
    SslContext sslContextCopy = sslContextBuilder.build();
    sslContext = sslContextCopy;
    makePendingCallbacks(sslContextCopy);
  } catch (CertificateException | IOException | CertStoreException e) {
    logger.log(Level.SEVERE, "exception in updateSslContext", e);
  }
}
 
Example #9
Source File: NettySslHttp2Factory.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * @param config the {@link SSLConfig}
 * @return a configured {@link SslContext} object for a client.
 * @throws GeneralSecurityException
 * @throws IOException
 */
static SslContext getServerSslContext(SSLConfig config) throws GeneralSecurityException, IOException {
  logger.info("Using {} provider for server SslContext", SslContext.defaultServerProvider());
  SslContextBuilder sslContextBuilder;
  if (config.sslHttp2SelfSign) {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    sslContextBuilder = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey());
    logger.info("Using Self Signed Certificate.");
  } else {
    sslContextBuilder = SslContextBuilder.forServer(NettySslFactory.getKeyManagerFactory(config))
        .trustManager(NettySslFactory.getTrustManagerFactory(config));
  }
  return sslContextBuilder.sslProvider(SslContext.defaultClientProvider())
      .clientAuth(NettySslFactory.getClientAuth(config))
      /* 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))
      .build();
}
 
Example #10
Source File: NettySslHttp2Factory.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * @param config the {@link SSLConfig}
 * @return a configured {@link SslContext} object for a server.
 * @throws GeneralSecurityException
 * @throws IOException
 */
public static SslContext getClientSslContext(SSLConfig config) throws GeneralSecurityException, IOException {
  logger.info("Using {} provider for client ", SslContext.defaultClientProvider());
  SslContextBuilder sslContextBuilder;
  if (config.sslHttp2SelfSign) {
    sslContextBuilder = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE);
    logger.info("Using Self Signed Certificate.");
  } else {
    sslContextBuilder = SslContextBuilder.forClient()
        .keyManager(NettySslFactory.getKeyManagerFactory(config))
        .trustManager(NettySslFactory.getTrustManagerFactory(config));
  }
  return sslContextBuilder.sslProvider(SslContext.defaultClientProvider())
      /* 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))
      .build();
}
 
Example #11
Source File: OneWaySSLBase.java    From timely with Apache License 2.0 5 votes vote down vote up
protected SSLSocketFactory getSSLSocketFactory() throws Exception {
    SslContextBuilder builder = SslContextBuilder.forClient();
    builder.applicationProtocolConfig(ApplicationProtocolConfig.DISABLED);
    builder.sslProvider(SslProvider.JDK);
    builder.trustManager(clientTrustStoreFile); // Trust the server cert
    SslContext ctx = builder.build();
    Assert.assertTrue(ctx.isClient());
    Assert.assertTrue(ctx instanceof JdkSslContext);
    JdkSslContext jdk = (JdkSslContext) ctx;
    SSLContext jdkSslContext = jdk.context();
    return jdkSslContext.getSocketFactory();
}
 
Example #12
Source File: TwoWaySSLOpenSSLIT.java    From timely with Apache License 2.0 5 votes vote down vote up
protected SSLSocketFactory getSSLSocketFactory() throws Exception {
    SslContextBuilder builder = SslContextBuilder.forClient();
    builder.applicationProtocolConfig(ApplicationProtocolConfig.DISABLED);
    // Use server cert / key on client side.
    builder.keyManager(serverCert.key(), (String) null, serverCert.cert());
    builder.sslProvider(SslProvider.JDK);
    builder.trustManager(clientTrustStoreFile); // Trust the server cert
    SslContext ctx = builder.build();
    Assert.assertTrue(ctx.isClient());
    Assert.assertTrue(ctx instanceof JdkSslContext);
    JdkSslContext jdk = (JdkSslContext) ctx;
    SSLContext jdkSslContext = jdk.context();
    return jdkSslContext.getSocketFactory();
}
 
Example #13
Source File: SslProvider.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
void updateDefaultConfiguration() {
	switch (type) {
		case H2:
			sslContextBuilder.sslProvider(
			                     io.netty.handler.ssl.SslProvider.isAlpnSupported(io.netty.handler.ssl.SslProvider.OPENSSL) ?
			                             io.netty.handler.ssl.SslProvider.OPENSSL :
			                             io.netty.handler.ssl.SslProvider.JDK)
			                 .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
			                 .applicationProtocolConfig(new ApplicationProtocolConfig(
			                     ApplicationProtocolConfig.Protocol.ALPN,
			                     ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
			                     ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
			                     ApplicationProtocolNames.HTTP_2,
			                     ApplicationProtocolNames.HTTP_1_1));
			break;
		case TCP:
			sslContextBuilder.sslProvider(
			                     OpenSsl.isAvailable() ?
			                             io.netty.handler.ssl.SslProvider.OPENSSL :
			                             io.netty.handler.ssl.SslProvider.JDK)
			                 .ciphers(null, IdentityCipherSuiteFilter.INSTANCE)
			                 .applicationProtocolConfig(null);
			break;
		case NONE:
			break; //no default configuration
	}
}
 
Example #14
Source File: WebSocketClientIT.java    From timely with Apache License 2.0 5 votes vote down vote up
private void setupSslCtx() throws Exception {
    Assert.assertNotNull(clientTrustStoreFile);
    SslContextBuilder builder = SslContextBuilder.forClient();
    builder.applicationProtocolConfig(ApplicationProtocolConfig.DISABLED);
    builder.sslProvider(SslProvider.JDK);
    builder.trustManager(clientTrustStoreFile); // Trust the server cert
    SslContext ctx = builder.build();
    Assert.assertTrue(ctx.isClient());
    Assert.assertTrue(ctx instanceof JdkSslContext);
    JdkSslContext jdk = (JdkSslContext) ctx;
    sslCtx = jdk.context();
}
 
Example #15
Source File: TwoWaySSLIT.java    From timely with Apache License 2.0 5 votes vote down vote up
protected SSLSocketFactory getSSLSocketFactory() throws Exception {
    SslContextBuilder builder = SslContextBuilder.forClient();
    builder.applicationProtocolConfig(ApplicationProtocolConfig.DISABLED);
    // Use server cert / key on client side.
    builder.keyManager(serverCert.key(), (String) null, serverCert.cert());
    builder.sslProvider(SslProvider.JDK);
    builder.trustManager(clientTrustStoreFile); // Trust the server cert
    SslContext ctx = builder.build();
    Assert.assertTrue(ctx.isClient());
    Assert.assertTrue(ctx instanceof JdkSslContext);
    JdkSslContext jdk = (JdkSslContext) ctx;
    SSLContext jdkSslContext = jdk.context();
    return jdkSslContext.getSocketFactory();
}
 
Example #16
Source File: TwoWaySSLFailureIT.java    From timely with Apache License 2.0 5 votes vote down vote up
protected SSLSocketFactory getSSLSocketFactory() throws Exception {
    SslContextBuilder builder = SslContextBuilder.forClient();
    builder.applicationProtocolConfig(ApplicationProtocolConfig.DISABLED);
    // Use server cert / key on client side
    builder.keyManager(serverCert.key(), (String) null, serverCert.cert());
    builder.sslProvider(SslProvider.JDK);
    builder.trustManager(clientTrustStoreFile); // Trust the server cert
    SslContext ctx = builder.build();
    Assert.assertTrue(ctx.isClient());
    Assert.assertTrue(ctx instanceof JdkSslContext);
    JdkSslContext jdk = (JdkSslContext) ctx;
    SSLContext jdkSslContext = jdk.context();
    return jdkSslContext.getSocketFactory();
}
 
Example #17
Source File: TlsConfig.java    From xio with Apache License 2.0 5 votes vote down vote up
private static ApplicationProtocolConfig buildAlpnConfig(Config config) {
  ApplicationProtocolConfig.Protocol protocol =
      config.getEnum(ApplicationProtocolConfig.Protocol.class, "protocol");
  ApplicationProtocolConfig.SelectorFailureBehavior selectorBehavior =
      config.getEnum(ApplicationProtocolConfig.SelectorFailureBehavior.class, "selectorBehavior");
  ApplicationProtocolConfig.SelectedListenerFailureBehavior selectedBehavior =
      config.getEnum(
          ApplicationProtocolConfig.SelectedListenerFailureBehavior.class, "selectedBehavior");
  List<String> supportedProtocols = config.getStringList("supportedProtocols");
  return new ApplicationProtocolConfig(
      protocol, selectorBehavior, selectedBehavior, supportedProtocols);
}
 
Example #18
Source File: SpdyServer.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Configure SSL.
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslCtx = SslContext.newServerContext(
            ssc.certificate(), ssc.privateKey(), null, null, IdentityCipherSuiteFilter.INSTANCE,
            new ApplicationProtocolConfig(
                    Protocol.NPN,
                    SelectorFailureBehavior.FATAL_ALERT,
                    SelectedListenerFailureBehavior.FATAL_ALERT,
                    SelectedProtocol.SPDY_3_1.protocolName(),
                    SelectedProtocol.HTTP_1_1.protocolName()),
            0, 0);

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup)
         .channel(NioServerSocketChannel.class)
         .handler(new LoggingHandler(LogLevel.INFO))
         .childHandler(new SpdyServerInitializer(sslCtx));

        Channel ch = b.bind(PORT).sync().channel();

        System.err.println("Open your SPDY-enabled web browser and navigate to https://127.0.0.1:" + PORT + '/');
        System.err.println("If using Chrome browser, check your SPDY sessions at chrome://net-internals/#spdy");

        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example #19
Source File: ClientSSLContextManager.java    From cute-proxy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static SslContext createNettyClientSSlContext() {
    try {
        return SslContextBuilder.forClient()
                .trustManager(InsecureTrustManagerFactory.INSTANCE)
                .applicationProtocolConfig(new ApplicationProtocolConfig(
                        ApplicationProtocolConfig.Protocol.ALPN,
                        SelectorFailureBehavior.NO_ADVERTISE,
                        SelectedListenerFailureBehavior.ACCEPT,
                        ApplicationProtocolNames.HTTP_2,
                        ApplicationProtocolNames.HTTP_1_1))
                .build();
    } catch (SSLException e) {
        throw new SSLContextException(e);
    }
}
 
Example #20
Source File: VerificationHost_s.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
public static void createAndAttachSSLClient(ServiceHost h) throws Throwable {
    // we create a random userAgent string to validate host to host communication when
    // the client appears to be from an external, non-Xenon source.
    ServiceClient client = NettyHttpServiceClient.create(UUID.randomUUID().toString(),
            null,
            h.getScheduledExecutor(), h);

    if (NettyChannelContext.isALPNEnabled()) {
        SslContext http2ClientContext = SslContextBuilder.forClient()
                .trustManager(InsecureTrustManagerFactory.INSTANCE)
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .applicationProtocolConfig(new ApplicationProtocolConfig(
                        ApplicationProtocolConfig.Protocol.ALPN,
                        ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                        ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
                        ApplicationProtocolNames.HTTP_2))
                .build();
        ((NettyHttpServiceClient) client).setHttp2SslContext(http2ClientContext);
    }

    SSLContext clientContext = SSLContext.getInstance(ServiceClient.TLS_PROTOCOL_NAME);
    clientContext.init(null, InsecureTrustManagerFactory.INSTANCE.getTrustManagers(), null);
    client.setSSLContext(clientContext);
    h.setClient(client);

    SelfSignedCertificate ssc = new SelfSignedCertificate();
    h.setCertificateFileReference(ssc.certificate().toURI());
    h.setPrivateKeyFileReference(ssc.privateKey().toURI());
}
 
Example #21
Source File: VerificationHost_t.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
public static void createAndAttachSSLClient(ServiceHost h) throws Throwable {
    // we create a random userAgent string to validate host to host communication when
    // the client appears to be from an external, non-Xenon source.
    ServiceClient client = NettyHttpServiceClient.create(UUID.randomUUID().toString(),
            null,
            h.getScheduledExecutor(), h);

    if (NettyChannelContext.isALPNEnabled()) {
        SslContext http2ClientContext = SslContextBuilder.forClient()
                .trustManager(InsecureTrustManagerFactory.INSTANCE)
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .applicationProtocolConfig(new ApplicationProtocolConfig(
                        ApplicationProtocolConfig.Protocol.ALPN,
                        ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                        ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
                        ApplicationProtocolNames.HTTP_2))
                .build();
        ((NettyHttpServiceClient) client).setHttp2SslContext(http2ClientContext);
    }

    SSLContext clientContext = SSLContext.getInstance(ServiceClient.TLS_PROTOCOL_NAME);
    clientContext.init(null, InsecureTrustManagerFactory.INSTANCE.getTrustManagers(), null);
    client.setSSLContext(clientContext);
    h.setClient(client);

    SelfSignedCertificate ssc = new SelfSignedCertificate();
    h.setCertificateFileReference(ssc.certificate().toURI());
    h.setPrivateKeyFileReference(ssc.privateKey().toURI());
}
 
Example #22
Source File: GrpcSslContexts.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/**
 * Set ciphers and APN appropriate for gRPC. Precisely what is set is permitted to change, so if
 * an application requires particular settings it should override the options set here.
 */
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/1784")
@CanIgnoreReturnValue
public static SslContextBuilder configure(SslContextBuilder builder, SslProvider provider) {
  switch (provider) {
    case JDK:
    {
      Provider jdkProvider = findJdkProvider();
      if (jdkProvider == null) {
        throw new IllegalArgumentException(
            "Could not find Jetty NPN/ALPN or Conscrypt as installed JDK providers");
      }
      return configure(builder, jdkProvider);
    }
    case OPENSSL:
    {
      ApplicationProtocolConfig apc;
      if (OpenSsl.isAlpnSupported()) {
        apc = NPN_AND_ALPN;
      } else {
        apc = NPN;
      }
      return builder
          .sslProvider(SslProvider.OPENSSL)
          .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
          .applicationProtocolConfig(apc);
    }
    default:
      throw new IllegalArgumentException("Unsupported provider: " + provider);
  }
}
 
Example #23
Source File: GrpcSslContexts.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/**
 * Set ciphers and APN appropriate for gRPC. Precisely what is set is permitted to change, so if
 * an application requires particular settings it should override the options set here.
 */
@CanIgnoreReturnValue
public static SslContextBuilder configure(SslContextBuilder builder, Provider jdkProvider) {
  ApplicationProtocolConfig apc;
  if (SUN_PROVIDER_NAME.equals(jdkProvider.getName())) {
    // Jetty ALPN/NPN only supports one of NPN or ALPN
    if (JettyTlsUtil.isJettyAlpnConfigured()) {
      apc = ALPN;
    } else if (JettyTlsUtil.isJettyNpnConfigured()) {
      apc = NPN;
    } else if (JettyTlsUtil.isJava9AlpnAvailable()) {
      apc = ALPN;
    } else {
      throw new IllegalArgumentException(
          SUN_PROVIDER_NAME + " selected, but Java 9+ and Jetty NPN/ALPN unavailable");
    }
  } else if (ConscryptLoader.isConscrypt(jdkProvider)) {
    apc = ALPN;
  } else {
    throw new IllegalArgumentException("Unknown provider; can't configure: " + jdkProvider);
  }
  return builder
      .sslProvider(SslProvider.JDK)
      .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
      .applicationProtocolConfig(apc)
      .sslContextProvider(jdkProvider);
}
 
Example #24
Source File: ProtocolNegotiatorsTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void serverTlsHandler_userEventTriggeredSslEvent_supportedProtocolCustom()
    throws Exception {
  SslHandler goodSslHandler = new SslHandler(engine, false) {
    @Override
    public String applicationProtocol() {
      return "managed_mtls";
    }
  };

  File serverCert = TestUtils.loadCert("server1.pem");
  File key = TestUtils.loadCert("server1.key");
  List<String> alpnList = Arrays.asList("managed_mtls", "h2");
  ApplicationProtocolConfig apn = new ApplicationProtocolConfig(
      ApplicationProtocolConfig.Protocol.ALPN,
      ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
      ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
      alpnList);

  sslContext = GrpcSslContexts.forServer(serverCert, key)
      .ciphers(TestUtils.preferredTestCiphers(), SupportedCipherSuiteFilter.INSTANCE)
      .applicationProtocolConfig(apn).build();

  ChannelHandler handler = new ServerTlsHandler(grpcHandler, sslContext, null);
  pipeline.addLast(handler);

  pipeline.replace(SslHandler.class, null, goodSslHandler);
  channelHandlerCtx = pipeline.context(handler);
  Object sslEvent = SslHandshakeCompletionEvent.SUCCESS;

  pipeline.fireUserEventTriggered(sslEvent);

  assertTrue(channel.isOpen());
  ChannelHandlerContext grpcHandlerCtx = pipeline.context(grpcHandler);
  assertNotNull(grpcHandlerCtx);
}
 
Example #25
Source File: ProtocolNegotiatorsTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void clientTlsHandler_userEventTriggeredSslEvent_supportedProtocolCustom()
    throws Exception {
  SslHandler goodSslHandler = new SslHandler(engine, false) {
    @Override
    public String applicationProtocol() {
      return "managed_mtls";
    }
  };
  DefaultEventLoopGroup elg = new DefaultEventLoopGroup(1);

  File clientCert = TestUtils.loadCert("client.pem");
  File key = TestUtils.loadCert("client.key");
  List<String> alpnList = Arrays.asList("managed_mtls", "h2");
  ApplicationProtocolConfig apn = new ApplicationProtocolConfig(
      ApplicationProtocolConfig.Protocol.ALPN,
      ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
      ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
      alpnList);

  sslContext = GrpcSslContexts.forClient()
      .keyManager(clientCert, key)
      .ciphers(TestUtils.preferredTestCiphers(), SupportedCipherSuiteFilter.INSTANCE)
      .applicationProtocolConfig(apn).build();

  ClientTlsHandler handler = new ClientTlsHandler(grpcHandler, sslContext, "authority", elg);
  pipeline.addLast(handler);
  pipeline.replace(SslHandler.class, null, goodSslHandler);
  pipeline.fireUserEventTriggered(ProtocolNegotiationEvent.DEFAULT);
  channelHandlerCtx = pipeline.context(handler);
  Object sslEvent = SslHandshakeCompletionEvent.SUCCESS;

  pipeline.fireUserEventTriggered(sslEvent);

  ChannelHandlerContext grpcHandlerCtx = pipeline.context(grpcHandler);
  assertNotNull(grpcHandlerCtx);
}
 
Example #26
Source File: Http2Util.java    From tutorials with MIT License 5 votes vote down vote up
public static SslContext createSSLContext(boolean isServer) throws SSLException, CertificateException {

        SslContext sslCtx;

        SelfSignedCertificate ssc = new SelfSignedCertificate();

        if (isServer) {
            sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey())
                .sslProvider(SslProvider.JDK)
                .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 = SslContextBuilder.forClient()
                .sslProvider(SslProvider.JDK)
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .trustManager(InsecureTrustManagerFactory.INSTANCE)
                .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN,
                    SelectorFailureBehavior.NO_ADVERTISE,
                    SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2))
                .build();
        }
        return sslCtx;

    }
 
Example #27
Source File: Http2Configuration.java    From zuul with Apache License 2.0 5 votes vote down vote up
public static SslContext configureSSL(SslContextFactory sslContextFactory, String metricId) {
    SslContextBuilder builder = sslContextFactory.createBuilderForServer();

    String[] supportedProtocol;
    if (HTTP2_DISABLED.get()) {
        supportedProtocol = new String[]{ApplicationProtocolNames.HTTP_1_1};
    }
    else {
        supportedProtocol = new String[]{ApplicationProtocolNames.HTTP_2,
                ApplicationProtocolNames.HTTP_1_1};
    }

    ApplicationProtocolConfig apn = 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,
            supportedProtocol);

    final SslContext sslContext;
    try {
        sslContext = builder
                .applicationProtocolConfig(apn)
                .build();
    }
    catch (SSLException e) {
        throw new RuntimeException("Error configuring SslContext with ALPN!", e);
    }

    // Enable TLS Session Tickets support.
    sslContextFactory.enableSessionTickets(sslContext);

    // Setup metrics tracking the OpenSSL stats.
    sslContextFactory.configureOpenSslStatsMetrics(sslContext, metricId);

    return sslContext;
}
 
Example #28
Source File: SslUtils.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
/**
 * Create netty's {@link ApplicationProtocolConfig}.
 *
 * @param supportedAlpnProtocols the list of supported ALPN protocols.
 * @return the new {@link ApplicationProtocolConfig}.
 */
static ApplicationProtocolConfig nettyApplicationProtocol(List<String> supportedAlpnProtocols) {
    if (supportedAlpnProtocols.isEmpty()) {
        return ApplicationProtocolConfig.DISABLED;
    }
    return new ApplicationProtocolConfig(ALPN, NO_ADVERTISE, ACCEPT, supportedAlpnProtocols);
}
 
Example #29
Source File: GrpcSslContexts.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
/**
 * Set ciphers and APN appropriate for gRPC. Precisely what is set is permitted to change, so if
 * an application requires particular settings it should override the options set here.
 */
@CanIgnoreReturnValue
public static SslContextBuilder configure(SslContextBuilder builder, Provider jdkProvider) {
  ApplicationProtocolConfig apc;
  if (SUN_PROVIDER_NAME.equals(jdkProvider.getName())) {
    // Jetty ALPN/NPN only supports one of NPN or ALPN
    if (JettyTlsUtil.isJettyAlpnConfigured()) {
      apc = ALPN;
    } else if (JettyTlsUtil.isJettyNpnConfigured()) {
      apc = NPN;
    } else if (JettyTlsUtil.isJava9AlpnAvailable()) {
      apc = ALPN;
    } else {
      throw new IllegalArgumentException(
          SUN_PROVIDER_NAME + " selected, but Jetty NPN/ALPN unavailable");
    }
  } else if (isConscrypt(jdkProvider)) {
    apc = ALPN;
  } else {
    throw new IllegalArgumentException("Unknown provider; can't configure: " + jdkProvider);
  }
  return builder
      .sslProvider(SslProvider.JDK)
      .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
      .applicationProtocolConfig(apc)
      .sslContextProvider(jdkProvider);
}
 
Example #30
Source File: DefaultOpenDistroSecurityKeyStore.java    From deprecated-security-ssl with Apache License 2.0 5 votes vote down vote up
private SslContext buildSSLServerContext(final PrivateKey _key, final X509Certificate[] _cert,
        final X509Certificate[] _trustedCerts, final Iterable<String> ciphers, final SslProvider sslProvider,
        final ClientAuth authMode) throws SSLException {

    final SslContextBuilder _sslContextBuilder = SslContextBuilder.forServer(_key, _cert).ciphers(ciphers)
            .applicationProtocolConfig(ApplicationProtocolConfig.DISABLED)
            .clientAuth(Objects.requireNonNull(authMode)) // https://github.com/netty/netty/issues/4722
            .sessionCacheSize(0).sessionTimeout(0).sslProvider(sslProvider);

    if (_trustedCerts != null && _trustedCerts.length > 0) {
        _sslContextBuilder.trustManager(_trustedCerts);
    }

    return buildSSLContext0(_sslContextBuilder);
}