Search in sources :

Example 21 with SSLContext

use of javax.net.ssl.SSLContext in project jetty.project by eclipse.

the class JDK9ALPNTest method testClientNotSupportingALPNServerSpeaksDefaultProtocol.

@Test
public void testClientNotSupportingALPNServerSpeaksDefaultProtocol() throws Exception {
    startServer(new AbstractHandler.ErrorDispatchHandler() {

        @Override
        protected void doNonErrorHandle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            baseRequest.setHandled(true);
        }
    });
    SslContextFactory sslContextFactory = new SslContextFactory(true);
    sslContextFactory.start();
    SSLContext sslContext = sslContextFactory.getSslContext();
    try (SSLSocket client = (SSLSocket) sslContext.getSocketFactory().createSocket("localhost", connector.getLocalPort())) {
        client.setUseClientMode(true);
        client.setSoTimeout(5000);
        client.startHandshake();
        OutputStream output = client.getOutputStream();
        output.write(("" + "GET / HTTP/1.1\r\n" + "Host: localhost\r\n" + "Connection: close\r\n" + "\r\n" + "").getBytes(StandardCharsets.UTF_8));
        output.flush();
        InputStream input = client.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
        String line = reader.readLine();
        Assert.assertTrue(line.contains(" 200 "));
        while (true) {
            if (reader.readLine() == null)
                break;
        }
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) SSLSocket(javax.net.ssl.SSLSocket) OutputStream(java.io.OutputStream) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) SSLContext(javax.net.ssl.SSLContext) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) BufferedReader(java.io.BufferedReader) Test(org.junit.Test)

Example 22 with SSLContext

use of javax.net.ssl.SSLContext in project jetty.project by eclipse.

the class SslContextFactory method newSslSocket.

public SSLSocket newSslSocket() throws IOException {
    checkIsStarted();
    SSLContext context = getSslContext();
    SSLSocketFactory factory = context.getSocketFactory();
    SSLSocket socket = (SSLSocket) factory.createSocket();
    socket.setSSLParameters(customize(socket.getSSLParameters()));
    return socket;
}
Also used : SSLSocket(javax.net.ssl.SSLSocket) SSLContext(javax.net.ssl.SSLContext) SSLSocketFactory(javax.net.ssl.SSLSocketFactory)

Example 23 with SSLContext

use of javax.net.ssl.SSLContext in project jetty.project by eclipse.

the class TLSServerConnectionCloseTest method testServerSendsConnectionClose.

private void testServerSendsConnectionClose(boolean chunked, String content) throws Exception {
    ServerSocket server = new ServerSocket(0);
    int port = server.getLocalPort();
    startClient();
    Request request = client.newRequest("localhost", port).scheme("https").path("/ctx/path");
    FutureResponseListener listener = new FutureResponseListener(request);
    request.send(listener);
    Socket socket = server.accept();
    SSLContext sslContext = client.getSslContextFactory().getSslContext();
    SSLSocket sslSocket = (SSLSocket) sslContext.getSocketFactory().createSocket(socket, "localhost", port, false);
    sslSocket.setUseClientMode(false);
    sslSocket.startHandshake();
    InputStream input = sslSocket.getInputStream();
    consumeRequest(input);
    OutputStream output = sslSocket.getOutputStream();
    String serverResponse = "" + "HTTP/1.1 200 OK\r\n" + "Connection: close\r\n";
    if (chunked) {
        serverResponse += "" + "Transfer-Encoding: chunked\r\n" + "\r\n";
        for (int i = 0; i < 2; ++i) {
            serverResponse += Integer.toHexString(content.length()) + "\r\n" + content + "\r\n";
        }
        serverResponse += "" + "0\r\n" + "\r\n";
    } else {
        serverResponse += "Content-Length: " + content.length() + "\r\n";
        serverResponse += "\r\n";
        serverResponse += content;
    }
    output.write(serverResponse.getBytes("UTF-8"));
    output.flush();
    switch(closeMode) {
        case NONE:
            {
                break;
            }
        case CLOSE:
            {
                sslSocket.close();
                break;
            }
        case ABRUPT:
            {
                socket.shutdownOutput();
                break;
            }
        default:
            {
                throw new IllegalStateException();
            }
    }
    ContentResponse response = listener.get(5, TimeUnit.SECONDS);
    Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
    // Give some time to process the connection.
    Thread.sleep(1000);
    // Connection should have been removed from pool.
    HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP) client.getDestination("http", "localhost", port);
    DuplexConnectionPool connectionPool = (DuplexConnectionPool) destination.getConnectionPool();
    Assert.assertEquals(0, connectionPool.getConnectionCount());
    Assert.assertEquals(0, connectionPool.getIdleConnectionCount());
    Assert.assertEquals(0, connectionPool.getActiveConnectionCount());
}
Also used : ContentResponse(org.eclipse.jetty.client.api.ContentResponse) InputStream(java.io.InputStream) SSLSocket(javax.net.ssl.SSLSocket) OutputStream(java.io.OutputStream) Request(org.eclipse.jetty.client.api.Request) ServerSocket(java.net.ServerSocket) SSLContext(javax.net.ssl.SSLContext) HttpDestinationOverHTTP(org.eclipse.jetty.client.http.HttpDestinationOverHTTP) Socket(java.net.Socket) SSLSocket(javax.net.ssl.SSLSocket) ServerSocket(java.net.ServerSocket) FutureResponseListener(org.eclipse.jetty.client.util.FutureResponseListener)

