Java Code Examples for io.netty.handler.ssl.SslContextBuilder#build()

The following examples show how to use io.netty.handler.ssl.SslContextBuilder#build() . 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: SslSimpleBuilder.java    From jlogstash-input-plugin with Apache License 2.0 6 votes vote down vote up
public SslHandler build(ByteBufAllocator bufferAllocator) throws SSLException {
    SslContextBuilder builder = SslContextBuilder.forServer(sslCertificateFile, sslKeyFile, passPhrase);

    builder.ciphers(Arrays.asList(ciphers));

    if(requireClientAuth()) {
        logger.debug("Certificate Authorities: " + certificateAuthorities);
        builder.trustManager(new File(certificateAuthorities));
    }

    SslContext context = builder.build();
    SslHandler sslHandler = context.newHandler(bufferAllocator);

    SSLEngine engine = sslHandler.engine();
    engine.setEnabledProtocols(protocols);


    if(requireClientAuth()) {
        engine.setUseClientMode(false);
        engine.setNeedClientAuth(true);
    }

    return sslHandler;
}
 
Example 2
Source File: SslUtil.java    From Dream-Catcher with MIT License 6 votes vote down vote up
/**
 * Creates a netty SslContext for use when connecting to upstream servers. Retrieves the list of trusted root CAs
 * from the trustSource. When trustSource is true, no upstream certificate verification will be performed.
 * <b>This will make it possible for attackers to MITM communications with the upstream server</b>, so always
 * supply an appropriate trustSource except in extraordinary circumstances (e.g. testing with dynamically-generated
 * certificates).
 *
 * @param cipherSuites    cipher suites to allow when connecting to the upstream server
 * @param trustSource     the trust store that will be used to validate upstream servers' certificates, or null to accept all upstream server certificates
 * @return an SSLContext to connect to upstream servers with
 */
public static SslContext getUpstreamServerSslContext(Collection<String> cipherSuites, TrustSource trustSource) {
    SslContextBuilder sslContextBuilder = SslContextBuilder.forClient();

    if (trustSource == null) {
        log.warn("Disabling upstream server certificate verification. This will allow attackers to intercept communications with upstream servers.");

        sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslContextBuilder.trustManager(trustSource.getTrustedCAs());
    }

    sslContextBuilder.ciphers(cipherSuites, SupportedCipherSuiteFilter.INSTANCE);

    try {
        return sslContextBuilder.build();
    } catch (SSLException e) {
        throw new SslContextInitializationException("Error creating new SSL context for connection to upstream server", e);
    }
}
 
Example 3
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 4
Source File: SslUtil.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@NotNull
public SslContext createSslServerContext(@NotNull final KeyManagerFactory kmf, @Nullable final TrustManagerFactory tmFactory, @Nullable final List<String> cipherSuites, @Nullable final List<String> protocols) throws SSLException {

    final SslContextBuilder sslContextBuilder = SslContextBuilder.forServer(kmf);

    sslContextBuilder.sslProvider(SslProvider.JDK).trustManager(tmFactory);

    if (protocols != null && !protocols.isEmpty()) {
        sslContextBuilder.protocols(protocols.toArray(new String[0]));
    }

    //set chosen cipher suites if available
    if (cipherSuites != null && cipherSuites.size() > 0) {
        sslContextBuilder.ciphers(cipherSuites, SupportedCipherSuiteFilter.INSTANCE);
    } else {
        sslContextBuilder.ciphers(null, SupportedCipherSuiteFilter.INSTANCE);
    }
    return sslContextBuilder.build();
}
 
