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

The following examples show how to use org.eclipse.jetty.util.ssl.SslContextFactory#setKeyManagerPassword() . 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: SSLUtils.java    From kop with Apache License 2.0 6 votes vote down vote up
/**
 * Configures KeyStore related settings in SslContextFactory.
 */
protected static void configureSslContextFactoryKeyStore(SslContextFactory ssl,
                                                         Map<String, Object> sslConfigValues) {
    ssl.setKeyStoreType((String)
        getOrDefault(sslConfigValues, SslConfigs.SSL_KEYSTORE_TYPE_CONFIG, SslConfigs.DEFAULT_SSL_KEYSTORE_TYPE));

    String sslKeystoreLocation = (String) sslConfigValues.get(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG);
    if (sslKeystoreLocation != null) {
        ssl.setKeyStorePath(sslKeystoreLocation);
    }

    Password sslKeystorePassword =
        new Password((String) sslConfigValues.get(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG));
    if (sslKeystorePassword != null) {
        ssl.setKeyStorePassword(sslKeystorePassword.value());
    }

    Password sslKeyPassword =
        new Password((String) sslConfigValues.get(SslConfigs.SSL_KEY_PASSWORD_CONFIG));
    if (sslKeyPassword != null) {
        ssl.setKeyManagerPassword(sslKeyPassword.value());
    }
}
 
Example 2
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 3
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 4
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 5
Source File: JettySeverTools.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
protected static void addHttpsConnector(Server server, Integer port) throws Exception {
	SslContextFactory sslContextFactory = new SslContextFactory();
	sslContextFactory.setKeyStorePath(Config.sslKeyStore().getAbsolutePath());
	sslContextFactory.setKeyStorePassword(Config.token().getSslKeyStorePassword());
	sslContextFactory.setKeyManagerPassword(Config.token().getSslKeyManagerPassword());
	sslContextFactory.setTrustAll(true);
	HttpConfiguration config = new HttpConfiguration();
	config.setSecureScheme("https");
	config.setOutputBufferSize(32768);
	config.setRequestHeaderSize(8192 * 2);
	config.setResponseHeaderSize(8192 * 2);
	config.setSendServerVersion(true);
	config.setSendDateHeader(false);
	ServerConnector sslConnector = new ServerConnector(server,
			new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
			new HttpConnectionFactory(config));
	sslConnector.setPort(port);
	server.addConnector(sslConnector);
}
 
Example 6
Source File: EventServer.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 6 votes vote down vote up
private SslConnectionFactory getSSLConnectionFactory() {
    Resource keyStoreResource = null;
    try {
        keyStoreResource = Resource.newClassPathResource("localhost");
        System.out.println(keyStoreResource);
    } catch (Exception ex) {
        Logger.getLogger(EventServer.class.getName()).log(Level.SEVERE, null, ex);
    }

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStoreResource(keyStoreResource);
    String secret = readresource();
    sslContextFactory.setKeyStorePassword(Encrypt.getInstance().decrypt(secret));
    sslContextFactory.setKeyManagerPassword(Encrypt.getInstance().decrypt(secret));
    return new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString());
}
 
Example 7
Source File: JettyHttpsServer.java    From sumk with Apache License 2.0 5 votes vote down vote up
@Override
protected ConnectionFactory[] getConnectionFactorys() throws URISyntaxException {
	@SuppressWarnings("deprecation")
	SslContextFactory sslContextFactory = new SslContextFactory();
	String path = get(HttpPlugin.KEY_STORE_PATH);
	File keystoreFile = FileUtil.file(path);
	if (!keystoreFile.exists()) {
		String msg = path + " is not exist";
		Logs.http().error(msg);
		SumkException.throwException(-2345345, msg);
	}
	sslContextFactory.setKeyStorePath(keystoreFile.getAbsolutePath());
	sslContextFactory.setKeyStorePassword(get("sumk.jetty.ssl.storePassword"));
	sslContextFactory.setKeyManagerPassword(get("sumk.jetty.ssl.managerPassword"));
	sslContextFactory.setCertAlias(get("sumk.jetty.ssl.alias"));

	String v = AppInfo.get("sumk.jetty.ssl.storeType", null);
	if (v != null) {
		sslContextFactory.setKeyStoreType(v);
	}

	sslContextFactory.setTrustAll(AppInfo.getBoolean("sumk.jetty.ssl.trustAll", false));

	Logs.http().info("using https");
	return new ConnectionFactory[] { new SslConnectionFactory(sslContextFactory, "http/1.1"),
			new HttpConnectionFactory() };
}
 
