Search in sources :

Example 66 with SSLHandshakeException

use of javax.net.ssl.SSLHandshakeException in project netty by netty.

the class SSLEngineTest method testMutualAuthDiffCertsServerFailure.

@Test
public void testMutualAuthDiffCertsServerFailure() throws Exception {
    File serverKeyFile = new File(getClass().getResource("test_encrypted.pem").getFile());
    File serverCrtFile = new File(getClass().getResource("test.crt").getFile());
    String serverKeyPassword = "12345";
    File clientKeyFile = new File(getClass().getResource("test2_encrypted.pem").getFile());
    File clientCrtFile = new File(getClass().getResource("test2.crt").getFile());
    String clientKeyPassword = "12345";
    // Client trusts server but server only trusts itself
    mySetupMutualAuth(serverCrtFile, serverKeyFile, serverCrtFile, serverKeyPassword, serverCrtFile, clientKeyFile, clientCrtFile, clientKeyPassword);
    assertTrue(serverLatch.await(2, TimeUnit.SECONDS));
    assertTrue(serverException instanceof SSLHandshakeException);
}
Also used : File(java.io.File) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) Test(org.junit.Test)

Example 67 with SSLHandshakeException

use of javax.net.ssl.SSLHandshakeException in project hadoop by apache.

the class TestSSLHttpServer method testOneEnabledCiphers.

/** Test that verified that additionally included cipher
   * TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA is only available cipher for working
   * TLS connection from client to server disabled for all other common ciphers.
   */
@Test
public void testOneEnabledCiphers() throws Exception {
    URL url = new URL(baseUrl, "/echo?a=b&c=d");
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    SSLSocketFactory sslSocketF = clientSslFactory.createSSLSocketFactory();
    PrefferedCipherSSLSocketFactory testPreferredCipherSSLSocketF = new PrefferedCipherSSLSocketFactory(sslSocketF, oneEnabledCiphers.split(","));
    conn.setSSLSocketFactory(testPreferredCipherSSLSocketF);
    assertFalse("excludedCipher list is empty", oneEnabledCiphers.isEmpty());
    try {
        InputStream in = conn.getInputStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        IOUtils.copyBytes(in, out, 1024);
        assertEquals(out.toString(), "a:b\nc:d\n");
        LOG.info("Atleast one additional enabled cipher than excluded ciphers," + " expected successful test result.");
    } catch (SSLHandshakeException ex) {
        fail("Atleast one additional cipher available for successful handshake." + " Unexpected test failure: " + ex);
    }
}
Also used : InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) URL(java.net.URL) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) Test(org.junit.Test)

Example 68 with SSLHandshakeException

use of javax.net.ssl.SSLHandshakeException in project XobotOS by xamarin.

the class Connection method openHttpConnection.

/**
     * @return true on success
     */
private boolean openHttpConnection(Request req) {
    long now = SystemClock.uptimeMillis();
    int error = EventHandler.OK;
    Exception exception = null;
    try {
        // reset the certificate to null before opening a connection
        mCertificate = null;
        mHttpClientConnection = openConnection(req);
        if (mHttpClientConnection != null) {
            mHttpClientConnection.setSocketTimeout(SOCKET_TIMEOUT);
            mHttpContext.setAttribute(HTTP_CONNECTION, mHttpClientConnection);
        } else {
            // we tried to do SSL tunneling, failed,
            // and need to drop the request;
            // we have already informed the handler
            req.mFailCount = RETRY_REQUEST_LIMIT;
            return false;
        }
    } catch (UnknownHostException e) {
        if (HttpLog.LOGV)
            HttpLog.v("Failed to open connection");
        error = EventHandler.ERROR_LOOKUP;
        exception = e;
    } catch (IllegalArgumentException e) {
        if (HttpLog.LOGV)
            HttpLog.v("Illegal argument exception");
        error = EventHandler.ERROR_CONNECT;
        req.mFailCount = RETRY_REQUEST_LIMIT;
        exception = e;
    } catch (SSLConnectionClosedByUserException e) {
        // hack: if we have an SSL connection failure,
        // we don't want to reconnect
        req.mFailCount = RETRY_REQUEST_LIMIT;
        // no error message
        return false;
    } catch (SSLHandshakeException e) {
        // hack: if we have an SSL connection failure,
        // we don't want to reconnect
        req.mFailCount = RETRY_REQUEST_LIMIT;
        if (HttpLog.LOGV)
            HttpLog.v("SSL exception performing handshake");
        error = EventHandler.ERROR_FAILED_SSL_HANDSHAKE;
        exception = e;
    } catch (IOException e) {
        error = EventHandler.ERROR_CONNECT;
        exception = e;
    }
    if (HttpLog.LOGV) {
        long now2 = SystemClock.uptimeMillis();
        HttpLog.v("Connection.openHttpConnection() " + (now2 - now) + " " + mHost);
    }
    if (error == EventHandler.OK) {
        return true;
    } else {
        if (req.mFailCount < RETRY_REQUEST_LIMIT) {
            // requeue
            mRequestFeeder.requeueRequest(req);
            req.mFailCount++;
        } else {
            httpFailure(req, error, exception);
        }
        return error == EventHandler.OK;
    }
}
Also used : UnknownHostException(java.net.UnknownHostException) IOException(java.io.IOException) ParseException(org.apache.http.ParseException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) HttpException(org.apache.http.HttpException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException)

