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

The following examples show how to use org.eclipse.jetty.util.ssl.SslContextFactory#setKeyStorePath() . 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: SubmarineServer.java    From submarine with Apache License 2.0 6 votes vote down vote up
private static SslContextFactory getSslContextFactory(SubmarineConfiguration conf) {
  SslContextFactory sslContextFactory = new SslContextFactory();

  // Set keystore
  sslContextFactory.setKeyStorePath(conf.getKeyStorePath());
  sslContextFactory.setKeyStoreType(conf.getKeyStoreType());
  sslContextFactory.setKeyStorePassword(conf.getKeyStorePassword());
  sslContextFactory.setKeyManagerPassword(conf.getKeyManagerPassword());

  if (conf.useClientAuth()) {
    sslContextFactory.setNeedClientAuth(conf.useClientAuth());

    // Set truststore
    sslContextFactory.setTrustStorePath(conf.getTrustStorePath());
    sslContextFactory.setTrustStoreType(conf.getTrustStoreType());
    sslContextFactory.setTrustStorePassword(conf.getTrustStorePassword());
  }

  return sslContextFactory;
}
 
Example 2
Source File: HttpTestUtil.java    From gocd with Apache License 2.0 6 votes vote down vote up
public void httpsConnector(final int port) {
	HttpConfiguration httpsConfig = new HttpConfiguration();
	httpsConfig.setOutputBufferSize(RESPONSE_BUFFER_SIZE); // 32 MB
	httpsConfig.addCustomizer(new SecureRequestCustomizer());

	SslContextFactory sslContextFactory = new SslContextFactory();
	sslContextFactory.setKeyStorePath(serverKeyStore.getAbsolutePath());
	sslContextFactory.setKeyStorePassword(STORE_PASSWORD);
	sslContextFactory.setKeyManagerPassword(STORE_PASSWORD);
	sslContextFactory.setWantClientAuth(true);

	ServerConnector https = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(httpsConfig));
	// https.setHost(host);
	https.setPort(port);
	https.setIdleTimeout(MAX_IDLE_TIME);

	server.addConnector(https);
}
 
Example 3
Source File: HandleHttpRequest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private 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 4
Source File: App.java    From schedge with MIT License 5 votes vote down vote up
private static SslContextFactory getSslContextFactory() {
  SslContextFactory sslContextFactory = new SslContextFactory.Server();
  URL resource = Utils.class.getResource("/keystore.jks");
  if (resource == null) {
    logger.info("Couldn't find keystore at src/main/resources/keystore.jks");
    return null;
  } else {
    logger.info("Using keystore for HTTPS");
  }

  sslContextFactory.setKeyStorePath(resource.toExternalForm());
  sslContextFactory.setKeyStorePassword("password");
  return sslContextFactory;
}
 
Example 5
Source File: RestChangeIngestor.java    From nifi-minifi with Apache License 2.0 5 votes vote down vote up
private void createSecureConnector(Properties properties) {
    SslContextFactory ssl = new SslContextFactory();

    if (properties.getProperty(KEYSTORE_LOCATION_KEY) != null) {
        ssl.setKeyStorePath(properties.getProperty(KEYSTORE_LOCATION_KEY));
        ssl.setKeyStorePassword(properties.getProperty(KEYSTORE_PASSWORD_KEY));
        ssl.setKeyStoreType(properties.getProperty(KEYSTORE_TYPE_KEY));
    }

    if (properties.getProperty(TRUSTSTORE_LOCATION_KEY) != null) {
        ssl.setTrustStorePath(properties.getProperty(TRUSTSTORE_LOCATION_KEY));
        ssl.setTrustStorePassword(properties.getProperty(TRUSTSTORE_PASSWORD_KEY));
        ssl.setTrustStoreType(properties.getProperty(TRUSTSTORE_TYPE_KEY));
        ssl.setNeedClientAuth(Boolean.parseBoolean(properties.getProperty(NEED_CLIENT_AUTH_KEY, "true")));
    }

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

    // set host and port
    https.setPort(Integer.parseInt(properties.getProperty(PORT_KEY, "0")));
    https.setHost(properties.getProperty(HOST_KEY, "localhost"));

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

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

    logger.info("Added an https connector on the host '{}' and port '{}'", new Object[]{https.getHost(), https.getPort()});
}
 
