Java Code Examples for org.eclipse.jetty.util.ssl.SslContextFactory#setTrustStore()

The following examples show how to use org.eclipse.jetty.util.ssl.SslContextFactory#setTrustStore() . 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: RestClient20.java    From java-11-examples with Apache License 2.0 5 votes vote down vote up
public RestClient20(String host, int port, KeyStore keyStore, String keyStorePassword) {
    try {
        this.client = new HTTP2Client();
        this.address = new InetSocketAddress(host, port);
        sslContextFactory = new SslContextFactory();
        sslContextFactory.setTrustStore(keyStore);
        sslContextFactory.setTrustStorePassword(keyStorePassword);
        client.addBean(sslContextFactory);
        client.start();
    } catch (Exception e) {
        LOG.error("Exception: ", e);
    }
}
 
Example 2
Source File: ServerBuilder.java    From java-11-examples with Apache License 2.0 4 votes vote down vote up
public Server build() throws Exception {
    Server server = new Server();

    // Register servlets
    ServletContextHandler context = new ServletContextHandler(server, contextUrn, ServletContextHandler.SESSIONS);
    servletHandlers.forEach((uri, servletHolder) -> { context.addServlet(servletHolder, uri);});
    // Register servlet filters
    filters.forEach((urn, filterHolder) -> { context.addFilter(filterHolder, urn,
            EnumSet.of(DispatcherType.REQUEST)); });
    // Register EventListener instances
    sessionEventListeners.forEach( listener -> { context.getSessionHandler().addEventListener(listener); });

    // Register jersey rest services
    ServletContainer restServletContainer = new ServletContainer(resourceConfig);
    ServletHolder restServletHolder = new ServletHolder(restServletContainer);
    context.addServlet(restServletHolder, restUriPrefix);

    // Register static resources (html pages, images, javascripts, ...)
    String externalResource = this.getClass().getResource(staticResourceBasePath).toExternalForm();
    DefaultServlet defaultServlet = new DefaultServlet();
    ServletHolder holderPwd = new ServletHolder("default", defaultServlet);
    holderPwd.setInitParameter("resourceBase", externalResource);
    context.addServlet(holderPwd, staticResourceBaseUrn);

    server.setHandler(context);

    // HTTP Configuration
    HttpConfiguration httpConfig = new HttpConfiguration();
    httpConfig.setSecureScheme("https");
    httpConfig.setSecurePort(secureHttpPort);
    httpConfig.setSendXPoweredBy(true);
    httpConfig.setSendServerVersion(true);

    // HTTP Connector
    HttpConnectionFactory httpConnectionFactory = new HttpConnectionFactory(httpConfig);
    HTTP2CServerConnectionFactory http2CServerConnectionFactory = new HTTP2CServerConnectionFactory(httpConfig);
    ServerConnector http = new ServerConnector(server, httpConnectionFactory, http2CServerConnectionFactory);
    http.setPort(httpPort);
    server.addConnector(http);

    // SSL Context Factory for HTTPS and HTTP/2
    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setTrustStore(keyStore);
    sslContextFactory.setTrustStorePassword(keyStorePassword);
    sslContextFactory.setKeyStore(keyStore);
    sslContextFactory.setKeyStorePassword(keyStorePassword);
    sslContextFactory.setCipherComparator(HTTP2Cipher.COMPARATOR);

    // HTTPS Configuration
    HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig);
    httpsConfig.addCustomizer(new SecureRequestCustomizer());

    // HTTP/2 Connection Factory
    ServerConnectionFactory h2 = new ServerConnectionFactory(httpsConfig, streamProcessors);

    //NegotiatingServerConnectionFactory.checkProtocolNegotiationAvailable();
    ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory();
    alpn.setDefaultProtocol(http.getDefaultProtocol());

    // SSL Connection Factory
    SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, alpn.getProtocol());

    // HTTP/2 Connector
    ServerConnector http2Connector =
            new ServerConnector(server, ssl, alpn, h2, new HttpConnectionFactory(httpsConfig));
    http2Connector.setPort(secureHttpPort);
    server.addConnector(http2Connector);

    ALPN.debug=false;

    return server;
}
 
Example 3
Source File: HttpsConnectorGenerator.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Create an HTTPS connector for given jetty server instance. If the config has specified keystore/truststore settings
 * they will be used else a self-signed certificate is generated and used.
 *
 * @param hostName      hostname
 * @param config        {@link DremioConfig} containing SSL related settings if any.
 * @param embeddedJetty Jetty server instance needed for creating a ServerConnector.
 * @return Initialized {@link ServerConnector} for HTTPS connections and the trust store. Trust store is non-null only
 * when in case of auto generated self-signed certificate.
 * @throws Exception
 */
