Java Code Examples for javax.net.ssl.SSLSocket#addHandshakeCompletedListener()

The following examples show how to use javax.net.ssl.SSLSocket#addHandshakeCompletedListener() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SocketFactory.java    From dacapobench with Apache License 2.0 5 votes vote down vote up
/**
 * Create an SSL client socket using the IOR-encoded
 * security characteristics.
 * Setting want/need client auth on a client socket has no effect so all we can do is use the right host, port, ciphers
 *
 * @param host     The target host name.
 * @param port     The target connection port.
 *
 * @return An appropriately configured client SSLSocket.
 * @exception IOException if ssl socket can't be obtained and configured.
 */
private Socket createSSLSocket(String host, int port, int requires, int supports) throws IOException {
    SSLSocketFactory factory = getSocketFactory();
    SSLSocket socket = (SSLSocket) factory.createSocket(host, port);

    socket.setSoTimeout(SOCKET_TIMEOUT_MS);

    // get a set of cipher suites appropriate for this connections requirements.
    // We request this for each connection, since the outgoing IOR's requirements may be different from
    // our server listener requirements.
    String[] iorSuites = SSLCipherSuiteDatabase.getCipherSuites(requires, supports, factory.getSupportedCipherSuites());
    socket.setEnabledCipherSuites(iorSuites);
    if (log.isDebugEnabled()) {
        log.debug("Created SSL socket to " + host + ":" + port);
        log.debug("    cipher suites:");

        for (int i = 0; i < iorSuites.length; i++) {
            log.debug("    " + iorSuites[i]);
        }
        socket.addHandshakeCompletedListener(new HandshakeCompletedListener() {

            public void handshakeCompleted(HandshakeCompletedEvent handshakeCompletedEvent) {
                Certificate[] certs = handshakeCompletedEvent.getLocalCertificates();
                if (certs != null) {
                    log.debug("handshake returned local certs count: " + certs.length);
                    for (int i = 0; i < certs.length; i++) {
                        Certificate cert = certs[i];
                        log.debug("cert: " + cert.toString());
                    }
                } else {
                    log.debug("handshake returned no local certs");
                }
            }
        });
    }
    return socket;
}
 
Example 2
Source File: CustomSslSocketFactory.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {

	SSLSocket socket = (SSLSocket) this.sslSocketFactory.createSocket(s, host, port, autoClose);

	if (!sniEnabled) {
		disableSNI(socket);
	}

	if (this.handshakeListener != null) {
		socket.addHandshakeCompletedListener(this.handshakeListener);
	}

	return socket;
}
 
Example 3
Source File: CustomSslSocketFactory.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Socket createSocket(String paramString, int paramInt) throws IOException, UnknownHostException {

	SSLSocket socket = (SSLSocket) this.sslSocketFactory.createSocket(paramString, paramInt);

	if (this.handshakeListener != null) {
		socket.addHandshakeCompletedListener(this.handshakeListener);
	}

	return socket;
}
 
Example 4
Source File: CustomSslSocketFactory.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Socket createSocket(String paramString, int paramInt1, InetAddress paramInetAddress, int paramInt2)
		throws IOException, UnknownHostException {

	SSLSocket socket = (SSLSocket) this.sslSocketFactory.createSocket(paramString, paramInt1, paramInetAddress,
			paramInt2);

	if (this.handshakeListener != null) {
		socket.addHandshakeCompletedListener(this.handshakeListener);
	}

	return socket;
}
 
Example 5
Source File: CustomSslSocketFactory.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Socket createSocket(InetAddress paramInetAddress, int paramInt) throws IOException {

	SSLSocket socket = (SSLSocket) this.sslSocketFactory.createSocket(paramInetAddress, paramInt);

	if (this.handshakeListener != null) {
		socket.addHandshakeCompletedListener(this.handshakeListener);
	}

	return socket;
}
 