Example 6
Source File: HandleHttpRequest.java    From nifi with Apache License 2.0 5 votes vote down vote up
private SslContextFactory createSslFactory(final SSLContextService sslService, final boolean needClientAuth, final boolean wantClientAuth) {
    final SslContextFactory sslFactory = new SslContextFactory();

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

    sslFactory.setProtocol(sslService.getSslAlgorithm());

    // 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.
    sslFactory.setEndpointIdentificationAlgorithm(null);

    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 7
Source File: ResourcesHttpsConnectorFactory.java    From keywhiz with Apache License 2.0 5 votes vote down vote up
@Override protected SslContextFactory configureSslContextFactory(SslContextFactory factory) {
  factory = super.configureSslContextFactory(factory);
  factory.setKeyStorePath(resolveResource(super.getKeyStorePath()));
  factory.setTrustStorePath(resolveResource(super.getTrustStorePath()));
  factory.setCrlPath(resolveResource(getCrlPath().getName()));
  return factory;
}
 
Example 8
Source File: ExchangeSocketServer.java    From conga with Apache License 2.0 5 votes vote down vote up
public void init() {

    // connector configuration
    SslContextFactory sslContextFactory = new SslContextFactory();
    if (null != keyStorePath) {
      sslContextFactory.setKeyStorePath(keyStorePath);
    }
    if (null != keyStorePassword) {
      sslContextFactory.setKeyStorePassword(keyStorePassword);
    }
    if (null != keyManagerPassword) {
      sslContextFactory.setKeyManagerPassword(keyManagerPassword);
    }
    SslConnectionFactory sslConnectionFactory =
        new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString());
    HttpConnectionFactory httpConnectionFactory =
        new HttpConnectionFactory(new HttpConfiguration());
    ServerConnector sslConnector =
        new ServerConnector(server, sslConnectionFactory, httpConnectionFactory);
    sslConnector.setHost(host);
    sslConnector.setPort(port);
    server.addConnector(sslConnector);

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    ServletHolder servletHolder = new ServletHolder(new ExchangeServlet(sessions, ringBuffer));
    context.addServlet(servletHolder, "/trade/*");
    // context.addServlet(DefaultServlet.class, "/");
    server.setHandler(context);
  }
 
Example 9
Source File: WebSocketServerEcho.java    From quarks with Apache License 2.0 5 votes vote down vote up
private Server createServer(URI endpointURI, boolean needClientAuth) {
    if ("ws".equals(endpointURI.getScheme())) {
        return new Server(endpointURI.getPort());
    }
    else if ("wss".equals(endpointURI.getScheme())) {
        // see http://git.eclipse.org/c/jetty/org.eclipse.jetty.project.git/tree/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyConnectors.java
        //     http://git.eclipse.org/c/jetty/org.eclipse.jetty.project.git/tree/examples/embedded/src/main/java/org/eclipse/jetty/embedded/LikeJettyXml.java
        
        Server server = new Server();
        
        SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setKeyStorePath(getStorePath("serverKeyStore.jks"));
        sslContextFactory.setKeyStorePassword("passw0rd");
        sslContextFactory.setKeyManagerPassword("passw0rd");
        sslContextFactory.setCertAlias("default");
        sslContextFactory.setNeedClientAuth(needClientAuth);
        sslContextFactory.setTrustStorePath(getStorePath("serverTrustStore.jks"));
        sslContextFactory.setTrustStorePassword("passw0rd");
        
        HttpConfiguration httpsConfig = new HttpConfiguration();
        httpsConfig.addCustomizer(new SecureRequestCustomizer());
        
        ServerConnector https= new ServerConnector(server,
                new SslConnectionFactory(sslContextFactory,
                        HttpVersion.HTTP_1_1.asString()),
                new HttpConnectionFactory(httpsConfig));
        https.setPort(endpointURI.getPort());
        
        server.addConnector(https);
        return server;
    }
    else
        throw new IllegalArgumentException("unrecognized uri: "+endpointURI);
}
 