public Pair<ServerConnector, KeyStore> createHttpsConnector(
    final Server embeddedJetty,
    final DremioConfig config,
    final String hostName,
    final String... alternativeNames
) throws Exception {
  logger.info("Setting up HTTPS connector for web server");

  final SSLConfigurator configurator = new SSLConfigurator(config, DremioConfig.WEB_SSL_PREFIX, "web");
  final Optional<SSLConfig> sslConfigOption = configurator.getSSLConfig(true, hostName, alternativeNames);
  Preconditions.checkState(sslConfigOption.isPresent()); // caller's responsibility
  final SSLConfig sslConfig = sslConfigOption.get();

  final KeyStore keyStore = KeyStore.getInstance(sslConfig.getKeyStoreType());
  try (InputStream stream = Files.newInputStream(Paths.get(sslConfig.getKeyStorePath()))) {
    keyStore.load(stream, sslConfig.getKeyStorePassword().toCharArray());
  }

  KeyStore trustStore = null;
  //noinspection StringEquality
  if (sslConfig.getTrustStorePath() != SSLConfig.UNSPECIFIED) {
    trustStore = KeyStore.getInstance(sslConfig.getTrustStoreType());
    try (InputStream stream = Files.newInputStream(Paths.get(sslConfig.getTrustStorePath()))) {
      trustStore.load(stream, sslConfig.getTrustStorePassword().toCharArray());
    }
  }

  final SslContextFactory sslContextFactory = new SslContextFactory.Server();
  sslContextFactory.setKeyStore(keyStore);
  sslContextFactory.setKeyManagerPassword(sslConfig.getKeyPassword());
  // TODO(DX-12920): sslContextFactory.setKeyStorePassword(sslConfig.getKeyStorePassword());
  sslContextFactory.setTrustStore(trustStore);

  final String[] enabledCiphers;
  final String customCipherSuite = System.getProperty(DREMIO_SSL_CIPHERSUITE_OVERRIDE);
  if (customCipherSuite != null) {
    logger.info("Using custom cipher list for web server");
    enabledCiphers = Splitter.on(",")
        .trimResults()
        .omitEmptyStrings()
        .splitToList(customCipherSuite)
        .toArray(new String[0]);
    logger.info("Selected cipher list: {}", Arrays.toString(enabledCiphers));
  } else {
    /* By default, only enable the OWASP broad compatibility list of cipher suites, the order listed
     * is the preferred priority of the cipher suites.
     * TLS 1.3 is not supported in JDK 8, but the first three ciphers are still included for future compatibility.
     *
     * See: https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/TLS_Cipher_String_Cheat_Sheet.md
     */
    enabledCiphers = new String[] {
      "TLS_AES_256_GCM_SHA384", // TLS 1.3
      "TLS_CHACHA20_POLY1305_SHA256", // TLS 1.3
      "TLS_AES_128_GCM_SHA256", // TLS 1.3
      "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384",
      "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256",
      "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
      "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
      "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256",
      "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256",
      "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384",
      "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"
    };
  }
  sslContextFactory.setIncludeCipherSuites(enabledCiphers);
  sslContextFactory.setRenegotiationAllowed(false);

  // TODO(DX-12920): sslContextFactory.setValidateCerts(true); to ensure that the server starts up with a valid
  // certificate
  // TODO(DX-12920): sslContextFactory.setValidatePeerCerts(!sslConfig.disableCertificateVerification());

  // this ensures that jersey is aware that we are using https - without this it thinks that every connection is unsecured
  final HttpConfiguration httpConfig = new HttpConfiguration();
  httpConfig.setSecureScheme("https");
  httpConfig.addCustomizer(new SecureRequestCustomizer());

  final ServerConnector sslConnector =
    new ServerConnector(
      embeddedJetty,
      new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
      new HttpConnectionFactory(httpConfig)
    );

  return Pair.of(sslConnector, trustStore);
}
 