Example 24 with SSLContext

use of javax.net.ssl.SSLContext in project jetty.project by eclipse.

the class ThreadStarvationTest method params.

@Parameterized.Parameters(name = "{0}")
public static List<Object[]> params() {
    List<Object[]> params = new ArrayList<>();
    // HTTP
    ConnectorProvider http = (server, acceptors, selectors) -> new ServerConnector(server, acceptors, selectors);
    ClientSocketProvider httpClient = (host, port) -> new Socket(host, port);
    params.add(new Object[] { "http", http, httpClient });
    // HTTPS/SSL/TLS
    ConnectorProvider https = (server, acceptors, selectors) -> {
        Path keystorePath = MavenTestingUtils.getTestResourcePath("keystore");
        SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setKeyStorePath(keystorePath.toString());
        sslContextFactory.setKeyStorePassword("storepwd");
        sslContextFactory.setKeyManagerPassword("keypwd");
        sslContextFactory.setTrustStorePath(keystorePath.toString());
        sslContextFactory.setTrustStorePassword("storepwd");
        ByteBufferPool pool = new LeakTrackingByteBufferPool(new MappedByteBufferPool.Tagged());
        HttpConnectionFactory httpConnectionFactory = new HttpConnectionFactory();
        ServerConnector connector = new ServerConnector(server, (Executor) null, (Scheduler) null, pool, acceptors, selectors, AbstractConnectionFactory.getFactories(sslContextFactory, httpConnectionFactory));
        SecureRequestCustomizer secureRequestCustomer = new SecureRequestCustomizer();
        secureRequestCustomer.setSslSessionAttribute("SSL_SESSION");
        httpConnectionFactory.getHttpConfiguration().addCustomizer(secureRequestCustomer);
        return connector;
    };
    ClientSocketProvider httpsClient = new ClientSocketProvider() {

        private SSLContext sslContext;

        {
            try {
                HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
                sslContext = SSLContext.getInstance("TLS");
                sslContext.init(null, SslContextFactory.TRUST_ALL_CERTS, new java.security.SecureRandom());
                HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }

        @Override
        public Socket newSocket(String host, int port) throws IOException {
            return sslContext.getSocketFactory().createSocket(host, port);
        }
    };
    params.add(new Object[] { "https/ssl/tls", https, httpsClient });
    return params;
}
Also used : Socket(java.net.Socket) Arrays(java.util.Arrays) SSLContext(javax.net.ssl.SSLContext) ServletException(javax.servlet.ServletException) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) MavenTestingUtils(org.eclipse.jetty.toolchain.test.MavenTestingUtils) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) Scheduler(org.eclipse.jetty.util.thread.Scheduler) RunWith(org.junit.runner.RunWith) Callable(java.util.concurrent.Callable) ArrayList(java.util.ArrayList) LeakTrackingByteBufferPool(org.eclipse.jetty.io.LeakTrackingByteBufferPool) Assert.assertThat(org.junit.Assert.assertThat) Future(java.util.concurrent.Future) HttpServletRequest(javax.servlet.http.HttpServletRequest) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) After(org.junit.After) HttpStatus(org.eclipse.jetty.http.HttpStatus) Path(java.nio.file.Path) ExecutorService(java.util.concurrent.ExecutorService) Parameterized(org.junit.runners.Parameterized) OutputStream(java.io.OutputStream) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) Executor(java.util.concurrent.Executor) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) TestTracker(org.eclipse.jetty.toolchain.test.TestTracker) Test(org.junit.Test) ByteBufferPool(org.eclipse.jetty.io.ByteBufferPool) IO(org.eclipse.jetty.util.IO) StandardCharsets(java.nio.charset.StandardCharsets) Executors(java.util.concurrent.Executors) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) Rule(org.junit.Rule) DispatcherType(javax.servlet.DispatcherType) MappedByteBufferPool(org.eclipse.jetty.io.MappedByteBufferPool) Matchers.is(org.hamcrest.Matchers.is) Matchers.containsString(org.hamcrest.Matchers.containsString) Assert.assertEquals(org.junit.Assert.assertEquals) InputStream(java.io.InputStream) Path(java.nio.file.Path) LeakTrackingByteBufferPool(org.eclipse.jetty.io.LeakTrackingByteBufferPool) ByteBufferPool(org.eclipse.jetty.io.ByteBufferPool) MappedByteBufferPool(org.eclipse.jetty.io.MappedByteBufferPool) Scheduler(org.eclipse.jetty.util.thread.Scheduler) LeakTrackingByteBufferPool(org.eclipse.jetty.io.LeakTrackingByteBufferPool) ArrayList(java.util.ArrayList) SSLContext(javax.net.ssl.SSLContext) Matchers.containsString(org.hamcrest.Matchers.containsString) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) Executor(java.util.concurrent.Executor) Socket(java.net.Socket)