Example 10
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 11
Source File: SSLUtilsTest.java    From athenz with Apache License 2.0 4 votes vote down vote up
private static JettyServer createHttpsJettyServer(boolean clientAuth) throws IOException {
    Server server = new Server();
    HttpConfiguration https_config = new HttpConfiguration();
    https_config.setSecureScheme("https");
    int port;
    try (ServerSocket socket = new ServerSocket(0)) {
        port = socket.getLocalPort();
    }
    https_config.setSecurePort(port);
    https_config.setOutputBufferSize(32768);

    SslContextFactory sslContextFactory = new SslContextFactory();
    File keystoreFile = new File(DEFAULT_SERVER_KEY_STORE);
    if (!keystoreFile.exists()) {
        throw new FileNotFoundException();
    }

    String trustStorePath = DEFAULT_CA_TRUST_STORE;
    File trustStoreFile = new File(trustStorePath);
    if (!trustStoreFile.exists()) {
        throw new FileNotFoundException();
    }

    sslContextFactory.setEndpointIdentificationAlgorithm(null);

    sslContextFactory.setTrustStorePath(trustStorePath);
    sslContextFactory.setTrustStoreType(DEFAULT_SSL_STORE_TYPE);
    sslContextFactory.setTrustStorePassword(DEFAULT_CERT_PWD);

    sslContextFactory.setKeyStorePath(keystoreFile.getAbsolutePath());
    sslContextFactory.setKeyStoreType(DEFAULT_SSL_STORE_TYPE);
    sslContextFactory.setKeyStorePassword(DEFAULT_CERT_PWD);

    sslContextFactory.setProtocol(DEFAULT_SSL_PROTOCOL);
    sslContextFactory.setNeedClientAuth(clientAuth);

    ServerConnector https = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory,HttpVersion.HTTP_1_1.asString()),
            new HttpConnectionFactory(https_config));
    https.setPort(port);
    https.setIdleTimeout(500000);
    server.setConnectors(new Connector[] { https });
    HandlerList handlers = new HandlerList();
    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setBaseResource(Resource.newResource("."));
    handlers.setHandlers(new Handler[]
            { resourceHandler, new DefaultHandler() });
    server.setHandler(handlers);
    return new JettyServer(server, port);
}
 
