org.eclipse.jetty.util.ssl.SslContextFactory Java Examples

The following examples show how to use org.eclipse.jetty.util.ssl.SslContextFactory. 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: PrometheusServer.java    From nifi with Apache License 2.0 6 votes vote down vote up
private SslContextFactory createSslFactory(final SSLContextService sslService, boolean needClientAuth, boolean wantClientAuth) {
    SslContextFactory sslFactory = new SslContextFactory();

    sslFactory.setNeedClientAuth(needClientAuth);
    sslFactory.setWantClientAuth(wantClientAuth);
    sslFactory.setProtocol(sslService.getSslAlgorithm());

    if (sslService.isKeyStoreConfigured()) {
        sslFactory.setKeyStorePath(sslService.getKeyStoreFile());
        sslFactory.setKeyStorePassword(sslService.getKeyStorePassword());
        sslFactory.setKeyStoreType(sslService.getKeyStoreType());
    }

    if (sslService.isTrustStoreConfigured()) {
        sslFactory.setTrustStorePath(sslService.getTrustStoreFile());
        sslFactory.setTrustStorePassword(sslService.getTrustStorePassword());
        sslFactory.setTrustStoreType(sslService.getTrustStoreType());
    }

    return sslFactory;
}
 
Example #2
Source File: SSLTestConfig.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public SSLConfig buildClientSSLConfig() {
  if (!isSSLMode()) {
    return null;
  }

  return new SSLConfig(isSSLMode(), isClientAuthMode(), null, null, null, null) {
    @Override
    public SslContextFactory.Client createClientContextFactory() {
      SslContextFactory.Client factory = new SslContextFactory.Client(!checkPeerName);
      try {
        factory.setSslContext(buildClientSSLContext());
      } catch (KeyManagementException | UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException e) {
        throw new IllegalStateException("Unable to setup https scheme for HTTPClient to test SSL.", e);
      }
      return factory;
    }
  };
}
 
Example #3
Source File: ConnectorManager.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Verifies all the needed bits are present in Jetty XML configuration (as HTTPS must be enabled by users).
 */
private void verifyConfiguration(final HttpScheme httpScheme) {
  try {
    if (HttpScheme.HTTP == httpScheme) {
      bean(HTTP_CONFIG_ID, HttpConfiguration.class);
      bean(HTTP_CONNECTOR_ID, ServerConnector.class);
    }
    else if (HttpScheme.HTTPS == httpScheme) {
      bean(SSL_CONTEXT_FACTORY_ID, SslContextFactory.class);
      bean(HTTPS_CONFIG_ID, HttpConfiguration.class);
      bean(HTTPS_CONNECTOR_ID, ServerConnector.class);
    }
    else {
      throw new UnsupportedHttpSchemeException(httpScheme);
    }
  }
  catch (IllegalStateException e) {
    throw new IllegalStateException("Jetty HTTPS is not enabled in Nexus", e);
  }
}
 
Example #4
Source File: ServerDaemon.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
private void createHttpsConnector(final HttpConfiguration httpConfig) {
    // Configure SSL
    if (httpsEnable && !Strings.isNullOrEmpty(keystoreFile) && new File(keystoreFile).exists()) {
        // SSL Context
        final SslContextFactory sslContextFactory = new SslContextFactory();

        // Define keystore path and passwords
        sslContextFactory.setKeyStorePath(keystoreFile);
        sslContextFactory.setKeyStorePassword(keystorePassword);
        sslContextFactory.setKeyManagerPassword(keystorePassword);

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

        // HTTPS Connector
        final ServerConnector sslConnector = new ServerConnector(server,
                new SslConnectionFactory(sslContextFactory, "http/1.1"),
                new HttpConnectionFactory(httpsConfig));
        sslConnector.setPort(httpsPort);
        sslConnector.setHost(bindInterface);
        server.addConnector(sslConnector);
    }
}
 
