Search in sources :

Example 56 with SslContextFactory

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);
}
Also used : KeyPair(java.security.KeyPair) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) SecureRandom(java.security.SecureRandom) KeyPairGenerator(java.security.KeyPairGenerator) ByteArrayOutputStream(java.io.ByteArrayOutputStream) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) KeyStore(java.security.KeyStore) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) ServerConnector(org.eclipse.jetty.server.ServerConnector) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) X509V3CertificateGenerator(org.bouncycastle.x509.X509V3CertificateGenerator) X509Principal(org.bouncycastle.jce.X509Principal) ByteArrayInputStream(java.io.ByteArrayInputStream) DefaultResourceLoader(org.springframework.core.io.DefaultResourceLoader)

Example 57 with SslContextFactory

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();
        }
    }
}
Also used : ServiceError(com.kixeye.chassis.transport.dto.ServiceError) HashMap(java.util.HashMap) WebSocketMessageRegistry(com.kixeye.chassis.transport.websocket.WebSocketMessageRegistry) JsonJacksonMessageSerDe(com.kixeye.chassis.transport.serde.converter.JsonJacksonMessageSerDe) ProtobufMessageSerDe(com.kixeye.chassis.transport.serde.converter.ProtobufMessageSerDe) YamlJacksonMessageSerDe(com.kixeye.chassis.transport.serde.converter.YamlJacksonMessageSerDe) XmlMessageSerDe(com.kixeye.chassis.transport.serde.converter.XmlMessageSerDe) MessageSerDe(com.kixeye.chassis.transport.serde.MessageSerDe) WebSocketClient(org.eclipse.jetty.websocket.client.WebSocketClient) Envelope(com.kixeye.chassis.transport.dto.Envelope) AnnotationConfigWebApplicationContext(org.springframework.web.context.support.AnnotationConfigWebApplicationContext) URI(java.net.URI) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) Header(com.kixeye.chassis.transport.dto.Header) MapPropertySource(org.springframework.core.env.MapPropertySource) QueuingWebSocketListener(com.kixeye.chassis.transport.websocket.QueuingWebSocketListener) StandardEnvironment(org.springframework.core.env.StandardEnvironment) Session(org.eclipse.jetty.websocket.api.Session) WebSocketSession(org.eclipse.jetty.websocket.common.WebSocketSession) Test(org.junit.Test)

Example 58 with SslContextFactory

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;
}
Also used : SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory)

Example 59 with SslContextFactory

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;
}
Also used : SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory)

Example 60 with SslContextFactory

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;
}
Also used : Path(java.nio.file.Path) ServerConnector(org.eclipse.jetty.server.ServerConnector) Connector(org.eclipse.jetty.server.Connector) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) Request(org.eclipse.jetty.server.Request) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) URISyntaxException(java.net.URISyntaxException) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) URI(java.net.URI) ForwardedRequestCustomizer(org.eclipse.jetty.server.ForwardedRequestCustomizer) ServerConnector(org.eclipse.jetty.server.ServerConnector) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) AuthType(com.google.gerrit.extensions.client.AuthType) ForwardedRequestCustomizer(org.eclipse.jetty.server.ForwardedRequestCustomizer) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer)

Aggregations

SslContextFactory (org.eclipse.jetty.util.ssl.SslContextFactory)139 ServerConnector (org.eclipse.jetty.server.ServerConnector)54 HttpConnectionFactory (org.eclipse.jetty.server.HttpConnectionFactory)44 Server (org.eclipse.jetty.server.Server)43 SslConnectionFactory (org.eclipse.jetty.server.SslConnectionFactory)43 Test (org.junit.Test)40 HttpConfiguration (org.eclipse.jetty.server.HttpConfiguration)37 SecureRequestCustomizer (org.eclipse.jetty.server.SecureRequestCustomizer)35 QueuedThreadPool (org.eclipse.jetty.util.thread.QueuedThreadPool)23 InputStream (java.io.InputStream)18 IOException (java.io.IOException)17 File (java.io.File)15 SSLContext (javax.net.ssl.SSLContext)15 ServletException (javax.servlet.ServletException)15 OutputStream (java.io.OutputStream)14 HttpServletRequest (javax.servlet.http.HttpServletRequest)13 HttpServletResponse (javax.servlet.http.HttpServletResponse)13 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)13 AbstractHandler (org.eclipse.jetty.server.handler.AbstractHandler)11 InetSocketAddress (java.net.InetSocketAddress)10