Example 6
Source File: CustomSslSocketFactory.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Socket createSocket(InetAddress paramInetAddress1, int paramInt1, InetAddress paramInetAddress2,
		int paramInt2) throws IOException {

	SSLSocket socket = (SSLSocket) this.sslSocketFactory.createSocket(paramInetAddress1, paramInt1,
			paramInetAddress2, paramInt2);

	if (this.handshakeListener != null) {
		socket.addHandshakeCompletedListener(this.handshakeListener);
	}

	return socket;
}
 
Example 7
Source File: SSLSocketTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * javax.net.ssl.SSLSocket#addHandshakeCompletedListener(HandshakeCompletedListener listener)
 */
// AndroidOnly("RI doesn't throw the specified IAE")
public void j2objcNotImplemented_test_addHandshakeCompletedListener() throws IOException {
    SSLSocket ssl = getSSLSocket();
    HandshakeCompletedListener ls = new HandshakeCL();
    try {
        ssl.addHandshakeCompletedListener(null);
        fail();
    } catch (IllegalArgumentException expected) {
    }
    ssl.addHandshakeCompletedListener(ls);
    ssl.close();
}
 
Example 8
Source File: HandshakeCompletedEventTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void run() {
    try {
        KeyManager[] keyManagers = provideKeys ? getKeyManagers(keys) : null;
        TrustManager[] trustManagers = new TrustManager[] { trustManager };

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagers, trustManagers, null);

        SSLSocket socket = (SSLSocket)sslContext.getSocketFactory().createSocket();

        socket.connect(serverSocket.getLocalSocketAddress());
        socket.addHandshakeCompletedListener(listener);
        socket.startHandshake();

        OutputStream ostream = socket.getOutputStream();

        for (int i = 0; i < 256; i++) {
            ostream.write(i);
        }

        ostream.flush();
        ostream.close();

        InputStream istream = socket.getInputStream();

        for (int i = 0; i < 256; i++) {
            int j = istream.read();
            assertEquals(i, j);
        }

        istream.close();

        socket.close();

    } catch (Exception ex) {
        exception = ex;
    }
}
 
Example 9
Source File: SSLSocketTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test_SSLSocket_HandshakeCompletedListener_RuntimeException() throws Exception {
    final Thread self = Thread.currentThread();
    final UncaughtExceptionHandler original = self.getUncaughtExceptionHandler();

    final RuntimeException expectedException = new RuntimeException("expected");
    final TestUncaughtExceptionHandler test = new TestUncaughtExceptionHandler();
    self.setUncaughtExceptionHandler(test);

    final TestSSLContext c = TestSSLContext.create();
    final SSLSocket client = (SSLSocket)
            c.clientContext.getSocketFactory().createSocket(c.host, c.port);
    final SSLSocket server = (SSLSocket) c.serverSocket.accept();
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<Void> future = executor.submit(new Callable<Void>() {
        @Override public Void call() throws Exception {
            server.startHandshake();
            return null;
        }
    });
    executor.shutdown();
    client.addHandshakeCompletedListener(new HandshakeCompletedListener() {
        public void handshakeCompleted(HandshakeCompletedEvent event) {
            throw expectedException;
        }
    });
    client.startHandshake();
    future.get();
    client.close();
    server.close();
    c.close();

    assertSame(expectedException, test.actualException);
    self.setUncaughtExceptionHandler(original);
}
 
Example 10
Source File: TestSsl.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@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;
    if (TesterSupport.isDefaultTLSProtocolForTesting13(tomcat.getConnector())) {
        // Force TLS 1.2 if TLS 1.3 is available as JSSE's TLS 1.3
        // implementation doesn't support Post Handshake Authentication
        // which is required for this test to pass.
        sslCtx = SSLContext.getInstance(Constants.SSL_PROTO_TLSv1_2);
    } else {
        sslCtx = SSLContext.getInstance(Constants.SSL_PROTO_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);
    Assert.assertTrue("Checking no client issuer has been requested",
            TesterSupport.getLastClientAuthRequestedIssuerCount() == 0);

    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);
            Assert.assertTrue("Checking no client issuer has been requested",
                    TesterSupport.getLastClientAuthRequestedIssuerCount() == 0);
            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");
}
 
