summaryrefslogtreecommitdiffstats
blob: 1d8fba7502388e18fc0b2e82f8ddaa5c8b1726ac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
/*  Copyright (c) 2012, Isode Limited, London, England.
 *  All rights reserved.
 *
 *  Acquisition and use of this software and related materials for any
 *  purpose requires a written licence agreement from Isode Limited,
 *  or a written licence from an organisation licensed by Isode Limited Limited
 *  to grant such a licence.
 *
 */
 
package com.isode.stroke.tls.java;

import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
import java.util.Vector;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLEngineResult.Status;
import javax.net.ssl.SSLException;

import com.isode.stroke.base.ByteArray;
import com.isode.stroke.tls.Certificate;
import com.isode.stroke.tls.CertificateVerificationError;
import com.isode.stroke.tls.CertificateVerificationError.Type;
import com.isode.stroke.tls.PKCS12Certificate;
import com.isode.stroke.tls.TLSContext;


/**
 * Concrete implementation of a TLSContext which uses SSLEngine 
 * and maybe other stuff? ..tbs...
 * 
 */
public class JSSEContext extends TLSContext {

    private static class JSSEContextError {
        public Throwable throwable;
        public String message;
        /**
         * Create a new object
         * @param t throwable; may be null
         * @param m message; may be null
         */
        public JSSEContextError(Throwable t, String m) {
            throwable = t;
            message = m;
        }
        @Override
        public String toString() {
            return "JSSEContextError: " +
                    (message == null ? "No message" : message) + "; " +
                    (throwable == null ? "No exception" : throwable.getMessage());
        }
    }
    /**
     * If an error occurs, it will be added to this vector
     */
    private Vector<JSSEContextError> errorsEmitted = new Vector<JSSEContextError>();
    
    /**
     * Whether the handshake has finished
     */
    private boolean handshakeCompleted = false;
    
    /**
     * Determine whether an error has occurred.  If an error has occurred, then
     * you probably don't want to try doing any more stuff.
     * 
     * @return <em>true</em> if an error has occurred, <em>false</em>
     * otherwise
     */
    private boolean hasError() {
        return (!errorsEmitted.isEmpty());
    }
    /**
     * Emit an error, and keep track of which errors have been emitted
     * @param t the Throwable which caused this error (may be null)
     * @param m a String describing what caused this error (may be null)
     */
    private void emitError(Throwable t, String m) {
        JSSEContextError jsseContextError = new JSSEContextError(t,m);
        errorsEmitted.add(jsseContextError);
        onError.emit();        
    }
    
    @Override
    public void connect() {
        try {
            doSetup();
        }
        catch (SSLException e) {
            emitError(e,"doSetup() failed");
        }       
    }

