Java Code Examples for org.eclipse.jetty.server.HttpConfiguration#setSecureScheme()

The following examples show how to use org.eclipse.jetty.server.HttpConfiguration#setSecureScheme() . 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: App.java    From mysql_perf_analyzer with Apache License 2.0 6 votes vote down vote up
/**
 * Create ssl connector if https is used
 * @return
 */
private ServerConnector sslConnector() {
	HttpConfiguration http_config = new HttpConfiguration();
	http_config.setSecureScheme("https");
	http_config.setSecurePort(this.getPort());
	
	HttpConfiguration https_config = new HttpConfiguration(http_config);
	https_config.addCustomizer(new SecureRequestCustomizer());
	
	SslContextFactory sslContextFactory = new SslContextFactory(this.getCertKeyStorePath());
	sslContextFactory.setKeyStorePassword(this.getCertKeyStorePassword());
	//exclude weak ciphers
	sslContextFactory.setExcludeCipherSuites("^.*_(MD5|SHA|SHA1)$");
	//only support tlsv1.2
	sslContextFactory.addExcludeProtocols("SSL", "SSLv2", "SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.1");
	
	ServerConnector connector = new ServerConnector(jettyServer, 
			new SslConnectionFactory(sslContextFactory, "http/1.1"),
			new HttpConnectionFactory(https_config));
	connector.setPort(this.getPort());
	connector.setIdleTimeout(50000);
	return connector;
}
 
Example 2
Source File: PrometheusServer.java    From nifi with Apache License 2.0 6 votes vote down vote up
public PrometheusServer(int addr, SSLContextService sslContextService, ComponentLog logger, boolean needClientAuth, boolean wantClientAuth) throws Exception {
    PrometheusServer.logger = logger;
    this.server = new Server();
    this.handler = new ServletContextHandler(server, "/metrics");
    this.handler.addServlet(new ServletHolder(new MetricsServlet()), "/");

    SslContextFactory sslFactory = createSslFactory(sslContextService, needClientAuth, wantClientAuth);
    HttpConfiguration httpsConfiguration = new HttpConfiguration();
    httpsConfiguration.setSecureScheme("https");
    httpsConfiguration.setSecurePort(addr);
    httpsConfiguration.addCustomizer(new SecureRequestCustomizer());

    ServerConnector https = new ServerConnector(server, new SslConnectionFactory(sslFactory, "http/1.1"),
            new HttpConnectionFactory(httpsConfiguration));
    https.setPort(addr);
    this.server.setConnectors(new Connector[]{https});
    this.server.start();

}
 
Example 3
Source File: ReporterFactoryTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setUp() throws Exception {
    server = new Server();

    Path keyStorePath = Paths.get(ReporterFactoryTest.class.getResource("/keystore").toURI());
    final SslContextFactory sslContextFactory = new SslContextFactory(keyStorePath.toAbsolutePath().toString());
    sslContextFactory.setKeyStorePassword("password");
    sslContextFactory.getSslContext();

    final HttpConfiguration httpConfiguration = new HttpConfiguration();
    httpConfiguration.setSecureScheme("https");
    httpConfiguration.setSecurePort(0);

    final HttpConfiguration httpsConfiguration = new HttpConfiguration(httpConfiguration);
    httpsConfiguration.addCustomizer(new SecureRequestCustomizer());
    final ServerConnector httpsConnector = new ServerConnector(server,
        new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
        new HttpConnectionFactory(httpsConfiguration));
    httpsConnector.setPort(0);
    server.addConnector(httpsConnector);
    server.setHandler(new AbstractHandler() {
        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) {
            baseRequest.setHandled(true);
            requestHandled.set(true);
        }
    });
    server.start();
    configuration = SpyConfiguration.createSpyConfig();
    reporterConfiguration = configuration.getConfig(ReporterConfiguration.class);
    when(reporterConfiguration.getServerUrls()).thenReturn(Collections.singletonList(new URL("https://localhost:" + getPort())));
}
 