Example 12
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 13
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 14
Source File: TestHttpClient.java    From nifi with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void setup() throws Exception {
    // Create embedded Jetty server
    // Use less threads to mitigate Gateway Timeout (504) with proxy test
    // Minimum thread pool size = (acceptors=2 + selectors=8 + request=1), defaults to max=200
    final QueuedThreadPool threadPool = new QueuedThreadPool(50);
    server = new Server(threadPool);

    final ContextHandlerCollection handlerCollection = new ContextHandlerCollection();

    final ServletContextHandler contextHandler = new ServletContextHandler();
    contextHandler.setContextPath("/nifi-api");

    final ServletContextHandler wrongPathContextHandler = new ServletContextHandler();
    wrongPathContextHandler.setContextPath("/wrong/nifi-api");

    handlerCollection.setHandlers(new Handler[]{contextHandler, wrongPathContextHandler});

    server.setHandler(handlerCollection);

    final ServletHandler servletHandler = new ServletHandler();
    contextHandler.insertHandler(servletHandler);

    final ServletHandler wrongPathServletHandler = new ServletHandler();
    wrongPathContextHandler.insertHandler(wrongPathServletHandler);

    final SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath("src/test/resources/certs/keystore.jks");
    sslContextFactory.setKeyStorePassword("passwordpassword");
    sslContextFactory.setKeyStoreType("JKS");
    sslContextFactory.setProtocol(CertificateUtils.getHighestCurrentSupportedTlsProtocolVersion());
    sslContextFactory.setExcludeProtocols("TLS", "TLSv1", "TLSv1.1");

    httpConnector = new ServerConnector(server);

    final HttpConfiguration https = new HttpConfiguration();
    https.addCustomizer(new SecureRequestCustomizer());
    sslConnector = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory, "http/1.1"),
            new HttpConnectionFactory(https));
    logger.info("SSL Connector: " + sslConnector.dump());

    server.setConnectors(new Connector[] { httpConnector, sslConnector });

    wrongPathServletHandler.addServletWithMapping(WrongSiteInfoServlet.class, "/site-to-site");

    servletHandler.addServletWithMapping(SiteInfoServlet.class, "/site-to-site");
    servletHandler.addServletWithMapping(PeersServlet.class, "/site-to-site/peers");

    servletHandler.addServletWithMapping(PortTransactionsAccessDeniedServlet.class, "/data-transfer/input-ports/input-access-denied-id/transactions");
    servletHandler.addServletWithMapping(PortTransactionsServlet.class, "/data-transfer/input-ports/input-running-id/transactions");
    servletHandler.addServletWithMapping(InputPortTransactionServlet.class, "/data-transfer/input-ports/input-running-id/transactions/transaction-id");
    servletHandler.addServletWithMapping(FlowFilesServlet.class, "/data-transfer/input-ports/input-running-id/transactions/transaction-id/flow-files");

    servletHandler.addServletWithMapping(PortTransactionsServlet.class, "/data-transfer/input-ports/input-timeout-id/transactions");
    servletHandler.addServletWithMapping(InputPortTransactionServlet.class, "/data-transfer/input-ports/input-timeout-id/transactions/transaction-id");
    servletHandler.addServletWithMapping(FlowFilesTimeoutServlet.class, "/data-transfer/input-ports/input-timeout-id/transactions/transaction-id/flow-files");

    servletHandler.addServletWithMapping(PortTransactionsServlet.class, "/data-transfer/input-ports/input-timeout-data-ex-id/transactions");
    servletHandler.addServletWithMapping(InputPortTransactionServlet.class, "/data-transfer/input-ports/input-timeout-data-ex-id/transactions/transaction-id");
    servletHandler.addServletWithMapping(FlowFilesTimeoutAfterDataExchangeServlet.class, "/data-transfer/input-ports/input-timeout-data-ex-id/transactions/transaction-id/flow-files");

    servletHandler.addServletWithMapping(PortTransactionsServlet.class, "/data-transfer/output-ports/output-running-id/transactions");
    servletHandler.addServletWithMapping(OutputPortTransactionServlet.class, "/data-transfer/output-ports/output-running-id/transactions/transaction-id");
    servletHandler.addServletWithMapping(FlowFilesServlet.class, "/data-transfer/output-ports/output-running-id/transactions/transaction-id/flow-files");

    servletHandler.addServletWithMapping(PortTransactionsServlet.class, "/data-transfer/output-ports/output-timeout-id/transactions");
    servletHandler.addServletWithMapping(OutputPortTransactionServlet.class, "/data-transfer/output-ports/output-timeout-id/transactions/transaction-id");
    servletHandler.addServletWithMapping(FlowFilesTimeoutServlet.class, "/data-transfer/output-ports/output-timeout-id/transactions/transaction-id/flow-files");

    servletHandler.addServletWithMapping(PortTransactionsServlet.class, "/data-transfer/output-ports/output-timeout-data-ex-id/transactions");
    servletHandler.addServletWithMapping(OutputPortTransactionServlet.class, "/data-transfer/output-ports/output-timeout-data-ex-id/transactions/transaction-id");
    servletHandler.addServletWithMapping(FlowFilesTimeoutAfterDataExchangeServlet.class, "/data-transfer/output-ports/output-timeout-data-ex-id/transactions/transaction-id/flow-files");

    server.start();

    logger.info("Starting server on port {} for HTTP, and {} for HTTPS", httpConnector.getLocalPort(), sslConnector.getLocalPort());

    startProxyServer();
    startProxyServerWithAuth();
}
 
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: JettyServer.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
protected static void configureSslContextFactory(SslContextFactory contextFactory, NiFiProperties props) {
    // require client auth when not supporting login, Kerberos service, or anonymous access
    if (props.isClientAuthRequiredForRestApi()) {
        contextFactory.setNeedClientAuth(true);
    } else {
        contextFactory.setWantClientAuth(true);
    }

    /* below code sets JSSE system properties when values are provided */
    // keystore properties
    if (StringUtils.isNotBlank(props.getProperty(NiFiProperties.SECURITY_KEYSTORE))) {
        contextFactory.setKeyStorePath(props.getProperty(NiFiProperties.SECURITY_KEYSTORE));
    }
    String keyStoreType = props.getProperty(NiFiProperties.SECURITY_KEYSTORE_TYPE);
    if (StringUtils.isNotBlank(keyStoreType)) {
        contextFactory.setKeyStoreType(keyStoreType);
        String keyStoreProvider = KeyStoreUtils.getKeyStoreProvider(keyStoreType);
        if (StringUtils.isNoneEmpty(keyStoreProvider)) {
            contextFactory.setKeyStoreProvider(keyStoreProvider);
        }
    }
    final String keystorePassword = props.getProperty(NiFiProperties.SECURITY_KEYSTORE_PASSWD);
    final String keyPassword = props.getProperty(NiFiProperties.SECURITY_KEY_PASSWD);
    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.setKeyStorePassword(keystorePassword);
        contextFactory.setKeyManagerPassword(defaultKeyPassword);
    } else if (StringUtils.isNotBlank(keyPassword)) {
        // since no keystore password was provided, there will be no keystore integrity check
        contextFactory.setKeyManagerPassword(keyPassword);
    }

    // truststore properties
    if (StringUtils.isNotBlank(props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE))) {
        contextFactory.setTrustStorePath(props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE));
    }
    String trustStoreType = props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_TYPE);
    if (StringUtils.isNotBlank(trustStoreType)) {
        contextFactory.setTrustStoreType(trustStoreType);
        String trustStoreProvider = KeyStoreUtils.getKeyStoreProvider(trustStoreType);
        if (StringUtils.isNoneEmpty(trustStoreProvider)) {
            contextFactory.setTrustStoreProvider(trustStoreProvider);
        }
    }
    if (StringUtils.isNotBlank(props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD))) {
        contextFactory.setTrustStorePassword(props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD));
    }
}
 
