Search in sources :

Example 61 with SSLSession

use of javax.net.ssl.SSLSession in project cloudstack by apache.

the class Link method read.

public byte[] read(SocketChannel ch) throws IOException {
    if (_readHeader) {
        // Start of a packet
        if (_readBuffer.position() == 0) {
            _readBuffer.limit(4);
        }
        if (ch.read(_readBuffer) == -1) {
            throw new IOException("Connection closed with -1 on reading size.");
        }
        if (_readBuffer.hasRemaining()) {
            s_logger.trace("Need to read the rest of the packet length");
            return null;
        }
        _readBuffer.flip();
        int header = _readBuffer.getInt();
        int readSize = (short) header;
        if (s_logger.isTraceEnabled()) {
            s_logger.trace("Packet length is " + readSize);
        }
        if (readSize > MAX_SIZE_PER_PACKET) {
            throw new IOException("Wrong packet size: " + readSize);
        }
        if (!_gotFollowingPacket) {
            _plaintextBuffer = ByteBuffer.allocate(2000);
        }
        if ((header & HEADER_FLAG_FOLLOWING) != 0) {
            _gotFollowingPacket = true;
        } else {
            _gotFollowingPacket = false;
        }
        _readBuffer.clear();
        _readHeader = false;
        if (_readBuffer.capacity() < readSize) {
            if (s_logger.isTraceEnabled()) {
                s_logger.trace("Resizing the byte buffer from " + _readBuffer.capacity());
            }
            _readBuffer = ByteBuffer.allocate(readSize);
        }
        _readBuffer.limit(readSize);
    }
    if (ch.read(_readBuffer) == -1) {
        throw new IOException("Connection closed with -1 on read.");
    }
    if (_readBuffer.hasRemaining()) {
        // We're not done yet.
        if (s_logger.isTraceEnabled()) {
            s_logger.trace("Still has " + _readBuffer.remaining());
        }
        return null;
    }
    _readBuffer.flip();
    ByteBuffer appBuf;
    SSLSession sslSession = _sslEngine.getSession();
    SSLEngineResult engResult;
    int remaining = 0;
    while (_readBuffer.hasRemaining()) {
        remaining = _readBuffer.remaining();
        appBuf = ByteBuffer.allocate(sslSession.getApplicationBufferSize() + 40);
        engResult = _sslEngine.unwrap(_readBuffer, appBuf);
        if (engResult.getHandshakeStatus() != HandshakeStatus.FINISHED && engResult.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING && engResult.getStatus() != SSLEngineResult.Status.OK) {
            throw new IOException("SSL: SSLEngine return bad result! " + engResult);
        }
        if (remaining == _readBuffer.remaining()) {
            throw new IOException("SSL: Unable to unwrap received data! still remaining " + remaining + "bytes!");
        }
        appBuf.flip();
        if (_plaintextBuffer.remaining() < appBuf.limit()) {
            // We need to expand _plaintextBuffer for more data
            ByteBuffer newBuffer = ByteBuffer.allocate(_plaintextBuffer.capacity() + appBuf.limit() * 5);
            _plaintextBuffer.flip();
            newBuffer.put(_plaintextBuffer);
            _plaintextBuffer = newBuffer;
        }
        _plaintextBuffer.put(appBuf);
        if (s_logger.isTraceEnabled()) {
            s_logger.trace("Done with packet: " + appBuf.limit());
        }
    }
    _readBuffer.clear();
    _readHeader = true;
    if (!_gotFollowingPacket) {
        _plaintextBuffer.flip();
        byte[] result = new byte[_plaintextBuffer.limit()];
        _plaintextBuffer.get(result);
        return result;
    } else {
        if (s_logger.isTraceEnabled()) {
            s_logger.trace("Waiting for more packets");
        }
        return null;
    }
}
Also used : SSLEngineResult(javax.net.ssl.SSLEngineResult) SSLSession(javax.net.ssl.SSLSession) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer)

Example 62 with SSLSession

use of javax.net.ssl.SSLSession in project platform_external_apache-http by android.