Example #5
Source File: WebClientFactoryImpl.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Deprecated
private SslContextFactory createSslContextFactoryFromTrustManagerProvider(@Nullable String endpoint) {
    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setEndpointIdentificationAlgorithm("HTTPS");
    if (endpoint != null && trustmanagerProvider != null) {
        Stream<TrustManager> trustManagerStream = trustmanagerProvider.getTrustManagers(endpoint);
        TrustManager[] trustManagers = trustManagerStream.toArray(TrustManager[]::new);
        if (trustManagers.length > 0) {
            logger.debug("using custom trustmanagers (certificate pinning) for httpClient for endpoint {}",
                    endpoint);
            try {
                SSLContext sslContext = SSLContext.getInstance("TLS");
                sslContext.init(null, trustManagers, null);
                sslContextFactory.setSslContext(sslContext);
            } catch (NoSuchAlgorithmException | KeyManagementException ex) {
                throw new HttpClientInitializationException(
                        "Cannot create an TLS context for the endpoint '" + endpoint + "'!", ex);
            }
        }
    }

    String excludeCipherSuites[] = { "^.*_(MD5)$" };
    sslContextFactory.setExcludeCipherSuites(excludeCipherSuites);
    return sslContextFactory;
}
 
Example #6
Source File: HttpManagement.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Override
public boolean updateSSLContext(final HttpPort httpPort)
{
    final SslContextFactory sslContextFactory = getSslContextFactory(httpPort);
    if ( sslContextFactory != null)
    {
        try
        {
            final SSLContext sslContext = createSslContext(httpPort);
            sslContextFactory.reload(f -> {
                f.setSslContext(sslContext);
                f.setNeedClientAuth(httpPort.getNeedClientAuth());
                f.setWantClientAuth(httpPort.getWantClientAuth());
            });
            return true;
        }
        catch (Exception e)
        {
            throw new IllegalConfigurationException("Unexpected exception on reload of ssl context factory", e);
        }
    }
    return false;
}
 
Example #7
Source File: SSLConfig.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public SslContextFactory.Client createClientContextFactory() {
  if (! isSSLMode()) {
    return null;
  }
  // else...

  SslContextFactory.Client factory = new SslContextFactory.Client();
  if (getKeyStore() != null) {
    factory.setKeyStorePath(getKeyStore());
  }
  if (getKeyStorePassword() != null) {
    factory.setKeyStorePassword(getKeyStorePassword());
  }

  if (isClientAuthMode()) {
    if (getTrustStore() != null)
      factory.setTrustStorePath(getTrustStore());
    if (getTrustStorePassword() != null)
      factory.setTrustStorePassword(getTrustStorePassword());
  }

  return factory;
}
 
Example #8
Source File: WebServer.java    From hop with Apache License 2.0 6 votes vote down vote up
private ServerConnector getConnector() {
  if ( sslConfig != null ) {
    log.logBasic( BaseMessages.getString( PKG, "WebServer.Log.SslModeUsing" ) );
    SslConnectionFactory connector = new SslConnectionFactory();

    SslContextFactory contextFactory = new SslContextFactory();
    contextFactory.setKeyStoreResource( new PathResource( new File( sslConfig.getKeyStore() ) ) );
    contextFactory.setKeyStorePassword( sslConfig.getKeyStorePassword() );
    contextFactory.setKeyManagerPassword( sslConfig.getKeyPassword() );
    contextFactory.setKeyStoreType( sslConfig.getKeyStoreType() );
    return new ServerConnector( server, connector );
  } else {
    return new ServerConnector( server );
  }

}
 
