Search in sources :

Example 11 with HandshakeCompletedListener

use of javax.net.ssl.HandshakeCompletedListener in project robovm by robovm.

the class SSLSocketTest method test_removeHandshakeCompletedListener.

/**
     * javax.net.ssl.SSLSocket#removeHandshakeCompletedListener(HandshakeCompletedListener listener)
     */
public void test_removeHandshakeCompletedListener() throws IOException {
    SSLSocket ssl = getSSLSocket();
    HandshakeCompletedListener ls = new HandshakeCL();
    try {
        ssl.removeHandshakeCompletedListener(null);
        fail();
    } catch (IllegalArgumentException expected) {
    }
    try {
        ssl.removeHandshakeCompletedListener(ls);
    } catch (IllegalArgumentException expected) {
    }
    ssl.addHandshakeCompletedListener(ls);
    ssl.removeHandshakeCompletedListener(ls);
    ssl.close();
}
Also used : HandshakeCompletedListener(javax.net.ssl.HandshakeCompletedListener) SSLSocket(javax.net.ssl.SSLSocket)

Example 12 with HandshakeCompletedListener

use of javax.net.ssl.HandshakeCompletedListener in project kdeconnect-android by KDE.

the class LanLinkProvider method identityPackageReceived.

private void identityPackageReceived(final NetworkPackage identityPackage, final Socket socket, final LanLink.ConnectionStarted connectionStarted) {
    String myId = DeviceHelper.getDeviceId(context);
    final String deviceId = identityPackage.getString("deviceId");
    if (deviceId.equals(myId)) {
        Log.e("KDE/LanLinkProvider", "Somehow I'm connected to myself, ignoring. This should not happen.");
        return;
    }
    // If I'm the TCP server I will be the SSL client and viceversa.
    final boolean clientMode = (connectionStarted == LanLink.ConnectionStarted.Locally);
    // Add ssl handler if device uses new protocol
    try {
        if (identityPackage.getInt("protocolVersion") >= MIN_VERSION_WITH_SSL_SUPPORT) {
            SharedPreferences preferences = context.getSharedPreferences("trusted_devices", Context.MODE_PRIVATE);
            boolean isDeviceTrusted = preferences.getBoolean(deviceId, false);
            if (isDeviceTrusted && !SslHelper.isCertificateStored(context, deviceId)) {
                //Device paired with and old version, we can't use it as we lack the certificate
                BackgroundService.RunCommand(context, new BackgroundService.InstanceCallback() {

                    @Override
                    public void onServiceStart(BackgroundService service) {
                        Device device = service.getDevice(deviceId);
                        if (device == null)
                            return;
                        device.unpair();
                        //Retry as unpaired
                        identityPackageReceived(identityPackage, socket, connectionStarted);
                    }
                });
            }
            Log.i("KDE/LanLinkProvider", "Starting SSL handshake with " + identityPackage.getString("deviceName") + " trusted:" + isDeviceTrusted);
            final SSLSocket sslsocket = SslHelper.convertToSslSocket(context, socket, deviceId, isDeviceTrusted, clientMode);
            sslsocket.addHandshakeCompletedListener(new HandshakeCompletedListener() {

                @Override
                public void handshakeCompleted(HandshakeCompletedEvent event) {
                    String mode = clientMode ? "client" : "server";
                    try {
                        Certificate certificate = event.getPeerCertificates()[0];
                        identityPackage.set("certificate", Base64.encodeToString(certificate.getEncoded(), 0));
                        Log.i("KDE/LanLinkProvider", "Handshake as " + mode + " successful with " + identityPackage.getString("deviceName") + " secured with " + event.getCipherSuite());
                        addLink(identityPackage, sslsocket, connectionStarted);
                    } catch (Exception e) {
                        Log.e("KDE/LanLinkProvider", "Handshake as " + mode + " failed with " + identityPackage.getString("deviceName"));
                        e.printStackTrace();
                        BackgroundService.RunCommand(context, new BackgroundService.InstanceCallback() {

                            @Override
                            public void onServiceStart(BackgroundService service) {
                                Device device = service.getDevice(deviceId);
                                if (device == null)
                                    return;
                                device.unpair();
                            }
                        });
                    }
                }
            });
            //Handshake is blocking, so do it on another thread and free this thread to keep receiving new connection
            new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        sslsocket.startHandshake();
                    } catch (Exception e) {
                        Log.e("KDE/LanLinkProvider", "Handshake failed with " + identityPackage.getString("deviceName"));
                        e.printStackTrace();
                    //String[] ciphers = sslsocket.getSupportedCipherSuites();
                    //for (String cipher : ciphers) {
                    //    Log.i("SupportedCiphers","cipher: " + cipher);
                    //}
                    }
                }
            }).start();
        } else {
            addLink(identityPackage, socket, connectionStarted);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : BackgroundService(org.kde.kdeconnect.BackgroundService) SharedPreferences(android.content.SharedPreferences) Device(org.kde.kdeconnect.Device) SSLSocket(javax.net.ssl.SSLSocket) SocketException(java.net.SocketException) IOException(java.io.IOException) HandshakeCompletedListener(javax.net.ssl.HandshakeCompletedListener) HandshakeCompletedEvent(javax.net.ssl.HandshakeCompletedEvent) Certificate(java.security.cert.Certificate)

Example 13 with HandshakeCompletedListener

use of javax.net.ssl.HandshakeCompletedListener in project tomcat70 by apache.

the class TestSsl method testRenegotiateFail.

@Test
public void testRenegotiateFail() throws Exception {
    // 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();
        Assert.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;
    }
    Assert.fail("Re-negotiation worked");
}
Also used : 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) BufferedReader(java.io.BufferedReader) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) HandshakeCompletedListener(javax.net.ssl.HandshakeCompletedListener) HandshakeCompletedEvent(javax.net.ssl.HandshakeCompletedEvent) BufferedReader(java.io.BufferedReader) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) File(java.io.File) TomcatBaseTest(org.apache.catalina.startup.TomcatBaseTest) Test(org.junit.Test)

