Java Code Examples for org.eclipse.jetty.util.ssl.SslContextFactory#Server

The following examples show how to use org.eclipse.jetty.util.ssl.SslContextFactory#Server . 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: JettyServer.java    From pippo with Apache License 2.0 6 votes vote down vote up
protected ServerConnector createServerConnector(Server server) {
    String keyStoreFile = getSettings().getKeystoreFile();
    if (keyStoreFile == null) {
        return new ServerConnector(server);
    }

    SslContextFactory sslContextFactory = new SslContextFactory.Server();
    sslContextFactory.setKeyStorePath(asJettyFriendlyPath(keyStoreFile, "Keystore file"));

    if (getSettings().getKeystorePassword() != null) {
        sslContextFactory.setKeyStorePassword(getSettings().getKeystorePassword());
    }
    String truststoreFile = getSettings().getTruststoreFile();
    if (truststoreFile != null) {
        sslContextFactory.setTrustStorePath(asJettyFriendlyPath(truststoreFile, "Truststore file"));
    }
    if (getSettings().getTruststorePassword() != null) {
        sslContextFactory.setTrustStorePassword(getSettings().getTruststorePassword());
    }

    return new ServerConnector(server, sslContextFactory);
}
 
Example 2
Source File: WebServer.java    From haxademic with MIT License 6 votes vote down vote up
protected void addSSL() {
        // add self-signed ssl
		// generate a self-signed cert: 
		// $ keytool -genkey -keyalg RSA -alias tomcat -keystore selfsigned.jks -validity 9999 -keysize 2048
		// password: haxademic
		// Migrate to pkcs12
		// $ keytool -importkeystore -srckeystore selfsigned.jks -destkeystore selfsigned.jks -deststoretype pkcs12
		SslContextFactory.Server ssl = new SslContextFactory.Server();
	    ssl.setKeyStorePath(FileUtil.getPath("haxademic/net/config/haxademic-selfsigned.jks"));
	    ssl.setKeyStorePassword("haxademic");
	    ssl.setKeyManagerPassword("haxademic");
	    ssl.setKeyStoreType("PKCS12"); // "JKS" if not migrated
	    ssl.setNeedClientAuth(false);
	    ssl.setTrustAll(true);
	    ssl.setValidateCerts(false);
	    // build the connector
	    final ServerConnector https = new ServerConnector(server, ssl);
	    https.setPort(PORT_SSL);
//	    https.setIdleTimeout(30000L);
//	    https.setHost("localhost");
	    server.addConnector(https);
	}
 
Example 3
Source File: AthenzJettyContainerTest.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateSSLContextObjectNoValues() {
    
    AthenzJettyContainer container = new AthenzJettyContainer();
    SslContextFactory.Server sslContextFactory = container.createSSLContextObject(false);
    
    assertNotNull(sslContextFactory);
    assertNull(sslContextFactory.getKeyStoreResource());
    // store type always defaults to PKCS12
    assertEquals(sslContextFactory.getKeyStoreType(), "PKCS12");
    assertNull(sslContextFactory.getTrustStoreResource());
    // store type always defaults to PKCS12
    assertEquals(sslContextFactory.getTrustStoreType(), "PKCS12");
    assertTrue(sslContextFactory.getWantClientAuth());
    assertFalse(sslContextFactory.getNeedClientAuth());
}
 
Example 4
Source File: SSLConfig.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Returns an SslContextFactory.Server that should be used by a jetty server based on this SSLConfig instance,
 * or null if SSL should not be used.
 *
 * The default implementation generates a simple factory according to the keystore, truststore, 
 * and clientAuth properties of this object.
 *
 * @see #getKeyStore
 * @see #getKeyStorePassword
 * @see #isClientAuthMode
 * @see #getTrustStore
 * @see #getTrustStorePassword
 */
public SslContextFactory.Server createContextFactory() {
  if (! isSSLMode()) {
    return null;
  }
  // else...
  
  SslContextFactory.Server factory = new SslContextFactory.Server();
  if (getKeyStore() != null)
    factory.setKeyStorePath(getKeyStore());
  if (getKeyStorePassword() != null)
    factory.setKeyStorePassword(getKeyStorePassword());
  
  factory.setNeedClientAuth(isClientAuthMode());
  
  if (isClientAuthMode()) {
    if (getTrustStore() != null)
      factory.setTrustStorePath(getTrustStore());
    if (getTrustStorePassword() != null)
      factory.setTrustStorePassword(getTrustStorePassword());
  }
  return factory;
}
 