Example 4
Source File: HttpBindManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
private Connector createSSLConnector( final Server httpBindServer ) {
    final int securePort = getHttpBindSecurePort();
    try {
        final IdentityStore identityStore = XMPPServer.getInstance().getCertificateStoreManager().getIdentityStore( ConnectionType.BOSH_C2S );

        if (securePort > 0 && identityStore.getStore().aliases().hasMoreElements() ) {
            if ( !identityStore.containsDomainCertificate( ) ) {
                Log.warn("HTTP binding: Using certificates but they are not valid for the hosted domain");
            }

            final ConnectionManagerImpl connectionManager = ((ConnectionManagerImpl) XMPPServer.getInstance().getConnectionManager());
            final ConnectionConfiguration configuration = connectionManager.getListener( ConnectionType.BOSH_C2S, true ).generateConnectionConfiguration();
            final SslContextFactory sslContextFactory = new EncryptionArtifactFactory(configuration).getSslContextFactory();

            final HttpConfiguration httpsConfig = new HttpConfiguration();
            httpsConfig.setSecureScheme("https");
            httpsConfig.setSecurePort(securePort);
            configureProxiedConnector(httpsConfig);
            httpsConfig.addCustomizer(new SecureRequestCustomizer());
            httpsConfig.setSendServerVersion( false );

            final ServerConnector sslConnector = new ServerConnector(httpBindServer, new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(httpsConfig));
            sslConnector.setHost(getBindInterface());
            sslConnector.setPort(securePort);
            return sslConnector;
        }
    }
    catch (Exception e) {
        Log.error("Error creating SSL connector for Http bind", e);
    }

    return null;
}
 
Example 5
Source File: ConsoleProxyNoVNCServer.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public ConsoleProxyNoVNCServer(byte[] ksBits, String ksPassword) {
    this.server = new Server();
    ConsoleProxyNoVNCHandler handler = new ConsoleProxyNoVNCHandler();
    this.server.setHandler(handler);

    try {
        final HttpConfiguration httpConfig = new HttpConfiguration();
        httpConfig.setSecureScheme("https");
        httpConfig.setSecurePort(wsPort);

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

        final SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
        char[] passphrase = ksPassword != null ? ksPassword.toCharArray() : null;
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(new ByteArrayInputStream(ksBits), passphrase);
        sslContextFactory.setKeyStore(ks);
        sslContextFactory.setKeyStorePassword(ksPassword);
        sslContextFactory.setKeyManagerPassword(ksPassword);

        final ServerConnector sslConnector = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory, "http/1.1"),
            new HttpConnectionFactory(httpsConfig));
        sslConnector.setPort(wsPort);
        server.addConnector(sslConnector);
    } catch (Exception e) {
        s_logger.error("Unable to secure server due to exception ", e);
    }
}
 
Example 6
Source File: JettyServer.java    From nifi with Apache License 2.0 5 votes vote down vote up
private ServerConnector createUnconfiguredSslServerConnector(Server server, HttpConfiguration httpConfiguration, int port) {
    // add some secure config
    final HttpConfiguration httpsConfiguration = new HttpConfiguration(httpConfiguration);
    httpsConfiguration.setSecureScheme("https");
    httpsConfiguration.setSecurePort(port);
    httpsConfiguration.setSendServerVersion(props.shouldSendServerVersion());
    httpsConfiguration.addCustomizer(new SecureRequestCustomizer());

    // build the connector
    return new ServerConnector(server,
            new SslConnectionFactory(createSslContextFactory(), "http/1.1"),
            new HttpConnectionFactory(httpsConfiguration));
}
 
Example 7
Source File: JettyServer.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private ServerConnector createUnconfiguredSslServerConnector(Server server, HttpConfiguration httpConfiguration) {
    // add some secure config
    final HttpConfiguration httpsConfiguration = new HttpConfiguration(httpConfiguration);
    httpsConfiguration.setSecureScheme("https");
    httpsConfiguration.setSecurePort(props.getSslPort());
    httpsConfiguration.addCustomizer(new SecureRequestCustomizer());

    // build the connector
    return new ServerConnector(server,
            new SslConnectionFactory(createSslContextFactory(), "http/1.1"),
            new HttpConnectionFactory(httpsConfiguration));
}
 
