下面列出了org.eclipse.jetty.server.HttpConfiguration#setSecurePort ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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;
}
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();
}
@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())));
}
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));
}
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);
}
}
public HttpsServer start(int httpsPort, String httpsHostname) {
server.setHandler(
new AbstractHandler() {
@Override
public void handle(String path,
Request request,
HttpServletRequest httpRequest,
HttpServletResponse response) throws IOException {
response.setHeader(CONTENT_TYPE, responseContentType);
try (PrintWriter writer = response.getWriter()) {
writer.println(responseContent);
}
}
});
// SSL HTTP Configuration
HttpConfiguration httpsConfig = new HttpConfiguration(); //httpConfig);
httpsConfig.setSecureScheme("https");
httpsConfig.setSecurePort(httpsPort);
ServerConnector sslConnector = new ServerConnector(server,
new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
new HttpConnectionFactory(httpsConfig)
);
sslConnector.setPort(httpsPort);
sslConnector.setHost(httpsHostname);
server.addConnector(sslConnector);
try {
server.start();
}
catch (Exception e) {
throw new RuntimeException("Failed to start https server", e);
}
return this;
}
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;
}
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));
}
@Override
public void start() {
HttpConfiguration httpConfig = new HttpConfiguration();
httpConfig.setSecureScheme("https");
httpConfig.setSecurePort(securePort);
ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(httpConfig));
http.setPort(port);
http.setIdleTimeout(500000);
Path keystore = getKeyStore();
if (!Files.exists(keystore)) {
throw new RuntimeException(
"Cannot find keystore for SSL cert: " + keystore.toAbsolutePath());
}
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStorePath(keystore.toAbsolutePath().toString());
sslContextFactory.setKeyStorePassword("password");
sslContextFactory.setKeyManagerPassword("password");
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.setPort(securePort);
https.setIdleTimeout(500000);
server.setConnectors(new Connector[]{http, https});
try {
server.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void createSecureConnector() {
org.eclipse.jetty.util.ssl.SslContextFactory contextFactory = new org.eclipse.jetty.util.ssl.SslContextFactory();
// 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);
}
/**
* Creates an HTTPS server that requires client authentication (though doesn't validate the chain)
*
* @param caPath The path to a CA certificate to put in the keystore.
* @param certificatePath The path to a pem encoded x509 certificate
* @param keyPath The path to a pem encoded PKCS#8 certificate
* @throws IOException Any of the keys could not be read
* @throws KeyStoreException There's a problem writing the key into the keystore
* @throws CertificateException The certificate was not valid
* @throws NoSuchAlgorithmException The algorithm used by the certificate/key are invalid
*/
public HttpdForTests(Path caPath, Path certificatePath, Path keyPath)
throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException {
// Configure the logging for jetty. Which uses a singleton. Ho hum.
Log.setLog(new JavaUtilLog());
server = new Server();
String password = "super_sekret";
ImmutableList<X509Certificate> caCerts =
ClientCertificateHandler.parseCertificates(Optional.of(caPath), true);
ClientCertificateHandler.CertificateInfo certInfo =
ClientCertificateHandler.parseCertificateChain(Optional.of(certificatePath), true).get();
PrivateKey privateKey =
ClientCertificateHandler.parsePrivateKey(
Optional.of(keyPath), certInfo.getPrimaryCert(), true)
.get();
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null, password.toCharArray());
for (int i = 0; i < caCerts.size(); i++) {
ks.setCertificateEntry(String.format("ca%d", i), caCerts.get(i));
}
ks.setKeyEntry(
"private",
privateKey,
password.toCharArray(),
new Certificate[] {certInfo.getPrimaryCert()});
SslContextFactory sslFactory = new SslContextFactory();
sslFactory.setKeyStore(ks);
sslFactory.setKeyStorePassword(password);
sslFactory.setCertAlias("private");
sslFactory.setTrustStore(ks);
sslFactory.setTrustStorePassword(password);
// *Require* a client cert, but don't validate it (getting TLS auth working properly was a
// bit of a pain). We'll store peers' certs in the handler, and validate the certs manually
// in our tests.
sslFactory.setNeedClientAuth(true);
sslFactory.setTrustAll(true);
HttpConfiguration https_config = new HttpConfiguration();
https_config.setSecurePort(0);
https_config.setSecureScheme("https");
https_config.addCustomizer(new SecureRequestCustomizer());
ServerConnector sslConnector =
new ServerConnector(
server,
new SslConnectionFactory(sslFactory, HttpVersion.HTTP_1_1.toString()),
new HttpConnectionFactory(https_config));
server.addConnector(sslConnector);
handlerList = new HandlerList();
localhost = getLocalhostAddress(false).getHostAddress();
}
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);
}
}
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);
}
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;
}
public static void main(String[] args) throws Exception {
int timeout = (int) Duration.ONE_HOUR.getMilliseconds();
System.setProperty(WICKET_CFG, CfgType.development.toString());
Server server = new Server();
ServerConnector connector = new ServerConnector(server);
// Set some timeout options to make debugging easier.
connector.setIdleTimeout(timeout);
connector.setSoLingerTime(-1);
connector.setPort(8080);
server.addConnector(connector);
Resource keystore = Resource.newClassPathResource("/keystore");
if (keystore != null && keystore.exists()) {
// if a keystore for a SSL certificate is available, start a SSL
// connector on port 8443.
// By default, the quickstart comes with a Apache Wicket Quickstart
// Certificate that expires about half way september 2021. Do not
// use this certificate anywhere important as the passwords are
// available in the source.
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStoreResource(keystore);
sslContextFactory.setKeyStorePassword("wicket");
sslContextFactory.setTrustStoreResource(keystore);
sslContextFactory.setKeyManagerPassword("wicket");
// HTTP Configuration
HttpConfiguration httpConfig = new HttpConfiguration();
httpConfig.setSecureScheme("https");
httpConfig.setSecurePort(8443);
httpConfig.setOutputBufferSize(32768);
httpConfig.setRequestHeaderSize(8192);
httpConfig.setResponseHeaderSize(8192);
httpConfig.setSendServerVersion(true);
httpConfig.setSendDateHeader(false);
// SSL HTTP Configuration
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(8443);
server.addConnector(sslConnector);
System.out.println("SSL access to the quickstart has been enabled on port 8443");
System.out.println("You can access the application using SSL on https://localhost:8443");
System.out.println();
}
WebAppContext bb = new WebAppContext();
bb.setServer(server);
bb.setContextPath("/");
bb.setWar("src/main/webapp");
// START JMX SERVER
// MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
// MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer);
// server.getContainer().addEventListener(mBeanContainer);
// mBeanContainer.start();
server.setHandler(bb);
try {
System.out.println(">>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP");
server.start();
System.in.read();
System.out.println(">>> STOPPING EMBEDDED JETTY SERVER");
server.stop();
server.join();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
/**
* Inits the.
*
* @throws Exception the exception
*/
public final void init() throws Exception {
initialised = true;
server = new Server();
Security.addProvider(new BouncyCastleProvider());
// Setup JMX
final MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
server.addBean(mbContainer);
final org.eclipse.jetty.webapp.Configurations classlist = org.eclipse.jetty.webapp.Configurations.setServerDefault(server);
final HttpConfiguration http_config = new HttpConfiguration();
http_config.setSecureScheme("https");
http_config.setSecurePort(28443);
http_config.setSendServerVersion(false);
final HttpConfiguration https_config = new HttpConfiguration(http_config);
https_config.addCustomizer(new SecureRequestCustomizer());
final SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
sslContextFactory.setKeyStoreType("PKCS12");
sslContextFactory.setKeyStorePath("target/keystore.p12");
sslContextFactory.setTrustStorePath("target/keystore.p12");
sslContextFactory.setTrustStoreType("PKCS12");
sslContextFactory.setKeyStorePassword("changeit");
sslContextFactory.setTrustStorePassword("changeit");
sslContextFactory.setKeyManagerPassword("changeit");
sslContextFactory.setCertAlias("jetty");
sslContextFactory.setIncludeCipherSuites("TLS_AES_256_GCM_SHA384", "TLS_CHACHA20_POLY1305_SHA256",
"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
"TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256");
sslContextFactory.setExcludeProtocols("SSL", "SSLv2", "SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.1");
sslContextFactory.setIncludeProtocols("TLSv1.2", "TLSv1.3");
final ServerConnector sslConnector = new ServerConnector(server,
new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(https_config),
new HTTP2CServerConnectionFactory(https_config));
sslConnector.setPort(PORT);
server.setConnectors(new ServerConnector[] { sslConnector });
final WebAppContext handler = new WebAppContext("src/main/webapp", "/");
handler.setExtraClasspath("target/classes");
handler.setParentLoaderPriority(true);
handler.setConfigurationDiscovered(true);
handler.setClassLoader(Thread.currentThread().getContextClassLoader());
final HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] { handler, new DefaultHandler() });
server.setHandler(handlers);
}
@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();
}
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;
}
/**
* Main function, starts the jetty server.
*
* @param args
*/
public static void main(String[] args)
{
System.setProperty("wicket.configuration", "development");
Server server = new Server();
HttpConfiguration http_config = new HttpConfiguration();
http_config.setSecureScheme("https");
http_config.setSecurePort(8443);
http_config.setOutputBufferSize(32768);
ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(http_config));
http.setPort(8080);
http.setIdleTimeout(1000 * 60 * 60);
server.addConnector(http);
Resource keystore = Resource.newClassPathResource("/keystore");
if (keystore != null && keystore.exists())
{
// if a keystore for a SSL certificate is available, start a SSL
// connector on port 8443.
// By default, the quickstart comes with a Apache Wicket Quickstart
// Certificate that expires about half way september 2021. Do not
// use this certificate anywhere important as the passwords are
// available in the source.
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStoreResource(keystore);
sslContextFactory.setKeyStorePassword("wicket");
sslContextFactory.setKeyManagerPassword("wicket");
HttpConfiguration https_config = new HttpConfiguration(http_config);
https_config.addCustomizer(new SecureRequestCustomizer());
ServerConnector https = new ServerConnector(server, new SslConnectionFactory(
sslContextFactory, "http/1.1"), new HttpConnectionFactory(https_config));
https.setPort(8443);
https.setIdleTimeout(500000);
server.addConnector(https);
System.out.println("SSL access to the examples has been enabled on port 8443");
System.out
.println("You can access the application using SSL on https://localhost:8443");
System.out.println();
}
WebAppContext bb = new WebAppContext();
bb.setServer(server);
bb.setContextPath("/");
bb.setWar("src/main/webapp");
// uncomment next line if you want to test with JSESSIONID encoded in the urls
// ((AbstractSessionManager)
// bb.getSessionHandler().getSessionManager()).setUsingCookies(false);
server.setHandler(bb);
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer);
server.addEventListener(mBeanContainer);
server.addBean(mBeanContainer);
try
{
server.start();
server.join();
}
catch (Exception e)
{
e.printStackTrace();
System.exit(100);
}
}
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);
}