the class CertificateChainValidator method doHandshakeAndValidateServerCertificates.

/**
     * Performs the handshake and server certificates validation
     * Notice a new chain will be rebuilt by tracing the issuer and subject
     * before calling checkServerTrusted().
     * And if the last traced certificate is self issued and it is expired, it
     * will be dropped.
     * @param sslSocket The secure connection socket
     * @param domain The website domain
     * @return An SSL error object if there is an error and null otherwise
     */
public SslError doHandshakeAndValidateServerCertificates(HttpsConnection connection, SSLSocket sslSocket, String domain) throws IOException {
    // get a valid SSLSession, close the socket if we fail
    SSLSession sslSession = sslSocket.getSession();
    if (!sslSession.isValid()) {
        closeSocketThrowException(sslSocket, "failed to perform SSL handshake");
    }
    // retrieve the chain of the server peer certificates
    Certificate[] peerCertificates = sslSocket.getSession().getPeerCertificates();
    if (peerCertificates == null || peerCertificates.length == 0) {
        closeSocketThrowException(sslSocket, "failed to retrieve peer certificates");
    } else {
        // update the SSL certificate associated with the connection
        if (connection != null) {
            if (peerCertificates[0] != null) {
                connection.setCertificate(new SslCertificate((X509Certificate) peerCertificates[0]));
            }
        }
    }
    return verifyServerDomainAndCertificates((X509Certificate[]) peerCertificates, domain, "RSA");
}
Also used : SSLSession(javax.net.ssl.SSLSession) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 63 with SSLSession

use of javax.net.ssl.SSLSession in project platform_external_apache-http by android.

the class CertificateChainValidator method closeSocketThrowException.

private void closeSocketThrowException(SSLSocket socket, String errorMessage) throws IOException {
    if (HttpLog.LOGV) {
        HttpLog.v("validation error: " + errorMessage);
    }
    if (socket != null) {
        SSLSession session = socket.getSession();
        if (session != null) {
            session.invalidate();
        }
        socket.close();
    }
    throw new SSLHandshakeException(errorMessage);
}
Also used : SSLSession(javax.net.ssl.SSLSession) SSLHandshakeException(javax.net.ssl.SSLHandshakeException)

Example 64 with SSLSession

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

the class SSLSocketTest method test_SSLSocket_getSession.

public void test_SSLSocket_getSession() throws Exception {
    SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket ssl = (SSLSocket) sf.createSocket();
    SSLSession session = ssl.getSession();
    assertNotNull(session);
    assertFalse(session.isValid());
}
Also used : SSLSocket(javax.net.ssl.SSLSocket) SSLSession(javax.net.ssl.SSLSession) SSLSocketFactory(javax.net.ssl.SSLSocketFactory)

Example 65 with SSLSession

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

the class SSLSocketTest method test_SSLSocket_HandshakeCompletedListener.