Example 5
Source File: HealthCheckProxyHandler.java    From vespa with Apache License 2.0 6 votes vote down vote up
private SSLContext getSslContext(SslContextFactory.Server sslContextFactory) {
    if (sslContextFactory.getNeedClientAuth()) {
        log.info(String.format("Port %d requires client certificate. HTTPS client will use the target server connector's ssl context.", port));
        // A client certificate is only required if the server connector's ssl context factory is configured with "need-auth".
        // We use the server's ssl context (truststore + keystore) if a client certificate is required.
        // This will only work if the server certificate's CA is in the truststore.
        return sslContextFactory.getSslContext();
    } else {
        log.info(String.format(
                "Port %d does not require a client certificate. HTTPS client will use a custom ssl context accepting all certificates.", port));
        // No client certificate required. The client is configured with a trust manager that accepts all certificates.
        try {
            return SSLContexts.custom().loadTrustMaterial(new TrustAllStrategy()).build();
        } catch (GeneralSecurityException e) {
            throw new RuntimeException(e);
        }
    }
}
 
Example 6
Source File: JettyAdapter.java    From enkan with Eclipse Public License 1.0 6 votes vote down vote up
private SslContextFactory createSslContextFactory(OptionMap options) {
    final SslContextFactory.Server context = new SslContextFactory.Server();
    Object keystore = options.get("keystore");
    if (keystore instanceof KeyStore) {
        context.setKeyStore((KeyStore) keystore);
    } else {
        throw new MisconfigurationException("");
    }
    context.setKeyStorePassword(options.getString("keystorePassword"));

    Object truststore = options.get("truststore");
     if (truststore instanceof KeyStore) {
        context.setTrustStore((KeyStore) truststore);
    }
    context.setTrustStorePassword(options.getString("truststorePassword"));

    String clientAuth = options.getString("clientAuth", "none");
    switch (clientAuth) {
        case "need": context.setNeedClientAuth(true); break;
        case "want": context.setWantClientAuth(true); break;
    }

    return context;
}
 
Example 7
Source File: HttpServer2.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
private ServerConnector createHttpsChannelConnector(
    Server server, HttpConfiguration httpConfig) {
  httpConfig.setSecureScheme(HTTPS_SCHEME);
  httpConfig.addCustomizer(new SecureRequestCustomizer());
  ServerConnector conn = createHttpChannelConnector(server, httpConfig);

  SslContextFactory.Server sslContextFactory =
      new SslContextFactory.Server();
  sslContextFactory.setNeedClientAuth(needsClientAuth);
  if (keyPassword != null) {
    sslContextFactory.setKeyManagerPassword(keyPassword);
  }
  if (keyStore != null) {
    sslContextFactory.setKeyStorePath(keyStore);
    sslContextFactory.setKeyStoreType(keyStoreType);
    if (keyStorePassword != null) {
      sslContextFactory.setKeyStorePassword(keyStorePassword);
    }
  }
  if (trustStore != null) {
    sslContextFactory.setTrustStorePath(trustStore);
    sslContextFactory.setTrustStoreType(trustStoreType);
    if (trustStorePassword != null) {
      sslContextFactory.setTrustStorePassword(trustStorePassword);
    }
  }
  if (null != excludeCiphers && !excludeCiphers.isEmpty()) {
    sslContextFactory.setExcludeCipherSuites(
        StringUtils.getTrimmedStrings(excludeCiphers));
    LOG.info("Excluded Cipher List: {}", excludeCiphers);
  }

  conn.addFirstConnectionFactory(new SslConnectionFactory(sslContextFactory,
      HttpVersion.HTTP_1_1.asString()));

  return conn;
}
 