Example 69 with SSLHandshakeException

use of javax.net.ssl.SSLHandshakeException in project XobotOS by xamarin.

the class SSLEngineImpl method unwrap.

/**
     * Decodes one complete SSL/TLS record provided in the source buffer.
     * If decoded record contained application data, this data will
     * be placed in the destination buffers.
     * For more information about TLS record fragmentation see
     * TLS v 1 specification (http://www.ietf.org/rfc/rfc2246.txt) p 6.2.
     * @param src source buffer containing SSL/TLS record.
     * @param dsts destination buffers to place received application data.
     * @see javax.net.ssl.SSLEngine#unwrap(ByteBuffer,ByteBuffer[],int,int)
     * method documentation for more information
     */
@Override
public SSLEngineResult unwrap(ByteBuffer src, ByteBuffer[] dsts, int offset, int length) throws SSLException {
    if (engine_was_shutteddown) {
        return new SSLEngineResult(SSLEngineResult.Status.CLOSED, SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING, 0, 0);
    }
    if ((src == null) || (dsts == null)) {
        throw new IllegalStateException("Some of the input parameters are null");
    }
    if (!handshake_started) {
        beginHandshake();
    }
    SSLEngineResult.HandshakeStatus handshakeStatus = getHandshakeStatus();
    // check if this call was made in spite of handshake status
    if ((session == null || engine_was_closed) && (handshakeStatus.equals(SSLEngineResult.HandshakeStatus.NEED_WRAP) || handshakeStatus.equals(SSLEngineResult.HandshakeStatus.NEED_TASK))) {
        return new SSLEngineResult(getEngineStatus(), handshakeStatus, 0, 0);
    }
    if (src.remaining() < recordProtocol.getMinRecordSize()) {
        return new SSLEngineResult(SSLEngineResult.Status.BUFFER_UNDERFLOW, getHandshakeStatus(), 0, 0);
    }
    try {
        src.mark();
        // check the destination buffers and count their capacity
        int capacity = 0;
        for (int i = offset; i < offset + length; i++) {
            if (dsts[i] == null) {
                throw new IllegalStateException("Some of the input parameters are null");
            }
            if (dsts[i].isReadOnly()) {
                throw new ReadOnlyBufferException();
            }
            capacity += dsts[i].remaining();
        }
        if (capacity < recordProtocol.getDataSize(src.remaining())) {
            return new SSLEngineResult(SSLEngineResult.Status.BUFFER_OVERFLOW, getHandshakeStatus(), 0, 0);
        }
        recProtIS.setSourceBuffer(src);
        // unwrap the record contained in source buffer, pass it
        // to appropriate client protocol (alert, handshake, or app)
        // and retrieve the type of unwrapped data
        int type = recordProtocol.unwrap();
        // process the data and return the result
        switch(type) {
            case ContentType.HANDSHAKE:
            case ContentType.CHANGE_CIPHER_SPEC:
                if (handshakeProtocol.getStatus().equals(SSLEngineResult.HandshakeStatus.FINISHED)) {
                    session = recordProtocol.getSession();
                }
                break;
            case ContentType.APPLICATION_DATA:
                break;
            case ContentType.ALERT:
                if (alertProtocol.isFatalAlert()) {
                    alertProtocol.setProcessed();
                    if (session != null) {
                        session.invalidate();
                    }
                    String description = "Fatal alert received " + alertProtocol.getAlertDescription();
                    shutdown();
                    throw new SSLException(description);
                } else {
                    if (logger != null) {
                        logger.println("Warning allert has been received: " + alertProtocol.getAlertDescription());
                    }
                    switch(alertProtocol.getDescriptionCode()) {
                        case AlertProtocol.CLOSE_NOTIFY:
                            alertProtocol.setProcessed();
                            close_notify_was_received = true;
                            if (!close_notify_was_sent) {
                                closeOutbound();
                                closeInbound();
                            } else {
                                closeInbound();
                                shutdown();
                            }
                            break;
                        case AlertProtocol.NO_RENEGOTIATION:
                            alertProtocol.setProcessed();
                            if (session == null) {
                                // handshake
                                throw new AlertException(AlertProtocol.HANDSHAKE_FAILURE, new SSLHandshakeException("Received no_renegotiation " + "during the initial handshake"));
                            } else {
                                // just stop the handshake
                                handshakeProtocol.stop();
                            }
                            break;
                        default:
                            alertProtocol.setProcessed();
                    }
                }
                break;
        }
        return new SSLEngineResult(getEngineStatus(), getHandshakeStatus(), recProtIS.consumed(), // and get the number of produced bytes:
        appData.placeTo(dsts, offset, length));
    } catch (BufferUnderflowException e) {
        // there was not enought data ource buffer to make complete packet
        src.reset();
        return new SSLEngineResult(SSLEngineResult.Status.BUFFER_UNDERFLOW, getHandshakeStatus(), 0, 0);
    } catch (AlertException e) {
        // fatal alert occured
        alertProtocol.alert(AlertProtocol.FATAL, e.getDescriptionCode());
        engine_was_closed = true;
        src.reset();
        if (session != null) {
            session.invalidate();
        }
        // to another peer (by wrap method)
        throw e.getReason();
    } catch (SSLException e) {
        throw e;
    } catch (IOException e) {
        alertProtocol.alert(AlertProtocol.FATAL, AlertProtocol.INTERNAL_ERROR);
        engine_was_closed = true;
        // to another peer (by wrap method)
        throw new SSLException(e.getMessage());
    }
}
Also used : ReadOnlyBufferException(java.nio.ReadOnlyBufferException) SSLEngineResult(javax.net.ssl.SSLEngineResult) IOException(java.io.IOException) SSLException(javax.net.ssl.SSLException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) BufferUnderflowException(java.nio.BufferUnderflowException)

