Search in sources :

Example 41 with SslContextFactory

use of org.eclipse.jetty.util.ssl.SslContextFactory in project jetty.project by eclipse.

the class SniSslConnectionFactoryTest method testSameConnectionRequestsForManyDomains.

@Test
public void testSameConnectionRequestsForManyDomains() throws Exception {
    SslContextFactory clientContextFactory = new SslContextFactory(true);
    clientContextFactory.start();
    SSLSocketFactory factory = clientContextFactory.getSslContext().getSocketFactory();
    try (SSLSocket sslSocket = (SSLSocket) factory.createSocket("127.0.0.1", _port)) {
        SNIHostName serverName = new SNIHostName("m.san.com");
        SSLParameters params = sslSocket.getSSLParameters();
        params.setServerNames(Collections.singletonList(serverName));
        sslSocket.setSSLParameters(params);
        sslSocket.startHandshake();
        // The first request binds the socket to an alias.
        String request = "" + "GET /ctx/path HTTP/1.1\r\n" + "Host: m.san.com\r\n" + "\r\n";
        OutputStream output = sslSocket.getOutputStream();
        output.write(request.getBytes(StandardCharsets.UTF_8));
        output.flush();
        InputStream input = sslSocket.getInputStream();
        String response = response(input);
        Assert.assertTrue(response.startsWith("HTTP/1.1 200 "));
        // Same socket, send a request for a different domain but same alias.
        request = "" + "GET /ctx/path HTTP/1.1\r\n" + "Host: www.san.com\r\n" + "\r\n";
        output.write(request.getBytes(StandardCharsets.UTF_8));
        output.flush();
        response = response(input);
        Assert.assertTrue(response.startsWith("HTTP/1.1 200 "));
        // Same socket, send a request for a different domain but different alias.
        request = "" + "GET /ctx/path HTTP/1.1\r\n" + "Host: www.example.com\r\n" + "\r\n";
        output.write(request.getBytes(StandardCharsets.UTF_8));
        output.flush();
        response = response(input);
        assertThat(response, startsWith("HTTP/1.1 400 "));
        assertThat(response, containsString("Host does not match SNI"));
    } finally {
        clientContextFactory.stop();
    }
}
Also used : SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) SSLParameters(javax.net.ssl.SSLParameters) SNIHostName(javax.net.ssl.SNIHostName) InputStream(java.io.InputStream) SSLSocket(javax.net.ssl.SSLSocket) OutputStream(java.io.OutputStream) Matchers.containsString(org.hamcrest.Matchers.containsString) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) Test(org.junit.Test)

Example 42 with SslContextFactory

use of org.eclipse.jetty.util.ssl.SslContextFactory in project Openfire by igniterealtime.

the class AdminConsolePlugin method startup.

/**
     * Starts the Jetty instance.
     */