Example 8
Source File: HealthCheckProxyHandler.java    From vespa with Apache License 2.0 5 votes vote down vote up
private static ProxyTarget createProxyTarget(int targetPort, Duration targetTimeout, List<JDiscServerConnector> connectors) {
    JDiscServerConnector targetConnector = connectors.stream()
            .filter(connector -> connector.listenPort() == targetPort)
            .findAny()
            .orElseThrow(() -> new IllegalArgumentException("Could not find any connector with listen port " + targetPort));
    SslContextFactory.Server sslContextFactory =
            Optional.ofNullable(targetConnector.getConnectionFactory(SslConnectionFactory.class))
                    .or(() -> Optional.ofNullable(targetConnector.getConnectionFactory(DetectorConnectionFactory.class))
                            .map(detectorConnFactory -> detectorConnFactory.getBean(SslConnectionFactory.class)))
                    .map(connFactory -> (SslContextFactory.Server) connFactory.getSslContextFactory())
                    .orElseThrow(() -> new IllegalArgumentException("Health check proxy can only target https port"));
    return new ProxyTarget(targetPort, targetTimeout, sslContextFactory);
}
 
Example 9
Source File: SlaveWebServerTask.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Override
protected SslContextFactory.Server createSslContextFactory() {
  SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
  File keyStore = getWorkerHttpsKeystore();
  if (!keyStore.exists()) {
    throw new IllegalStateException(Utils.format("Keystore file '{}' does not exist on worker", keyStore.getPath()));
  }
  String password = conf.get(HTTPS_WORKER_KEYSTORE_PASSWORD, HTTPS_WORKER_KEYSTORE_PASSWORD_DEFAULT).trim();
  sslContextFactory.setKeyStorePath(keyStore.getPath());
  sslContextFactory.setKeyStorePassword(password);
  sslContextFactory.setKeyManagerPassword(password);
  File trustStoreFile = getWorkerHttpsTruststore();
  if (trustStoreFile != null) {
    if (trustStoreFile.exists()) {
      sslContextFactory.setTrustStorePath(trustStoreFile.getPath());
      String truststorePassword = Utils.checkNotNull(
          conf.get(HTTPS_WORKER_TRUSTSTORE_PASSWORD, HTTPS_WORKER_TRUSTSTORE_PASSWORD_DEFAULT),
          HTTPS_WORKER_TRUSTSTORE_PASSWORD
      );
      sslContextFactory.setTrustStorePassword(truststorePassword.trim());
    } else {
      throw new IllegalStateException(Utils.format(
          "Truststore file: '{}' doesn't exist on worker",
          trustStoreFile.getPath()
      ));
    }
  }
  return sslContextFactory;
}
 
Example 10
Source File: ConfiguredSslContextFactoryProvider.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Override
public SslContextFactory getInstance(String containerId, int port) {
    ConnectorConfig.Ssl sslConfig = connectorConfig.ssl();
    if (!sslConfig.enabled()) throw new IllegalStateException();

    SslContextBuilder builder = new SslContextBuilder();
    if (sslConfig.certificateFile().isBlank() || sslConfig.privateKeyFile().isBlank()) {
        PrivateKey privateKey = KeyUtils.fromPemEncodedPrivateKey(getPrivateKey(sslConfig));
        List<X509Certificate> certificates = X509CertificateUtils.certificateListFromPem(getCertificate(sslConfig));
        builder.withKeyStore(privateKey, certificates);
    } else {
        keyManager = AutoReloadingX509KeyManager.fromPemFiles(Paths.get(sslConfig.privateKeyFile()), Paths.get(sslConfig.certificateFile()));
        builder.withKeyManager(keyManager);
    }
    List<X509Certificate> caCertificates = getCaCertificates(sslConfig)
            .map(X509CertificateUtils::certificateListFromPem)
            .orElse(List.of());
    builder.withTrustStore(caCertificates);

    SSLContext sslContext = builder.build();

    SslContextFactory.Server factory = new SslContextFactory.Server();
    factory.setSslContext(sslContext);

    factory.setNeedClientAuth(sslConfig.clientAuth() == ClientAuth.Enum.NEED_AUTH);
    factory.setWantClientAuth(sslConfig.clientAuth() == ClientAuth.Enum.WANT_AUTH);

    List<String> protocols = !sslConfig.enabledProtocols().isEmpty()
            ? sslConfig.enabledProtocols()
            : new ArrayList<>(TlsContext.getAllowedProtocols(sslContext));
    setEnabledProtocols(factory, sslContext, protocols);

    List<String> ciphers = !sslConfig.enabledCipherSuites().isEmpty()
            ? sslConfig.enabledCipherSuites()
            : new ArrayList<>(TlsContext.getAllowedCipherSuites(sslContext));
    setEnabledCipherSuites(factory, sslContext, ciphers);

    return factory;
}
 