public void test_SSLSocket_HandshakeCompletedListener() throws Exception {
    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();
    final boolean[] handshakeCompletedListenerCalled = new boolean[1];
    client.addHandshakeCompletedListener(new HandshakeCompletedListener() {

        public void handshakeCompleted(HandshakeCompletedEvent event) {
            try {
                SSLSession session = event.getSession();
                String cipherSuite = event.getCipherSuite();
                Certificate[] localCertificates = event.getLocalCertificates();
                Certificate[] peerCertificates = event.getPeerCertificates();
                javax.security.cert.X509Certificate[] peerCertificateChain = event.getPeerCertificateChain();
                Principal peerPrincipal = event.getPeerPrincipal();
                Principal localPrincipal = event.getLocalPrincipal();
                Socket socket = event.getSocket();
                if (false) {
                    System.out.println("Session=" + session);
                    System.out.println("CipherSuite=" + cipherSuite);
                    System.out.println("LocalCertificates=" + Arrays.toString(localCertificates));
                    System.out.println("PeerCertificates=" + Arrays.toString(peerCertificates));
                    System.out.println("PeerCertificateChain=" + Arrays.toString(peerCertificateChain));
                    System.out.println("PeerPrincipal=" + peerPrincipal);
                    System.out.println("LocalPrincipal=" + localPrincipal);
                    System.out.println("Socket=" + socket);
                }
                assertNotNull(session);
                byte[] id = session.getId();
                assertNotNull(id);
                assertEquals(32, id.length);
                assertNotNull(c.clientContext.getClientSessionContext().getSession(id));
                assertNotNull(cipherSuite);
                assertTrue(Arrays.asList(client.getEnabledCipherSuites()).contains(cipherSuite));
                assertTrue(Arrays.asList(c.serverSocket.getEnabledCipherSuites()).contains(cipherSuite));
                assertNull(localCertificates);
                assertNotNull(peerCertificates);
                TestKeyStore.assertChainLength(peerCertificates);
                assertNotNull(peerCertificates[0]);
                TestSSLContext.assertServerCertificateChain(c.clientTrustManager, peerCertificates);
                TestSSLContext.assertCertificateInKeyStore(peerCertificates[0], c.serverKeyStore);
                assertNotNull(peerCertificateChain);
                TestKeyStore.assertChainLength(peerCertificateChain);
                assertNotNull(peerCertificateChain[0]);
                TestSSLContext.assertCertificateInKeyStore(peerCertificateChain[0].getSubjectDN(), c.serverKeyStore);
                assertNotNull(peerPrincipal);
                TestSSLContext.assertCertificateInKeyStore(peerPrincipal, c.serverKeyStore);
                assertNull(localPrincipal);
                assertNotNull(socket);
                assertSame(client, socket);
                synchronized (handshakeCompletedListenerCalled) {
                    handshakeCompletedListenerCalled[0] = true;
                    handshakeCompletedListenerCalled.notify();
                }
                handshakeCompletedListenerCalled[0] = true;
            } catch (RuntimeException e) {
                throw e;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    });
    client.startHandshake();
    future.get();
    if (!TestSSLContext.sslServerSocketSupportsSessionTickets()) {
        assertNotNull(c.serverContext.getServerSessionContext().getSession(client.getSession().getId()));
    }
    synchronized (handshakeCompletedListenerCalled) {
        while (!handshakeCompletedListenerCalled[0]) {
            handshakeCompletedListenerCalled.wait();
        }
    }
    client.close();
    server.close();
    c.close();
}
Also used : SSLSocket(javax.net.ssl.SSLSocket) SSLSession(javax.net.ssl.SSLSession) SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) SSLProtocolException(javax.net.ssl.SSLProtocolException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) SSLException(javax.net.ssl.SSLException) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) HandshakeCompletedListener(javax.net.ssl.HandshakeCompletedListener) HandshakeCompletedEvent(javax.net.ssl.HandshakeCompletedEvent) ExecutorService(java.util.concurrent.ExecutorService) Principal(java.security.Principal) Socket(java.net.Socket) SSLSocket(javax.net.ssl.SSLSocket) ServerSocket(java.net.ServerSocket) SSLServerSocket(javax.net.ssl.SSLServerSocket)

Aggregations

SSLSession (javax.net.ssl.SSLSession)187 HostnameVerifier (javax.net.ssl.HostnameVerifier)50 SSLSocket (javax.net.ssl.SSLSocket)34 X509Certificate (java.security.cert.X509Certificate)32 IOException (java.io.IOException)31 SSLContext (javax.net.ssl.SSLContext)30 Test (org.junit.Test)29 CertificateException (java.security.cert.CertificateException)27 Certificate (java.security.cert.Certificate)20 SSLException (javax.net.ssl.SSLException)17 X509TrustManager (javax.net.ssl.X509TrustManager)16 URL (java.net.URL)14 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)14 SSLPeerUnverifiedException (javax.net.ssl.SSLPeerUnverifiedException)14 TrustManager (javax.net.ssl.TrustManager)14 SecureRandom (java.security.SecureRandom)13 FakeSSLSession (okhttp3.FakeSSLSession)13 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)12 InputStream (java.io.InputStream)11 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)11