public void startup() {
    restartNeeded = false;
    // Add listener for certificate events
    certificateListener = new CertificateListener();
    CertificateManager.addListener(certificateListener);
    // the number of threads allocated to each connector/port
    int serverThreads = JiveGlobals.getXMLProperty("adminConsole.serverThreads", 2);
    adminPort = JiveGlobals.getXMLProperty("adminConsole.port", 9090);
    adminSecurePort = JiveGlobals.getXMLProperty("adminConsole.securePort", 9091);
    final QueuedThreadPool tp = new QueuedThreadPool();
    tp.setName("Jetty-QTP-AdminConsole");
    adminServer = new Server(tp);
    if (JMXManager.isEnabled()) {
        JMXManager jmx = JMXManager.getInstance();
        adminServer.addBean(jmx.getContainer());
    }
    // Create connector for http traffic if it's enabled.
    if (adminPort > 0) {
        final HttpConfiguration httpConfig = new HttpConfiguration();
        // Do not send Jetty info in HTTP headers
        httpConfig.setSendServerVersion(false);
        final ServerConnector httpConnector = new ServerConnector(adminServer, null, null, null, -1, serverThreads, new HttpConnectionFactory(httpConfig));
        // Listen on a specific network interface if it has been set.
        String bindInterface = getBindInterface();
        httpConnector.setHost(bindInterface);
        httpConnector.setPort(adminPort);
        adminServer.addConnector(httpConnector);
    }
    // Create a connector for https traffic if it's enabled.
    sslEnabled = false;
    try {
        IdentityStore identityStore = null;
        if (XMPPServer.getInstance().getCertificateStoreManager() == null) {
            Log.warn("Admin console: CertifcateStoreManager has not been initialized yet. HTTPS will be unavailable.");
        } else {
            identityStore = XMPPServer.getInstance().getCertificateStoreManager().getIdentityStore(ConnectionType.WEBADMIN);
        }
        if (identityStore != null && adminSecurePort > 0) {
            if (identityStore.getAllCertificates().isEmpty()) {
                Log.warn("Admin console: Identity store does not have any certificates. HTTPS will be unavailable.");
            } else {
                if (!identityStore.containsDomainCertificate("RSA")) {
                    Log.warn("Admin console: Using RSA certificates but they are not valid for the hosted domain");
                }
                final ConnectionManagerImpl connectionManager = ((ConnectionManagerImpl) XMPPServer.getInstance().getConnectionManager());
                final ConnectionConfiguration configuration = connectionManager.getListener(ConnectionType.WEBADMIN, true).generateConnectionConfiguration();
                final SslContextFactory sslContextFactory = new EncryptionArtifactFactory(configuration).getSslContextFactory();
                final ServerConnector httpsConnector;
                if ("npn".equals(JiveGlobals.getXMLProperty("spdy.protocol", ""))) {
                    httpsConnector = new HTTPSPDYServerConnector(adminServer, sslContextFactory);
                } else {
                    final HttpConfiguration httpsConfig = new HttpConfiguration();
                    httpsConfig.setSendServerVersion(false);
                    httpsConfig.setSecureScheme("https");
                    httpsConfig.setSecurePort(adminSecurePort);
                    httpsConfig.addCustomizer(new SecureRequestCustomizer());
                    final HttpConnectionFactory httpConnectionFactory = new HttpConnectionFactory(httpsConfig);
                    final SslConnectionFactory sslConnectionFactory = new SslConnectionFactory(sslContextFactory, org.eclipse.jetty.http.HttpVersion.HTTP_1_1.toString());
                    httpsConnector = new ServerConnector(adminServer, null, null, null, -1, serverThreads, sslConnectionFactory, httpConnectionFactory);
                }
                final String bindInterface = getBindInterface();
                httpsConnector.setHost(bindInterface);
                httpsConnector.setPort(adminSecurePort);
                adminServer.addConnector(httpsConnector);
                sslEnabled = true;
            }
        }
    } catch (Exception e) {
        Log.error("An exception occurred while trying to make available the admin console via HTTPS.", e);
    }
    // Make sure that at least one connector was registered.
    if (adminServer.getConnectors() == null || adminServer.getConnectors().length == 0) {
        adminServer = null;
        // Log warning.
        log(LocaleUtils.getLocalizedString("admin.console.warning"));
        return;
    }
    HandlerCollection collection = new HandlerCollection();
    adminServer.setHandler(collection);
    collection.setHandlers(new Handler[] { contexts, new DefaultHandler() });
    try {
        adminServer.start();
        // Log the ports that the admin server is listening on.
        logAdminConsolePorts();
    } catch (Exception e) {
        Log.error("Could not start admin console server", e);
    }
}
Also used : JMXManager(org.jivesoftware.openfire.JMXManager) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) XMPPServer(org.jivesoftware.openfire.XMPPServer) Server(org.eclipse.jetty.server.Server) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) ConnectionManagerImpl(org.jivesoftware.openfire.spi.ConnectionManagerImpl) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) HTTPSPDYServerConnector(org.eclipse.jetty.spdy.server.http.HTTPSPDYServerConnector) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler) HTTPSPDYServerConnector(org.eclipse.jetty.spdy.server.http.HTTPSPDYServerConnector) ServerConnector(org.eclipse.jetty.server.ServerConnector) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) ConnectionConfiguration(org.jivesoftware.openfire.spi.ConnectionConfiguration) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) EncryptionArtifactFactory(org.jivesoftware.openfire.spi.EncryptionArtifactFactory) ContextHandlerCollection(org.eclipse.jetty.server.handler.ContextHandlerCollection) HandlerCollection(org.eclipse.jetty.server.handler.HandlerCollection) IdentityStore(org.jivesoftware.openfire.keystore.IdentityStore)