Example 17
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 18
Source File: WebServer.java    From Bats with Apache License 2.0 4 votes vote down vote up
/**
 * Create an HTTPS connector for given jetty server instance. If the admin has specified keystore/truststore settings
 * they will be used else a self-signed certificate is generated and used.
 *
 * @return Initialized {@link ServerConnector} for HTTPS connections.
 */
private ServerConnector createHttpsConnector(int port, int acceptors, int selectors) throws Exception {
  logger.info("Setting up HTTPS connector for web server");

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

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

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

    final DateTime now = DateTime.now();

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

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

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

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

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

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

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

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

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

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

  return sslConnector;
}
 
Example 19
Source File: JettyServerFactory.java    From gravitee-management-rest-api with Apache License 2.0 4 votes vote down vote up
@Override
public Server getObject() throws Exception {

    // Setup ThreadPool
    QueuedThreadPool threadPool = new QueuedThreadPool(
            jettyConfiguration.getPoolMaxThreads(),
            jettyConfiguration.getPoolMinThreads(),
            jettyConfiguration.getPoolIdleTimeout(),
            new ArrayBlockingQueue<Runnable>(jettyConfiguration.getPoolQueueSize())
    );
    threadPool.setName("gravitee-listener");

    Server server = new Server(threadPool);

    // Extra options
    server.setDumpAfterStart(false);
    server.setDumpBeforeStop(false);
    server.setStopAtShutdown(true);

    // Setup JMX
    if (jettyConfiguration.isJmxEnabled()) {
        MBeanContainer mbContainer = new MBeanContainer(
                ManagementFactory.getPlatformMBeanServer());
        server.addBean(mbContainer);
    }

    // HTTP Configuration
    HttpConfiguration httpConfig = new HttpConfiguration();
    httpConfig.setOutputBufferSize(32768);
    httpConfig.setRequestHeaderSize(8192);
    httpConfig.setResponseHeaderSize(8192);
    httpConfig.setSendServerVersion(false);
    httpConfig.setSendDateHeader(false);

    // Setup Jetty HTTP or HTTPS Connector
    if (jettyConfiguration.isSecured()) {
        httpConfig.setSecureScheme("https");
        httpConfig.setSecurePort(jettyConfiguration.getHttpPort());

        // SSL Context Factory
        SslContextFactory sslContextFactory = new SslContextFactory.Server();

        if (jettyConfiguration.getKeyStorePath() != null) {
            sslContextFactory.setKeyStorePath(jettyConfiguration.getKeyStorePath());
            sslContextFactory.setKeyStorePassword(jettyConfiguration.getKeyStorePassword());

            if (KEYSTORE_TYPE_PKCS12.equalsIgnoreCase(jettyConfiguration.getKeyStoreType())) {
                sslContextFactory.setKeyStoreType(KEYSTORE_TYPE_PKCS12);
            }
        }

        if (jettyConfiguration.getTrustStorePath() != null) {
            sslContextFactory.setTrustStorePath(jettyConfiguration.getTrustStorePath());
            sslContextFactory.setTrustStorePassword(jettyConfiguration.getTrustStorePassword());

            if (KEYSTORE_TYPE_PKCS12.equalsIgnoreCase(jettyConfiguration.getTrustStoreType())) {
                sslContextFactory.setTrustStoreType(KEYSTORE_TYPE_PKCS12);
            }
        }

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

        ServerConnector https = new ServerConnector(server,
                new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
                new HttpConnectionFactory(httpsConfig));
        https.setHost(jettyConfiguration.getHttpHost());
        https.setPort(jettyConfiguration.getHttpPort());
        server.addConnector(https);
    } else {
        ServerConnector http = new ServerConnector(server,
                jettyConfiguration.getAcceptors(),
                jettyConfiguration.getSelectors(),
                new HttpConnectionFactory(httpConfig));
        http.setHost(jettyConfiguration.getHttpHost());
        http.setPort(jettyConfiguration.getHttpPort());
        http.setIdleTimeout(jettyConfiguration.getIdleTimeout());

        server.addConnector(http);
    }

    // Setup Jetty statistics
    if (jettyConfiguration.isStatisticsEnabled()) {
        StatisticsHandler stats = new StatisticsHandler();
        stats.setHandler(server.getHandler());
        server.setHandler(stats);
    }

    if (jettyConfiguration.isAccessLogEnabled()) {
        CustomRequestLog requestLog = new CustomRequestLog(
                new AsyncRequestLogWriter(jettyConfiguration.getAccessLogPath()),
                CustomRequestLog.EXTENDED_NCSA_FORMAT);

        server.setRequestLog(requestLog);
    }

    return server;
}
 