Example 5
Source File: SslUtil.java    From browserup-proxy with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a netty SslContext for use when connecting to upstream servers. Retrieves the list of trusted root CAs
 * from the trustSource. When trustSource is true, no upstream certificate verification will be performed.
 * <b>This will make it possible for attackers to MITM communications with the upstream server</b>, so always
 * supply an appropriate trustSource except in extraordinary circumstances (e.g. testing with dynamically-generated
 * certificates).
 *
 * @param cipherSuites    cipher suites to allow when connecting to the upstream server
 * @param trustSource     the trust store that will be used to validate upstream servers' certificates, or null to accept all upstream server certificates
 * @return an SSLContext to connect to upstream servers with
 */
public static SslContext getUpstreamServerSslContext(Collection<String> cipherSuites, TrustSource trustSource) {
    SslContextBuilder sslContextBuilder = SslContextBuilder.forClient();

    if (trustSource == null) {
        log.warn("Disabling upstream server certificate verification. This will allow attackers to intercept communications with upstream servers.");

        sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslContextBuilder.trustManager(trustSource.getTrustedCAs());
    }

    sslContextBuilder.ciphers(cipherSuites, SupportedCipherSuiteFilter.INSTANCE);

    try {
        return sslContextBuilder.build();
    } catch (SSLException e) {
        throw new SslContextInitializationException("Error creating new SSL context for connection to upstream server", e);
    }
}
 
Example 6
Source File: RPCBootstrap.java    From WeCross with Apache License 2.0 6 votes vote down vote up
/**
 * init SslContext for http server
 *
 * @param caCrt
 * @param nodeCrt
 * @param nodeKey
 * @return
 * @throws IOException
 */
public SslContext initSslContextForServer(
        org.springframework.core.io.Resource caCrt,
        org.springframework.core.io.Resource nodeCrt,
        org.springframework.core.io.Resource nodeKey,
        int sslSwitch)
        throws IOException {

    SslContextBuilder sslContextBuilder =
            SslContextBuilder.forServer(nodeCrt.getInputStream(), nodeKey.getInputStream())
                    .trustManager(caCrt.getInputStream())
                    .sslProvider(SslProvider.JDK);

    if (sslSwitch == RPCConfig.SSLSwitch.SSL_ON_CLIENT_AUTH.getSwh()) {
        logger.info(" clientAuth ");
        sslContextBuilder.clientAuth(ClientAuth.REQUIRE);
    }

    return sslContextBuilder.build();
}
 
Example 7
Source File: SecretVolumeServerSslContextProvider.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
SslContext buildSslContextFromSecrets()
    throws IOException, CertificateException, CertStoreException {
  SslContextBuilder sslContextBuilder =
      GrpcSslContexts.forServer(
          new File(certificateChain), new File(privateKey), privateKeyPassword);
  setClientAuthValues(sslContextBuilder, certContext);
  return sslContextBuilder.build();
}
 
Example 8
Source File: Server.java    From timely with Apache License 2.0 5 votes vote down vote up
protected SslContext createSSLContext(Configuration config) throws Exception {

        ServerSsl sslCfg = config.getSecurity().getServerSsl();
        Boolean generate = sslCfg.isUseGeneratedKeypair();
        SslContextBuilder ssl;
        if (generate) {
            LOG.warn("Using generated self signed server certificate");
            Date begin = new Date();
            Date end = new Date(begin.getTime() + TimeUnit.DAYS.toMillis(7));
            SelfSignedCertificate ssc = new SelfSignedCertificate("localhost", begin, end);
            ssl = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey());
        } else {
            String cert = sslCfg.getCertificateFile();
            String key = sslCfg.getKeyFile();
            String keyPass = sslCfg.getKeyPassword();
            if (null == cert || null == key) {
                throw new IllegalArgumentException("Check your SSL properties, something is wrong.");
            }
            ssl = SslContextBuilder.forServer(new File(cert), new File(key), keyPass);
        }

        ssl.ciphers(sslCfg.getUseCiphers());

        // Can't set to REQUIRE because the CORS pre-flight requests will fail.
        ssl.clientAuth(ClientAuth.OPTIONAL);

        Boolean useOpenSSL = sslCfg.isUseOpenssl();
        if (useOpenSSL) {
            ssl.sslProvider(SslProvider.OPENSSL);
        } else {
            ssl.sslProvider(SslProvider.JDK);
        }
        String trustStore = sslCfg.getTrustStoreFile();
        if (null != trustStore) {
            if (!trustStore.isEmpty()) {
                ssl.trustManager(new File(trustStore));
            }
        }
        return ssl.build();
    }
 