Example 43 with SslContextFactory

use of org.eclipse.jetty.util.ssl.SslContextFactory in project killbill by killbill.

the class HttpServer method configureSslConnector.

private ServerConnector configureSslConnector(final HttpConfiguration httpConfiguration, final boolean isStatsOn, final int localSslPort, final String sslKeyStorePath, final String sslKeyStorePassword) {
    // SSL Context Factory for HTTPS
    final SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(sslKeyStorePath);
    sslContextFactory.setKeyStorePassword(sslKeyStorePassword);
    // HTTPS Configuration
    final HttpConfiguration httpsConfig = new HttpConfiguration(httpConfiguration);
    httpsConfig.addCustomizer(new SecureRequestCustomizer());
    // HTTPS connector
    final ServerConnector https = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(httpsConfig));
    https.setPort(localSslPort);
    if (isStatsOn) {
        final ConnectorStatistics stats = new ConnectorStatistics();
        https.addBean(stats);
    }
    return https;
}
Also used : ServerConnector(org.eclipse.jetty.server.ServerConnector) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) ConnectorStatistics(org.eclipse.jetty.server.ConnectorStatistics) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory)

Example 44 with SslContextFactory

use of org.eclipse.jetty.util.ssl.SslContextFactory in project ninja by ninjaframework.

the class NinjaJetty method doConfigure.

@Override
protected void doConfigure() throws Exception {
    // current value or system property or conf/application.conf or default value
    jettyConfiguration(overlayedNinjaProperties.get(KEY_NINJA_JETTY_CONFIGURATION, this.jettyConfiguration, DEFAULT_JETTY_CONFIGURATION));
    // build jetty server, context, and servlet
    if (this.jettyConfiguration != null) {
        String[] configs = this.jettyConfiguration.split(",");
        for (String config : configs) {
            jetty = buildServerOrApplyConfiguration(config, jetty);
        }
        // since we don't know host and port, try to get it from jetty
        tryToSetHostAndPortFromJetty();
    } else {
        // create very simple jetty configuration
        jetty = new Server();
        if (port > -1) {
            // build http cleartext connector
            ServerConnector http = new ServerConnector(jetty);
            http.setPort(port);
            http.setIdleTimeout(idleTimeout);
            if (host != null) {
                http.setHost(host);
            }
            jetty.addConnector(http);
        }
        if (sslPort > -1) {
            // build https secure connector
            // http://git.eclipse.org/c/jetty/org.eclipse.jetty.project.git/tree/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyConnectors.java
            HttpConfiguration httpConfig = new HttpConfiguration();
            httpConfig.setSecureScheme("https");
            httpConfig.setSecurePort(sslPort);
            httpConfig.setOutputBufferSize(32768);
            HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig);
            httpsConfig.addCustomizer(new SecureRequestCustomizer());
            // unfortunately jetty seems to only work when we pass a keystore
            // and truststore (as opposed to our own prepared SSLContext)
            // call createSSLContext() to simply verify configuration is correct
            this.createSSLContext();
            SslContextFactory sslContextFactory = new SslContextFactory();
            sslContextFactory.setKeyStore(StandaloneHelper.loadKeyStore(this.sslKeystoreUri, this.sslKeystorePassword.toCharArray()));
            sslContextFactory.setKeyManagerPassword(this.sslKeystorePassword);
            sslContextFactory.setTrustStore(StandaloneHelper.loadKeyStore(this.sslTruststoreUri, this.sslTruststorePassword.toCharArray()));
            ServerConnector https = new ServerConnector(jetty, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(httpsConfig));
            https.setPort(sslPort);
            https.setIdleTimeout(idleTimeout);
            jetty.addConnector(https);
        }
    }
    this.ninjaServletListener.setNinjaProperties(ninjaProperties);
    this.contextHandler = new ServletContextHandler(jetty, getContextPath());
    this.contextHandler.addEventListener(ninjaServletListener);
    this.contextHandler.addFilter(GuiceFilter.class, "/*", null);
    this.contextHandler.addServlet(DefaultServlet.class, "/");
    // disable directory browsing
    this.contextHandler.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
    // Add an error handler that does not print stack traces in case
    // something happens that is not under control of Ninja
    this.contextHandler.setErrorHandler(new SilentErrorHandler());
}
Also used : ServerConnector(org.eclipse.jetty.server.ServerConnector) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) Server(org.eclipse.jetty.server.Server) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler)

