use of org.eclipse.jetty.util.ssl.SslContextFactory in project chassis by Kixeye.
the class JettyConnectorRegistry method registerHttpsConnector.
/**
* Register to listen to HTTPS.
*
* @param server
* @param address
* @throws Exception
*/
public static void registerHttpsConnector(Server server, InetSocketAddress address, boolean selfSigned, boolean mutualSsl, String keyStorePath, String keyStoreData, String keyStorePassword, String keyManagerPassword, String trustStorePath, String trustStoreData, String trustStorePassword, String[] excludedCipherSuites) throws Exception {
// SSL Context Factory
SslContextFactory sslContextFactory = new SslContextFactory();
if (selfSigned) {
char[] passwordChars = UUID.randomUUID().toString().toCharArray();
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, passwordChars);
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();
v3CertGen.setSerialNumber(BigInteger.valueOf(new SecureRandom().nextInt()).abs());
v3CertGen.setIssuerDN(new X509Principal("CN=" + "kixeye.com" + ", OU=None, O=None L=None, C=None"));
v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)));
v3CertGen.setSubjectDN(new X509Principal("CN=" + "kixeye.com" + ", OU=None, O=None L=None, C=None"));
v3CertGen.setPublicKey(keyPair.getPublic());
v3CertGen.setSignatureAlgorithm("MD5WithRSAEncryption");
X509Certificate privateKeyCertificate = v3CertGen.generateX509Certificate(keyPair.getPrivate());
keyStore.setKeyEntry("selfSigned", keyPair.getPrivate(), passwordChars, new java.security.cert.Certificate[] { privateKeyCertificate });
ByteArrayOutputStream keyStoreBaos = new ByteArrayOutputStream();
keyStore.store(keyStoreBaos, passwordChars);
keyStoreData = new String(Hex.encode(keyStoreBaos.toByteArray()), Charsets.UTF_8);
keyStorePassword = new String(passwordChars);
keyManagerPassword = keyStorePassword;
sslContextFactory.setTrustAll(true);
}
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
if (StringUtils.isNotBlank(keyStoreData)) {
keyStore.load(new ByteArrayInputStream(Hex.decode(keyStoreData)), keyStorePassword.toCharArray());
} else if (StringUtils.isNotBlank(keyStorePath)) {
try (InputStream inputStream = new DefaultResourceLoader().getResource(keyStorePath).getInputStream()) {
keyStore.load(inputStream, keyStorePassword.toCharArray());
}
}
sslContextFactory.setKeyStore(keyStore);
sslContextFactory.setKeyStorePassword(keyStorePassword);
if (StringUtils.isBlank(keyManagerPassword)) {
keyManagerPassword = keyStorePassword;
}
sslContextFactory.setKeyManagerPassword(keyManagerPassword);
KeyStore trustStore = null;
if (StringUtils.isNotBlank(trustStoreData)) {
trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(new ByteArrayInputStream(Hex.decode(trustStoreData)), trustStorePassword.toCharArray());
} else if (StringUtils.isNotBlank(trustStorePath)) {
trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
try (InputStream inputStream = new DefaultResourceLoader().getResource(trustStorePath).getInputStream()) {
trustStore.load(inputStream, trustStorePassword.toCharArray());
}
}
if (trustStore != null) {
sslContextFactory.setTrustStore(trustStore);
sslContextFactory.setTrustStorePassword(trustStorePassword);
}
sslContextFactory.setNeedClientAuth(mutualSsl);
sslContextFactory.setExcludeCipherSuites(excludedCipherSuites);
// SSL Connector
ServerConnector connector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.toString()), new HttpConnectionFactory());
connector.setHost(address.getHostName());
connector.setPort(address.getPort());
server.addConnector(connector);
}
use of org.eclipse.jetty.util.ssl.SslContextFactory in project chassis by Kixeye.
the class WebSocketTransportTest method testWebSocketServiceWithJsonWithWss.
@Test
public void testWebSocketServiceWithJsonWithWss() throws Exception {
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("secureWebsocket.enabled", "true");
properties.put("secureWebsocket.port", "" + SocketUtils.findAvailableTcpPort());
properties.put("secureWebsocket.hostname", "localhost");
properties.put("secureWebsocket.selfSigned", "true");
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
StandardEnvironment environment = new StandardEnvironment();
environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
context.setEnvironment(environment);
context.register(PropertySourcesPlaceholderConfigurer.class);
context.register(TransportConfiguration.class);
context.register(TestWebSocketService.class);
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setTrustAll(true);
WebSocketClient wsClient = new WebSocketClient(sslContextFactory);
try {
context.refresh();
final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class);
final WebSocketMessageRegistry messageRegistry = context.getBean(WebSocketMessageRegistry.class);
messageRegistry.registerType("stuff", TestObject.class);
wsClient.start();
QueuingWebSocketListener webSocket = new QueuingWebSocketListener(serDe, messageRegistry, null);
Session session = wsClient.connect(webSocket, new URI("wss://localhost:" + properties.get("secureWebsocket.port") + "/" + serDe.getMessageFormatName())).get(5000, TimeUnit.MILLISECONDS);
Envelope envelope = new Envelope("getStuff", null, null, Lists.newArrayList(new Header("testheadername", Lists.newArrayList("testheaderval"))), null);
session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));
TestObject response = webSocket.getResponse(5, TimeUnit.SECONDS);
Assert.assertNotNull(response);
Assert.assertEquals("stuff", response.value);
byte[] rawStuff = serDe.serialize(new TestObject("more stuff"));
envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff));
session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));
response = webSocket.getResponse(5, TimeUnit.SECONDS);
Assert.assertNotNull(response);
Assert.assertEquals("stuff", response.value);
envelope = new Envelope("getStuff", null, null, null);
session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));
response = webSocket.getResponse(5, TimeUnit.SECONDS);
Assert.assertNotNull(response);
Assert.assertEquals("more stuff", response.value);
rawStuff = serDe.serialize(new TestObject(RandomStringUtils.randomAlphanumeric(100)));
envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff));
session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));
ServiceError error = webSocket.getResponse(5, TimeUnit.SECONDS);
Assert.assertNotNull(error);
Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.code);
envelope = new Envelope("expectedError", null, null, null);
session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));
error = webSocket.getResponse(5, TimeUnit.SECONDS);
Assert.assertNotNull(error);
Assert.assertEquals(TestWebSocketService.EXPECTED_EXCEPTION.code, error.code);
Assert.assertEquals(TestWebSocketService.EXPECTED_EXCEPTION.description, error.description);
envelope = new Envelope("unexpectedError", null, null, null);
session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));
error = webSocket.getResponse(5, TimeUnit.SECONDS);
Assert.assertNotNull(error);
Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.code);
} finally {
try {
wsClient.stop();
} finally {
context.close();
}
}
}
use of org.eclipse.jetty.util.ssl.SslContextFactory in project lucene-solr by apache.
the class SSLConfig method createContextFactory.
/**
* Returns an SslContextFactory that should be used by a jetty server based on this SSLConfig instance,
* or null if SSL should not be used.
*
* The default implementation generates a simple factory according to the keystore, truststore,
* and clientAuth properties of this object.
*
* @see #getKeyStore
* @see #getKeyStorePassword
* @see #isClientAuthMode
* @see #getTrustStore
* @see #getTrustStorePassword
*/
public SslContextFactory createContextFactory() {
if (!isSSLMode()) {
return null;
}
// else...
SslContextFactory factory = new SslContextFactory(false);
if (getKeyStore() != null)
factory.setKeyStorePath(getKeyStore());
if (getKeyStorePassword() != null)
factory.setKeyStorePassword(getKeyStorePassword());
factory.setNeedClientAuth(isClientAuthMode());
if (isClientAuthMode()) {
if (getTrustStore() != null)
factory.setTrustStorePath(getTrustStore());
if (getTrustStorePassword() != null)
factory.setTrustStorePassword(getTrustStorePassword());
}
return factory;
}
use of org.eclipse.jetty.util.ssl.SslContextFactory in project lucene-solr by apache.
the class SSLConfig method configureSslFromSysProps.
private static SslContextFactory configureSslFromSysProps() {
SslContextFactory sslcontext = new SslContextFactory(false);
if (null != System.getProperty("javax.net.ssl.keyStore")) {
sslcontext.setKeyStorePath(System.getProperty("javax.net.ssl.keyStore"));
}
if (null != System.getProperty("javax.net.ssl.keyStorePassword")) {
sslcontext.setKeyStorePassword(System.getProperty("javax.net.ssl.keyStorePassword"));
}
if (null != System.getProperty("javax.net.ssl.trustStore")) {
sslcontext.setTrustStorePath(System.getProperty("javax.net.ssl.trustStore"));
}
if (null != System.getProperty("javax.net.ssl.trustStorePassword")) {
sslcontext.setTrustStorePassword(System.getProperty("javax.net.ssl.trustStorePassword"));
}
sslcontext.setNeedClientAuth(Boolean.getBoolean("tests.jettySsl.clientAuth"));
return sslcontext;
}
use of org.eclipse.jetty.util.ssl.SslContextFactory 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 ssl = new SslContextFactory();
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(new HttpConfiguration.Customizer() {
@Override
public void customize(Connector connector, HttpConfiguration channelConfig, Request 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;
}
Aggregations