    private void doSetup() throws SSLException {
       
        // May throw NoSuchAlgorithmException
        SSLContext sslContext = null;

        sslContext = getSSLContext();
        
        if (sslContext == null) {
            throw new SSLException("Could not create SSLContext");
        }
        
        sslEngine = null;
        try {
            sslEngine = sslContext.createSSLEngine();
        }
        catch (UnsupportedOperationException e) {
            // "the underlying provider does not implement the operation"
            throw new SSLException(e);
        }
        catch (IllegalStateException e) {
            // "the SSLContextImpl requires initialization and init() has not been called"
            throw new SSLException(e);
        }
        
        sslEngine.setUseClientMode(true); // I am a client
        sslEngine.setEnableSessionCreation(true); // can create new sessions
        

        int appBufferMax = sslEngine.getSession().getApplicationBufferSize();
        int netBufferMax = sslEngine.getSession().getPacketBufferSize();
        
        // All buffers are normally in "write" mode. Access to all of them
        // must be synchronized
        plainToSend = ByteBuffer.allocate(appBufferMax + 50);
        wrappedToSend = ByteBuffer.allocate(netBufferMax);
        encryptedReceived = ByteBuffer.allocate(netBufferMax);
        unwrappedReceived = ByteBuffer.allocate(appBufferMax + 50); 
        
        // Note that calling beginHandshake might not actually do anything; 
        // the SSLEngine may not actually send the handshake until it's had 
        // some data from the application.  And the higher level won't send 
        // any data until it thinks the handshake is completed.  
        //
        // So this is a hack to force the handshake to occur: on the assumption
        // that the first thing to be sent once TLS is running is 
        // the "<" from the start of a tag, we send a less-than sign now, 
        // which we'll remember must be removed that from the first message
        // we get told to send.
        
        sslEngine.beginHandshake();

        ByteArray ba = new ByteArray("<".getBytes());
        hack = HackStatus.SENDING_FAKE_LT;
        handleDataFromApplication(ba);
                
    }

    
    /**
     * Unwrap any data in the "encryptedReceived" buffer and put it into
     * the "unwrappedReceived" buffer. An event will be generated to the
     * end-user's listener if there's anything pending in the 
     * unwrappedReceived buffer.  Caller should check handshake status
     * after this returns
     * 
     * @return the number of bytes that SSLEngine consumed
     */
    private int unwrapPendingData()
    {
        SSLEngineResult sslEngineResult;
        Status status;   
        int bytesProduced = 0;
        int bytesConsumed = 0;
        HandshakeStatus handshakeStatus = null;
        ByteArray byteArray = null;

        synchronized(recvMutex) {
            try {
                encryptedReceived.flip();
                sslEngineResult = sslEngine.unwrap(encryptedReceived, unwrappedReceived);
                encryptedReceived.compact();

                // A call to unwrap can generate a status of FINISHED, which
                // you won't get from SSLEngine.getHandshakeStatus.  Such
                // a status is an indication that we need to re-check whether
                // anything's pending to be written
                handshakeStatus = sslEngineResult.getHandshakeStatus();


                bytesConsumed += sslEngineResult.bytesConsumed();
                bytesProduced = sslEngineResult.bytesProduced();
            }
            catch (SSLException e) {
                throw new RuntimeException("unwrap produced: " + e);
            }


            status = sslEngineResult.getStatus();
            boolean finished = false;
            while (!finished) {
                switch (status) {
                case BUFFER_UNDERFLOW:
                    // There's not enough data yet for engine to be able to decode
                    // a full message. Not a problem; assume that more will come
                    // in to the socket eventually
                    finished = true;
                    break;
                case OK:
                    // Unwrap was OK
                    finished = true;
                    break;
                case BUFFER_OVERFLOW:
                    // Not enough room in "unwrappedReceived" to write the data
                    // TODO: need to fix this
                case CLOSED:
                    // Engine closed - don't expect this here
                    emitError(null, "SSLEngine.unwrap returned " + status);
                    return bytesConsumed;
                }
            }

            if (handshakeStatus == HandshakeStatus.FINISHED) {
                // Special case will happen when the handshake completes following
                // an unwrap.  The first time we tried wrapping some plain stuff,
                // it triggers the handshake but won't itself have been dealt with.
                // So now the handshake has finished, we have to try sending it
                // again
                handshakeCompleted = true;
                wrapAndSendData();
                onConnected.emit();
            }

            if (bytesProduced > 0) {
                unwrappedReceived.flip();
                byte[] result = new byte[0];
                result = new byte[unwrappedReceived.remaining()];
                unwrappedReceived.get(result);
                unwrappedReceived.compact();
                byteArray = new ByteArray(result);
            }

        }
        
        // Now out of synchronized block
        if (byteArray != null) {
            onDataForApplication.emit(byteArray);
        }
        return bytesConsumed;

    }