Example #9
Source File: HttpServerExtension.java    From kareldb with Apache License 2.0 6 votes vote down vote up
private static void configureClientAuth(KarelDbConfig config, SslContextFactory sslContextFactory) {
    String clientAuthentication = config.getString(KarelDbConfig.SSL_CLIENT_AUTHENTICATION_CONFIG);

    switch (clientAuthentication) {
        case KarelDbConfig.SSL_CLIENT_AUTHENTICATION_REQUIRED:
            sslContextFactory.setNeedClientAuth(true);
            break;
        case KarelDbConfig.SSL_CLIENT_AUTHENTICATION_REQUESTED:
            sslContextFactory.setWantClientAuth(true);
            break;
        case KarelDbConfig.SSL_CLIENT_AUTHENTICATION_NONE:
            break;
        default:
            throw new ConfigException(
                "Unexpected value for {} configuration: {}",
                KarelDbConfig.SSL_CLIENT_AUTHENTICATION_CONFIG,
                clientAuthentication
            );
    }
}
 
Example #10
Source File: ErrorCases.java    From scheduling with GNU Affero General Public License v3.0 6 votes vote down vote up
@BeforeClass
public static void startHttpsServer() throws Exception {
    skipIfHeadlessEnvironment();
    server = new Server();

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(ErrorCases.class.getResource("keystore").getPath());
    sslContextFactory.setKeyStorePassword("activeeon");

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

    ServerConnector sslConnector = new ServerConnector(server,
                                                       new ConnectionFactory[] { new SslConnectionFactory(sslContextFactory,
                                                                                                          HttpVersion.HTTP_1_1.asString()),
                                                                                 new HttpConnectionFactory(httpsConfig) });

    server.addConnector(sslConnector);
    server.start();
    serverUrl = "https://localhost:" + sslConnector.getLocalPort() + "/rest";
}
 
Example #11
Source File: ZTSUtilsTest.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateSSLContextObject() {
    
    System.setProperty(ZTSConsts.ZTS_PROP_KEYSTORE_PATH, "file:///tmp/keystore");
    System.setProperty(ZTSConsts.ZTS_PROP_KEYSTORE_TYPE, "PKCS12");
    System.setProperty(ZTSConsts.ZTS_PROP_KEYSTORE_PASSWORD, "pass123");
    System.setProperty(ZTSConsts.ZTS_PROP_TRUSTSTORE_PATH, "file:///tmp/truststore");
    System.setProperty(ZTSConsts.ZTS_PROP_TRUSTSTORE_TYPE, "PKCS12");
    System.setProperty(ZTSConsts.ZTS_PROP_TRUSTSTORE_PASSWORD, "pass123");
    System.setProperty(ZTSConsts.ZTS_PROP_KEYMANAGER_PASSWORD, "pass123");
    System.setProperty(ZTSConsts.ZTS_PROP_EXCLUDED_CIPHER_SUITES, ZTSUtils.ZTS_DEFAULT_EXCLUDED_CIPHER_SUITES);
    System.setProperty(ZTSConsts.ZTS_PROP_EXCLUDED_PROTOCOLS, ZTSUtils.ZTS_DEFAULT_EXCLUDED_PROTOCOLS);
    System.setProperty(ZTSConsts.ZTS_PROP_WANT_CLIENT_CERT, "true");
    
    SslContextFactory sslContextFactory = ZTSUtils.createSSLContextObject(null);
    assertNotNull(sslContextFactory);
    assertEquals(sslContextFactory.getKeyStorePath(), "file:///tmp/keystore");
    assertEquals(sslContextFactory.getKeyStoreType(), "PKCS12");
    assertEquals(sslContextFactory.getTrustStoreResource().toString(), "file:///tmp/truststore");
    assertEquals(sslContextFactory.getTrustStoreType(), "PKCS12");
    assertEquals(sslContextFactory.getExcludeCipherSuites(), ZTSUtils.ZTS_DEFAULT_EXCLUDED_CIPHER_SUITES.split(","));
    assertEquals(sslContextFactory.getExcludeProtocols(), ZTSUtils.ZTS_DEFAULT_EXCLUDED_PROTOCOLS.split(","));
    assertTrue(sslContextFactory.getWantClientAuth());
}
 