Example 11
Source File: WebServerTask.java    From datacollector with Apache License 2.0 5 votes vote down vote up
protected SslContextFactory.Server createSslContextFactory() {
  SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
  File keyStore = getHttpsKeystore(conf, runtimeInfo.getConfigDir());
  if (!keyStore.exists()) {
    throw new RuntimeException(Utils.format("KeyStore file '{}' does not exist", keyStore.getPath()));
  }
  String password = conf.get(HTTPS_KEYSTORE_PASSWORD_KEY, HTTPS_KEYSTORE_PASSWORD_DEFAULT).trim();
  sslContextFactory.setKeyStorePath(keyStore.getPath());
  sslContextFactory.setKeyStorePassword(password);
  sslContextFactory.setKeyManagerPassword(password);
  if (conf.get(HTTP2_ENABLE_KEY, false)) {
    sslContextFactory.setProvider("Conscrypt");
    sslContextFactory.setCipherComparator(HTTP2Cipher.COMPARATOR);
    sslContextFactory.setUseCipherSuitesOrder(true);
  }
  File trustStoreFile = getHttpsTruststore(conf, runtimeInfo.getConfigDir());
  if (trustStoreFile != null) {
    if (trustStoreFile.exists()) {
      sslContextFactory.setTrustStorePath(trustStoreFile.getPath());
      String trustStorePassword = Utils.checkNotNull(conf.get(HTTPS_TRUSTSTORE_PASSWORD_KEY,
          HTTPS_TRUSTSTORE_PASSWORD_DEFAULT
      ), HTTPS_TRUSTSTORE_PASSWORD_KEY);
      sslContextFactory.setTrustStorePassword(trustStorePassword.trim());
    } else {
      throw new IllegalStateException(Utils.format(
          "Truststore file: '{}' " + "doesn't exist",
          trustStoreFile.getAbsolutePath()
      ));
    }
  }
  return sslContextFactory;
}
 
Example 12
Source File: PullHttpChangeIngestorSSLTest.java    From nifi-minifi with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception {
    PullHttpChangeIngestorCommonTest.init();

    SslContextFactory.Server ssl = new SslContextFactory.Server();

    ssl.setKeyStorePath("./src/test/resources/localhost-ks.jks");
    ssl.setKeyStorePassword("localtest");
    ssl.setKeyStoreType("JKS");
    ssl.setTrustStorePath("./src/test/resources/localhost-ts.jks");
    ssl.setTrustStorePassword("localtest");
    ssl.setTrustStoreType("JKS");
    ssl.setNeedClientAuth(true);

    // build the connector
    final ServerConnector https = new ServerConnector(jetty, ssl);

    // set host and port
    https.setPort(0);
    https.setHost("localhost");

    // Severely taxed environments may have significant delays when executing.
    https.setIdleTimeout(30000L);

    // add the connector
    jetty.addConnector(https);

    jetty.start();

    Thread.sleep(1000);

    if (!jetty.isStarted()) {
        throw new IllegalStateException("Jetty server not started");
    }
}
 
Example 13
Source File: ZeppelinServer.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
private static void setupTruststoreWithPemFiles(SslContextFactory.Server sslContextFactory, ZeppelinConfiguration conf) {
  File pemCa = new File(conf.getPemCAFile());
  if (Files.isReadable(pemCa.toPath())) {
    try {
      sslContextFactory.setTrustStore(PEMImporter.loadTrustStore(pemCa));
      sslContextFactory.setTrustStoreType("JKS");
      sslContextFactory.setTrustStorePassword("");
      sslContextFactory.setNeedClientAuth(conf.useClientAuth());
    } catch (IOException | GeneralSecurityException e) {
      LOG.error("Failed to initialize TrustStore from PEM CA file", e);
    }
  } else {
    LOG.error("PEM CA file {} is not readable", pemCa);
  }
}
 