Example 8
Source File: SecureEmbeddedServer.java    From atlas with Apache License 2.0 4 votes vote down vote up
@Override
protected Connector getConnector(String host, int port) throws IOException {
    org.apache.commons.configuration.Configuration config = getConfiguration();

    SSLContext sslContext = getSSLContext();
    if (sslContext != null) {
        SSLContext.setDefault(sslContext);
    }

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(config.getString(KEYSTORE_FILE_KEY,
            System.getProperty(KEYSTORE_FILE_KEY, DEFAULT_KEYSTORE_FILE_LOCATION)));
    sslContextFactory.setKeyStorePassword(getPassword(config, KEYSTORE_PASSWORD_KEY));
    sslContextFactory.setKeyManagerPassword(getPassword(config, SERVER_CERT_PASSWORD_KEY));
    sslContextFactory.setTrustStorePath(config.getString(TRUSTSTORE_FILE_KEY,
            System.getProperty(TRUSTSTORE_FILE_KEY, DEFATULT_TRUSTORE_FILE_LOCATION)));
    sslContextFactory.setTrustStorePassword(getPassword(config, TRUSTSTORE_PASSWORD_KEY));
    sslContextFactory.setWantClientAuth(config.getBoolean(CLIENT_AUTH_KEY, Boolean.getBoolean(CLIENT_AUTH_KEY)));

    List<Object> cipherList = config.getList(ATLAS_SSL_EXCLUDE_CIPHER_SUITES, DEFAULT_CIPHER_SUITES);
    sslContextFactory.setExcludeCipherSuites(cipherList.toArray(new String[cipherList.size()]));
    sslContextFactory.setRenegotiationAllowed(false);

    String[] excludedProtocols = config.containsKey(ATLAS_SSL_EXCLUDE_PROTOCOLS) ?
            config.getStringArray(ATLAS_SSL_EXCLUDE_PROTOCOLS) : DEFAULT_EXCLUDE_PROTOCOLS;
    if (excludedProtocols != null && excludedProtocols.length > 0) {
        sslContextFactory.addExcludeProtocols(excludedProtocols);
    }

    // SSL HTTP Configuration
    // HTTP Configuration
    HttpConfiguration http_config = new HttpConfiguration();
    http_config.setSecureScheme("https");
    final int bufferSize = AtlasConfiguration.WEBSERVER_REQUEST_BUFFER_SIZE.getInt();
    http_config.setSecurePort(port);
    http_config.setRequestHeaderSize(bufferSize);
    http_config.setResponseHeaderSize(bufferSize);
    http_config.setSendServerVersion(true);
    http_config.setSendDateHeader(false);

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

    // SSL Connector
    ServerConnector sslConnector = new ServerConnector(server,
        new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
        new HttpConnectionFactory(https_config));
    sslConnector.setPort(port);
    server.addConnector(sslConnector);

    return sslConnector;
}
 