Example #12
Source File: WebClientLoggingIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenJettyHttpClient_whenEndpointIsConsumed_thenRequestAndResponseBodyLogged() {
    SslContextFactory.Client sslContextFactory = new SslContextFactory.Client();
    org.eclipse.jetty.client.HttpClient httpClient = new org.eclipse.jetty.client.HttpClient(sslContextFactory) {
        @Override
        public Request newRequest(URI uri) {
            Request request = super.newRequest(uri);
            return enhance(request);
        }
    };

    WebClient
      .builder()
      .clientConnector(new JettyClientHttpConnector(httpClient))
      .build()
      .post()
      .uri(sampleUrl)
      .body(BodyInserters.fromObject(post))
      .retrieve()
      .bodyToMono(String.class)
      .block();

    verify(jettyAppender).doAppend(argThat(argument -> (((LoggingEvent) argument).getFormattedMessage()).contains(sampleResponseBody)));
}
 
Example #13
Source File: SSLConfig.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private static SslContextFactory.Server configureSslFromSysProps() {
  SslContextFactory.Server sslcontext = new SslContextFactory.Server();

  if (null != System.getProperty("javax.net.ssl.keyStore")) {
    sslcontext.setKeyStorePath
        (System.getProperty("javax.net.ssl.keyStore"));
  }
  if (null != System.getProperty("javax.net.ssl.keyStorePassword")) {
    sslcontext.setKeyStorePassword
        (System.getProperty("javax.net.ssl.keyStorePassword"));
  }
  if (null != System.getProperty("javax.net.ssl.trustStore")) {
    sslcontext.setTrustStorePath
        (System.getProperty("javax.net.ssl.trustStore"));
  }
  if (null != System.getProperty("javax.net.ssl.trustStorePassword")) {
    sslcontext.setTrustStorePassword
        (System.getProperty("javax.net.ssl.trustStorePassword"));
  }
  sslcontext.setNeedClientAuth(Boolean.getBoolean("tests.jettySsl.clientAuth"));

  return sslcontext;
}
 
Example #14
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 #15
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 #16
Source File: AbstractJettyWebSocketService.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
protected SslContextFactory createSslFactory(final SSLContextService sslService, final boolean needClientAuth, final boolean wantClientAuth) {
    final SslContextFactory sslFactory = new SslContextFactory();

    sslFactory.setNeedClientAuth(needClientAuth);
    sslFactory.setWantClientAuth(wantClientAuth);

    if (sslService.isKeyStoreConfigured()) {
        sslFactory.setKeyStorePath(sslService.getKeyStoreFile());
        sslFactory.setKeyStorePassword(sslService.getKeyStorePassword());
        sslFactory.setKeyStoreType(sslService.getKeyStoreType());
    }

    if (sslService.isTrustStoreConfigured()) {
        sslFactory.setTrustStorePath(sslService.getTrustStoreFile());
        sslFactory.setTrustStorePassword(sslService.getTrustStorePassword());
        sslFactory.setTrustStoreType(sslService.getTrustStoreType());
    }

    return sslFactory;
}
 
Example #17
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 #18
Source File: JettyWebSocketServer.java    From nifi with Apache License 2.0 6 votes vote down vote up
private SslContextFactory createSslFactory(final ConfigurationContext context) {
    final SSLContextService sslService = context.getProperty(SSL_CONTEXT).asControllerService(SSLContextService.class);

    final String clientAuthValue = context.getProperty(CLIENT_AUTH).getValue();
    final boolean need;
    final boolean want;
    if (CLIENT_NEED.equals(clientAuthValue)) {
        need = true;
        want = false;
    } else if (CLIENT_WANT.equals(clientAuthValue)) {
        need = false;
        want = true;
    } else {
        need = false;
        want = false;
    }

    final SslContextFactory sslFactory = (sslService == null) ? null : createSslFactory(sslService, need, want, null);
    return sslFactory;
}
 
