Search in sources :

Example 76 with SSLContext

use of javax.net.ssl.SSLContext in project elasticsearch by elastic.

the class GceDiscoverTests method startHttpd.

@BeforeClass
public static void startHttpd() throws Exception {
    logDir = createTempDir();
    SSLContext sslContext = getSSLContext();
    httpsServer = MockHttpServer.createHttps(new InetSocketAddress(InetAddress.getLoopbackAddress().getHostAddress(), 0), 0);
    httpServer = MockHttpServer.createHttp(new InetSocketAddress(InetAddress.getLoopbackAddress().getHostAddress(), 0), 0);
    httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext));
    httpServer.createContext("/computeMetadata/v1/instance/service-accounts/default/token", (s) -> {
        String response = GceMockUtils.readGoogleInternalJsonResponse("http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token");
        byte[] responseAsBytes = response.getBytes(StandardCharsets.UTF_8);
        s.sendResponseHeaders(200, responseAsBytes.length);
        OutputStream responseBody = s.getResponseBody();
        responseBody.write(responseAsBytes);
        responseBody.close();
    });
    httpsServer.createContext("/compute/v1/projects/testproject/zones/primaryzone/instances", (s) -> {
        Headers headers = s.getResponseHeaders();
        headers.add("Content-Type", "application/json; charset=UTF-8");
        Logger logger = Loggers.getLogger(GceDiscoverTests.class);
        try {
            Path[] files = FileSystemUtils.files(logDir);
            StringBuilder builder = new StringBuilder("{\"id\": \"dummy\",\"items\":[");
            int foundFiles = 0;
            for (int i = 0; i < files.length; i++) {
                Path resolve = files[i].resolve("transport.ports");
                if (Files.exists(resolve)) {
                    if (foundFiles++ > 0) {
                        builder.append(",");
                    }
                    List<String> addressses = Files.readAllLines(resolve);
                    Collections.shuffle(addressses, random());
                    logger.debug("addresses for node: [{}] published addresses [{}]", files[i].getFileName(), addressses);
                    builder.append("{\"description\": \"ES Node ").append(files[i].getFileName()).append("\",\"networkInterfaces\": [ {");
                    builder.append("\"networkIP\": \"").append(addressses.get(0)).append("\"}],");
                    builder.append("\"status\" : \"RUNNING\"}");
                }
            }
            builder.append("]}");
            String responseString = builder.toString();
            final byte[] responseAsBytes = responseString.getBytes(StandardCharsets.UTF_8);
            s.sendResponseHeaders(200, responseAsBytes.length);
            OutputStream responseBody = s.getResponseBody();
            responseBody.write(responseAsBytes);
            responseBody.close();
        } catch (Exception e) {
            //
            byte[] responseAsBytes = ("{ \"error\" : {\"message\" : \"" + e.toString() + "\" } }").getBytes(StandardCharsets.UTF_8);
            s.sendResponseHeaders(500, responseAsBytes.length);
            OutputStream responseBody = s.getResponseBody();
            responseBody.write(responseAsBytes);
            responseBody.close();
        }
    });
    httpsServer.start();
    httpServer.start();
}
Also used : Path(java.nio.file.Path) HttpsConfigurator(com.sun.net.httpserver.HttpsConfigurator) InetSocketAddress(java.net.InetSocketAddress) Headers(com.sun.net.httpserver.Headers) OutputStream(java.io.OutputStream) SSLContext(javax.net.ssl.SSLContext) Logger(org.apache.logging.log4j.Logger) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) BeforeClass(org.junit.BeforeClass)

Example 77 with SSLContext

use of javax.net.ssl.SSLContext in project elasticsearch by elastic.

the class GceDiscoverTests method getSSLContext.

private static SSLContext getSSLContext() throws Exception {
    char[] passphrase = "keypass".toCharArray();
    KeyStore ks = KeyStore.getInstance("JKS");
    try (InputStream stream = GceDiscoverTests.class.getResourceAsStream("/test-node.jks")) {
        assertNotNull("can't find keystore file", stream);
        ks.load(stream, passphrase);
    }
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks, passphrase);
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(ks);
    SSLContext ssl = SSLContext.getInstance("TLS");
    ssl.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    return ssl;
}
Also used : InputStream(java.io.InputStream) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) KeyManagerFactory(javax.net.ssl.KeyManagerFactory)

Example 78 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 79 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 80 with SSLContext

use of javax.net.ssl.SSLContext in project tomcat by apache.

the class TestSsl method testRenegotiateWorks.

@Test
public void testRenegotiateWorks() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    Assume.assumeTrue("SSL renegotiation has to be supported for this test", TesterSupport.isClientRenegotiationSupported(getTomcatInstance()));
    Context root = tomcat.addContext("", TEMP_DIR);
    Wrapper w = Tomcat.addServlet(root, "tester", new TesterServlet());
    w.setAsyncSupported(true);
    root.addServletMappingDecoded("/", "tester");
    TesterSupport.initSsl(tomcat);
    tomcat.start();
    SSLContext sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(null, TesterSupport.getTrustManagers(), null);
    SSLSocketFactory socketFactory = sslCtx.getSocketFactory();
    SSLSocket socket = (SSLSocket) socketFactory.createSocket("localhost", getPort());
    OutputStream os = socket.getOutputStream();
    InputStream is = socket.getInputStream();
    Reader r = new InputStreamReader(is);
    doRequest(os, r);
    TesterHandshakeListener listener = new TesterHandshakeListener();
    socket.addHandshakeCompletedListener(listener);
    socket.startHandshake();
    // One request should be sufficient
    int requestCount = 0;
    int listenerComplete = 0;
    try {
        while (requestCount < 10) {
            requestCount++;
            doRequest(os, r);
            if (listener.isComplete() && listenerComplete == 0) {
                listenerComplete = requestCount;
            }
        }
    } catch (AssertionError | IOException e) {
        String message = "Failed on request number " + requestCount + " after startHandshake(). " + e.getMessage();
        log.error(message, e);
        Assert.fail(message);
    }
    Assert.assertTrue(listener.isComplete());
    System.out.println("Renegotiation completed after " + listenerComplete + " requests");
}
Also used : SSLContext(javax.net.ssl.SSLContext) Context(org.apache.catalina.Context) Wrapper(org.apache.catalina.Wrapper) Tomcat(org.apache.catalina.startup.Tomcat) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) SSLSocket(javax.net.ssl.SSLSocket) OutputStream(java.io.OutputStream) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) TesterServlet(org.apache.catalina.startup.TesterServlet) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) TomcatBaseTest(org.apache.catalina.startup.TomcatBaseTest) Test(org.junit.Test)

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