Search in sources :

Example 71 with SSLContext

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

the class SSLEngineTest method testRequestJettyHttps.

@Test
public void testRequestJettyHttps() throws Exception {
    server.setHandler(new HelloWorldHandler());
    server.start();
    final int loops = 10;
    final int numConns = 20;
    Socket[] client = new Socket[numConns];
    SSLContext ctx = SSLContext.getInstance("TLSv1.2");
    ctx.init(null, SslContextFactory.TRUST_ALL_CERTS, new java.security.SecureRandom());
    int port = connector.getLocalPort();
    try {
        for (int l = 0; l < loops; l++) {
            // System.err.print('.');
            try {
                for (int i = 0; i < numConns; ++i) {
                    // System.err.println("write:"+i);
                    client[i] = ctx.getSocketFactory().createSocket("localhost", port);
                    OutputStream os = client[i].getOutputStream();
                    os.write(REQUEST0.getBytes());
                    os.write(REQUEST0.getBytes());
                    os.flush();
                }
                for (int i = 0; i < numConns; ++i) {
                    // System.err.println("flush:"+i);
                    OutputStream os = client[i].getOutputStream();
                    os.write(REQUEST1.getBytes());
                    os.flush();
                }
                for (int i = 0; i < numConns; ++i) {
                    // System.err.println("read:"+i);
                    // Read the response.
                    String responses = readResponse(client[i]);
                    // Check the responses
                    assertEquals(String.format("responses loop=%d connection=%d", l, i), RESPONSE0 + RESPONSE0 + RESPONSE1, responses);
                }
            } finally {
                for (int i = 0; i < numConns; ++i) {
                    if (client[i] != null) {
                        try {
                            assertEquals(-1, client[i].getInputStream().read());
                        } catch (SocketException e) {
                        }
                    }
                }
            }
        }
    } finally {
    // System.err.println();
    }
}
Also used : SocketException(java.net.SocketException) ServletOutputStream(javax.servlet.ServletOutputStream) OutputStream(java.io.OutputStream) SSLContext(javax.net.ssl.SSLContext) Socket(java.net.Socket) Test(org.junit.Test)

Example 72 with SSLContext

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

the class SSLEngineTest method testBigResponse.

@Test
public void testBigResponse() throws Exception {
    server.setHandler(new HelloWorldHandler());
    server.start();
    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(null, SslContextFactory.TRUST_ALL_CERTS, new java.security.SecureRandom());
    int port = connector.getLocalPort();
    Socket client = ctx.getSocketFactory().createSocket("localhost", port);
    OutputStream os = client.getOutputStream();
    String request = "GET /?dump=102400 HTTP/1.1\r\n" + "Host: localhost:" + port + "\r\n" + "Connection: close\r\n" + "\r\n";
    os.write(request.getBytes());
    os.flush();
    String response = IO.toString(client.getInputStream());
    assertThat(response.length(), greaterThan(102400));
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) OutputStream(java.io.OutputStream) SSLContext(javax.net.ssl.SSLContext) Socket(java.net.Socket) Test(org.junit.Test)

Example 73 with SSLContext

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

the class SlowClientsTest method testSlowClientsWithSmallThreadPool.

@Test(timeout = 10000)
public void testSlowClientsWithSmallThreadPool() throws Exception {
    File keystore = MavenTestingUtils.getTestResourceFile("keystore");
    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(keystore.getAbsolutePath());
    sslContextFactory.setKeyStorePassword("storepwd");
    sslContextFactory.setKeyManagerPassword("keypwd");
    int maxThreads = 6;
    int contentLength = 8 * 1024 * 1024;
    QueuedThreadPool serverThreads = new QueuedThreadPool(maxThreads);
    serverThreads.setDetailedDump(true);
    Server server = new Server(serverThreads);
    try {
        ServerConnector connector = new ServerConnector(server, 1, 1, sslContextFactory);
        connector.setPort(8888);
        server.addConnector(connector);
        server.setHandler(new AbstractHandler() {

            @Override
            public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
                baseRequest.setHandled(true);
                logger.info("SERVING {}", target);
                // Write some big content.
                response.getOutputStream().write(new byte[contentLength]);
                logger.info("SERVED {}", target);
            }
        });
        server.start();
        SSLContext sslContext = sslContextFactory.getSslContext();
        CompletableFuture[] futures = new CompletableFuture[2 * maxThreads];
        ExecutorService executor = Executors.newFixedThreadPool(futures.length);
        for (int i = 0; i < futures.length; i++) {
            int k = i;
            futures[i] = CompletableFuture.runAsync(() -> {
                try (SSLSocket socket = (SSLSocket) sslContext.getSocketFactory().createSocket("localhost", connector.getLocalPort())) {
                    socket.setSoTimeout(contentLength / 1024);
                    OutputStream output = socket.getOutputStream();
                    String target = "/" + k;
                    String request = "GET " + target + " HTTP/1.1\r\n" + "Host: localhost\r\n" + "Connection: close\r\n" + "\r\n";
                    output.write(request.getBytes(StandardCharsets.UTF_8));
                    output.flush();
                    while (serverThreads.getIdleThreads() > 0) Thread.sleep(50);
                    InputStream input = socket.getInputStream();
                    while (true) {
                        int read = input.read();
                        if (read < 0)
                            break;
                    }
                    logger.info("FINISHED {}", target);
                } catch (IOException x) {
                    throw new UncheckedIOException(x);
                } catch (InterruptedException x) {
                    throw new UncheckedIOException(new InterruptedIOException());
                }
            }, executor);
        }
        CompletableFuture.allOf(futures).join();
    } finally {
        server.stop();
    }
}
Also used : InterruptedIOException(java.io.InterruptedIOException) Server(org.eclipse.jetty.server.Server) 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) UncheckedIOException(java.io.UncheckedIOException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) SSLContext(javax.net.ssl.SSLContext) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) ServerConnector(org.eclipse.jetty.server.ServerConnector) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) CompletableFuture(java.util.concurrent.CompletableFuture) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) ExecutorService(java.util.concurrent.ExecutorService) File(java.io.File) Test(org.junit.Test)

Example 74 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 75 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)

Aggregations

SSLContext (javax.net.ssl.SSLContext)745 IOException (java.io.IOException)171 TrustManager (javax.net.ssl.TrustManager)139 KeyStore (java.security.KeyStore)130 TrustManagerFactory (javax.net.ssl.TrustManagerFactory)112 SecureRandom (java.security.SecureRandom)110 X509TrustManager (javax.net.ssl.X509TrustManager)107 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)106 KeyManagementException (java.security.KeyManagementException)92 KeyManagerFactory (javax.net.ssl.KeyManagerFactory)92 CertificateException (java.security.cert.CertificateException)84 X509Certificate (java.security.cert.X509Certificate)84 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)69 Test (org.junit.Test)65 SSLSocket (javax.net.ssl.SSLSocket)64 InputStream (java.io.InputStream)59 FileInputStream (java.io.FileInputStream)56 SSLEngine (javax.net.ssl.SSLEngine)54 KeyManager (javax.net.ssl.KeyManager)52 KeyStoreException (java.security.KeyStoreException)45