Example 14 with HandshakeCompletedListener

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

the class UnifiedServerSocketTest method connectWithSSL.

private SSLSocket connectWithSSL() throws IOException, X509Exception, InterruptedException {
    SSLSocket sslSocket = null;
    int retries = 0;
    while (retries < MAX_RETRIES) {
        try {
            sslSocket = x509Util.createSSLSocket();
            sslSocket.addHandshakeCompletedListener(new HandshakeCompletedListener() {

                @Override
                public void handshakeCompleted(HandshakeCompletedEvent handshakeCompletedEvent) {
                    synchronized (handshakeCompletedLock) {
                        handshakeCompleted = true;
                        handshakeCompletedLock.notifyAll();
                    }
                }
            });
            sslSocket.setSoTimeout(TIMEOUT);
            sslSocket.connect(localServerAddress, TIMEOUT);
            break;
        } catch (ConnectException connectException) {
            connectException.printStackTrace();
            forceClose(sslSocket);
            sslSocket = null;
            Thread.sleep(TIMEOUT);
        }
        retries++;
    }
    assertNotNull(sslSocket, "Failed to connect to server with SSL");
    return sslSocket;
}
Also used : HandshakeCompletedListener(javax.net.ssl.HandshakeCompletedListener) HandshakeCompletedEvent(javax.net.ssl.HandshakeCompletedEvent) SSLSocket(javax.net.ssl.SSLSocket) ConnectException(java.net.ConnectException)

Example 15 with HandshakeCompletedListener

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

the class X509UtilTest method testClientRenegotiationFails.