    /**
     * Use the SSLEngine to wrap everything that we've so far got
     * in "plainToSend", and then send all of that to the socket.  Caller
     * is responsible for checking the handshake status on return
     * 
     */
    private void wrapAndSendData() {

        int bytesSentToSocket = 0;
        ByteArray byteArray = null;
        SSLEngineResult sslEngineResult = null;
        Status status = null;
        boolean handshakeFinished = false;
       
        synchronized(sendMutex) {
            // Check if there's anything outstanding to be sent at the
            // top of the loop, so that we clear the "wrappedToSend"
            // buffer before asking the engine to encrypt anything
            // TODO: is this required? I don't think anything gets put in
            // wrappedToSend apart from in here?
            wrappedToSend.flip();
            if (wrappedToSend.hasRemaining()) {
                byte[] b = new byte[(wrappedToSend.remaining())];
                wrappedToSend.get(b);
                byteArray = new ByteArray(b);
            }
            wrappedToSend.compact();
        } // end synchronized

        if (byteArray != null) {
            int s = byteArray.getSize();
            
            onDataForNetwork.emit(byteArray);
            bytesSentToSocket += s;
            byteArray = null;
        }

        // There's nothing waiting to be sent. Now see what new data needs 
        // encrypting
        synchronized(sendMutex) {
            plainToSend.flip();
            if (!plainToSend.hasRemaining()) {
                // Nothing more to be encrypted
                plainToSend.compact();
                return;
            }
            try {
                sslEngineResult = sslEngine.wrap(plainToSend, wrappedToSend);
            }
            catch (SSLException e) {
                // TODO: Is there anything more that can be done here?
                // TODO: this is called inside the mutex, does this matter?
                emitError(e,"SSLEngine.wrap failed");
                return;
            }
            plainToSend.compact();

            status = sslEngineResult.getStatus();

            // FINISHED can only come back for wrap() or unwrap(); so check to
            // see if we just had it
            if (sslEngineResult.getHandshakeStatus() == HandshakeStatus.FINISHED) {
                handshakeFinished = true;
            }

            switch (status) {
            case OK:
                // This is the only status we expect here. It means the
                // data was successfully wrapped and that there's something
                // to be sent.  
                wrappedToSend.flip();
                if (wrappedToSend.hasRemaining()) {
                    byte[] b = new byte[(wrappedToSend.remaining())];
                    wrappedToSend.get(b);
                    byteArray = new ByteArray(b);
                }
                wrappedToSend.compact();
                break;

            case BUFFER_UNDERFLOW:
                // Can't happen for a wrap
            case CLOSED :
                // ???
            case BUFFER_OVERFLOW:
                // The "wrappedToSend" buffer, which we had previously made
                // sure was empty, isn't big enough. 
                // TODO: I don't think this can happen though
                // TODO: Note that we're in sychronized block here
                emitError(null, "SSLEngine.wrap returned " + status);
                return;

            }
        } // end synchronized
        
        if (handshakeFinished) {
            handshakeCompleted = true;
            onConnected.emit();
        }
        
        if (byteArray != null) {
            int s = byteArray.getSize();
            onDataForNetwork.emit(byteArray);
            bytesSentToSocket += s;
            byteArray = null;
        }

        // Note that there may still be stuff in "plainToSend" that hasn't
        // yet been consumed
        return;

    }

    
    /**
     * Process the current handshake status. 
     * @return <em>true</em> if this method needs to be called again, or
     * <em>false</em> if there's no more handshake status to be processed
     */
    private boolean processHandshakeStatus() {
        HandshakeStatus handshakeStatus;
        
        handshakeStatus = sslEngine.getHandshakeStatus();
        switch (handshakeStatus) {
        case NOT_HANDSHAKING:
            // No handshaking going on - session is available, no more
            // handshake status to process
            return false;
        case NEED_TASK:
            runDelegatedTasks(false); // false==don't create separate threads 
            
            // after tasks have run, need to come back here and check
            // handshake status again
            return true;
            
        case NEED_WRAP:
            // SSLEngine wants some data that it can wrap for sending to the
            // other side
            wrapAndSendData();
            // after sending data, need to check handshake status again
            return true;
        case NEED_UNWRAP:
            
            // SSLEngine wants data from other side that it can unwrap and
            // process
            int consumed = unwrapPendingData();
            return (consumed > 0);
             
        case FINISHED:
            // "This value is only generated by a call to wrap/unwrap when
            // that call finishes a handshake. It is never generated by
            // SSLEngine.getHandshakeStatus()"
            
        default:
            // There are no other values, but compiler requires this
            throw new RuntimeException("unexpected handshake status " + handshakeStatus);
        }        
    }
    