Example 14
Source File: WebSocketProvider.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
private SslContextFactory createSslContextFactory(final AmqpPort<?> port)
{
    SslContextFactory.Server sslContextFactory = new SslContextFactory.Server()
    {
        @Override
        public void customize(final SSLEngine sslEngine)
        {
            super.customize(sslEngine);
            SSLUtil.updateEnabledCipherSuites(sslEngine,
                                              port.getTlsCipherSuiteWhiteList(),
                                              port.getTlsCipherSuiteBlackList());
            SSLUtil.updateEnabledTlsProtocols(sslEngine,
                                              port.getTlsProtocolWhiteList(),
                                              port.getTlsProtocolBlackList());

            if (port.getTlsCipherSuiteWhiteList() != null
                && !port.getTlsCipherSuiteWhiteList().isEmpty())
            {
                SSLParameters sslParameters = sslEngine.getSSLParameters();
                sslParameters.setUseCipherSuitesOrder(true);
                sslEngine.setSSLParameters(sslParameters);
            }
        }
    };
    sslContextFactory.setSslContext(port.getSSLContext());
    sslContextFactory.setNeedClientAuth(port.getNeedClientAuth());
    sslContextFactory.setWantClientAuth(port.getWantClientAuth());
    return sslContextFactory;
}
 
Example 15
Source File: AthenzJettyContainer.java    From athenz with Apache License 2.0 4 votes vote down vote up
SslContextFactory.Server createSSLContextObject(boolean needClientAuth) {
    
    final String keyStorePath = System.getProperty(AthenzConsts.ATHENZ_PROP_KEYSTORE_PATH);
    final String keyStorePasswordAppName = System.getProperty(AthenzConsts.ATHENZ_PROP_KEYSTORE_PASSWORD_APPNAME);
    final String keyStorePassword = System.getProperty(AthenzConsts.ATHENZ_PROP_KEYSTORE_PASSWORD);
    final String keyStoreType = System.getProperty(AthenzConsts.ATHENZ_PROP_KEYSTORE_TYPE, "PKCS12");
    final String keyManagerPassword = System.getProperty(AthenzConsts.ATHENZ_PROP_KEYMANAGER_PASSWORD);
    final String keyManagerPasswordAppName = System.getProperty(AthenzConsts.ATHENZ_PROP_KEYMANAGER_PASSWORD_APPNAME);
    final String trustStorePath = System.getProperty(AthenzConsts.ATHENZ_PROP_TRUSTSTORE_PATH);
    final String trustStorePassword = System.getProperty(AthenzConsts.ATHENZ_PROP_TRUSTSTORE_PASSWORD);
    final String trustStorePasswordAppName = System.getProperty(AthenzConsts.ATHENZ_PROP_TRUSTSTORE_PASSWORD_APPNAME);
    final String trustStoreType = System.getProperty(AthenzConsts.ATHENZ_PROP_TRUSTSTORE_TYPE, "PKCS12");
    final String includedCipherSuites = System.getProperty(AthenzConsts.ATHENZ_PROP_INCLUDED_CIPHER_SUITES);
    final String excludedCipherSuites = System.getProperty(AthenzConsts.ATHENZ_PROP_EXCLUDED_CIPHER_SUITES);
    final String excludedProtocols = System.getProperty(AthenzConsts.ATHENZ_PROP_EXCLUDED_PROTOCOLS,
            ATHENZ_DEFAULT_EXCLUDED_PROTOCOLS);
    boolean enableOCSP = Boolean.parseBoolean(System.getProperty(AthenzConsts.ATHENZ_PROP_ENABLE_OCSP, "false"));
    boolean renegotiationAllowed = Boolean.parseBoolean(System.getProperty(AthenzConsts.ATHENZ_PROP_RENEGOTIATION_ALLOWED, "true"));

    SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
    sslContextFactory.setEndpointIdentificationAlgorithm(null);

    if (keyStorePath != null) {
        LOG.info("Using SSL KeyStore path: {}", keyStorePath);
        sslContextFactory.setKeyStorePath(keyStorePath);
    }
    if (keyStorePassword != null) {
        //default implementation should just return the same
        sslContextFactory.setKeyStorePassword(this.privateKeyStore.getApplicationSecret(keyStorePasswordAppName, keyStorePassword));
    }
    sslContextFactory.setKeyStoreType(keyStoreType);

    if (keyManagerPassword != null) {
        sslContextFactory.setKeyManagerPassword(this.privateKeyStore.getApplicationSecret(keyManagerPasswordAppName, keyManagerPassword));
    }
    if (trustStorePath != null) {
        LOG.info("Using SSL TrustStore path: {}", trustStorePath);
        sslContextFactory.setTrustStorePath(trustStorePath);
    }
    if (trustStorePassword != null) {
        sslContextFactory.setTrustStorePassword(this.privateKeyStore.getApplicationSecret(trustStorePasswordAppName, trustStorePassword));
    }
    sslContextFactory.setTrustStoreType(trustStoreType);

    if (includedCipherSuites != null && !includedCipherSuites.isEmpty()) {
        sslContextFactory.setIncludeCipherSuites(includedCipherSuites.split(","));
    }
    
    if (excludedCipherSuites != null && !excludedCipherSuites.isEmpty()) {
        sslContextFactory.setExcludeCipherSuites(excludedCipherSuites.split(","));
    }
    
    if (!excludedProtocols.isEmpty()) {
        sslContextFactory.setExcludeProtocols(excludedProtocols.split(","));
    }
    
    if (needClientAuth) {
        sslContextFactory.setNeedClientAuth(true);
    } else {
        sslContextFactory.setWantClientAuth(true);
    }

    sslContextFactory.setEnableOCSP(enableOCSP);
    sslContextFactory.setRenegotiationAllowed(renegotiationAllowed);

    return sslContextFactory;
}
 