// This test makes sure that client-initiated TLS renegotiation does not
// succeed. We explicitly disable it at the top of X509Util.java.
@ParameterizedTest
@MethodSource("data")
public void testClientRenegotiationFails(X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex) throws Throwable {
    init(caKeyType, certKeyType, keyPassword, paramIndex);
    assertThrows(SSLHandshakeException.class, () -> {
        int port = PortAssignment.unique();
        ExecutorService workerPool = Executors.newCachedThreadPool();
        final SSLServerSocket listeningSocket = x509Util.createSSLServerSocket();
        SSLSocket clientSocket = null;
        SSLSocket serverSocket = null;
        final AtomicInteger handshakesCompleted = new AtomicInteger(0);
        final CountDownLatch handshakeCompleted = new CountDownLatch(1);
        try {
            InetSocketAddress localServerAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), port);
            listeningSocket.bind(localServerAddress);
            Future<SSLSocket> acceptFuture;
            acceptFuture = workerPool.submit(new Callable<SSLSocket>() {

                @Override
                public SSLSocket call() throws Exception {
                    SSLSocket sslSocket = (SSLSocket) listeningSocket.accept();
                    sslSocket.addHandshakeCompletedListener(new HandshakeCompletedListener() {

                        @Override
                        public void handshakeCompleted(HandshakeCompletedEvent handshakeCompletedEvent) {
                            handshakesCompleted.getAndIncrement();
                            handshakeCompleted.countDown();
                        }
                    });
                    assertEquals(1, sslSocket.getInputStream().read());
                    try {
                        // 2nd read is after the renegotiation attempt and will fail
                        sslSocket.getInputStream().read();
                        return sslSocket;
                    } catch (Exception e) {
                        forceClose(sslSocket);
                        throw e;
                    }
                }
            });
            clientSocket = x509Util.createSSLSocket();
            clientSocket.connect(localServerAddress);
            clientSocket.getOutputStream().write(1);
            // Attempt to renegotiate after establishing the connection
            clientSocket.startHandshake();
            clientSocket.getOutputStream().write(1);
            // The exception is thrown on the server side, we need to unwrap it
            try {
                serverSocket = acceptFuture.get();
            } catch (ExecutionException e) {
                throw e.getCause();
            }
        } finally {
            forceClose(serverSocket);
            forceClose(clientSocket);
            forceClose(listeningSocket);
            workerPool.shutdown();
            // Make sure the first handshake completed and only the second
            // one failed.
            handshakeCompleted.await(5, TimeUnit.SECONDS);
            assertEquals(1, handshakesCompleted.get());
        }
    });
}
Also used : InetSocketAddress(java.net.InetSocketAddress) SSLSocket(javax.net.ssl.SSLSocket) SSLServerSocket(javax.net.ssl.SSLServerSocket) CountDownLatch(java.util.concurrent.CountDownLatch) Callable(java.util.concurrent.Callable) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) HandshakeCompletedListener(javax.net.ssl.HandshakeCompletedListener) HandshakeCompletedEvent(javax.net.ssl.HandshakeCompletedEvent) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ExecutorService(java.util.concurrent.ExecutorService) ExecutionException(java.util.concurrent.ExecutionException) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Aggregations

HandshakeCompletedListener (javax.net.ssl.HandshakeCompletedListener)20 SSLSocket (javax.net.ssl.SSLSocket)19 HandshakeCompletedEvent (javax.net.ssl.HandshakeCompletedEvent)14 IOException (java.io.IOException)10 InetSocketAddress (java.net.InetSocketAddress)6 SocketException (java.net.SocketException)6 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)5 SSLServerSocket (javax.net.ssl.SSLServerSocket)5 KeyManagementException (java.security.KeyManagementException)4 ExecutorService (java.util.concurrent.ExecutorService)4 SSLHandshakeException (javax.net.ssl.SSLHandshakeException)4 Test (org.junit.Test)4 InputStream (java.io.InputStream)3 OutputStream (java.io.OutputStream)3 InetAddress (java.net.InetAddress)3 NetworkInterface (java.net.NetworkInterface)3 SocketTimeoutException (java.net.SocketTimeoutException)3 UnknownHostException (java.net.UnknownHostException)3 CertificateException (java.security.cert.CertificateException)3 Enumeration (java.util.Enumeration)3