Example 9
Source File: PHttpServer.java    From jphp with Apache License 2.0 4 votes vote down vote up
@Signature
public void listen(Memory value, ArrayMemory sslSettings) {
    ServerConnector connector;

    if (sslSettings != null) {
        SslContextFactory contextFactory = new SslContextFactory();

        // key store
        if (sslSettings.containsKey("keyStorePath"))
            contextFactory.setKeyStorePath(sslSettings.valueOfIndex("keyStorePath").toString());

        if (sslSettings.containsKey("keyStorePassword"))
            contextFactory.setKeyStoreType(sslSettings.valueOfIndex("keyStorePassword").toString());

        if (sslSettings.containsKey("keyStoreType"))
            contextFactory.setKeyStoreType(sslSettings.valueOfIndex("keyStoreType").toString());

        if (sslSettings.containsKey("keyStoreProvider"))
            contextFactory.setKeyStoreProvider(sslSettings.valueOfIndex("keyStoreProvider").toString());

        // trust store
        if (sslSettings.containsKey("trustStorePath"))
            contextFactory.setTrustStorePath(sslSettings.valueOfIndex("trustStorePath").toString());

        if (sslSettings.containsKey("trustStorePassword"))
            contextFactory.setTrustStoreType(sslSettings.valueOfIndex("trustStorePassword").toString());

        if (sslSettings.containsKey("trustStoreType"))
            contextFactory.setTrustStoreType(sslSettings.valueOfIndex("trustStoreType").toString());

        if (sslSettings.containsKey("trustStoreProvider"))
            contextFactory.setTrustStoreProvider(sslSettings.valueOfIndex("trustStoreProvider").toString());

        if (sslSettings.containsKey("trustAll"))
            contextFactory.setTrustAll(sslSettings.valueOfIndex("trustAll").toBoolean());

        if (sslSettings.containsKey("trustManagerFactoryAlgorithm"))
            contextFactory.setTrustManagerFactoryAlgorithm(sslSettings.valueOfIndex("trustManagerFactoryAlgorithm").toString());

        // key manager
        if (sslSettings.containsKey("keyManagerFactoryAlgorithm"))
            contextFactory.setKeyManagerFactoryAlgorithm(sslSettings.valueOfIndex("keyManagerFactoryAlgorithm").toString());

        if (sslSettings.containsKey("keyManagerPassword"))
            contextFactory.setKeyManagerPassword(sslSettings.valueOfIndex("keyManagerPassword").toString());

        // other
        if (sslSettings.containsKey("certAlias"))
            contextFactory.setCertAlias(sslSettings.valueOfIndex("certAlias").toString());

        if (sslSettings.containsKey("protocol"))
            contextFactory.setProtocol(sslSettings.valueOfIndex("protocol").toString());

        if (sslSettings.containsKey("provider"))
            contextFactory.setProvider(sslSettings.valueOfIndex("provider").toString());

        if (sslSettings.containsKey("validateCerts"))
            contextFactory.setValidateCerts(sslSettings.valueOfIndex("validateCerts").toBoolean());

        connector = new ServerConnector(server, contextFactory);
    } else {
        connector = new ServerConnector(server);
    }

    if (value.isNumber()) {
        connector.setName("0.0.0.0:" + value.toInteger());
        connector.setPort(value.toInteger());
    } else {
        String[] strings = value.toString().split("\\:");

        if (strings.length < 2) {
            throw new IllegalArgumentException("Invalid listen value: " + value);
        }

        connector.setHost(strings[0]);
        connector.setPort(Integer.parseInt(strings[1]));
        connector.setName(strings[0] + ":" + strings[1]);
    }

    server.addConnector(connector);
}
 
Example 10
Source File: StandardTLSTest.java    From apiman with Apache License 2.0 4 votes vote down vote up
@Before
public void setupJetty() throws Exception {
    server = new Server();
    server.setStopAtShutdown(true);

    http_config = new HttpConfiguration();
    http_config.setSecureScheme("https");

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setTrustStorePath(getResourcePath("2waytest/mutual_trust_via_ca/common_ts.jks"));
    sslContextFactory.setTrustStorePassword("password");
    sslContextFactory.setKeyStorePath(getResourcePath("2waytest/mutual_trust_via_ca/service_ks.jks"));
    sslContextFactory.setKeyStorePassword("password");
    sslContextFactory.setKeyManagerPassword("password");
    // Use default trust store
    // No client auth
    sslContextFactory.setNeedClientAuth(false);
    sslContextFactory.setWantClientAuth(false);

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

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

    server.addConnector(sslConnector);
    // Thanks to Jetty getting started guide.
    server.setHandler(new AbstractHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {

            Enumeration<String> z = request.getAttributeNames();

            while (z.hasMoreElements()) {
                String elem = z.nextElement();
                System.out.println(elem + " - " + request.getAttribute(elem));
            }

            response.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
            response.getWriter().println("apiman");
        }
    });
    server.start();
}
 
