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

The following examples show how to use org.eclipse.jetty.util.ssl.SslContextFactory#setKeyStore() . 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: TlsCertificateAuthorityService.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private static Server createServer(Handler handler, int port, KeyStore keyStore, String keyPassword) throws Exception {
    Server server = new Server();

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setIncludeProtocols("TLSv1.2");
    sslContextFactory.setKeyStore(keyStore);
    sslContextFactory.setKeyManagerPassword(keyPassword);

    HttpConfiguration httpsConfig = new HttpConfiguration();
    httpsConfig.addCustomizer(new SecureRequestCustomizer());

    ServerConnector sslConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(httpsConfig));
    sslConnector.setPort(port);

    server.addConnector(sslConnector);
    server.setHandler(handler);

    return server;
}
 
Example 2
Source File: C2Properties.java    From nifi-minifi with Apache License 2.0 6 votes vote down vote up
public SslContextFactory getSslContextFactory() throws GeneralSecurityException, IOException {
    SslContextFactory sslContextFactory = new SslContextFactory();
    KeyStore keyStore = KeyStore.getInstance(properties.getProperty(MINIFI_C2_SERVER_KEYSTORE_TYPE));
    Path keyStorePath = Paths.get(C2_SERVER_HOME).resolve(properties.getProperty(MINIFI_C2_SERVER_KEYSTORE)).toAbsolutePath();
    logger.debug("keystore path: " + keyStorePath);
    try (InputStream inputStream = Files.newInputStream(keyStorePath)) {
        keyStore.load(inputStream, properties.getProperty(MINIFI_C2_SERVER_KEYSTORE_PASSWD).toCharArray());
    }
    sslContextFactory.setKeyStore(keyStore);
    sslContextFactory.setKeyManagerPassword(properties.getProperty(MINIFI_C2_SERVER_KEY_PASSWD));
    sslContextFactory.setWantClientAuth(true);

    String trustStorePath = Paths.get(C2_SERVER_HOME).resolve(properties.getProperty(MINIFI_C2_SERVER_TRUSTSTORE)).toAbsolutePath().toFile().getAbsolutePath();
    logger.debug("truststore path: " + trustStorePath);
    sslContextFactory.setTrustStorePath(trustStorePath);
    sslContextFactory.setTrustStoreType(properties.getProperty(MINIFI_C2_SERVER_TRUSTSTORE_TYPE));
    sslContextFactory.setTrustStorePassword(properties.getProperty(MINIFI_C2_SERVER_TRUSTSTORE_PASSWD));
    try {
        sslContextFactory.start();
    } catch (Exception e) {
        throw new IOException(e);
    }
    return sslContextFactory;
}
 
Example 3
Source File: TlsCertificateAuthorityService.java    From nifi with Apache License 2.0 6 votes vote down vote up
private static Server createServer(Handler handler, int port, KeyStore keyStore, String keyPassword) throws Exception {
    Server server = new Server();

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setIncludeProtocols(CertificateUtils.getHighestCurrentSupportedTlsProtocolVersion());
    sslContextFactory.setKeyStore(keyStore);
    sslContextFactory.setKeyManagerPassword(keyPassword);

    // Need to set SslContextFactory's endpointIdentificationAlgorithm to null; this is a server,
    // not a client.  Server does not need to perform hostname verification on the client.
    // Previous to Jetty 9.4.15.v20190215, this defaulted to null, and now defaults to "HTTPS".
    sslContextFactory.setEndpointIdentificationAlgorithm(null);

    HttpConfiguration httpsConfig = new HttpConfiguration();
    httpsConfig.addCustomizer(new SecureRequestCustomizer());

    ServerConnector sslConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(httpsConfig));
    sslConnector.setPort(port);

    server.addConnector(sslConnector);
    server.setHandler(handler);

    return server;
}
 
Example 4
Source File: ForceUtils.java    From datacollector with Apache License 2.0 5 votes vote down vote up
public static SslContextFactory makeSslContextFactory(ForceConfigBean conf) throws StageException {
  SslContextFactory sslContextFactory = new SslContextFactory();
  if (conf.mutualAuth.useMutualAuth) {
    sslContextFactory.setKeyStore(conf.mutualAuth.getUnderlyingConfig().getKeyStore());
    // Need to set password in the SSLContextFactory even though it's set in the KeyStore
    sslContextFactory.setKeyStorePassword(conf.mutualAuth.getUnderlyingConfig().keyStorePassword.get());
  }
  return sslContextFactory;
}
 
