Search in sources :

Example 81 with SSLException

use of javax.net.ssl.SSLException in project jersey by jersey.

the class SslFilter method handleHandshakeFinished.

private void handleHandshakeFinished() {
    // Apply a custom host verifier if present. Do it for both handshaking and re-handshaking.
    if (customHostnameVerifier != null && !customHostnameVerifier.verify(serverHost, sslEngine.getSession())) {
        handleSslError(new SSLException("Server host name verification using " + customHostnameVerifier.getClass() + " has failed"));
        return;
    }
    if (state == State.HANDSHAKING) {
        state = State.DATA;
        upstreamFilter.onSslHandshakeCompleted();
    } else if (state == State.REHANDSHAKING) {
        state = State.DATA;
        if (pendingApplicationWrite != null) {
            Runnable write = pendingApplicationWrite;
            // set pending write to null to cover the extremely improbable case that we start re-handshaking again
            pendingApplicationWrite = null;
            write.run();
        }
    }
}
Also used : SSLException(javax.net.ssl.SSLException)

Example 82 with SSLException

use of javax.net.ssl.SSLException in project jersey by jersey.

the class SslFilter method handleRead.

private boolean handleRead(ByteBuffer networkData) {
    try {
        applicationInputBuffer.clear();
        SSLEngineResult result = sslEngine.unwrap(networkData, applicationInputBuffer);
        switch(result.getStatus()) {
            case BUFFER_OVERFLOW:
                {
                    /* This means that the content of the ssl packet (max 16kB) did not fit into
                       applicationInputBuffer, but we make sure to set applicationInputBuffer > max 16kB
                       when initializing this filter. This indicates a bug.*/
                    throw new IllegalStateException("Contents of a SSL packet did not fit into buffer: " + applicationInputBuffer + "\n" + getDebugState());
                }
            case BUFFER_UNDERFLOW:
                {
                    // the ssl packet is not full, return and indicate that we won't get more from this buffer
                    return false;
                }
            case CLOSED:
            case OK:
                {
                    if (result.bytesProduced() > 0) {
                        applicationInputBuffer.flip();
                        upstreamFilter.onRead(applicationInputBuffer);
                        applicationInputBuffer.compact();
                    }
                    if (sslEngine.isInboundDone()) {
                        // signal that there is nothing useful left in this buffer
                        return false;
                    }
                    // we started re-handshaking
                    if (result.getHandshakeStatus() != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING && // make sure we don't confuse re-handshake with closing handshake
                    !sslEngine.isOutboundDone()) {
                        state = State.REHANDSHAKING;
                        return doHandshakeStep(networkData);
                    }
                    break;
                }
        }
    } catch (SSLException e) {
        handleSslError(e);
    }
    return true;
}
Also used : SSLEngineResult(javax.net.ssl.SSLEngineResult) SSLException(javax.net.ssl.SSLException)

Example 83 with SSLException

use of javax.net.ssl.SSLException in project jersey by jersey.

the class SslFilterTest method testHostameVerificationFail.

@Test
public void testHostameVerificationFail() throws Throwable {
    CountDownLatch latch = new CountDownLatch(1);
    SslEchoServer server = new SslEchoServer();
    try {
        server.start();
        System.out.println("=== SSLHandshakeException (certificate_unknown) on the server expected ===");
        openClientSocket("127.0.0.1", ByteBuffer.allocate(0), latch, null);
        fail();
    } catch (SSLException e) {
    // expected
    } finally {
        server.stop();
    }
}
Also used : CountDownLatch(java.util.concurrent.CountDownLatch) SSLException(javax.net.ssl.SSLException) Test(org.junit.Test)

Example 84 with SSLException

use of javax.net.ssl.SSLException in project k-9 by k9mail.

the class ImapConnection method open.

public void open() throws IOException, MessagingException {
    if (open) {
        return;
    } else if (stacktraceForClose != null) {
        throw new IllegalStateException("open() called after close(). " + "Check wrapped exception to see where close() was called.", stacktraceForClose);
    }
    open = true;
    boolean authSuccess = false;
    nextCommandTag = 1;
    adjustDNSCacheTTL();
    try {
        socket = connect();
        configureSocket();
        setUpStreamsAndParserFromSocket();
        readInitialResponse();
        requestCapabilitiesIfNecessary();
        upgradeToTlsIfNecessary();
        authenticate();
        authSuccess = true;
        enableCompressionIfRequested();
        retrievePathPrefixIfNecessary();
        retrievePathDelimiterIfNecessary();
    } catch (SSLException e) {
        handleSslException(e);
    } catch (ConnectException e) {
        handleConnectException(e);
    } catch (GeneralSecurityException e) {
        throw new MessagingException("Unable to open connection to IMAP server due to security error.", e);
    } finally {
        if (!authSuccess) {
            Log.e(LOG_TAG, "Failed to login, closing connection for " + getLogId());
            close();
        }
    }
}
Also used : MessagingException(com.fsck.k9.mail.MessagingException) GeneralSecurityException(java.security.GeneralSecurityException) SSLException(javax.net.ssl.SSLException) ConnectException(java.net.ConnectException)

Example 85 with SSLException

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

the class SelectChannelEndPointSslTest method testTcpClose.