Example 9
Source File: WebSocketClientIT.java    From qonduit 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());
    JdkSslContext jdk = (JdkSslContext) ctx;
    sslCtx = jdk.context();
}
 
Example 10
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 11
Source File: SslContextFactory.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
/**
 * A new context for a client using the passed {@code config}.
 *
 * @param config SSL config.
 * @param supportedAlpnProtocols the list of supported ALPN protocols.
 * @return A new {@link SslContext} for a client.
 */
public static SslContext forClient(ReadOnlyClientSecurityConfig config, List<String> supportedAlpnProtocols) {
    requireNonNull(config);
    SslContextBuilder builder = SslContextBuilder.forClient()
            .sessionCacheSize(config.sessionCacheSize()).sessionTimeout(config.sessionTimeout());
    configureTrustManager(config, builder);
    KeyManagerFactory keyManagerFactory = config.keyManagerFactory();
    if (keyManagerFactory != null) {
        builder.keyManager(keyManagerFactory);
    } else {
        InputStream keyCertChainSupplier = null;
        InputStream keySupplier = null;
        try {
            keyCertChainSupplier = config.keyCertChainSupplier().get();
            keySupplier = config.keySupplier().get();
            builder.keyManager(keyCertChainSupplier, keySupplier, config.keyPassword());
        } finally {
            try {
                closeAndRethrowUnchecked(keyCertChainSupplier);
            } finally {
                closeAndRethrowUnchecked(keySupplier);
            }
        }
    }
    builder.sslProvider(toNettySslProvider(config.provider(), !supportedAlpnProtocols.isEmpty()));

    builder.protocols(config.protocols());
    builder.ciphers(config.ciphers());
    builder.applicationProtocolConfig(nettyApplicationProtocol(supportedAlpnProtocols));
    try {
        return builder.build();
    } catch (SSLException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example 12
Source File: SecurityUtility.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public static SslContext createNettySslContextForServer(boolean allowInsecureConnection, String trustCertsFilePath,
        String certFilePath, String keyFilePath, Set<String> ciphers, Set<String> protocols,
        boolean requireTrustedClientCertOnConnect)
        throws GeneralSecurityException, SSLException, FileNotFoundException, IOException {
    X509Certificate[] certificates = loadCertificatesFromPemFile(certFilePath);
    PrivateKey privateKey = loadPrivateKeyFromPemFile(keyFilePath);

    SslContextBuilder builder = SslContextBuilder.forServer(privateKey, (X509Certificate[]) certificates);
    setupCiphers(builder, ciphers);
    setupProtocols(builder, protocols);
    setupTrustCerts(builder, allowInsecureConnection, trustCertsFilePath);
    setupKeyManager(builder, privateKey, certificates);
    setupClientAuthentication(builder, requireTrustedClientCertOnConnect);
    return builder.build();
}
 
Example 13
Source File: Ssl.java    From zbus-server with MIT License 5 votes vote down vote up
public static SslContext buildServerSsl(InputStream certStream, InputStream privateKeyStream) { 
	try {
		SslContextBuilder builder = SslContextBuilder.forServer(certStream, privateKeyStream);
		return builder.build(); 
	} catch (Exception e) {
		throw new IllegalArgumentException(e.getMessage(), e);
	}
}
 
Example 14
Source File: TwoWaySSLOpenSSLIT.java    From qonduit 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());
    JdkSslContext jdk = (JdkSslContext) ctx;
    SSLContext jdkSslContext = jdk.context();
    return jdkSslContext.getSocketFactory();
}
 