Example 11
Source File: CipherAndProtocolSelectionTest.java    From apiman with Apache License 2.0 4 votes vote down vote up
@Before
public void setupJetty() throws Exception {
    server = new Server();
    server.setStopAtShutdown(true);

    http_config = new HttpConfiguration();
    http_config.setSecureScheme("https");

    jettySslContextFactory = new SslContextFactory();
    jettySslContextFactory.setTrustStorePath(getResourcePath("2waytest/mutual_trust_via_ca/common_ts.jks"));
    jettySslContextFactory.setTrustStorePassword("password");
    jettySslContextFactory.setKeyStorePath(getResourcePath("2waytest/mutual_trust_via_ca/service_ks.jks"));
    jettySslContextFactory.setKeyStorePassword("password");
    jettySslContextFactory.setKeyManagerPassword("password");
    // Use default trust store
    // No client auth
    jettySslContextFactory.setNeedClientAuth(false);
    jettySslContextFactory.setWantClientAuth(false);

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

    ServerConnector sslConnector = new ServerConnector(server,
        new SslConnectionFactory(jettySslContextFactory,"http/1.1"),
        new HttpConnectionFactory(https_config));
    sslConnector.setPort(8008);

    server.addConnector(sslConnector);
    // Thanks to Jetty getting started guide.
    server.setHandler(new AbstractHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {

            jettyRequestAttributes = new HashMap<>();
            Enumeration<String> requestAttrNames = request.getAttributeNames();

            while (requestAttrNames.hasMoreElements()) {
                String elem = requestAttrNames.nextElement();
                jettyRequestAttributes.put(elem, request.getAttribute(elem).toString());
                System.out.println(elem + " - " + request.getAttribute(elem).toString());
            }

            response.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
            response.getWriter().println("apiman");
        }
    });
}
 
Example 12
Source File: JettyServerWrapper.java    From cougar with Apache License 2.0 4 votes vote down vote up
public void initialiseConnectors() throws Exception {
    threadPool = new QueuedThreadPool();
    threadPool.setMaxThreads(maxThreads);
    threadPool.setMinThreads(minThreads);
    threadPool.setName("JettyThread");
    jettyServer = new Server(threadPool);

    jettyServer.setStopAtShutdown(true);

    MBeanContainer container = new MBeanContainer(mbeanServer);
    jettyServer.addBean(container);

    LowResourceMonitor lowResourcesMonitor = new LowResourceMonitor(jettyServer);
    lowResourcesMonitor.setPeriod(lowResourcesPeriod);
    lowResourcesMonitor.setLowResourcesIdleTimeout(lowResourcesIdleTime);
    lowResourcesMonitor.setMonitorThreads(lowResourcesMonitorThreads);
    lowResourcesMonitor.setMaxConnections(lowResourcesMaxConnections);
    lowResourcesMonitor.setMaxMemory(lowResourcesMaxMemory);
    lowResourcesMonitor.setMaxLowResourcesTime(lowResourcesMaxTime);
    jettyServer.addBean(lowResourcesMonitor);

    // US24803 - Needed for preventing Hashtable key collision DoS CVE-2012-2739
    jettyServer.setAttribute("org.eclipse.jetty.server.Request.maxFormContentSize", maxFormContentSize);

    List<Connector> connectors = new ArrayList<Connector>();

    if (httpPort != -1) {
        httpConfiguration = createHttpConfiguration();
        setBufferSizes(httpConfiguration);
        if (httpForwarded) {
            httpConfiguration.addCustomizer(new ForwardedRequestCustomizer());
        }
        httpConnector = createHttpConnector(jettyServer, httpConfiguration, httpAcceptors, httpSelectors);
        httpConnector.setPort(httpPort);
        httpConnector.setReuseAddress(httpReuseAddress);
        httpConnector.setIdleTimeout(httpMaxIdle);
        httpConnector.setAcceptQueueSize(httpAcceptQueueSize);
        httpConnector.addBean(new ConnectorStatistics());

        connectors.add(httpConnector);
    }

    if (httpsPort != -1) {
        SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setKeyStorePath(httpsKeystore.getFile().getCanonicalPath());
        sslContextFactory.setKeyStoreType(httpsKeystoreType);
        sslContextFactory.setKeyStorePassword(httpsKeyPassword);
        if (StringUtils.isNotBlank(httpsCertAlias)) {
            sslContextFactory.setCertAlias(httpsCertAlias);
        }
        sslContextFactory.setKeyManagerPassword(httpsKeyPassword);
        // if you need it then you defo want it
        sslContextFactory.setWantClientAuth(httpsNeedClientAuth || httpsWantClientAuth);
        sslContextFactory.setNeedClientAuth(httpsNeedClientAuth);
        sslContextFactory.setRenegotiationAllowed(httpsAllowRenegotiate);

        httpsConfiguration = createHttpConfiguration();
        setBufferSizes(httpsConfiguration);
        if (httpsForwarded) {
            httpsConfiguration.addCustomizer(new ForwardedRequestCustomizer());
        }

        httpsConnector = createHttpsConnector(jettyServer, httpsConfiguration, httpsAcceptors, httpsSelectors, sslContextFactory);
        httpsConnector.setPort(httpsPort);
        httpsConnector.setReuseAddress(httpsReuseAddress);
        httpsConnector.setIdleTimeout(httpsMaxIdle);
        httpsConnector.setAcceptQueueSize(httpsAcceptQueueSize);
        httpsConnector.addBean(new ConnectorStatistics());

        mbeanServer.registerMBean(getKeystoreCertificateChains(), new ObjectName("CoUGAR.https:name=keyStore"));
        // truststore is not required if we don't want client auth
        if (httpsWantClientAuth) {
            sslContextFactory.setTrustStorePath(httpsTruststore.getFile().getCanonicalPath());
            sslContextFactory.setTrustStoreType(httpsTruststoreType);
            sslContextFactory.setTrustStorePassword(httpsTrustPassword);
            mbeanServer.registerMBean(getTruststoreCertificateChains(), new ObjectName("CoUGAR.https:name=trustStore"));
        }
        connectors.add(httpsConnector);
    }

    if (connectors.size() == 0) {
        throw new IllegalStateException("HTTP transport requires at least one port enabled to function correctly.");
    }

    jettyServer.setConnectors(connectors.toArray(new Connector[connectors.size()]));
}
 