Example 25 with SSLContext

use of javax.net.ssl.SSLContext in project jetty.project by eclipse.

the class ALPNNegotiationTest method testClientAdvertisingMultipleProtocolsServerSpeaksHTTPWhenNegotiated.

@Test
public void testClientAdvertisingMultipleProtocolsServerSpeaksHTTPWhenNegotiated() throws Exception {
    InetSocketAddress address = prepare();
    SslContextFactory sslContextFactory = newSslContextFactory();
    sslContextFactory.start();
    SSLContext sslContext = sslContextFactory.getSslContext();
    try (SSLSocket client = (SSLSocket) sslContext.getSocketFactory().createSocket(address.getAddress(), address.getPort())) {
        client.setUseClientMode(true);
        client.setSoTimeout(5000);
        ALPN.put(client, new ALPN.ClientProvider() {

            @Override
            public void unsupported() {
            }

            @Override
            public List<String> protocols() {
                return Arrays.asList("unknown/1.0", "http/1.1");
            }

            @Override
            public void selected(String protocol) {
                Assert.assertEquals("http/1.1", protocol);
            }
        });
        client.startHandshake();
        // Verify that the server really speaks http/1.1
        OutputStream output = client.getOutputStream();
        output.write(("" + "GET / HTTP/1.1\r\n" + "Host: localhost:" + address.getPort() + "\r\n" + "\r\n" + "").getBytes(StandardCharsets.UTF_8));
        output.flush();
        InputStream input = client.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
        String line = reader.readLine();
        Assert.assertTrue(line.contains(" 404 "));
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) InetSocketAddress(java.net.InetSocketAddress) InputStream(java.io.InputStream) SSLSocket(javax.net.ssl.SSLSocket) OutputStream(java.io.OutputStream) SSLContext(javax.net.ssl.SSLContext) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) ALPN(org.eclipse.jetty.alpn.ALPN) BufferedReader(java.io.BufferedReader) List(java.util.List) Test(org.junit.Test)

Aggregations

SSLContext (javax.net.ssl.SSLContext)660 IOException (java.io.IOException)136 TrustManager (javax.net.ssl.TrustManager)116 KeyStore (java.security.KeyStore)112 SecureRandom (java.security.SecureRandom)97 TrustManagerFactory (javax.net.ssl.TrustManagerFactory)96 X509TrustManager (javax.net.ssl.X509TrustManager)87 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)83 KeyManagerFactory (javax.net.ssl.KeyManagerFactory)81 KeyManagementException (java.security.KeyManagementException)73 X509Certificate (java.security.cert.X509Certificate)68 CertificateException (java.security.cert.CertificateException)66 Test (org.junit.Test)61 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)60 SSLSocket (javax.net.ssl.SSLSocket)59 SSLEngine (javax.net.ssl.SSLEngine)51 FileInputStream (java.io.FileInputStream)48 InputStream (java.io.InputStream)48 KeyManager (javax.net.ssl.KeyManager)43 GeneralSecurityException (java.security.GeneralSecurityException)41