Example #19
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 #20
Source File: TestWebServicesFetcher.java    From datacollector with Apache License 2.0 6 votes vote down vote up
protected Server createServer(int port, boolean serverSsl, boolean clientSsl) {
  Server server = new Server();
  if (!serverSsl) {
    InetSocketAddress addr = new InetSocketAddress("localhost", port);
    ServerConnector connector = new ServerConnector(server);
    connector.setHost(addr.getHostName());
    connector.setPort(addr.getPort());
    server.setConnectors(new Connector[]{connector});
  } else {
    SslContextFactory sslContextFactory = createSslContextFactory(clientSsl);
    ServerConnector httpsConnector = new ServerConnector(server,
        new SslConnectionFactory(sslContextFactory, "http/1.1"),
        new HttpConnectionFactory()
    );
    httpsConnector.setPort(port);
    httpsConnector.setHost("localhost");
    server.setConnectors(new Connector[]{httpsConnector});
  }
  return server;
}
 
Example #21
Source File: AggregatorApplication.java    From ambari-metrics with Apache License 2.0 6 votes vote down vote up
protected HttpServer createHttpServer() throws Exception {
  ResourceConfig resourceConfig = new PackagesResourceConfig("org.apache.hadoop.metrics2.host.aggregator");
  HashMap<String, Object> params = new HashMap();
  params.put("com.sun.jersey.api.json.POJOMappingFeature", "true");
  resourceConfig.setPropertiesAndFeatures(params);
  HttpServer server = HttpServerFactory.create(getURI(), resourceConfig);

  if (webServerProtocol.equalsIgnoreCase("https")) {
    HttpsServer httpsServer = (HttpsServer) server;
    SslContextFactory sslContextFactory = new SslContextFactory();
    String keyStorePath = configuration.get("ssl.server.keystore.location");
    String keyStorePassword = configuration.get("ssl.server.keystore.password");
    String keyManagerPassword = configuration.get("ssl.server.keystore.keypassword");
    String trustStorePath = configuration.get("ssl.server.truststore.location");
    String trustStorePassword = configuration.get("ssl.server.truststore.password");

    sslContextFactory.setKeyStorePath(keyStorePath);
    sslContextFactory.setKeyStorePassword(keyStorePassword);
    sslContextFactory.setKeyManagerPassword(keyManagerPassword);
    sslContextFactory.setTrustStorePath(trustStorePath);
    sslContextFactory.setTrustStorePassword(trustStorePassword);

    sslContextFactory.start();
    SSLContext sslContext = sslContextFactory.getSslContext();
    sslContextFactory.stop();
    HttpsConfigurator httpsConfigurator = new HttpsConfigurator(sslContext);
    httpsServer.setHttpsConfigurator(httpsConfigurator);
    server = httpsServer;
  }
  return server;
}
 
Example #22
Source File: FritzahaWebInterface.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Constructor to set up interface
 * 
 * @param host
 *            Hostname/IP address of Fritzbox
 * @param port
 *            Port to use for Fritzbox connection
 * @param protocol
 *            Protocol to use (HTTP,HTTPS)
 * @param username
 *            Username for login
 * @param password
 *            Password for login
 * @param synctimeout
 *            Timeout for synchronous http-connections
 * @param asynctimeout
 *            Timeout for asynchronous http-connections
 */
public FritzahaWebInterface(String host, int port, String protocol, String username, String password,
        int synctimeout, int asynctimeout) {
    this.host = host;
    this.port = port;
    this.protocol = protocol;
    this.username = username;
    this.password = password;
    this.timeout = synctimeout;
    this.asynctimeout = asynctimeout;
    sid = null;
    asyncclient = new HttpClient(new SslContextFactory(true));
    asyncclient.setConnectorType(HttpClient.CONNECTOR_SELECT_CHANNEL);
    asyncclient.setMaxConnectionsPerAddress(asyncmaxconns);
    asyncclient.setTimeout(asynctimeout);
    try {
        asyncclient.start();
    } catch (Exception e) {
        logger.error("Could not start HTTP Client for " + getURL(""));
    }
    authenticate();
    logger.debug("Starting with SID " + sid);
}
 