    /**
     * Create and start running delegated tasks for all pending delegated tasks
     * @param createThreads <em>true</em> to run tasks in separate threads,
     * <em>false</em> to run them all in series in the current thread
     */
    private void runDelegatedTasks(boolean createThreads)    
    {
        Runnable nextTask = sslEngine.getDelegatedTask();
        
        while (nextTask != null) {
            final Runnable task = nextTask;
            Thread delegatedTaskThread = new Thread() {
                public void run() {
                    task.run();
                }
            };
            
            if (createThreads) {
                delegatedTaskThread.setDaemon(true);
                delegatedTaskThread.start();
            }
            else {
                delegatedTaskThread.run();
            }
            nextTask = sslEngine.getDelegatedTask();
        } 
    }
    
    /**
     * This method must be called to inform the JSSEContext object of the 
     * certificate(s) which were presented by the peer during the handshake.
     * 
     * <p>For example, an X509TrustManager implementation may obtain
     * peer certificates inside <em>checkServerTrusted</em>, and call this
     * method with those certificates. 
     * 
     * @param certs chain of certificates presented by the server.  Will
     * subsequently be returned by any call to {@link #getPeerCertificate()}
     * 
     * @param certificateException any exception resulting from an attempt 
     * to verify the certificate. May be null. If non-null, then will be used 
     * to generate the value that is returned by any subsequent call to 
     * {@link #getPeerCertificateVerificationError()}
     */
    public void setPeerCertificateInfo(X509Certificate[] certs, 
            CertificateException certificateException) {
        if (certs == null || certs.length == 0) {
            return;
        }
                
        peerCertificate = new JavaCertificate(certs[0]);
        
        // Swiften uses SSL_get_verify_result() for this, and the documentation
        // for that says it "while the verification of a certificate can fail
        // because of many reasons at the same time. Only the last verification
        // error that occurred..is available". 
        // So once one problem is found, don't bother looking for others.

        if (certificateException != null) {
            if (certificateException instanceof CertificateNotYetValidException) {
                peerCertificateVerificationError = new CertificateVerificationError(Type.NotYetValid);
                return;
                
            }
            
            if (certificateException instanceof CertificateExpiredException) {
                peerCertificateVerificationError = new CertificateVerificationError(Type.Expired);
                return;
            }
        }
        
    }
    
    
    @Override
    public boolean setClientCertificate(PKCS12Certificate cert) {
        // TODO: NYI.
        // It's possible this is going to change as a result of Alexey's work
        // so will leave for now
        return false;
    }

    @Override
    public void handleDataFromNetwork(ByteArray data) {
        if (hasError()) {
            // We have previously seen, and reported, an error.  Emit again
            onError.emit();        
            return;
        }
        byte[] b = data.getData();
        
        synchronized(recvMutex) {
            try {
                // TODO: could "encryptedReceived" already have stuff in it?
                encryptedReceived.put(b);
            }
            catch (BufferOverflowException e) {
                emitError(e, "Unable to add data to encryptedReceived");
                return;
            }
        }
        
        unwrapPendingData();
        
        // Now keep checking SSLEngine until no more handshakes are required
        do {
            //
        } while (processHandshakeStatus());
               
    }

    @Override
    public void handleDataFromApplication(ByteArray data) {
        if (hasError()) {
            // We have previously seen, and reported, an error.  Emit again
            onError.emit();        
            return;
        }
        byte[] b = data.getData();
               
        synchronized(sendMutex) {
            try {
                // Note that "plainToSend" may not be empty, because it's possible
                // that calls to SSLEngine.wrap haven't yet consumed everything
                // in there
                switch (hack) {
                case SENDING_FAKE_LT :
                    plainToSend.put(b);
                    hack = HackStatus.DISCARD_FIRST_LT;
                    break;
                    
                case DISCARD_FIRST_LT:
                    if (b.length > 0) {
                        if (b[0] == (byte)'<') {
                            plainToSend.put(b,1,b.length - 1);
                            hack = HackStatus.HACK_DONE;
                        }
                        else {
                            emitError(null,
                                    "First character sent after TLS started was " + 
                                    b[0] + " and not '<'");                            
                        }
                    }
                    break;
                case HACK_DONE:
                    plainToSend.put(b);
                    break;
                }
            }
            catch (BufferOverflowException e) {
                // TODO: anything else here?
                emitError(e, "plainToSend.put failed");
                return;
            }
        }

        wrapAndSendData();
        
        // Now keep checking SSLEngine until no more handshakes are required
        do {
            //
        } while (processHandshakeStatus());

    }

