Search in sources :

Example 16 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)

Example 17 with SSLContext

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

the class X509Util method createSSLContext.

public static SSLContext createSSLContext(ZKConfig config) throws SSLContextException {
    KeyManager[] keyManagers = null;
    TrustManager[] trustManagers = null;
    String keyStoreLocationProp = config.getProperty(ZKConfig.SSL_KEYSTORE_LOCATION);
    String keyStorePasswordProp = config.getProperty(ZKConfig.SSL_KEYSTORE_PASSWD);
    if (keyStoreLocationProp == null && keyStorePasswordProp == null) {
        LOG.warn("keystore not specified for client connection");
    } else {
        if (keyStoreLocationProp == null) {
            throw new SSLContextException("keystore location not specified for client connection");
        }
        if (keyStorePasswordProp == null) {
            throw new SSLContextException("keystore password not specified for client connection");
        }
        try {
            keyManagers = new KeyManager[] { createKeyManager(keyStoreLocationProp, keyStorePasswordProp) };
        } catch (KeyManagerException e) {
            throw new SSLContextException("Failed to create KeyManager", e);
        }
    }
    String trustStoreLocationProp = config.getProperty(ZKConfig.SSL_TRUSTSTORE_LOCATION);
    String trustStorePasswordProp = config.getProperty(ZKConfig.SSL_TRUSTSTORE_PASSWD);
    if (trustStoreLocationProp == null && trustStorePasswordProp == null) {
        LOG.warn("keystore not specified for client connection");
    } else {
        if (trustStoreLocationProp == null) {
            throw new SSLContextException("keystore location not specified for client connection");
        }
        if (trustStorePasswordProp == null) {
            throw new SSLContextException("keystore password not specified for client connection");
        }
        try {
            trustManagers = new TrustManager[] { createTrustManager(trustStoreLocationProp, trustStorePasswordProp) };
        } catch (TrustManagerException e) {
            throw new SSLContextException("Failed to create KeyManager", e);
        }
    }
    SSLContext sslContext = null;
    try {
        sslContext = SSLContext.getInstance("TLSv1");
        sslContext.init(keyManagers, trustManagers, null);
    } catch (Exception e) {
        throw new SSLContextException(e);
    }
    return sslContext;
}
Also used : KeyManagerException(org.apache.zookeeper.common.X509Exception.KeyManagerException) SSLContextException(org.apache.zookeeper.common.X509Exception.SSLContextException) TrustManagerException(org.apache.zookeeper.common.X509Exception.TrustManagerException) SSLContext(javax.net.ssl.SSLContext) X509KeyManager(javax.net.ssl.X509KeyManager) KeyManager(javax.net.ssl.KeyManager) TrustManagerException(org.apache.zookeeper.common.X509Exception.TrustManagerException) IOException(java.io.IOException) KeyManagerException(org.apache.zookeeper.common.X509Exception.KeyManagerException) SSLContextException(org.apache.zookeeper.common.X509Exception.SSLContextException) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager)

Example 18 with SSLContext

use of javax.net.ssl.SSLContext in project cas by apereo.

the class SimpleHttpClientTests method getFriendlyToAllSSLSocketFactory.

private static SSLConnectionSocketFactory getFriendlyToAllSSLSocketFactory() throws Exception {
    final TrustManager trm = new X509TrustManager() {

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(final X509Certificate[] certs, final String authType) {
        }

        @Override
        public void checkServerTrusted(final X509Certificate[] certs, final String authType) {
        }
    };
    final SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, new TrustManager[] { trm }, null);
    return new SSLConnectionSocketFactory(sc, new NoopHostnameVerifier());
}
Also used : NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) X509TrustManager(javax.net.ssl.X509TrustManager) SSLContext(javax.net.ssl.SSLContext) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) X509Certificate(java.security.cert.X509Certificate) X509TrustManager(javax.net.ssl.X509TrustManager) TrustManager(javax.net.ssl.TrustManager)

Example 19 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 20 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)

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