Example 20
Source File: GitLabConnectionConfigSSLTest.java    From gitlab-plugin with GNU General Public License v2.0 4 votes vote down vote up
@BeforeClass
// based on https://www.eclipse.org/jetty/documentation/9.4.x/embedded-examples.html#Multiple%20Connectors
public static void startJetty() throws Exception {
    port = PortFactory.findFreePort();
    int _http_port = PortFactory.findFreePort();

    // Create a basic jetty server object without declaring the port. Since
    // we are configuring connectors directly we'll be setting ports on
    // those connectors.
    server = new Server();

    // HTTP Configuration
    // HttpConfiguration is a collection of configuration information
    // appropriate for http and https. The default scheme for http is
    // <code>http</code> of course, as the default for secured http is
    // <code>https</code> but we show setting the scheme to show it can be
    // done. The port for secured communication is also set here.
    HttpConfiguration http_config = new HttpConfiguration();
    http_config.setSecureScheme("https");
    http_config.setSecurePort(port);
    http_config.setOutputBufferSize(32768);

    // HTTP connector
    // The first server connector we create is the one for http, passing in
    // the http configuration we configured above so it can get things like
    // the output buffer size, etc. We also set the port (8080) and
    // configure an idle timeout.
    ServerConnector http = new ServerConnector(server,
        new HttpConnectionFactory(http_config));
    http.setPort(_http_port);
    http.setIdleTimeout(30000);

    // SSL Context Factory for HTTPS
    // SSL requires a certificate so we configure a factory for ssl contents
    // with information pointing to what keystore the ssl connection needs
    // to know about. Much more configuration is available the ssl context,
    // including things like choosing the particular certificate out of a
    // keystore to be used.

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath("src/test/resources/keystore");
    sslContextFactory.setKeyStorePassword("password");

    // OPTIONAL: Un-comment the following to use Conscrypt for SSL instead of
    // the native JSSE implementation.

    //Security.addProvider(new OpenSSLProvider());
    //sslContextFactory.setProvider("Conscrypt");

    // HTTPS Configuration
    // A new HttpConfiguration object is needed for the next connector and
    // you can pass the old one as an argument to effectively clone the
    // contents. On this HttpConfiguration object we add a
    // SecureRequestCustomizer which is how a new connector is able to
    // resolve the https connection before handing control over to the Jetty
    // Server.
    HttpConfiguration https_config = new HttpConfiguration(http_config);
    SecureRequestCustomizer src = new SecureRequestCustomizer();
    src.setStsMaxAge(2000);
    src.setStsIncludeSubDomains(true);
    https_config.addCustomizer(src);

    // HTTPS connector
    // We create a second ServerConnector, passing in the http configuration
    // we just made along with the previously created ssl context factory.
    // Next we set the port and a longer idle timeout.
    ServerConnector https = new ServerConnector(server,
        new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
        new HttpConnectionFactory(https_config));
    https.setPort(port);
    https.setIdleTimeout(500000);

    // Set the connectors
    server.setConnectors(new Connector[] { http, https });

    HandlerCollection handlerCollection = new HandlerCollection();
    handlerCollection.setHandlers(new Handler[] {
        new AbstractHandler() {
            public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
                response.setStatus(HttpServletResponse.SC_OK);
                baseRequest.setHandled(true);
            }
        }
    });
    server.setHandler(handlerCollection);
    server.start();


}