Example 16
Source File: ApplicationServer.java    From rest-utils with Apache License 2.0 4 votes vote down vote up
private SslContextFactory createSslContextFactory(RestConfig config) {
  SslContextFactory sslContextFactory = new SslContextFactory.Server();
  if (!config.getString(RestConfig.SSL_KEYSTORE_LOCATION_CONFIG).isEmpty()) {
    sslContextFactory.setKeyStorePath(
            config.getString(RestConfig.SSL_KEYSTORE_LOCATION_CONFIG)
    );
    sslContextFactory.setKeyStorePassword(
            config.getPassword(RestConfig.SSL_KEYSTORE_PASSWORD_CONFIG).value()
    );
    sslContextFactory.setKeyManagerPassword(
            config.getPassword(RestConfig.SSL_KEY_PASSWORD_CONFIG).value()
    );
    sslContextFactory.setKeyStoreType(
            config.getString(RestConfig.SSL_KEYSTORE_TYPE_CONFIG)
    );

    if (!config.getString(RestConfig.SSL_KEYMANAGER_ALGORITHM_CONFIG).isEmpty()) {
      sslContextFactory.setKeyManagerFactoryAlgorithm(
              config.getString(RestConfig.SSL_KEYMANAGER_ALGORITHM_CONFIG));
    }

    if (config.getBoolean(RestConfig.SSL_KEYSTORE_RELOAD_CONFIG)) {
      Path watchLocation = getWatchLocation(config);
      try {
        FileWatcher.onFileChange(watchLocation, () -> {
              // Need to reset the key store path for symbolic link case
              sslContextFactory.setKeyStorePath(
                  config.getString(RestConfig.SSL_KEYSTORE_LOCATION_CONFIG)
              );
              sslContextFactory.reload(scf -> log.info("Reloaded SSL cert"));
            }
        );
        log.info("Enabled SSL cert auto reload for: " + watchLocation);
      } catch (java.io.IOException e) {
        log.error("Can not enabled SSL cert auto reload", e);
      }
    }
  }

  configureClientAuth(sslContextFactory, config);

  List<String> enabledProtocols = config.getList(RestConfig.SSL_ENABLED_PROTOCOLS_CONFIG);
  if (!enabledProtocols.isEmpty()) {
    sslContextFactory.setIncludeProtocols(enabledProtocols.toArray(new String[0]));
  }

  List<String> cipherSuites = config.getList(RestConfig.SSL_CIPHER_SUITES_CONFIG);
  if (!cipherSuites.isEmpty()) {
    sslContextFactory.setIncludeCipherSuites(cipherSuites.toArray(new String[0]));
  }

  sslContextFactory.setEndpointIdentificationAlgorithm(
          config.getString(RestConfig.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG));

  if (!config.getString(RestConfig.SSL_TRUSTSTORE_LOCATION_CONFIG).isEmpty()) {
    sslContextFactory.setTrustStorePath(
            config.getString(RestConfig.SSL_TRUSTSTORE_LOCATION_CONFIG)
    );
    sslContextFactory.setTrustStorePassword(
            config.getPassword(RestConfig.SSL_TRUSTSTORE_PASSWORD_CONFIG).value()
    );
    sslContextFactory.setTrustStoreType(
            config.getString(RestConfig.SSL_TRUSTSTORE_TYPE_CONFIG)
    );

    if (!config.getString(RestConfig.SSL_TRUSTMANAGER_ALGORITHM_CONFIG).isEmpty()) {
      sslContextFactory.setTrustManagerFactoryAlgorithm(
              config.getString(RestConfig.SSL_TRUSTMANAGER_ALGORITHM_CONFIG)
      );
    }
  }

  sslContextFactory.setProtocol(config.getString(RestConfig.SSL_PROTOCOL_CONFIG));
  if (!config.getString(RestConfig.SSL_PROVIDER_CONFIG).isEmpty()) {
    sslContextFactory.setProtocol(config.getString(RestConfig.SSL_PROVIDER_CONFIG));
  }

  sslContextFactory.setRenegotiationAllowed(false);

  return sslContextFactory;
}
 