Example 13
Source File: TestSdcIpcTarget.java    From datacollector with Apache License 2.0 4 votes vote down vote up
private void testHttps(boolean hostVerification) throws Exception {
  String hostname = (hostVerification) ? TLSTestUtils.getHostname() : "localhost";

  File testDir = new File("target", UUID.randomUUID().toString()).getAbsoluteFile();
  Assert.assertTrue(testDir.mkdirs());
  KeyPair keyPair = TLSTestUtils.generateKeyPair();
  Certificate cert = TLSTestUtils.generateCertificate("CN=" + hostname, keyPair, 30);
  File keyStore = new File(testDir, "keystore.jks");
  TLSTestUtils.createKeyStore(keyStore.toString(), "keystore", "web", keyPair.getPrivate(), cert);
  File trustStore = new File(testDir, "truststore.jks");
  TLSTestUtils.createTrustStore(trustStore.toString(), "truststore", "web", cert);

  Server server = new Server(0);
  ServletContextHandler context = new ServletContextHandler();
  context.addServlet(new ServletHolder(new ReceiverServlet()), Constants.IPC_PATH);
  context.setContextPath("/");
  server.setHandler(context);

  //Create a connector for HTTPS
  HttpConfiguration httpsConf = new HttpConfiguration();
  httpsConf.addCustomizer(new SecureRequestCustomizer());
  SslContextFactory sslContextFactory = new SslContextFactory();
  sslContextFactory.setKeyStorePath(keyStore.getPath());
  sslContextFactory.setKeyStorePassword("keystore");
  sslContextFactory.setKeyManagerPassword("keystore");
  ServerConnector httpsConnector = new ServerConnector(server,
                                                       new SslConnectionFactory(sslContextFactory, "http/1.1"),
                                                       new HttpConnectionFactory(httpsConf));
  httpsConnector.setPort(0);
  server.setConnectors(new Connector[]{httpsConnector});

  try {
    server.start();

    Configs config = new Configs();
    config.appId = () -> "appId";
    config.connectionTimeOutMs = 1000;
    config.readTimeOutMs = 2000;
    config.hostPorts = ImmutableList.of(hostname + ":" + server.getURI().getPort());
    config.retriesPerBatch = 2;
    config.tlsConfigBean.tlsEnabled = true;
    config.tlsConfigBean.trustStoreFilePath = trustStore.getName();
    config.tlsConfigBean.trustStorePassword = () -> "truststore";
    config.hostVerification = hostVerification;

    SdcIpcTarget target = new SdcIpcTarget(config);

    TargetRunner runner = new TargetRunner.Builder(SdcIpcDTarget.class, target)
        .setOnRecordError(OnRecordError.TO_ERROR).setResourcesDir(testDir.toString()).build();
    try {
      runner.runInit();
      List<Record> records = ImmutableList.of(RecordCreator.create(), RecordCreator.create());
      runner.runWrite(records);
      Assert.assertTrue(runner.getErrorRecords().isEmpty());
      Assert.assertTrue(runner.getErrors().isEmpty());
    } finally {
      runner.runDestroy();
    }

  } finally {
    server.stop();
  }
}
 