Example 15
Source File: Ssl.java    From zbus-server with MIT License 5 votes vote down vote up
public static SslContext buildClientSsl(InputStream certStream){
	try { 
		SslContextBuilder builder = SslContextBuilder.forClient().trustManager(certStream);
		return builder.build();
	} catch (Exception e) { 
		throw new IllegalArgumentException(e.getMessage(), e);
	}
}
 
Example 16
Source File: SecretVolumeClientSslContextProvider.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
SslContext buildSslContextFromSecrets()
    throws IOException, CertificateException, CertStoreException {
  SslContextBuilder sslContextBuilder =
      GrpcSslContexts.forClient().trustManager(new SdsTrustManagerFactory(certContext));
  if (privateKey != null && certificateChain != null) {
    sslContextBuilder.keyManager(
        new File(certificateChain), new File(privateKey), privateKeyPassword);
  }
  return sslContextBuilder.build();
}
 
Example 17
Source File: HelloWorldTlsServiceTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void init() throws SSLException {
    SslContextBuilder builder = GrpcSslContexts.forClient();
    builder.trustManager(new File("src/main/resources/tls/ca.pem"));
    SslContext context = builder.build();

    channel = NettyChannelBuilder.forAddress("localhost", 9000)
            .sslContext(context)
            .build();
}
 
Example 18
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 19
Source File: BridgeServerTlsContextImpl.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@Inject
public BridgeServerTlsContextImpl(BridgeServerConfig serverConfig, BridgeServerTrustManagerFactory trustManagerFactory) {
   this.useTls = serverConfig.isTlsServer();
   if (!this.useTls) {
      logger.info("BridgeServerTlsContext is disabled.");
      this.context = null;
      return;
   }

   try {
      SslContextBuilder serverContext = null;

      if (serverConfig.getTlsServerCertificateFilepath().length() != 0) {
         logger.debug("assuming use of PEM formatted certificate/key instead of keystore");
         serverContext = getSslContextFromPemFiles(
                 serverConfig.getTlsServerCertificateFilepath(),
                 serverConfig.getTlsServerPrivateKeyFilepath())
                 .sslProvider(createSslProvider(serverConfig));
      } else { // old default
         KeyManagerFactory kmf = createKeyManagerFactory(serverConfig);
         serverContext = SslContextBuilder.forServer(kmf)
                 .sslProvider(createSslProvider(serverConfig));
      }

      if (serverConfig.getTlsSessionCacheSize() > 0) {
         serverContext.sessionCacheSize(serverConfig.getTlsSessionCacheSize());
      }

      if (serverConfig.getTlsSessionTimeout() > 0) {
         serverContext.sessionTimeout(serverConfig.getTlsSessionTimeout());
      }

      if (serverConfig.isTlsNeedClientAuth()) {
         serverContext.clientAuth(ClientAuth.REQUIRE);
      } else if (serverConfig.isTlsRequestClientAuth()) {
         serverContext.clientAuth(ClientAuth.OPTIONAL);
      } else {
         serverContext.clientAuth(ClientAuth.NONE);
      }

      if (serverConfig.isTlsNeedClientAuth() || serverConfig.isTlsRequestClientAuth()) {
         TrustManagerFactory tmf = trustManagerFactory.getTrustManagerFactory();
         if (tmf != null) {
            serverContext.trustManager(tmf);
         }
      }

      context = serverContext.build();
   } catch (Exception ex) {
      logger.error("Failed to initialize the server-size SSLContext", ex);
      throw new IllegalStateException("Failed to initialize the server-side SSLContext", ex);
   }
}
 
