use of org.eclipse.jetty.server.SecureRequestCustomizer in project dropwizard by dropwizard.
the class HttpsConnectorFactory method buildHttpConfiguration.
@Override
protected HttpConfiguration buildHttpConfiguration() {
final HttpConfiguration config = super.buildHttpConfiguration();
config.setSecureScheme("https");
config.setSecurePort(getPort());
config.addCustomizer(new SecureRequestCustomizer());
return config;
}
use of org.eclipse.jetty.server.SecureRequestCustomizer in project gerrit by GerritCodeReview.
the class JettyServer method listen.
private Connector[] listen(Server server, Config cfg) {
// OpenID and certain web-based single-sign-on products can cause
// some very long headers, especially in the Referer header. We
// need to use a larger default header size to ensure we have
// the space required.
//
final int requestHeaderSize = cfg.getInt("httpd", "requestheadersize", 16386);
final URI[] listenUrls = listenURLs(cfg);
final boolean reuseAddress = cfg.getBoolean("httpd", "reuseaddress", true);
final int acceptors = cfg.getInt("httpd", "acceptorThreads", 2);
final AuthType authType = cfg.getEnum("auth", null, "type", AuthType.OPENID);
reverseProxy = isReverseProxied(listenUrls);
final Connector[] connectors = new Connector[listenUrls.length];
for (int idx = 0; idx < listenUrls.length; idx++) {
final URI u = listenUrls[idx];
final int defaultPort;
final ServerConnector c;
HttpConfiguration config = defaultConfig(requestHeaderSize);
if (AuthType.CLIENT_SSL_CERT_LDAP.equals(authType) && !"https".equals(u.getScheme())) {
throw new IllegalArgumentException("Protocol '" + u.getScheme() + "' " + " not supported in httpd.listenurl '" + u + "' when auth.type = '" + AuthType.CLIENT_SSL_CERT_LDAP.name() + "'; only 'https' is supported");
}
if ("http".equals(u.getScheme())) {
defaultPort = 80;
c = newServerConnector(server, acceptors, config);
} else if ("https".equals(u.getScheme())) {
SslContextFactory.Server ssl = new SslContextFactory.Server();
final Path keystore = getFile(cfg, "sslkeystore", "etc/keystore");
String password = cfg.getString("httpd", null, "sslkeypassword");
if (password == null) {
password = "gerrit";
}
ssl.setKeyStorePath(keystore.toAbsolutePath().toString());
ssl.setTrustStorePath(keystore.toAbsolutePath().toString());
ssl.setKeyStorePassword(password);
ssl.setTrustStorePassword(password);
if (AuthType.CLIENT_SSL_CERT_LDAP.equals(authType)) {
ssl.setNeedClientAuth(true);
Path crl = getFile(cfg, "sslCrl", "etc/crl.pem");
if (Files.exists(crl)) {
ssl.setCrlPath(crl.toAbsolutePath().toString());
ssl.setValidatePeerCerts(true);
}
}
defaultPort = 443;
config.addCustomizer(new SecureRequestCustomizer());
c = new ServerConnector(server, null, null, null, 0, acceptors, new SslConnectionFactory(ssl, "http/1.1"), new HttpConnectionFactory(config));
} else if ("proxy-http".equals(u.getScheme())) {
defaultPort = 8080;
config.addCustomizer(new ForwardedRequestCustomizer());
c = newServerConnector(server, acceptors, config);
} else if ("proxy-https".equals(u.getScheme())) {
defaultPort = 8080;
config.addCustomizer(new ForwardedRequestCustomizer());
config.addCustomizer((connector, channelConfig, request) -> {
request.setScheme(HttpScheme.HTTPS.asString());
request.setSecure(true);
});
c = newServerConnector(server, acceptors, config);
} else {
throw new IllegalArgumentException("Protocol '" + u.getScheme() + "' " + " not supported in httpd.listenurl '" + u + "';" + " only 'http', 'https', 'proxy-http, 'proxy-https'" + " are supported");
}
try {
if (u.getHost() == null && (//
u.getAuthority().equals("*") || u.getAuthority().startsWith("*:"))) {
// Bind to all local addresses. Port wasn't parsed right by URI
// due to the illegal host of "*" so replace with a legal name
// and parse the URI.
//
final URI r = new URI(u.toString().replace('*', 'A')).parseServerAuthority();
c.setHost(null);
c.setPort(0 < r.getPort() ? r.getPort() : defaultPort);
} else {
final URI r = u.parseServerAuthority();
c.setHost(r.getHost());
c.setPort(0 <= r.getPort() ? r.getPort() : defaultPort);
}
} catch (URISyntaxException e) {
throw new IllegalArgumentException("Invalid httpd.listenurl " + u, e);
}
c.setInheritChannel(cfg.getBoolean("httpd", "inheritChannel", false));
c.setReuseAddress(reuseAddress);
c.setIdleTimeout(cfg.getTimeUnit("httpd", null, "idleTimeout", 30000L, MILLISECONDS));
connectors[idx] = c;
}
return connectors;
}
use of org.eclipse.jetty.server.SecureRequestCustomizer in project mysql_perf_analyzer by yahoo.
the class App method sslConnector.
/**
* 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;
}
use of org.eclipse.jetty.server.SecureRequestCustomizer in project druid by druid-io.
the class JettyServerModule method makeAndInitializeServer.
static Server makeAndInitializeServer(Injector injector, Lifecycle lifecycle, DruidNode node, ServerConfig config, TLSServerConfig tlsServerConfig, Binding<SslContextFactory.Server> sslContextFactoryBinding, TLSCertificateChecker certificateChecker) {
// adjusting to make config.getNumThreads() mean, "number of threads
// that concurrently handle the requests".
int numServerThreads = config.getNumThreads() + getMaxJettyAcceptorsSelectorsNum(node);
final QueuedThreadPool threadPool;
if (config.getQueueSize() == Integer.MAX_VALUE) {
threadPool = new QueuedThreadPool();
threadPool.setMinThreads(numServerThreads);
threadPool.setMaxThreads(numServerThreads);
} else {
threadPool = new QueuedThreadPool(numServerThreads, numServerThreads, // same default is used in other case when threadPool = new QueuedThreadPool()
60000, new LinkedBlockingQueue<>(config.getQueueSize()));
}
threadPool.setDaemon(true);
jettyServerThreadPool = threadPool;
final Server server = new Server(threadPool);
// Without this bean set, the default ScheduledExecutorScheduler runs as non-daemon, causing lifecycle hooks to fail
// to fire on main exit. Related bug: https://github.com/apache/druid/pull/1627
server.addBean(new ScheduledExecutorScheduler("JettyScheduler", true), true);
final List<ServerConnector> serverConnectors = new ArrayList<>();
if (node.isEnablePlaintextPort()) {
log.info("Creating http connector with port [%d]", node.getPlaintextPort());
HttpConfiguration httpConfiguration = new HttpConfiguration();
if (config.isEnableForwardedRequestCustomizer()) {
httpConfiguration.addCustomizer(new ForwardedRequestCustomizer());
}
httpConfiguration.setRequestHeaderSize(config.getMaxRequestHeaderSize());
httpConfiguration.setSendServerVersion(false);
final ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory(httpConfiguration));
if (node.isBindOnHost()) {
connector.setHost(node.getHost());
}
connector.setPort(node.getPlaintextPort());
serverConnectors.add(connector);
}
final SslContextFactory.Server sslContextFactory;
if (node.isEnableTlsPort()) {
log.info("Creating https connector with port [%d]", node.getTlsPort());
if (sslContextFactoryBinding == null) {
// Never trust all certificates by default
sslContextFactory = new IdentityCheckOverrideSslContextFactory(tlsServerConfig, certificateChecker);
sslContextFactory.setKeyStorePath(tlsServerConfig.getKeyStorePath());
sslContextFactory.setKeyStoreType(tlsServerConfig.getKeyStoreType());
sslContextFactory.setKeyStorePassword(tlsServerConfig.getKeyStorePasswordProvider().getPassword());
sslContextFactory.setCertAlias(tlsServerConfig.getCertAlias());
sslContextFactory.setKeyManagerFactoryAlgorithm(tlsServerConfig.getKeyManagerFactoryAlgorithm() == null ? KeyManagerFactory.getDefaultAlgorithm() : tlsServerConfig.getKeyManagerFactoryAlgorithm());
sslContextFactory.setKeyManagerPassword(tlsServerConfig.getKeyManagerPasswordProvider() == null ? null : tlsServerConfig.getKeyManagerPasswordProvider().getPassword());
if (tlsServerConfig.getIncludeCipherSuites() != null) {
sslContextFactory.setIncludeCipherSuites(tlsServerConfig.getIncludeCipherSuites().toArray(new String[0]));
}
if (tlsServerConfig.getExcludeCipherSuites() != null) {
sslContextFactory.setExcludeCipherSuites(tlsServerConfig.getExcludeCipherSuites().toArray(new String[0]));
}
if (tlsServerConfig.getIncludeProtocols() != null) {
sslContextFactory.setIncludeProtocols(tlsServerConfig.getIncludeProtocols().toArray(new String[0]));
}
if (tlsServerConfig.getExcludeProtocols() != null) {
sslContextFactory.setExcludeProtocols(tlsServerConfig.getExcludeProtocols().toArray(new String[0]));
}
sslContextFactory.setNeedClientAuth(tlsServerConfig.isRequireClientCertificate());
sslContextFactory.setWantClientAuth(tlsServerConfig.isRequestClientCertificate());
if (tlsServerConfig.isRequireClientCertificate() || tlsServerConfig.isRequestClientCertificate()) {
if (tlsServerConfig.getCrlPath() != null) {
// setValidatePeerCerts is used just to enable revocation checking using a static CRL file.
// Certificate validation is always performed when client certificates are required.
sslContextFactory.setValidatePeerCerts(true);
sslContextFactory.setCrlPath(tlsServerConfig.getCrlPath());
}
if (tlsServerConfig.isValidateHostnames()) {
sslContextFactory.setEndpointIdentificationAlgorithm("HTTPS");
}
if (tlsServerConfig.getTrustStorePath() != null) {
sslContextFactory.setTrustStorePath(tlsServerConfig.getTrustStorePath());
sslContextFactory.setTrustStoreType(tlsServerConfig.getTrustStoreType() == null ? KeyStore.getDefaultType() : tlsServerConfig.getTrustStoreType());
sslContextFactory.setTrustManagerFactoryAlgorithm(tlsServerConfig.getTrustStoreAlgorithm() == null ? TrustManagerFactory.getDefaultAlgorithm() : tlsServerConfig.getTrustStoreAlgorithm());
sslContextFactory.setTrustStorePassword(tlsServerConfig.getTrustStorePasswordProvider() == null ? null : tlsServerConfig.getTrustStorePasswordProvider().getPassword());
}
}
} else {
sslContextFactory = sslContextFactoryBinding.getProvider().get();
}
final HttpConfiguration httpsConfiguration = new HttpConfiguration();
if (config.isEnableForwardedRequestCustomizer()) {
httpsConfiguration.addCustomizer(new ForwardedRequestCustomizer());
}
httpsConfiguration.setSecureScheme("https");
httpsConfiguration.setSecurePort(node.getTlsPort());
httpsConfiguration.addCustomizer(new SecureRequestCustomizer());
httpsConfiguration.setRequestHeaderSize(config.getMaxRequestHeaderSize());
httpsConfiguration.setSendServerVersion(false);
final ServerConnector connector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HTTP_1_1_STRING), new HttpConnectionFactory(httpsConfiguration));
if (node.isBindOnHost()) {
connector.setHost(node.getHost());
}
connector.setPort(node.getTlsPort());
serverConnectors.add(connector);
} else {
sslContextFactory = null;
}
final ServerConnector[] connectors = new ServerConnector[serverConnectors.size()];
int index = 0;
for (ServerConnector connector : serverConnectors) {
connectors[index++] = connector;
connector.setIdleTimeout(Ints.checkedCast(config.getMaxIdleTime().toStandardDuration().getMillis()));
// workaround suggested in -
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=435322#c66 for jetty half open connection issues during failovers
connector.setAcceptorPriorityDelta(-1);
List<ConnectionFactory> monitoredConnFactories = new ArrayList<>();
for (ConnectionFactory cf : connector.getConnectionFactories()) {
// connection factories (in this case HTTP/1.1 after the connection is unencrypted for SSL)
if (cf.getProtocol().equals(connector.getDefaultProtocol())) {
monitoredConnFactories.add(new JettyMonitoringConnectionFactory(cf, ACTIVE_CONNECTIONS));
} else {
monitoredConnFactories.add(cf);
}
}
connector.setConnectionFactories(monitoredConnFactories);
}
server.setConnectors(connectors);
final long gracefulStop = config.getGracefulShutdownTimeout().toStandardDuration().getMillis();
if (gracefulStop > 0) {
server.setStopTimeout(gracefulStop);
}
server.addLifeCycleListener(new LifeCycle.Listener() {
@Override
public void lifeCycleStarting(LifeCycle event) {
log.debug("Jetty lifecycle starting [%s]", event.getClass());
}
@Override
public void lifeCycleStarted(LifeCycle event) {
log.debug("Jetty lifeycle started [%s]", event.getClass());
}
@Override
public void lifeCycleFailure(LifeCycle event, Throwable cause) {
log.error(cause, "Jetty lifecycle event failed [%s]", event.getClass());
}
@Override
public void lifeCycleStopping(LifeCycle event) {
log.debug("Jetty lifecycle stopping [%s]", event.getClass());
}
@Override
public void lifeCycleStopped(LifeCycle event) {
log.debug("Jetty lifecycle stopped [%s]", event.getClass());
}
});
// initialize server
JettyServerInitializer initializer = injector.getInstance(JettyServerInitializer.class);
try {
initializer.initialize(server, injector);
} catch (Exception e) {
throw new RE(e, "server initialization exception");
}
lifecycle.addHandler(new Lifecycle.Handler() {
@Override
public void start() throws Exception {
log.debug("Starting Jetty Server...");
server.start();
if (node.isEnableTlsPort()) {
// Perform validation
Preconditions.checkNotNull(sslContextFactory);
final SSLEngine sslEngine = sslContextFactory.newSSLEngine();
if (sslEngine.getEnabledCipherSuites() == null || sslEngine.getEnabledCipherSuites().length == 0) {
throw new ISE("No supported cipher suites found, supported suites [%s], configured suites include list: [%s] exclude list: [%s]", Arrays.toString(sslEngine.getSupportedCipherSuites()), tlsServerConfig.getIncludeCipherSuites(), tlsServerConfig.getExcludeCipherSuites());
}
if (sslEngine.getEnabledProtocols() == null || sslEngine.getEnabledProtocols().length == 0) {
throw new ISE("No supported protocols found, supported protocols [%s], configured protocols include list: [%s] exclude list: [%s]", Arrays.toString(sslEngine.getSupportedProtocols()), tlsServerConfig.getIncludeProtocols(), tlsServerConfig.getExcludeProtocols());
}
}
}
@Override
public void stop() {
try {
final long unannounceDelay = config.getUnannouncePropagationDelay().toStandardDuration().getMillis();
if (unannounceDelay > 0) {
log.info("Sleeping %s ms for unannouncement to propagate.", unannounceDelay);
Thread.sleep(unannounceDelay);
} else {
log.debug("Skipping unannounce wait.");
}
log.debug("Stopping Jetty Server...");
server.stop();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RE(e, "Interrupted waiting for jetty shutdown.");
} catch (Exception e) {
log.warn(e, "Unable to stop Jetty server.");
}
}
}, Lifecycle.Stage.SERVER);
if (!config.isShowDetailedJettyErrors()) {
server.setErrorHandler(new ErrorHandler() {
@Override
public boolean isShowServlet() {
return false;
}
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, null);
super.handle(target, baseRequest, request, response);
}
});
}
return server;
}
use of org.eclipse.jetty.server.SecureRequestCustomizer in project XRTB by benmfaul.
the class AddShutdownHook method run.
/**
* Establishes the HTTP Handler, creates the Jetty server and attaches the
* handler and then joins the server. This method does not return, but it is
* interruptable by calling the halt() method.
*/
@Override
public void run() {
SSL ssl = Configuration.getInstance().ssl;
if (Configuration.getInstance().port == 0 && ssl == null) {
try {
logger.error("Neither HTTP or HTTPS configured, error, stop");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return;
}
QueuedThreadPool threadPool = new QueuedThreadPool(threads, 50);
server = new Server(threadPool);
ServerConnector connector = null;
if (Configuration.getInstance().port != 0) {
connector = new ServerConnector(server);
connector.setPort(Configuration.getInstance().port);
connector.setIdleTimeout(60000);
}
if (config.getInstance().ssl != null) {
HttpConfiguration https = new HttpConfiguration();
https.addCustomizer(new SecureRequestCustomizer());
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStorePath(ssl.setKeyStorePath);
sslContextFactory.setKeyStorePassword(ssl.setKeyStorePassword);
sslContextFactory.setKeyManagerPassword(ssl.setKeyManagerPassword);
ServerConnector sslConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(https));
sslConnector.setPort(Configuration.getInstance().sslPort);
if (connector != null)
server.setConnectors(new Connector[] { connector, sslConnector });
else
server.setConnectors(new Connector[] { sslConnector });
try {
logger.info("SSL configured on port {}", Configuration.getInstance().sslPort);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else
server.setConnectors(new Connector[] { connector });
Handler handler = new Handler();
node = null;
try {
new WebMQ(7379, null);
BidRequest.compile();
// org.eclipse.jetty.server.session.SessionHandler
SessionHandler sh = new SessionHandler();
sh.setHandler(handler);
// set session handle
server.setHandler(sh);
startPeridocLogger();
/**
* Override the start state if the deadmanswitch object is not null
* and the key doesn't exist
*/
if (Configuration.getInstance().deadmanSwitch != null) {
if (Configuration.getInstance().deadmanSwitch.canRun() == false) {
RTBServer.stopped = true;
}
}
server.start();
Thread.sleep(500);
ready = true;
// qps timer
deltaTime = System.currentTimeMillis();
if (Controller.getInstance().responseQueue != null)
Controller.getInstance().responseQueue.add(getStatus());
logger.info("********************* System start on port: {}/{}", Performance.getInternalAddress(), Configuration.getInstance().port);
startSeparateAdminServer();
startedLatch.countDown();
server.join();
} catch (Exception error) {
if (error.toString().contains("Interrupt"))
try {
logger.error("HALT: : {}", error.toString());
if (node != null)
node.halt();
} catch (Exception e) {
e.printStackTrace();
}
else
error.printStackTrace();
} finally {
if (node != null)
node.stop();
}
}
Aggregations