@Test
public void testTcpClose() throws Exception {
    // This test replaces SSLSocket() with a very manual SSL client
    // so we can close TCP underneath SSL.
    SocketChannel client = SocketChannel.open(_connector.socket().getLocalSocketAddress());
    client.socket().setSoTimeout(500);
    SocketChannel server = _connector.accept();
    server.configureBlocking(false);
    _manager.accept(server);
    SSLEngine engine = __sslCtxFactory.newSSLEngine();
    engine.setUseClientMode(true);
    engine.beginHandshake();
    ByteBuffer appOut = ByteBuffer.allocate(engine.getSession().getApplicationBufferSize());
    ByteBuffer sslOut = ByteBuffer.allocate(engine.getSession().getPacketBufferSize() * 2);
    ByteBuffer appIn = ByteBuffer.allocate(engine.getSession().getApplicationBufferSize());
    ByteBuffer sslIn = ByteBuffer.allocate(engine.getSession().getPacketBufferSize() * 2);
    boolean debug = false;
    if (debug)
        System.err.println(engine.getHandshakeStatus());
    int loop = 20;
    while (engine.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING) {
        if (--loop == 0)
            throw new IllegalStateException();
        if (engine.getHandshakeStatus() == HandshakeStatus.NEED_WRAP) {
            if (debug)
                System.err.printf("sslOut %d-%d-%d%n", sslOut.position(), sslOut.limit(), sslOut.capacity());
            if (debug)
                System.err.printf("appOut %d-%d-%d%n", appOut.position(), appOut.limit(), appOut.capacity());
            SSLEngineResult result = engine.wrap(appOut, sslOut);
            if (debug)
                System.err.println(result);
            sslOut.flip();
            int flushed = client.write(sslOut);
            if (debug)
                System.err.println("out=" + flushed);
            sslOut.clear();
        }
        if (engine.getHandshakeStatus() == HandshakeStatus.NEED_UNWRAP) {
            if (debug)
                System.err.printf("sslIn %d-%d-%d%n", sslIn.position(), sslIn.limit(), sslIn.capacity());
            if (sslIn.position() == 0) {
                int filled = client.read(sslIn);
                if (debug)
                    System.err.println("in=" + filled);
            }
            sslIn.flip();
            if (debug)
                System.err.printf("sslIn %d-%d-%d%n", sslIn.position(), sslIn.limit(), sslIn.capacity());
            SSLEngineResult result = engine.unwrap(sslIn, appIn);
            if (debug)
                System.err.println(result);
            if (debug)
                System.err.printf("sslIn %d-%d-%d%n", sslIn.position(), sslIn.limit(), sslIn.capacity());
            if (sslIn.hasRemaining())
                sslIn.compact();
            else
                sslIn.clear();
            if (debug)
                System.err.printf("sslIn %d-%d-%d%n", sslIn.position(), sslIn.limit(), sslIn.capacity());
        }
        if (engine.getHandshakeStatus() == HandshakeStatus.NEED_TASK) {
            Runnable task;
            while ((task = engine.getDelegatedTask()) != null) task.run();
            if (debug)
                System.err.println(engine.getHandshakeStatus());
        }
    }
    if (debug)
        System.err.println("\nSay Hello");
    // write a message
    appOut.put("HelloWorld".getBytes(StandardCharsets.UTF_8));
    appOut.flip();
    SSLEngineResult result = engine.wrap(appOut, sslOut);
    if (debug)
        System.err.println(result);
    sslOut.flip();
    int flushed = client.write(sslOut);
    if (debug)
        System.err.println("out=" + flushed);
    sslOut.clear();
    appOut.clear();
    // read the response
    int filled = client.read(sslIn);
    if (debug)
        System.err.println("in=" + filled);
    sslIn.flip();
    result = engine.unwrap(sslIn, appIn);
    if (debug)
        System.err.println(result);
    if (sslIn.hasRemaining())
        sslIn.compact();
    else
        sslIn.clear();
    appIn.flip();
    String reply = new String(appIn.array(), appIn.arrayOffset(), appIn.remaining());
    appIn.clear();
    Assert.assertEquals("HelloWorld", reply);
    if (debug)
        System.err.println("Shutting down output");
    client.socket().shutdownOutput();
    filled = client.read(sslIn);
    if (debug)
        System.err.println("in=" + filled);
    if (filled >= 0) {
        // this is the old behaviour. 
        sslIn.flip();
        try {
            // Since the client closed abruptly, the server is sending a close alert with a failure
            engine.unwrap(sslIn, appIn);
            Assert.fail();
        } catch (SSLException x) {
        // Expected
        }
    }
    sslIn.clear();
    filled = client.read(sslIn);
    Assert.assertEquals(-1, filled);
    // TODO This should not be needed
    Thread.sleep(100);
    Assert.assertFalse(server.isOpen());
}
Also used : SocketChannel(java.nio.channels.SocketChannel) SSLEngineResult(javax.net.ssl.SSLEngineResult) SSLEngine(javax.net.ssl.SSLEngine) ByteBuffer(java.nio.ByteBuffer) SSLException(javax.net.ssl.SSLException) Test(org.junit.Test)

Aggregations

SSLException (javax.net.ssl.SSLException)158 IOException (java.io.IOException)46 X509Certificate (java.security.cert.X509Certificate)26 SSLEngineResult (javax.net.ssl.SSLEngineResult)23 SocketException (java.net.SocketException)20 SSLSocket (javax.net.ssl.SSLSocket)20 ByteBuffer (java.nio.ByteBuffer)19 CertificateException (java.security.cert.CertificateException)19 Test (org.junit.Test)19 SSLHandshakeException (javax.net.ssl.SSLHandshakeException)18 SSLContext (javax.net.ssl.SSLContext)15 SSLPeerUnverifiedException (javax.net.ssl.SSLPeerUnverifiedException)15 SSLSession (javax.net.ssl.SSLSession)15 InetSocketAddress (java.net.InetSocketAddress)14 SSLEngine (javax.net.ssl.SSLEngine)14 X509TrustManager (javax.net.ssl.X509TrustManager)12 Bootstrap (io.netty.bootstrap.Bootstrap)11 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)11 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)11 Socket (java.net.Socket)11