org.eclipse.jetty.server.ForwardedRequestCustomizer Java Examples

The following examples show how to use org.eclipse.jetty.server.ForwardedRequestCustomizer. 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: WebServerTask.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
HttpConfiguration configureForwardRequestCustomizer(HttpConfiguration httpConf) {
  if (conf.get(HTTP_ENABLE_FORWARDED_REQUESTS_KEY, HTTP_ENABLE_FORWARDED_REQUESTS_DEFAULT)) {
    httpConf.addCustomizer(new ForwardedRequestCustomizer());
  }

  return httpConf;
}
 
Example #2
Source File: HttpBindManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
private void configureProxiedConnector(HttpConfiguration httpConfig) {
     // Check to see if we are deployed behind a proxy
     // Refer to http://eclipse.org/jetty/documentation/current/configuring-connectors.html
     if (isXFFEnabled()) {
         ForwardedRequestCustomizer customizer = new ForwardedRequestCustomizer();
         // default: "X-Forwarded-For"
         String forwardedForHeader = getXFFHeader();
         if (forwardedForHeader != null) {
             customizer.setForwardedForHeader(forwardedForHeader);
         }
         // default: "X-Forwarded-Server"
         String forwardedServerHeader = getXFFServerHeader();
         if (forwardedServerHeader != null) {
             customizer.setForwardedServerHeader(forwardedServerHeader);
         }
         // default: "X-Forwarded-Host"
         String forwardedHostHeader = getXFFHostHeader();
         if (forwardedHostHeader != null) {
             customizer.setForwardedHostHeader(forwardedHostHeader);
         }
         // default: none
         String hostName = getXFFHostName();
         if (hostName != null) {
             customizer.setHostHeader(hostName);
         }

         httpConfig.addCustomizer(customizer);
     }
     httpConfig.setRequestHeaderSize(JiveGlobals.getIntProperty(HTTP_BIND_REQUEST_HEADER_SIZE, HTTP_BIND_REQUEST_HEADER_SIZE_DEFAULT));
}
 
Example #3
Source File: Main.java    From passopolis-server with GNU General Public License v3.0 4 votes vote down vote up
/** Creates a Jetty server listening on HTTP and HTTPS, serving handlers. */
public static Server createJetty(Handler handler)
    throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
  final Server server = new Server();
  server.setHandler(handler);

  HttpConfiguration httpConfig = new HttpConfiguration();
  // Parses X-Forwarded-For headers for Servlet.getRemoteAddr()
  httpConfig.addCustomizer(new ForwardedRequestCustomizer());

  final ServerConnector connector = new ServerConnector(
      server,
      new HttpConnectionFactory(httpConfig)
  );
  server.addConnector(connector);

  connector.setPort(HTTP_PORT);

  // Enable SSL on port 8443 using the debug keystore
  KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
  InputStream keyStream = Main.class.getResourceAsStream("debug_keystore.jks");
  keyStore.load(keyStream, null);
  keyStream.close();

  SslContextFactory ssl = new SslContextFactory();
  ssl.setKeyStore(keyStore);
  ssl.setKeyStorePassword("password");
  SslConnectionFactory sslFactory = new SslConnectionFactory(ssl, "http/1.1");
  // SecureRequestCustomizer is required to correctly set scheme to https
  HttpConfiguration httpsConfig = new HttpConfiguration();
  httpsConfig.addCustomizer(new SecureRequestCustomizer());
  httpsConfig.addCustomizer(new ForwardedRequestCustomizer());
  ConnectionFactory httpsFactory = new HttpConnectionFactory(httpsConfig);

  ServerConnector sslConnector = new ServerConnector(server, sslFactory, httpsFactory);
  sslConnector.setPort(HTTPS_PORT);
  server.addConnector(sslConnector);

  registerShutdownHook(server);
  return server;
}
 
Example #4
Source File: ParaServer.java    From para with Apache License 2.0 4 votes vote down vote up
/**
 * @return Jetty config bean
 */
@Bean
public ServletWebServerFactory jettyConfigBean() {
	JettyServletWebServerFactory jef = new JettyServletWebServerFactory();
	jef.addServerCustomizers((JettyServerCustomizer) (Server server) -> {
		if (Config.getConfigBoolean("access_log_enabled", true)) {
			// enable access log via Logback
			HandlerCollection handlers = new HandlerCollection();
			for (Handler handler : server.getHandlers()) {
				handlers.addHandler(handler);
			}
			RequestLogHandler reqLogs = new RequestLogHandler();
			reqLogs.setServer(server);
			RequestLogImpl rli = new RequestLogImpl();
			rli.setResource("/logback-access.xml");
			rli.setQuiet(true);
			rli.start();
			reqLogs.setRequestLog(rli);
			handlers.addHandler(reqLogs);
			server.setHandler(handlers);
		}

		for (Connector y : server.getConnectors()) {
			for (ConnectionFactory cf : y.getConnectionFactories()) {
				if (cf instanceof HttpConnectionFactory) {
					HttpConnectionFactory dcf = (HttpConnectionFactory) cf;
					// support for X-Forwarded-Proto
					// redirect back to https if original request uses it
					if (Config.IN_PRODUCTION) {
						ForwardedRequestCustomizer frc = new ForwardedRequestCustomizer() {
							public void customize(Connector connector, HttpConfiguration config, Request request) {
								super.customize(connector, config, request);
								String cfProto = request.getHeader("CloudFront-Forwarded-Proto");
								if (StringUtils.equalsIgnoreCase(cfProto, config.getSecureScheme())) {
									request.setScheme(cfProto);
									request.setSecure(true);
								}
							}
						};
						HttpConfiguration httpConfiguration = dcf.getHttpConfiguration();
						httpConfiguration.addCustomizer(frc);
					}
					// Disable Jetty version header
					dcf.getHttpConfiguration().setSendServerVersion(false);
					// Increase idle timeout
					dcf.getHttpConfiguration().setIdleTimeout(TimeUnit.MINUTES.toMillis(5));
				}
			}
		}
	});
	String contextPath = Config.getConfigParam("context_path", "");
	if (StringUtils.length(contextPath) > 1 && contextPath.charAt(0) == '/') {
		jef.setContextPath(contextPath);
	}
	jef.setPort(getServerPort());
	logger.info("Listening on port {}...", jef.getPort());
	return jef;
}
 
Example #5
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 #6
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()]));
}