Example 45 with SslContextFactory

use of org.eclipse.jetty.util.ssl.SslContextFactory in project camel by apache.

the class SalesforceComponentVerifier method verifyConnectivity.

// *********************************
// Connectivity validation
// *********************************
@Override
protected Result verifyConnectivity(Map<String, Object> parameters) {
    // Default is success
    ResultBuilder builder = ResultBuilder.withStatusAndScope(Result.Status.OK, Scope.CONNECTIVITY);
    try {
        SalesforceEndpointConfig configuration = new SalesforceEndpointConfig();
        setProperties(configuration, parameters);
        SalesforceLoginConfig loginConfig = new SalesforceLoginConfig();
        setProperties(loginConfig, parameters);
        // Create a dummy SslContextFactory which is needed by SalesforceHttpClient
        // or the underlying jetty client fails with a NPE
        SSLContextParameters contextParameters = new SSLContextParameters();
        SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setSslContext(contextParameters.createSSLContext(getCamelContext()));
        SalesforceHttpClient httpClient = new SalesforceHttpClient(sslContextFactory);
        httpClient.setConnectTimeout(SalesforceComponent.CONNECTION_TIMEOUT);
        configureHttpProxy(httpClient, parameters);
        SalesforceSession session = new SalesforceSession(getCamelContext(), httpClient, httpClient.getTimeout(), loginConfig);
        DefaultRestClient client = new DefaultRestClient(httpClient, configuration.getApiVersion(), configuration.getFormat(), session);
        httpClient.setSession(session);
        httpClient.start();
        // For authentication check is is enough to use
        session.start();
        client.start();
        client.getVersions((response, exception) -> processSalesforceException(builder, Optional.ofNullable(exception)));
        client.stop();
        session.stop();
        httpClient.stop();
        httpClient.destroy();
    } catch (NoSuchOptionException e) {
        builder.error(ResultErrorBuilder.withMissingOption(e.getOptionName()).build());
    } catch (SalesforceException e) {
        processSalesforceException(builder, Optional.of(e));
    } catch (Exception e) {
        builder.error(ResultErrorBuilder.withException(e).build());
        throw new RuntimeException(e);
    }
    return builder.build();
}
Also used : ResultBuilder(org.apache.camel.impl.verifier.ResultBuilder) SalesforceException(org.apache.camel.component.salesforce.api.SalesforceException) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) NoSuchOptionException(org.apache.camel.NoSuchOptionException) SalesforceSession(org.apache.camel.component.salesforce.internal.SalesforceSession) DefaultRestClient(org.apache.camel.component.salesforce.internal.client.DefaultRestClient) URISyntaxException(java.net.URISyntaxException) NoSuchOptionException(org.apache.camel.NoSuchOptionException) SalesforceException(org.apache.camel.component.salesforce.api.SalesforceException) SSLContextParameters(org.apache.camel.util.jsse.SSLContextParameters)

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