Example #23
Source File: HelixRestServer.java    From helix with Apache License 2.0 6 votes vote down vote up
public void setupSslServer(int port, SslContextFactory sslContextFactory) {
  if (_server != null && port > 0) {
    try {
      HttpConfiguration https = new HttpConfiguration();
      https.addCustomizer(new SecureRequestCustomizer());
      ServerConnector sslConnector = new ServerConnector(
          _server,
          new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
          new HttpConnectionFactory(https));
      sslConnector.setPort(port);

      _server.addConnector(sslConnector);

      LOG.info("Helix SSL rest server is ready to start.");
    } catch (Exception ex) {
      LOG.error("Failed to setup Helix SSL rest server, " + ex);
    }
  }
}
 
Example #24
Source File: HttpOperatorFactory.java    From digdag with Apache License 2.0 6 votes vote down vote up
HttpClient client()
{
    boolean insecure = params.get("insecure", boolean.class, false);

    HttpClient httpClient = new HttpClient(new SslContextFactory(insecure));

    configureProxy(httpClient);

    boolean followRedirects = params.get("follow_redirects", boolean.class, true);

    httpClient.setFollowRedirects(followRedirects);
    httpClient.setMaxRedirects(maxRedirects);

    httpClient.setUserAgentField(new HttpField(
            USER_AGENT, userAgent + ' ' + httpClient.getUserAgentField().getValue()));

    try {
        httpClient.start();
    }
    catch (Exception e) {
        throw new TaskExecutionException(e);
    }
    return httpClient;
}
 
Example #25
Source File: JettyServerTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testConfigureSslContextFactoryWithKeystorePasswordAndKeyPassword() {
    // Expect that if we set both passwords, KeyStore password is used for KeyStore, Key password is used for Key Manager
    String testKeystorePassword = "testKeystorePassword";
    String testKeyPassword = "testKeyPassword";

    final Map<String, String> addProps = new HashMap<>();
    addProps.put(NiFiProperties.SECURITY_KEYSTORE_PASSWD, testKeystorePassword);
    addProps.put(NiFiProperties.SECURITY_KEY_PASSWD, testKeyPassword);
    NiFiProperties nifiProperties = NiFiProperties.createBasicNiFiProperties(null, addProps);
    SslContextFactory contextFactory = mock(SslContextFactory.class);

    JettyServer.configureSslContextFactory(contextFactory, nifiProperties);

    verify(contextFactory).setKeyStorePassword(testKeystorePassword);
    verify(contextFactory).setKeyManagerPassword(testKeyPassword);
}
 
Example #26
Source File: LogSearchWebServerCustomizer.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void customize(JettyServletWebServerFactory webServerFactory) {
  serverProperties.getServlet().getSession().setTimeout(Duration.ofMinutes(logSearchHttpConfig.getSessionTimeout()));
  serverProperties.getServlet().getSession().getCookie().setName(LOGSEARCH_SESSION_ID);

  if ("https".equals(logSearchHttpConfig.getProtocol())) {
    sslConfigurer.ensureStorePasswords();
    sslConfigurer.loadKeystore();
    webServerFactory.addServerCustomizers((JettyServerCustomizer) server -> {
      SslContextFactory sslContextFactory = sslConfigurer.getSslContextFactory();
      ServerConnector sslConnector = new ServerConnector(server, sslContextFactory);
      sslConnector.setPort(logSearchHttpConfig.getHttpsPort());
      server.setConnectors(new Connector[]{sslConnector});
    });
  } else {
    webServerFactory.setPort(logSearchHttpConfig.getHttpPort());
  }
  if (logSearchHttpConfig.isUseAccessLogs()) {
    webServerFactory.addServerCustomizers((JettyServerCustomizer) server -> {
      LoggerContext context = (LoggerContext) LogManager.getContext(false);
      Configuration configuration = context.getConfiguration();
      String logDir = configuration.getStrSubstitutor().getVariableResolver().lookup("log-path");
      String logFileNameSuffix = "logsearch-jetty-yyyy_mm_dd.request.log";
      String logFileName = logDir == null ? logFileNameSuffix : Paths.get(logDir, logFileNameSuffix).toString();
      NCSARequestLog requestLog = new NCSARequestLog(logFileName);
      requestLog.setAppend(true);
      requestLog.setExtended(false);
      requestLog.setLogTimeZone("GMT");
      server.setRequestLog(requestLog);
    });
  }
}
 