Example 8
Source File: ServersUtil.java    From joynr with Apache License 2.0 5 votes vote down vote up
private static Server startSSLServer(ContextHandlerCollection contexts,
                                     SSLSettings settings,
                                     int port) throws IOException, Exception {

    System.setProperty(MessagingPropertyKeys.PROPERTY_SERVLET_HOST_PATH, "http://localhost:" + port);
    logger.info("PORT: {}", System.getProperty(MessagingPropertyKeys.PROPERTY_SERVLET_HOST_PATH));
    final Server jettyServer = new Server();

    HttpConfiguration https_config = new HttpConfiguration();
    https_config.setSecureScheme("https");
    https_config.setSecurePort(port);
    https_config.setOutputBufferSize(32768);
    https_config.addCustomizer(new SecureRequestCustomizer());

    // Configure SSL
    final SslContextFactory contextFactory = new SslContextFactory();
    contextFactory.setKeyStorePath(settings.getKeyStorePath());
    contextFactory.setTrustStorePath(settings.getTrustStorePath());
    contextFactory.setKeyStorePassword(settings.getKeyStorePassword());
    contextFactory.setTrustStorePassword(settings.getKeyStorePassword());
    contextFactory.setNeedClientAuth(true);

    // Create and use an SSL connector
    ServerConnector connector = new ServerConnector(jettyServer,
                                                    new SslConnectionFactory(contextFactory, "http/1.1"),
                                                    new HttpConnectionFactory(https_config));
    connector.setPort(port);
    connector.setAcceptQueueSize(1);
    jettyServer.setConnectors(new Connector[]{ connector });

    String serverUrl = "https://localhost:" + port;
    System.getProperties().setProperty(MessagingPropertyKeys.PROPERTY_SERVLET_HOST_PATH, serverUrl);

    jettyServer.setHandler(contexts);
    jettyServer.start();

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

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

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

  return conn;
}
 
Example 10
Source File: ODataTestServer.java    From syndesis with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings( "deprecation" )
private void initServer(SSLContext sslContext, String userName) throws UnknownHostException {
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath(FORWARD_SLASH);
    this.setHandler(context);

    ServletHandler productsHandler = new ServletHandler();
    productsHandler.addServletWithMapping(
        ProductsServlet.class,
        FORWARD_SLASH + PRODUCTS_SVC + FORWARD_SLASH + STAR);
    productsHandler.addFilterWithMapping(ODataPathFilter.class, FORWARD_SLASH + STAR, FilterMapping.REQUEST);
    context.insertHandler(productsHandler);

    if (userName != null) {
        LoginService loginService = new HashLoginService("MyRealm", "src/test/resources/realm.properties");
        this.addBean(loginService);

        ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
        Constraint constraint = new Constraint();
        constraint.setName("auth");
        constraint.setAuthenticate(true);
        constraint.setRoles(new String[] { USER, "admin" });

        ConstraintMapping mapping = new ConstraintMapping();
        mapping.setPathSpec(FORWARD_SLASH + PRODUCTS_SVC + FORWARD_SLASH + STAR);
        mapping.setConstraint(constraint);

        securityHandler.setConstraintMappings(Collections.singletonList(mapping));
        securityHandler.setAuthenticator(new BasicAuthenticator());

        context.setSecurityHandler(securityHandler);
    }

    httpConnector = new ServerConnector(this);
    httpConnector.setPort(httpPort); // Finds next available port if still 0
    this.addConnector(httpConnector);


    if (sslContext != null) {
        // HTTPS
        HttpConfiguration httpConfiguration = new HttpConfiguration();
        httpConfiguration.setSecureScheme("https");
        httpConfiguration.setSecurePort(httpsPort); // Finds next available port if still 0
        httpConfiguration.addCustomizer(new SecureRequestCustomizer());

        final SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setSslContext(sslContext);
        httpsConnector = new ServerConnector(this, sslContextFactory, new HttpConnectionFactory(httpConfiguration));
        httpsConnector.setPort(httpsPort); // Finds next available port if still 0
        this.addConnector(httpsConnector);
    }
}
 