Example 5
Source File: WebServer.java    From Bats with Apache License 2.0 4 votes vote down vote up
/**
 * Create an HTTPS connector for given jetty server instance. If the admin has specified keystore/truststore settings
 * they will be used else a self-signed certificate is generated and used.
 *
 * @return Initialized {@link ServerConnector} for HTTPS connections.
 */
private ServerConnector createHttpsConnector(int port, int acceptors, int selectors) throws Exception {
  logger.info("Setting up HTTPS connector for web server");

  final SslContextFactory sslContextFactory = new SslContextFactory();
  SSLConfig ssl = new SSLConfigBuilder()
      .config(config)
      .mode(SSLConfig.Mode.SERVER)
      .initializeSSLContext(false)
      .validateKeyStore(true)
      .build();
  if(ssl.isSslValid()){
    logger.info("Using configured SSL settings for web server");

    sslContextFactory.setKeyStorePath(ssl.getKeyStorePath());
    sslContextFactory.setKeyStorePassword(ssl.getKeyStorePassword());
    sslContextFactory.setKeyManagerPassword(ssl.getKeyPassword());
    if(ssl.hasTrustStorePath()){
      sslContextFactory.setTrustStorePath(ssl.getTrustStorePath());
      if(ssl.hasTrustStorePassword()){
        sslContextFactory.setTrustStorePassword(ssl.getTrustStorePassword());
      }
    }
  } else {
    logger.info("Using generated self-signed SSL settings for web server");
    final SecureRandom random = new SecureRandom();

    // Generate a private-public key pair
    final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(1024, random);
    final KeyPair keyPair = keyPairGenerator.generateKeyPair();

    final DateTime now = DateTime.now();

    // Create builder for certificate attributes
    final X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE)
        .addRDN(BCStyle.OU, "Apache Drill (auth-generated)")
        .addRDN(BCStyle.O, "Apache Software Foundation (auto-generated)")
        .addRDN(BCStyle.CN, workManager.getContext().getEndpoint().getAddress());

    final Date notBefore = now.minusMinutes(1).toDate();
    final Date notAfter = now.plusYears(5).toDate();
    final BigInteger serialNumber = new BigInteger(128, random);

    // Create a certificate valid for 5years from now.
    final X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(
        nameBuilder.build(), // attributes
        serialNumber,
        notBefore,
        notAfter,
        nameBuilder.build(),
        keyPair.getPublic());

    // Sign the certificate using the private key
    final ContentSigner contentSigner =
        new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(keyPair.getPrivate());
    final X509Certificate certificate =
        new JcaX509CertificateConverter().getCertificate(certificateBuilder.build(contentSigner));

    // Check the validity
    certificate.checkValidity(now.toDate());

    // Make sure the certificate is self-signed.
    certificate.verify(certificate.getPublicKey());

    // Generate a random password for keystore protection
    final String keyStorePasswd = RandomStringUtils.random(20);
    final KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(null, null);
    keyStore.setKeyEntry("DrillAutoGeneratedCert", keyPair.getPrivate(),
        keyStorePasswd.toCharArray(), new java.security.cert.Certificate[]{certificate});

    sslContextFactory.setKeyStore(keyStore);
    sslContextFactory.setKeyStorePassword(keyStorePasswd);
  }

  final HttpConfiguration httpsConfig = new HttpConfiguration();
  httpsConfig.addCustomizer(new SecureRequestCustomizer());

  // SSL Connector
  final ServerConnector sslConnector = new ServerConnector(embeddedJetty,
      null, null, null, acceptors, selectors,
      new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
      new HttpConnectionFactory(httpsConfig));
  sslConnector.setPort(port);

  return sslConnector;
}
 