Example #27
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 #28
Source File: WebSocketTransport.java    From signalfx-java with Apache License 2.0 5 votes vote down vote up
protected WebSocketTransport(String token, SignalFxEndpoint endpoint, int apiVersion,
                             int timeout, boolean compress, int maxBinaryMessageSize) {
    this.token = token;
    this.endpoint = endpoint;
    this.path = "/v" + apiVersion + "/signalflow/connect";
    this.timeout = timeout;
    this.compress = compress;

    try {
        this.transportConnection = new TransportConnection(token);
        URI uri = new URIBuilder(String.format("%s://%s:%s%s", endpoint.getScheme(),
                endpoint.getHostname(), endpoint.getPort(), path)).build();

        this.webSocketClient = new WebSocketClient(new SslContextFactory());
        if (maxBinaryMessageSize > 0) {
            this.webSocketClient.getPolicy().setMaxBinaryMessageSize(maxBinaryMessageSize);
        }
        if (timeout > 0) {
            this.webSocketClient.setConnectTimeout(TimeUnit.SECONDS.toMillis(timeout));
        }
        this.webSocketClient.start();
        this.webSocketClient.connect(this.transportConnection, uri);
        this.transportConnection.awaitConnected(timeout, TimeUnit.SECONDS);
    } catch (Exception ex) {
        if (this.webSocketClient != null) {
            try {
                this.webSocketClient.stop();
            } catch (Exception e) {
                log.warn("error closing websocket client", e);
            }
        }
        throw new SignalFlowException("failed to construct websocket transport", ex);
    }
}
 
Example #29
Source File: SslConfigurer.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
public SslContextFactory getSslContextFactory() {
  SslContextFactory sslContextFactory = new SslContextFactory();
  sslContextFactory.setKeyStorePath(getKeyStoreLocation());
  sslContextFactory.setKeyStorePassword(getKeyStorePassword());
  sslContextFactory.setKeyStoreType(getKeyStoreType());
  if (isTrustStoreSpecified()) {
    sslContextFactory.setTrustStorePath(getTrustStoreLocation());
    sslContextFactory.setTrustStorePassword(getTrustStorePassword());
    sslContextFactory.setTrustStoreType(getTrustStoreType());
  }
  
  return sslContextFactory;
}
 
Example #30
Source File: WebSocketClient.java    From codenjoy with GNU General Public License v3.0 5 votes vote down vote up
private org.eclipse.jetty.websocket.client.WebSocketClient createClient() {
    if (UrlParser.WSS_PROTOCOL.equals(uri.getScheme())) {
        SslContextFactory ssl = new SslContextFactory(true);
        ssl.setValidateCerts(false);
        return new org.eclipse.jetty.websocket.client.WebSocketClient(ssl);
    }

    if (UrlParser.WS_PROTOCOL.equals(uri.getScheme())) {
        return new org.eclipse.jetty.websocket.client.WebSocketClient();
    }

    throw new UnsupportedOperationException("Unsupported WebSocket protocol: " + uri.getScheme());
}