Example 11
Source File: JSSESupport.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
JSSESupport(SSLSocket sock){
    ssl=sock;
    session = sock.getSession();
    sock.addHandshakeCompletedListener(listener);
}
 
Example 12
Source File: TestSsl.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
@Test
public void testRenegotiateFail() throws Exception {

    // If RFC5746 is supported, renegotiation will always work (and will
    // always be secure)
    if (TesterSupport.RFC_5746_SUPPORTED) {
        return;
    }

    Tomcat tomcat = getTomcatInstance();

    File appDir = new File(getBuildDirectory(), "webapps/examples");
    // app dir is relative to server home
    tomcat.addWebapp(null, "/examples", appDir.getAbsolutePath());

    TesterSupport.initSsl(tomcat);

    // Default - MITM attack prevented

    tomcat.start();
    SSLContext sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(null, TesterSupport.getTrustManagers(), null);
    SSLSocketFactory socketFactory = sslCtx.getSocketFactory();
    SSLSocket socket = (SSLSocket) socketFactory.createSocket("localhost", getPort());

    socket.addHandshakeCompletedListener(new HandshakeCompletedListener() {
        @Override
        public void handshakeCompleted(HandshakeCompletedEvent event) {
            handshakeDone = true;
        }
    });

    OutputStream os = socket.getOutputStream();
    os.write("GET /examples/servlets/servlet/HelloWorldExample HTTP/1.0\n".getBytes());
    os.flush();


    InputStream is = socket.getInputStream();

    // Make sure the NIO connector has read the request before the handshake
    Thread.sleep(100);

    socket.startHandshake();

    os = socket.getOutputStream();

    try {
        os.write("Host: localhost\n\n".getBytes());
    } catch (IOException ex) {
        ex.printStackTrace();
        fail("Re-negotiation failed");
    }
    Reader r = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(r);
    String line = br.readLine();
    while (line != null) {
        // For testing System.out.println(line);
        line = br.readLine();
    }

    if (!handshakeDone) {
        // success - we timed-out without handshake
        return;
    }

    fail("Re-negotiation worked");
}
 
Example 13
Source File: JSSESupport.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
JSSESupport(SSLSocket sock){
    ssl=sock;
    session = sock.getSession();
    sock.addHandshakeCompletedListener(listener);
}
 
Example 14
Source File: TestSsl.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
@Test
public void testRenegotiateFail() throws Exception {

    // If RFC5746 is supported, renegotiation will always work (and will
    // always be secure)
    if (TesterSupport.RFC_5746_SUPPORTED) {
        return;
    }

    Tomcat tomcat = getTomcatInstance();

    File appDir = new File(getBuildDirectory(), "webapps/examples");
    // app dir is relative to server home
    tomcat.addWebapp(null, "/examples", appDir.getAbsolutePath());

    TesterSupport.initSsl(tomcat);

    // Default - MITM attack prevented

    tomcat.start();
    SSLContext sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(null, TesterSupport.getTrustManagers(), null);
    SSLSocketFactory socketFactory = sslCtx.getSocketFactory();
    SSLSocket socket = (SSLSocket) socketFactory.createSocket("localhost", getPort());

    socket.addHandshakeCompletedListener(new HandshakeCompletedListener() {
        @Override
        public void handshakeCompleted(HandshakeCompletedEvent event) {
            handshakeDone = true;
        }
    });

    OutputStream os = socket.getOutputStream();
    os.write("GET /examples/servlets/servlet/HelloWorldExample HTTP/1.0\n".getBytes());
    os.flush();


    InputStream is = socket.getInputStream();

    // Make sure the NIO connector has read the request before the handshake
    Thread.sleep(100);

    socket.startHandshake();

    os = socket.getOutputStream();

    try {
        os.write("Host: localhost\n\n".getBytes());
    } catch (IOException ex) {
        ex.printStackTrace();
        fail("Re-negotiation failed");
    }
    Reader r = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(r);
    String line = br.readLine();
    while (line != null) {
        // For testing System.out.println(line);
        line = br.readLine();
    }

    if (!handshakeDone) {
        // success - we timed-out without handshake
        return;
    }

    fail("Re-negotiation worked");
}