Example 70 with SSLHandshakeException

use of javax.net.ssl.SSLHandshakeException in project XobotOS by xamarin.

the class HandshakeIODataStream method check.

// checks if the data can be written in the buffer
private void check(int length) {
    // 2. all written data was demanded by getData methods
    if (write_pos == write_pos_beg) {
        // just started to write after the reading
        if (read_pos != read_pos_end) {
            // all the inbound handshake data had been read
            throw new AlertException(AlertProtocol.INTERNAL_ERROR, new SSLHandshakeException("Data was not fully read: " + read_pos + " " + read_pos_end));
        }
        // set up the write positions
        if (write_pos_beg < read_pos_end) {
            write_pos_beg = read_pos_end;
            write_pos = write_pos_beg;
        }
    }
    // if there is not enought free space in the buffer - enlarge it:
    if (write_pos + length >= buff_size) {
        enlargeBuffer(length);
    }
}
Also used : SSLHandshakeException(javax.net.ssl.SSLHandshakeException)

Aggregations

SSLHandshakeException (javax.net.ssl.SSLHandshakeException)90 IOException (java.io.IOException)29 Test (org.junit.Test)22 CertificateException (java.security.cert.CertificateException)18 URL (java.net.URL)15 SSLException (javax.net.ssl.SSLException)15 SocketException (java.net.SocketException)13 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)12 SSLProtocolException (javax.net.ssl.SSLProtocolException)10 Socket (java.net.Socket)9 SSLSocket (javax.net.ssl.SSLSocket)9 SSLPeerUnverifiedException (javax.net.ssl.SSLPeerUnverifiedException)8 SocketTimeoutException (java.net.SocketTimeoutException)7 SSLSession (javax.net.ssl.SSLSession)7 InputStream (java.io.InputStream)6 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)6 Channel (io.netty.channel.Channel)5 InetSocketAddress (java.net.InetSocketAddress)5 MalformedURLException (java.net.MalformedURLException)5 ClosedChannelException (java.nio.channels.ClosedChannelException)5