Example 14
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 15
Source File: RESTApp.java    From account-provisioning-for-google-apps with Apache License 2.0 4 votes vote down vote up
/**
 * Initializes the Jetty server.
 */
private void initJettyServer() {
  logger.log(Level.INFO, "Initialzing Jetty server...");
  int port;
  if (customPort == null) {
    logger.log(Level.INFO, "Initialzing server in default port: " + PORT_DEFAULT_VALUE);
    port = PORT_DEFAULT_VALUE;
  } else {
    logger.log(Level.INFO, "Initialzing server in custom port: " + customPort.toString());
    port = customPort;
  }
  jettyServer = new Server(port);

  ConfigData config = ProvisioningApp.getInstance().getContext().getConfig();
  if (config.getUseSSL()) {
    HttpConfiguration https = new HttpConfiguration();
    https.addCustomizer(new SecureRequestCustomizer());

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(config.getKeyStorePath());
    sslContextFactory.setKeyStorePassword(config.getKeyStorePassword());
    sslContextFactory.setKeyManagerPassword(config.getKeyManagerPassword());

    ServerConnector sslConnector =
        new ServerConnector(jettyServer,
            new SslConnectionFactory(sslContextFactory, HTTP_VERSION), new HttpConnectionFactory(
                https));
    sslConnector.setPort(port);

    jettyServer.setConnectors(new Connector[] {sslConnector});
  }

  jettyServer.setHandler(servletContext);

  try {
    jettyServer.start();
    jettyServer.join();
  } catch (Throwable e) {
    logger.log(Level.SEVERE, "Exception during server initialization", e);
    jettyServer.destroy();
  }
}
 
Example 16
Source File: Http2Server.java    From http2-examples with Apache License 2.0 4 votes vote down vote up
public static void main(String... args) throws Exception {
    Server server = new Server();

    ServletContextHandler context = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
    context.addServlet(new ServletHolder(new Servlet()), "/");
    server.setHandler(context);

    // HTTP Configuration
    HttpConfiguration http_config = new HttpConfiguration();
    http_config.setSecureScheme("https");
    http_config.setSecurePort(8443);

    // SSL Context Factory for HTTPS and HTTP/2
    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStoreResource(newClassPathResource("keystore"));
    sslContextFactory.setKeyStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4");
    sslContextFactory.setKeyManagerPassword("OBF:1u2u1wml1z7s1z7a1wnl1u2g");
    sslContextFactory.setCipherComparator(HTTP2Cipher.COMPARATOR);

    // HTTPS Configuration
    HttpConfiguration https_config = new HttpConfiguration(http_config);
    https_config.addCustomizer(new SecureRequestCustomizer());

    // HTTP/2 Connection Factory
    HTTP2ServerConnectionFactory h2 = new MyConnectionFactory(https_config);

    NegotiatingServerConnectionFactory.checkProtocolNegotiationAvailable();
    ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory();
    alpn.setDefaultProtocol("h2");

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

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

    ALPN.debug=false;

    server.start();
    server.join();
}
 
Example 17
Source File: BasicAuthTest.java    From apiman with Apache License 2.0 4 votes vote down vote up
/**
 * With thanks to assistance of http://stackoverflow.com/b/20056601/2766538
 * @throws Exception any exception
 */