Example 17
Source File: CitizenIntelligenceAgencyServer.java    From cia with Apache License 2.0 4 votes vote down vote up
/**
 * Inits the.
 *
 * @throws Exception the exception
 */
public final void init() throws Exception {
	initialised = true;
	server = new Server();
	Security.addProvider(new BouncyCastleProvider());
	// Setup JMX
	final MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
	server.addBean(mbContainer);

	final org.eclipse.jetty.webapp.Configurations classlist = org.eclipse.jetty.webapp.Configurations.setServerDefault(server);
			
	final HttpConfiguration http_config = new HttpConfiguration();
	http_config.setSecureScheme("https");
	http_config.setSecurePort(28443);
	http_config.setSendServerVersion(false);

	final HttpConfiguration https_config = new HttpConfiguration(http_config);
	https_config.addCustomizer(new SecureRequestCustomizer());

	final SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
	sslContextFactory.setKeyStoreType("PKCS12");
	sslContextFactory.setKeyStorePath("target/keystore.p12");
	sslContextFactory.setTrustStorePath("target/keystore.p12");
	sslContextFactory.setTrustStoreType("PKCS12");

	sslContextFactory.setKeyStorePassword("changeit");
	sslContextFactory.setTrustStorePassword("changeit");
	sslContextFactory.setKeyManagerPassword("changeit");
	sslContextFactory.setCertAlias("jetty");
	sslContextFactory.setIncludeCipherSuites("TLS_AES_256_GCM_SHA384", "TLS_CHACHA20_POLY1305_SHA256",
			"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
			"TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256");
	sslContextFactory.setExcludeProtocols("SSL", "SSLv2", "SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.1");
	sslContextFactory.setIncludeProtocols("TLSv1.2", "TLSv1.3");

	final ServerConnector sslConnector = new ServerConnector(server,
			new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(https_config),
			new HTTP2CServerConnectionFactory(https_config));
	sslConnector.setPort(PORT);

	server.setConnectors(new ServerConnector[] { sslConnector });
	final WebAppContext handler = new WebAppContext("src/main/webapp", "/");
	handler.setExtraClasspath("target/classes");
	handler.setParentLoaderPriority(true);
	handler.setConfigurationDiscovered(true);
	handler.setClassLoader(Thread.currentThread().getContextClassLoader());
	final HandlerList handlers = new HandlerList();

	handlers.setHandlers(new Handler[] { handler, new DefaultHandler() });

	server.setHandler(handlers);
}
 