    @Override
    public Certificate getPeerCertificate() {
        return peerCertificate;
    }

    @Override
    public CertificateVerificationError getPeerCertificateVerificationError() {
        return peerCertificateVerificationError;
    }

    @Override
    public ByteArray getFinishMessage() {
        // TODO: Doesn't appear to be an obvious way to get this
        // information from SSLEngine et al.  For now, return null.
        
        return null;
    }
    
    @Override
    public String toString() {
        String errors = null;
        if (hasError()) {
            errors = "; errors emitted:";
            for (JSSEContextError e:errorsEmitted) {
                errors += "\n  " + e;
            }
        }
        
        String result = 
            "JSSEContext with SSLEngine = " + 
            sslEngine + 
            "; handshakeCompleted=" + handshakeCompleted;
        
        if (errors == null) {
            return result + " (no errors)";
        }
        return result + errors;
    }
    
    /**
     * Construct a new JSSEContext object. 
     */
    public JSSEContext() {
        //
    }

    /**
     * Reference to the SSLEngine being used
     */
    private SSLEngine sslEngine;
    /**
     * Contains plaintext information supplied by the caller which is
     * waiting to be encrypted and sent out over the socket. 
     */
    private ByteBuffer plainToSend;
    
    /**
     * Contains encrypted information produced by the SSLEngine which is
     * waiting to be sent over the socket
     */
    private ByteBuffer wrappedToSend;
    
    /**
     * Contains (presumably encrypted) information received from the socket
     * which is waiting to be unwrapped by the SSLEngine. 
    */
    private ByteBuffer encryptedReceived;
    
    /**
     * Contains data that the SSLEngine has unwrapped and is now waiting to
     * be read by the caller
     */
    private ByteBuffer unwrappedReceived;
    /**
     * Used to synchronize access to both plainToSend and wrappedToSend
     */
    private Object sendMutex = new Object();
    /**
     * Used to synchronize access to both encryptedReceived and unwrappedReceived
     */
    private Object recvMutex = new Object();
    
    /**
     * The server certificate as obtained from the TLS handshake
     */
    private JavaCertificate peerCertificate = null;
    
    /**
     * The CertificateVerificationError derived from the peerCertificate. This
     * may be null if no error was found.
     */
    private CertificateVerificationError peerCertificateVerificationError = null;
    
    /**
     * Used to remember what state we're in when doing the hack to overcome the
     * issue of SSLEngine not starting to handshake until it's got some data
     * to send
     */
    private static enum HackStatus { SENDING_FAKE_LT, DISCARD_FIRST_LT, HACK_DONE }
    private static HackStatus hack = HackStatus.SENDING_FAKE_LT;

          
    /**
     * Set up the SSLContext and JavaTrustManager that will be used for this
     * JSSEContext.
     * 
     * TODO: We probably want a way to allow callers to supply their own
     * values for SSLContext and TrustManager
     * 
     * @return an SSLContext, or null if one cannot be created. In this case,
     * an error will have been emitted.
     */
    private SSLContext getSSLContext()
    {
        try {
            JavaTrustManager [] tm = new JavaTrustManager[] { new JavaTrustManager(this)};
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(
                    null,   // KeyManager[]
                    tm,     // TrustManager[]
                    null);  // SecureRandom
            return sslContext;
        }
        catch (SSLException e) {
            emitError(e, "Couldn't create JavaTrustManager");
        }
        catch (NoSuchAlgorithmException e) {
            emitError(e, "Couldn't create SSLContext");
        }
        catch (KeyManagementException e) {
            emitError(e, "Couldn't initialise SSLContext");
        }
        return null;
        
    }
}