Example 20
Source File: Channels.java    From quarkus with Apache License 2.0 4 votes vote down vote up
public static Channel createChannel(String name) throws SSLException {
    InstanceHandle<GrpcClientConfigProvider> instance = Arc.container().instance(GrpcClientConfigProvider.class);

    if (!instance.isAvailable()) {
        throw new IllegalStateException("Unable to find the GrpcClientConfigProvider");
    }

    GrpcClientConfiguration config = instance.get().getConfiguration(name);
    String host = config.host;
    int port = config.port;
    boolean plainText = !config.ssl.trustStore.isPresent();
    Optional<Boolean> usePlainText = config.plainText;
    if (usePlainText.isPresent()) {
        plainText = usePlainText.get();
    }

    SslContext context = null;
    if (!plainText) {
        Path trustStorePath = config.ssl.trustStore.orElse(null);
        Path certificatePath = config.ssl.certificate.orElse(null);
        Path keyPath = config.ssl.key.orElse(null);
        SslContextBuilder sslContextBuilder = GrpcSslContexts.forClient();
        if (trustStorePath != null) {
            sslContextBuilder.trustManager(trustStorePath.toFile());
        }

        if (certificatePath != null && keyPath != null) {
            sslContextBuilder.keyManager(certificatePath.toFile(), keyPath.toFile());
        }

        context = sslContextBuilder.build();
    }

    NettyChannelBuilder builder = NettyChannelBuilder.forAddress(host, port)
            .flowControlWindow(config.flowControlWindow.orElse(DEFAULT_FLOW_CONTROL_WINDOW))
            .keepAliveWithoutCalls(config.keepAliveWithoutCalls)
            .maxHedgedAttempts(config.maxHedgedAttempts)
            .maxRetryAttempts(config.maxRetryAttempts)
            .maxInboundMetadataSize(config.maxInboundMessageSize.orElse(DEFAULT_MAX_HEADER_LIST_SIZE))
            .maxInboundMetadataSize(config.maxInboundMessageSize.orElse(DEFAULT_MAX_MESSAGE_SIZE))
            .negotiationType(NegotiationType.valueOf(config.negotiationType.toUpperCase()));

    if (config.retry) {
        builder.enableRetry();
    } else {
        builder.disableRetry();
    }

    if (config.maxTraceEvents.isPresent()) {
        builder.maxTraceEvents(config.maxTraceEvents.getAsInt());
    }
    Optional<String> userAgent = config.userAgent;
    if (userAgent.isPresent()) {
        builder.userAgent(userAgent.get());
    }
    if (config.retryBufferSize.isPresent()) {
        builder.retryBufferSize(config.retryBufferSize.getAsLong());
    }
    if (config.perRpcBufferLimit.isPresent()) {
        builder.perRpcBufferLimit(config.perRpcBufferLimit.getAsLong());
    }
    Optional<String> overrideAuthority = config.overrideAuthority;
    if (overrideAuthority.isPresent()) {
        builder.overrideAuthority(overrideAuthority.get());
    }
    Optional<Duration> keepAliveTime = config.keepAliveTime;
    if (keepAliveTime.isPresent()) {
        builder.keepAliveTime(keepAliveTime.get().toMillis(), TimeUnit.MILLISECONDS);
    }
    Optional<Duration> keepAliveTimeout = config.keepAliveTimeout;
    if (keepAliveTimeout.isPresent()) {
        builder.keepAliveTimeout(keepAliveTimeout.get().toMillis(), TimeUnit.MILLISECONDS);
    }
    Optional<Duration> idleTimeout = config.idleTimeout;
    if (idleTimeout.isPresent()) {
        builder.keepAliveTimeout(idleTimeout.get().toMillis(), TimeUnit.MILLISECONDS);
    }

    if (plainText) {
        builder.usePlaintext();
    }
    if (context != null) {
        builder.sslContext(context);
    }

    // Client-side interceptors
    Instance<ClientInterceptor> interceptors = Arc.container().beanManager().createInstance()
            .select(ClientInterceptor.class);
    for (ClientInterceptor clientInterceptor : getSortedInterceptors(interceptors)) {
        builder.intercept(clientInterceptor);
    }

    return builder.build();
}