Example 11
Source File: JettyServer.java    From selenium with Apache License 2.0 4 votes vote down vote up
public JettyServer(BaseServerOptions options, HttpHandler handler) {
  this.handler = Require.nonNull("Handler", handler);
  int port = options.getPort() == 0 ? PortProber.findFreePort() : options.getPort();

  String host = options.getHostname().orElseGet(() -> {
    try {
      return new NetworkUtils().getNonLoopbackAddressOfThisMachine();
    } catch (WebDriverException ignored) {
      return "localhost";
    }
  });

  try {
    this.url = new URL("http", host, port, "");
  } catch (MalformedURLException e) {
    throw new UncheckedIOException(e);
  }

  Log.setLog(new JavaUtilLog());
  this.server = new org.eclipse.jetty.server.Server(
      new QueuedThreadPool(options.getMaxServerThreads()));

  this.servletContextHandler = new ServletContextHandler(ServletContextHandler.SECURITY);
  ConstraintSecurityHandler
      securityHandler =
      (ConstraintSecurityHandler) servletContextHandler.getSecurityHandler();

  Constraint disableTrace = new Constraint();
  disableTrace.setName("Disable TRACE");
  disableTrace.setAuthenticate(true);
  ConstraintMapping disableTraceMapping = new ConstraintMapping();
  disableTraceMapping.setConstraint(disableTrace);
  disableTraceMapping.setMethod("TRACE");
  disableTraceMapping.setPathSpec("/");
  securityHandler.addConstraintMapping(disableTraceMapping);

  Constraint enableOther = new Constraint();
  enableOther.setName("Enable everything but TRACE");
  ConstraintMapping enableOtherMapping = new ConstraintMapping();
  enableOtherMapping.setConstraint(enableOther);
  enableOtherMapping.setMethodOmissions(new String[]{"TRACE"});
  enableOtherMapping.setPathSpec("/");
  securityHandler.addConstraintMapping(enableOtherMapping);

  // Allow CORS: Whether the Selenium server should allow web browser connections from any host
  if (options.getAllowCORS()) {
    FilterHolder
        filterHolder = servletContextHandler.addFilter(CrossOriginFilter.class, "/*", EnumSet
        .of(DispatcherType.REQUEST));
    filterHolder.setInitParameter("allowedMethods", "GET,POST,PUT,DELETE,HEAD");

    // Warning user
    LOG.warning("You have enabled CORS requests from any host. "
                + "Be careful not to visit sites which could maliciously "
                + "try to start Selenium sessions on your machine");
  }

  server.setHandler(servletContextHandler);

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

  ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(httpConfig));
  options.getHostname().ifPresent(http::setHost);
  http.setPort(getUrl().getPort());

  http.setIdleTimeout(500000);

  server.setConnectors(new Connector[]{http});
}
 
Example 12
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 13
Source File: CAMutualAuthTest.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.setKeyStorePath(getResourcePath("2waytest/mutual_trust_via_ca/service_ks.jks"));
    sslContextFactory.setKeyStorePassword("password");
    sslContextFactory.setKeyManagerPassword("password");
    sslContextFactory.setTrustStorePath(getResourcePath("2waytest/mutual_trust_via_ca/common_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));
            }

            response.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
            response.getWriter().println("apiman");
        }
    });
    server.start();
}
 
Example 14
Source File: InstanceProviderContainer.java    From athenz with Apache License 2.0 4 votes vote down vote up
public void run() {
    try {
        QueuedThreadPool threadPool = new QueuedThreadPool();
        threadPool.setMaxThreads(16);

        Server server = new Server(threadPool);
        ServletContextHandler handler = new ServletContextHandler();
        handler.setContextPath("");
        ResourceConfig config = new ResourceConfig(InstanceProviderResources.class)
                .register(JacksonFeature.class)
                .register(new Binder());
        handler.addServlet(new ServletHolder(new ServletContainer(config)), "/*");
        server.setHandler(handler);
        
        // SSL Context Factory

        SslContextFactory sslContextFactory = createSSLContextObject();

        // SSL HTTP Configuration
        
        HttpConfiguration httpConfig = new HttpConfiguration();
        httpConfig.setSecureScheme("https");
        httpConfig.setSecurePort(10043);

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

        // SSL Connector
        
        ServerConnector sslConnector = new ServerConnector(server,
                new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
                new HttpConnectionFactory(httpsConfig));
        sslConnector.setPort(10043);
        server.addConnector(sslConnector);
        
        server.start();
        server.join();
    } catch (Exception e) {
        System.err.println("*** " + e);
    }
}
 