Example 6
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 7
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 8
Source File: Main.java    From passopolis-server with GNU General Public License v3.0 4 votes vote down vote up
/** Creates a Jetty server listening on HTTP and HTTPS, serving handlers. */
public static Server createJetty(Handler handler)
    throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
  final Server server = new Server();
  server.setHandler(handler);

  HttpConfiguration httpConfig = new HttpConfiguration();
  // Parses X-Forwarded-For headers for Servlet.getRemoteAddr()
  httpConfig.addCustomizer(new ForwardedRequestCustomizer());

  final ServerConnector connector = new ServerConnector(
      server,
      new HttpConnectionFactory(httpConfig)
  );
  server.addConnector(connector);

  connector.setPort(HTTP_PORT);

  // Enable SSL on port 8443 using the debug keystore
  KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
  InputStream keyStream = Main.class.getResourceAsStream("debug_keystore.jks");
  keyStore.load(keyStream, null);
  keyStream.close();

  SslContextFactory ssl = new SslContextFactory();
  ssl.setKeyStore(keyStore);
  ssl.setKeyStorePassword("password");
  SslConnectionFactory sslFactory = new SslConnectionFactory(ssl, "http/1.1");
  // SecureRequestCustomizer is required to correctly set scheme to https
  HttpConfiguration httpsConfig = new HttpConfiguration();
  httpsConfig.addCustomizer(new SecureRequestCustomizer());
  httpsConfig.addCustomizer(new ForwardedRequestCustomizer());
  ConnectionFactory httpsFactory = new HttpConnectionFactory(httpsConfig);

  ServerConnector sslConnector = new ServerConnector(server, sslFactory, httpsFactory);
  sslConnector.setPort(HTTPS_PORT);
  server.addConnector(sslConnector);

  registerShutdownHook(server);
  return server;
}
 
Example 9
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 10
Source File: BrooklynWebServer.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
private SslContextFactory createContextFactory() throws KeyStoreException {
    SslContextFactory sslContextFactory = new SslContextFactory();

    // allow webconsole keystore & related properties to be set in brooklyn.properties
    String ksUrl = getKeystoreUrl();
    String ksPassword = getConfig(keystorePassword, BrooklynWebConfig.KEYSTORE_PASSWORD);
    String ksCertAlias = getConfig(keystoreCertAlias, BrooklynWebConfig.KEYSTORE_CERTIFICATE_ALIAS);
    String trProtos = getConfig(transportProtocols, BrooklynWebConfig.TRANSPORT_PROTOCOLS);
    String trCiphers = getConfig(transportCiphers, BrooklynWebConfig.TRANSPORT_CIPHERS);
    
    if (ksUrl!=null) {
        sslContextFactory.setKeyStorePath(getLocalKeyStorePath(ksUrl));
        if (Strings.isEmpty(ksPassword))
            throw new IllegalArgumentException("Keystore password is required and non-empty if keystore is specified.");
        sslContextFactory.setKeyStorePassword(ksPassword);
        if (Strings.isNonEmpty(ksCertAlias))
            sslContextFactory.setCertAlias(ksCertAlias);
    } else {
        log.info("No keystore specified but https enabled; creating a default keystore");
        
        if (Strings.isEmpty(ksCertAlias))
            ksCertAlias = "web-console";
        
        // if password is blank the process will block and read from stdin !
        if (Strings.isEmpty(ksPassword)) {
            ksPassword = Identifiers.makeRandomId(8);
            log.debug("created random password "+ksPassword+" for ad hoc internal keystore");
        }
        
        KeyStore ks = SecureKeys.newKeyStore();
        KeyPair key = SecureKeys.newKeyPair();
        X509Certificate cert = new FluentKeySigner("brooklyn").newCertificateFor("web-console", key);
        ks.setKeyEntry(ksCertAlias, key.getPrivate(), ksPassword.toCharArray(),
            new Certificate[] { cert });
        
        sslContextFactory.setKeyStore(ks);
        sslContextFactory.setKeyStorePassword(ksPassword);
        sslContextFactory.setCertAlias(ksCertAlias);
    }
    if (!Strings.isEmpty(truststorePath)) {
        sslContextFactory.setTrustStorePath(checkFileExists(truststorePath, "truststore"));
        sslContextFactory.setTrustStorePassword(trustStorePassword);
    }

    if (Strings.isNonBlank(trProtos)) {
        sslContextFactory.setIncludeProtocols(parseArray(trProtos));
    }
    if (Strings.isNonBlank(trCiphers)) {
        sslContextFactory.setIncludeCipherSuites(parseArray(trCiphers));
    }
    return sslContextFactory;
}
 