@Before
public void setupJetty() throws Exception {
    ContextHandlerCollection handlers = new ContextHandlerCollection();

    ServletContextHandler sch = new ServletContextHandler(ServletContextHandler.SESSIONS);
    sch.setSecurityHandler(createSecurityHandler());
    sch.setContextPath("/echo");
    ServletHolder mockEchoServlet = new ServletHolder(new EchoServlet());
    sch.addServlet(mockEchoServlet, "/*");
    sch.addFilter(AuthenticationFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));

    handlers.addHandler(sch);

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setTrustStorePath(getResourcePath("common_ts.jks"));
    sslContextFactory.setTrustStorePassword("password");
    sslContextFactory.setKeyStorePath(getResourcePath("service_ks.jks"));
    sslContextFactory.setKeyStorePassword("password");
    sslContextFactory.setKeyManagerPassword("password");
    sslContextFactory.setNeedClientAuth(false);
    sslContextFactory.setWantClientAuth(false);

    // Create the server.
    int serverPort = 8008;
    server = new Server(serverPort);
    server.setStopAtShutdown(true);

    HttpConfiguration http_config = new HttpConfiguration();
    http_config.setSecureScheme("https");
    HttpConfiguration https_config = new HttpConfiguration(http_config);
    https_config.addCustomizer(new SecureRequestCustomizer());
    ServerConnector sslConnector = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory, "http/1.1"),
            new HttpConnectionFactory(https_config));
    sslConnector.setPort(8009);
    server.addConnector(sslConnector);

    server.setHandler(handlers);
    server.start();

    globalConfig.put(TLSOptions.TLS_DEVMODE, "true");
}
 
Example 18
Source File: BasicMutualAuthTest.java    From apiman with Apache License 2.0 4 votes vote down vote up
/**
 * With thanks to assistance of http://stackoverflow.com/b/20056601/2766538
 * @throws Exception any exception
 */
@Before
public void setupJetty() throws Exception {
    server = new Server();
    server.setStopAtShutdown(true);

    http_config = new HttpConfiguration();
    http_config.setSecureScheme("https");

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(getResourcePath("2waytest/basic_mutual_auth/service_ks.jks"));

    sslContextFactory.setKeyStorePassword("password");
    sslContextFactory.setKeyManagerPassword("password");
    sslContextFactory.setTrustStorePath(getResourcePath("2waytest/basic_mutual_auth/service_ts.jks"));
    sslContextFactory.setTrustStorePassword("password");
    sslContextFactory.setNeedClientAuth(true);

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

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

    server.addConnector(sslConnector);
    // Thanks to Jetty getting started guide.
    server.setHandler(new AbstractHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {

            Enumeration<String> z = request.getAttributeNames();

            while (z.hasMoreElements()) {
                String elem = z.nextElement();
                System.out.println(elem + " - " + request.getAttribute(elem));
            }

            if (request.getAttribute("javax.servlet.request.X509Certificate") != null) {
                clientSerial = ((java.security.cert.X509Certificate[]) request
                        .getAttribute("javax.servlet.request.X509Certificate"))[0].getSerialNumber();
            }

            response.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
            response.getWriter().println("apiman");
        }
    });
    server.start();
}
 
Example 19
Source File: HttpServerExtension.java    From kareldb with Apache License 2.0 4 votes vote down vote up
private static SslContextFactory createSslContextFactory(KarelDbConfig config) {
    SslContextFactory sslContextFactory = new SslContextFactory();
    if (!config.getString(KarelDbConfig.SSL_KEYSTORE_LOCATION_CONFIG).isEmpty()) {
        sslContextFactory.setKeyStorePath(
            config.getString(KarelDbConfig.SSL_KEYSTORE_LOCATION_CONFIG)
        );
        sslContextFactory.setKeyStorePassword(
            config.getPassword(KarelDbConfig.SSL_KEYSTORE_PASSWORD_CONFIG).value()
        );
        sslContextFactory.setKeyManagerPassword(
            config.getPassword(KarelDbConfig.SSL_KEY_PASSWORD_CONFIG).value()
        );
        sslContextFactory.setKeyStoreType(
            config.getString(KarelDbConfig.SSL_KEYSTORE_TYPE_CONFIG)
        );

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

    configureClientAuth(config, sslContextFactory);

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

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

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

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

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

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

    sslContextFactory.setRenegotiationAllowed(false);

    return sslContextFactory;
}
 
Example 20
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;
}