Example 18
Source File: JettyServer.java    From nifi-registry with Apache License 2.0 4 votes vote down vote up
private SslContextFactory createSslContextFactory() {
    final SslContextFactory.Server contextFactory = new SslContextFactory.Server();

    // if needClientAuth is false then set want to true so we can optionally use certs
    if (properties.getNeedClientAuth()) {
        logger.info("Setting Jetty's SSLContextFactory needClientAuth to true");
        contextFactory.setNeedClientAuth(true);
    } else {
        logger.info("Setting Jetty's SSLContextFactory wantClientAuth to true");
        contextFactory.setWantClientAuth(true);
    }

    /* below code sets JSSE system properties when values are provided */
    // keystore properties
    if (StringUtils.isNotBlank(properties.getKeyStorePath())) {
        contextFactory.setKeyStorePath(properties.getKeyStorePath());
    }
    if (StringUtils.isNotBlank(properties.getKeyStoreType())) {
        contextFactory.setKeyStoreType(properties.getKeyStoreType());
    }
    final String keystorePassword = properties.getKeyStorePassword();
    final String keyPassword = properties.getKeyPassword();
    if (StringUtils.isNotBlank(keystorePassword)) {
        // if no key password was provided, then assume the keystore password is the same as the key password.
        final String defaultKeyPassword = (StringUtils.isBlank(keyPassword)) ? keystorePassword : keyPassword;
        contextFactory.setKeyManagerPassword(keystorePassword);
        contextFactory.setKeyStorePassword(defaultKeyPassword);
    } else if (StringUtils.isNotBlank(keyPassword)) {
        // since no keystore password was provided, there will be no keystore integrity check
        contextFactory.setKeyStorePassword(keyPassword);
    }

    // truststore properties
    if (StringUtils.isNotBlank(properties.getTrustStorePath())) {
        contextFactory.setTrustStorePath(properties.getTrustStorePath());
    }
    if (StringUtils.isNotBlank(properties.getTrustStoreType())) {
        contextFactory.setTrustStoreType(properties.getTrustStoreType());
    }
    if (StringUtils.isNotBlank(properties.getTrustStorePassword())) {
        contextFactory.setTrustStorePassword(properties.getTrustStorePassword());
    }

    return contextFactory;
}
 
Example 19
Source File: JettyITServerCustomizer.java    From nifi-registry with Apache License 2.0 4 votes vote down vote up
private SslContextFactory createSslContextFactory(Ssl properties) {
    // Calling SslContextFactory.Server() calls setEndpointIdentificationAlgorithm(null).
    // This ensures that Jetty server does not attempt to validate a hostname in the client certificate's SAN.
    final SslContextFactory.Server contextFactory = new SslContextFactory.Server();

    // if needClientAuth is false then set want to true so we can optionally use certs
    if(properties.getClientAuth() == Ssl.ClientAuth.NEED) {
        LOGGER.info("Setting Jetty's SSLContextFactory needClientAuth to true");
        contextFactory.setNeedClientAuth(true);
    } else {
        LOGGER.info("Setting Jetty's SSLContextFactory wantClientAuth to true");
        contextFactory.setWantClientAuth(true);
    }

    /* below code sets JSSE system properties when values are provided */
    // keystore properties
    if (StringUtils.isNotBlank(properties.getKeyStore())) {
        contextFactory.setKeyStorePath(properties.getKeyStore());
    }
    if (StringUtils.isNotBlank(properties.getKeyStoreType())) {
        contextFactory.setKeyStoreType(properties.getKeyStoreType());
    }
    final String keystorePassword = properties.getKeyStorePassword();
    final String keyPassword = properties.getKeyPassword();
    if (StringUtils.isNotBlank(keystorePassword)) {
        // if no key password was provided, then assume the keystore password is the same as the key password.
        final String defaultKeyPassword = (StringUtils.isBlank(keyPassword)) ? keystorePassword : keyPassword;
        contextFactory.setKeyManagerPassword(keystorePassword);
        contextFactory.setKeyStorePassword(defaultKeyPassword);
    } else if (StringUtils.isNotBlank(keyPassword)) {
        // since no keystore password was provided, there will be no keystore integrity check
        contextFactory.setKeyStorePassword(keyPassword);
    }

    // truststore properties
    if (StringUtils.isNotBlank(properties.getTrustStore())) {
        contextFactory.setTrustStorePath(properties.getTrustStore());
    }
    if (StringUtils.isNotBlank(properties.getTrustStoreType())) {
        contextFactory.setTrustStoreType(properties.getTrustStoreType());
    }
    if (StringUtils.isNotBlank(properties.getTrustStorePassword())) {
        contextFactory.setTrustStorePassword(properties.getTrustStorePassword());
    }

    return contextFactory;
}
 
Example 20
Source File: HealthCheckProxyHandler.java    From vespa with Apache License 2.0 4 votes vote down vote up
ProxyTarget(int port, Duration timeout, SslContextFactory.Server sslContextFactory) {
    this.port = port;
    this.timeout = timeout;
    this.sslContextFactory = sslContextFactory;
}