Example 11
Source File: HttpService.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public HttpService start() throws Exception {
    TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), ROOT_WAR_PATH);

    try {
        if (httpsEnabled) {
            //by default the server is configured with a http connector, this needs to be removed since we are going
            //to provide https
            for (Connector c: server.getConnectors()) {
                server.removeConnector(c);
            }

            InputStream keyStoreStream = ResourceUtils.create(this).getResourceFromUrl(SERVER_KEYSTORE);
            KeyStore keyStore;
            try {
                keyStore = SecureKeys.newKeyStore(keyStoreStream, "password");
            } finally {
                keyStoreStream.close();
            }

            // manually create like seen in XMLs at http://www.eclipse.org/jetty/documentation/current/configuring-ssl.html
            SslContextFactory sslContextFactory = new SslContextFactory();
            sslContextFactory.setKeyStore(keyStore);
            sslContextFactory.setTrustAll(true);
            sslContextFactory.setKeyStorePassword("password");

            HttpConfiguration sslHttpConfig = new HttpConfiguration();
            sslHttpConfig.setSecureScheme("https");
            sslHttpConfig.setSecurePort(actualPort);

            ServerConnector httpsConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(sslHttpConfig));
            httpsConnector.setPort(actualPort);

            server.addConnector(httpsConnector);
        }

        addShutdownHook();

        File tmpWarFile = Os.writeToTempFile(
                ResourceUtils.create(this).getResourceFromUrl(ROOT_WAR_URL), 
                "TestHttpService", 
                ".war");
        
        WebAppContext context = new WebAppContext();
        context.setWar(tmpWarFile.getAbsolutePath());
        context.setContextPath("/");
        context.setParentLoaderPriority(true);

        if (securityHandler.isPresent()) {
            context.setSecurityHandler(securityHandler.get());
        }

        server.setHandler(context);
        server.start();

        log.info("Started test HttpService at "+getUrl());
        
    } catch (Exception e) {
        try {
            shutdown();
        } catch (Exception e2) {
            log.warn("Error shutting down HttpService while recovering from earlier error (re-throwing earlier error)", e2);
            throw e;
        }
    }

    return this;
}
 
Example 12
Source File: TestClient1.java    From rice with Educational Community License v2.0 4 votes vote down vote up
/**
   * Creates a Server that exposes the TestClient1 services via http and https
   *
   * @return the Server instance
   */
  @Override
  protected Server createServer() {

      // Need this CredentialsSourceFactory in our config to enable our test of basic auth
      // with our httpInvoker-echoServiceSecure

      registerTestCredentialsSourceFactory();

      ConfigConstants configConstants = new ConfigConstants();

      Server server = new Server();

      SelectChannelConnector connector0 = new SelectChannelConnector();
      connector0.setPort(configConstants.SERVER_HTTP_PORT);
      connector0.setMaxIdleTime(30000);
      connector0.setRequestHeaderSize(8192);

      SslSelectChannelConnector ssl_connector = new SslSelectChannelConnector();

      ssl_connector.setPort(configConstants.SERVER_HTTPS_PORT);
      SslContextFactory cf = ssl_connector.getSslContextFactory();
      cf.setKeyStore(configConstants.KEYSTORE_PATH);
      cf.setKeyStorePassword(configConstants.KEYSTORE_PASS);
      cf.setKeyManagerPassword(configConstants.KEYSTORE_PASS);

      server.setConnectors(new Connector[]{connector0, ssl_connector});

      URL webRoot = getClass().getClassLoader().getResource(configConstants.WEB_ROOT);
      String location = webRoot.getPath();

      LOG.debug("#####################################");
LOG.debug("#");
LOG.debug("#  Starting Client1 using following web root " + location);
LOG.debug("#");
LOG.debug("#####################################");

      WebAppContext context = new WebAppContext();
      context.setResourceBase(location);
      context.setContextPath(configConstants.CONTEXT);

      HandlerCollection handlers = new HandlerCollection();
      handlers.addHandler(context);
      server.setHandler(handlers);

      server.setDumpAfterStart(true);
      //server.setDumpBeforeStop(true);

      return server;
  }
 
Example 13
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();
}