Example 4
Source File: WebSocketCommon.java    From datacollector with Apache License 2.0 4 votes vote down vote up
public static WebSocketClient createWebSocketClient(String resourceUrl, TlsConfigBean tlsConf) {
  try {
    resourceUrl = resourceUrl.toLowerCase();
    if (resourceUrl.startsWith("wss")) {
      SslContextFactory sslContextFactory = new SslContextFactory();
      if (tlsConf != null && tlsConf.isEnabled() && tlsConf.isInitialized()) {
        if (tlsConf.getKeyStore() != null) {
          sslContextFactory.setKeyStore(tlsConf.getKeyStore());
        } else {
          if (tlsConf.keyStoreFilePath != null) {
            sslContextFactory.setKeyStorePath(tlsConf.keyStoreFilePath);
          }
          if (tlsConf.keyStoreType != null) {
            sslContextFactory.setKeyStoreType(tlsConf.keyStoreType.getJavaValue());
          }
        }
        if (tlsConf.keyStorePassword != null) {
          sslContextFactory.setKeyStorePassword(tlsConf.keyStorePassword.get());
        }
        if (tlsConf.getTrustStore() != null) {
          sslContextFactory.setTrustStore(tlsConf.getTrustStore());
        } else {
          if (tlsConf.trustStoreFilePath != null) {
            sslContextFactory.setTrustStorePath(tlsConf.trustStoreFilePath);
          }
          if (tlsConf.trustStoreType != null) {
            sslContextFactory.setTrustStoreType(tlsConf.trustStoreType.getJavaValue());
          }
        }
        if (tlsConf.trustStorePassword != null) {
          sslContextFactory.setTrustStorePassword(tlsConf.trustStorePassword.get());
        }

        sslContextFactory.setSslContext(tlsConf.getSslContext());
        sslContextFactory.setIncludeCipherSuites(tlsConf.getFinalCipherSuites());
        sslContextFactory.setIncludeProtocols(tlsConf.getFinalProtocols());
      }
      return new WebSocketClient(sslContextFactory);
    } else {
     return new WebSocketClient();
    }
  } catch (Exception e) {
    throw new IllegalArgumentException(resourceUrl, e);
  }
}
 
Example 5
Source File: HttpdForTests.java    From buck with Apache License 2.0 4 votes vote down vote up
/**
 * Creates an HTTPS server that requires client authentication (though doesn't validate the chain)
 *
 * @param caPath The path to a CA certificate to put in the keystore.
 * @param certificatePath The path to a pem encoded x509 certificate
 * @param keyPath The path to a pem encoded PKCS#8 certificate
 * @throws IOException Any of the keys could not be read
 * @throws KeyStoreException There's a problem writing the key into the keystore
 * @throws CertificateException The certificate was not valid
 * @throws NoSuchAlgorithmException The algorithm used by the certificate/key are invalid
 */
public HttpdForTests(Path caPath, Path certificatePath, Path keyPath)
    throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException {

  // Configure the logging for jetty. Which uses a singleton. Ho hum.
  Log.setLog(new JavaUtilLog());
  server = new Server();

  String password = "super_sekret";

  ImmutableList<X509Certificate> caCerts =
      ClientCertificateHandler.parseCertificates(Optional.of(caPath), true);
  ClientCertificateHandler.CertificateInfo certInfo =
      ClientCertificateHandler.parseCertificateChain(Optional.of(certificatePath), true).get();
  PrivateKey privateKey =
      ClientCertificateHandler.parsePrivateKey(
              Optional.of(keyPath), certInfo.getPrimaryCert(), true)
          .get();

  KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  ks.load(null, password.toCharArray());
  for (int i = 0; i < caCerts.size(); i++) {
    ks.setCertificateEntry(String.format("ca%d", i), caCerts.get(i));
  }
  ks.setKeyEntry(
      "private",
      privateKey,
      password.toCharArray(),
      new Certificate[] {certInfo.getPrimaryCert()});

  SslContextFactory sslFactory = new SslContextFactory();
  sslFactory.setKeyStore(ks);
  sslFactory.setKeyStorePassword(password);
  sslFactory.setCertAlias("private");
  sslFactory.setTrustStore(ks);
  sslFactory.setTrustStorePassword(password);
  // *Require* a client cert, but don't validate it (getting TLS auth working properly was a
  // bit of a pain). We'll store peers' certs in the handler, and validate the certs manually
  // in our tests.
  sslFactory.setNeedClientAuth(true);
  sslFactory.setTrustAll(true);

  HttpConfiguration https_config = new HttpConfiguration();
  https_config.setSecurePort(0);
  https_config.setSecureScheme("https");
  https_config.addCustomizer(new SecureRequestCustomizer());

  ServerConnector sslConnector =
      new ServerConnector(
          server,
          new SslConnectionFactory(sslFactory, HttpVersion.HTTP_1_1.toString()),
          new HttpConnectionFactory(https_config));
  server.addConnector(sslConnector);

  handlerList = new HandlerList();
  localhost = getLocalhostAddress(false).getHostAddress();
}