Example 15
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 16
Source File: SecureEmbeddedServer.java    From incubator-atlas with Apache License 2.0 4 votes vote down vote up
protected Connector getConnector(int port) throws IOException {
    org.apache.commons.configuration.Configuration config = getConfiguration();

    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 17
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 18
Source File: ServerDaemon.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
@Override
public void start() throws Exception {
    // Thread pool
    final QueuedThreadPool threadPool = new QueuedThreadPool();
    threadPool.setMinThreads(10);
    threadPool.setMaxThreads(500);

    // Jetty Server
    server = new Server(threadPool);

    // Setup Scheduler
    server.addBean(new ScheduledExecutorScheduler());

    // Setup JMX
    final MBeanContainer mbeanContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
    server.addBean(mbeanContainer);

    // HTTP config
    final HttpConfiguration httpConfig = new HttpConfiguration();
    httpConfig.addCustomizer( new ForwardedRequestCustomizer() );
    httpConfig.setSecureScheme("https");
    httpConfig.setSecurePort(httpsPort);
    httpConfig.setOutputBufferSize(32768);
    httpConfig.setRequestHeaderSize(8192);
    httpConfig.setResponseHeaderSize(8192);
    httpConfig.setSendServerVersion(false);
    httpConfig.setSendDateHeader(false);

    // HTTP Connector
    createHttpConnector(httpConfig);

    // Setup handlers
    Pair<SessionHandler,HandlerCollection> pair = createHandlers();
    server.setHandler(pair.second());

    // Extra config options
    server.setStopAtShutdown(true);

    // HTTPS Connector
    createHttpsConnector(httpConfig);

    server.start();
    // Must set the session timeout after the server has started
    pair.first().setMaxInactiveInterval(sessionTimeout * 60);
    server.join();
}
 
Example 19
Source File: HttpService.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public HttpService start() throws Exception {
    TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), ROOT_WAR_PATH);

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

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

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

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

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

            server.addConnector(httpsConnector);
        }

        addShutdownHook();

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

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

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

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

    return this;
}
 
Example 20
Source File: NiFiTestServer.java    From nifi with Apache License 2.0 4 votes vote down vote up
private void createSecureConnector() {
    org.eclipse.jetty.util.ssl.SslContextFactory contextFactory = new org.eclipse.jetty.util.ssl.SslContextFactory();

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

    // require client auth when not supporting login or anonymous access
    if (StringUtils.isBlank(properties.getProperty(NiFiProperties.SECURITY_USER_LOGIN_IDENTITY_PROVIDER))) {
        contextFactory.setNeedClientAuth(true);
    } else {
        contextFactory.setWantClientAuth(true);
    }

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

    // truststore properties
    if (StringUtils.isNotBlank(properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE))) {
        contextFactory.setTrustStorePath(properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE));
    }
    if (StringUtils.isNotBlank(properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_TYPE))) {
        contextFactory.setTrustStoreType(properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_TYPE));
    }
    if (StringUtils.isNotBlank(properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD))) {
        contextFactory.setTrustStorePassword(properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD));
    }

    // add some secure config
    final HttpConfiguration httpsConfiguration = new HttpConfiguration();
    httpsConfiguration.setSecureScheme("https");
    httpsConfiguration.setSecurePort(0);
    httpsConfiguration.addCustomizer(new SecureRequestCustomizer());

    // build the connector
    final ServerConnector https = new ServerConnector(jetty,
            new SslConnectionFactory(contextFactory, "http/1.1"),
            new HttpConnectionFactory(httpsConfiguration));

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

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