forked from wolfSSL/wolfssljni
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWolfSSLEngine.java
More file actions
2823 lines (2505 loc) · 113 KB
/
WolfSSLEngine.java
File metadata and controls
2823 lines (2505 loc) · 113 KB
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
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* WolfSSLEngine.java
*
* Copyright (C) 2006-2026 wolfSSL Inc.
*
* This file is part of wolfSSL.
*
* wolfSSL is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* wolfSSL is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
*/
package com.wolfssl.provider.jsse;
import com.wolfssl.WolfSSL;
import com.wolfssl.WolfSSLDebug;
import com.wolfssl.WolfSSLException;
import com.wolfssl.WolfSSLByteBufferIORecvCallback;
import com.wolfssl.WolfSSLByteBufferIOSendCallback;
import com.wolfssl.WolfSSLJNIException;
import com.wolfssl.WolfSSLSession;
import com.wolfssl.WolfSSLALPNSelectCallback;
import com.wolfssl.WolfSSLSessionTicketCallback;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ReadOnlyBufferException;
import java.util.function.BiFunction;
import java.util.List;
import java.util.Arrays;
import java.util.ArrayList;
import java.security.cert.CertificateEncodingException;
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 javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SNIServerName;
import javax.net.ssl.SNIHostName;
import java.net.SocketException;
import java.net.SocketTimeoutException;
/**
* wolfSSL implementation of SSLEngine.
*
* There is more verbose debugging available for this class apart
* from the normal 'wolfjsse.debug' logging. To enable more verbose
* logging use both the following system properties:
*
* System.setProperty("wolfjsse.debug", "true");
* System.setProperty("wolfsslengine.debug", "true");
*
* This will add extra debug logs around wrap() and unwrap() calls, as well
* as printing out the data sent/received in the I/O callbacks.
*
* @author wolfSSL
*/
public class WolfSSLEngine extends SSLEngine {
private WolfSSLEngineHelper engineHelper = null;
private WolfSSLSession ssl = null;
private com.wolfssl.WolfSSLContext ctx = null;
private WolfSSLAuthStore authStore = null;
private WolfSSLParameters params = null;
private int nativeWantsToWrite = 0;
private int nativeWantsToRead = 0;
private HandshakeStatus hs = SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING;
/* Does TLS handshake need initialization */
private boolean needInit = true;
private final Object initLock = new Object();
/* Have cert/key been loaded? */
private boolean certKeyLoaded = false;
private boolean inBoundOpen = true;
private boolean outBoundOpen = true;
/* closed completely (post shutdown or before handshake) */
private boolean closed = true;
/* handshake started explicitly by user with beginHandshake() */
private boolean handshakeStartedExplicitly = false;
/* handshake completed */
private boolean handshakeFinished = false;
/* Last return values of ssl.connect() / ssl.accept(). Protected
* by ioLock. Can be used during state transitions to see if handshake
* has finished successfully from native wolfSSL perspective. */
private int lastSSLConnectRet = WolfSSL.SSL_FAILURE;
private int lastSSLAcceptRet = WolfSSL.SSL_FAILURE;
/* SNI mismatch detected during handshake */
private boolean sniMismatch = false;
/* closeNotify status when shutting down */
private boolean closeNotifySent = false;
private boolean closeNotifyReceived = false;
/* session stored (WOLFSSL_SESSION), relevant on client side */
private boolean sessionStored = false;
/* Skip record header peek in next unwrap, continue same TLS record */
private boolean contPartialRecord = false;
/* TLS 1.3 session ticket received (on client side) */
private boolean sessionTicketReceived = false;
/* Number of session tickets received, incremented in
* SessionTicketCB callback */
private int sessionTicketCount = 0;
/* client/server mode has been set */
private boolean clientModeSet = false;
private SendCB sendCb = null;
private RecvCB recvCb = null;
private SessionTicketCB sessTicketCb = null;
private ByteBuffer netData = null;
private final Object netDataLock = new Object();
/* Single buffer used to hold application data to be sent, allocated once
* inside SendAppData, of size SSLSession.getApplicationBufferSize() */
private ByteBuffer staticAppDataBuf = null;
/* Stashed decrypted data when output buffer too small.
* Served on next unwrap() without calling ssl_read(). */
private byte[] pendingAppData = null;
private int pendingAppDataLen = 0;
private int pendingNetConsumed = 0;
/* Scratch buffer for ssl.read() plaintext. Reused across unwrap() calls
* and expanded only when a larger output window requires it. */
private byte[] recvAppDataBuf = new byte[WolfSSL.MAX_RECORD_SIZE];
/* Default size of internalIOSendBuf, 16k to match TLS record size.
* TODO - add upper bound on I/O send buf resize allocations. */
private static final int INTERNAL_IOSEND_BUF_SZ = WolfSSL.MAX_RECORD_SIZE;
/* static buffer used to hold encrypted data to be sent, allocated inside
* internalSendCb() and expanded only if needed. Synchronize on toSendLock
* when accessing this buffer. */
private byte[] internalIOSendBuf = new byte[INTERNAL_IOSEND_BUF_SZ];
/* Total size of internalIOSendBuf */
private int internalIOSendBufSz = INTERNAL_IOSEND_BUF_SZ;
/* Offset into internalIOSendBuf to start writing data */
private int internalIOSendBufOffset = 0;
/* Locks for synchronization */
private final Object ioLock = new Object();
private final Object toSendLock = new Object();
/** ALPN selector callback, if set */
protected volatile
BiFunction<SSLEngine, List<String>, String> alpnSelector = null;
/** Turn on extra/verbose SSLEngine debug logging */
private boolean extraDebugEnabled = false;
/** Turn on Send/Recv callback debug to print out bytes sent/received.
* WARNING: enabling this will slow down sending and receiving data,
* enough so that app may run into timeouts. Enable with caution. */
private boolean ioDebugEnabled = false;
/**
* Turns on additional debugging based on system properties set.
*/
private void enableExtraDebug() {
/* turn on verbose extra debugging if 'wolfsslengine.debug'
* system property is set */
String engineDebug = System.getProperty("wolfsslengine.debug");
if ((engineDebug != null) && (engineDebug.equalsIgnoreCase("true"))) {
this.extraDebugEnabled = true;
}
}
/**
* Turns on additional debugging of I/O data based on system properties set.
*/
private void enableIODebug() {
/* turn on verbose extra debugging of bytes sent and received if
* 'wolfsslengine.io.debug' system property is set */
String engineIODebug = System.getProperty("wolfsslengine.io.debug");
if ((engineIODebug != null) &&
(engineIODebug.equalsIgnoreCase("true"))) {
this.ioDebugEnabled = true;
}
}
/**
* Create a new engine with no hints for session reuse
*
* @param ctx JNI level WolfSSLContext
* @param auth WolfSSLAuthStore to use
* @param params connection parameters to be used
* @throws WolfSSLException if there is an issue creating the engine
*/
protected WolfSSLEngine(com.wolfssl.WolfSSLContext ctx,
WolfSSLAuthStore auth, WolfSSLParameters params)
throws WolfSSLException {
super();
this.ctx = ctx;
this.authStore = auth;
this.params = params.copy();
try {
initSSL();
} catch (WolfSSLJNIException ex) {
throw new WolfSSLException("Error with WolfSSLEngine init");
}
this.engineHelper = new WolfSSLEngineHelper(this.ssl, this.authStore,
this.params);
}
/**
* Create a new engine with hints for session reuse
*
* @param ctx JNI level WolfSSLContext
* @param auth WolfSSLAuthStore to use
* @param params connection parameters to be used
* @param host to connect to
* @param port to connect to
* @throws WolfSSLException if there is an issue creating the engine
*/
protected WolfSSLEngine(com.wolfssl.WolfSSLContext ctx,
WolfSSLAuthStore auth, WolfSSLParameters params, String host,
int port) throws WolfSSLException {
super(host, port);
this.ctx = ctx;
this.authStore = auth;
this.params = params.copy();
try {
initSSL();
} catch (WolfSSLJNIException ex) {
throw new WolfSSLException("Error with WolfSSLEngine init");
}
this.engineHelper = new WolfSSLEngineHelper(this.ssl, this.authStore,
this.params, port, host);
}
/**
* Loads the key and certificate for this SSLEngine if not loaded yet.
*
* @throws SSLException on error
*/
private synchronized void LoadCertAndKey() throws SSLException {
/* Load cert and key */
if (certKeyLoaded) {
return;
}
try {
this.engineHelper.loadKeyAndCertChain(null, this);
certKeyLoaded = true;
} catch (CertificateEncodingException | IOException |
WolfSSLException e) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "failed to load private key and/or cert chain");
throw new SSLException(e);
}
}
/**
* Initialize this WolfSSLEngine prior to handshaking.
*
* Internal method, should be called before any handshake.
*
* This logic is not included directly in WolfSSLEngine constructors
* to avoid possible 'this' escape before subclass is fully initialized
* when using 'this' in loadKeyAndCertChain().
*
* @throws SSLException if initialization fails
*/
private void checkAndInitSSLEngine() throws SSLException {
final int ret;
synchronized (initLock) {
if (!needInit) {
return;
}
LoadCertAndKey();
this.engineHelper.initHandshake(this);
if ((this.ssl.dtls() == 1) &&
(!this.engineHelper.getUseClientMode())) {
ret = this.ssl.sendHrrCookie(null);
if (ret == WolfSSL.SSL_SUCCESS) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Enabled sending of DTLS cookie in " +
"HelloRetryRequest");
}
else if (ret < 0) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Failed to enable DTLS cookie in " +
"HelloRetryRequest, ret: " + ret);
}
}
needInit = false;
closed = false; /* opened a connection */
}
}
/**
* Cache requested SNI server names from raw network data.
*
* Parses SNI names from the ClientHello in the network input
* buffer and caches them into the session, if not already set.
* Only operates on the server side.
*/
protected synchronized void cacheRequestedServerNamesFromNetData() {
List<SNIServerName> cachedNames;
List<SNIServerName> names;
WolfSSLImplementSSLSession session;
if (this.engineHelper == null || this.engineHelper.getUseClientMode()) {
return;
}
session = this.engineHelper.getSession();
if (session == null) {
return;
}
cachedNames = session.getSNIServerNames();
if (cachedNames != null && !cachedNames.isEmpty()) {
return;
}
names = parseRequestedServerNamesFromNetData();
if (names == null || names.isEmpty()) {
return;
}
session.setSNIServerNames(names);
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Cached SNI names from pending SSLEngine input");
}
private List<SNIServerName> parseRequestedServerNamesFromNetData() {
ByteBuffer in;
byte[] clientHello;
byte[] sni;
int ret;
List<SNIServerName> names;
synchronized (netDataLock) {
if (this.netData == null ||
this.netData.remaining() < WolfSSL.TLS_RECORD_HEADER_LEN) {
return null;
}
in = this.netData.asReadOnlyBuffer();
clientHello = new byte[in.remaining()];
in.get(clientHello);
}
try {
/* Max SNI hostname is 255 bytes per RFC 6066 */
sni = new byte[255];
ret = WolfSSL.getSNIFromBuffer(clientHello,
(byte)WolfSSL.WOLFSSL_SNI_HOST_NAME, sni);
if (ret > 0 && ret <= sni.length) {
names = new ArrayList<SNIServerName>(1);
names.add(new SNIHostName(Arrays.copyOf(sni, ret)));
return names;
}
if (ret == WolfSSL.NOT_COMPILED_IN) {
return null;
}
} catch (IllegalArgumentException | WolfSSLException e) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Unable to parse SNI from pending input: " +
e.getMessage());
}
return null;
}
private void clearPendingAppData() {
if (this.pendingAppData != null) {
Arrays.fill(this.pendingAppData, (byte)0);
this.pendingAppData = null;
}
this.pendingAppDataLen = 0;
this.pendingNetConsumed = 0;
}
/**
* Register I/O callbacks and contexts with WolfSSLSession and native
* wolfSSL. Uses singleton pattern on callbacks.
*
* Call unsetSSLCallbacks to unset/unregister these. Since the I/O
* context is set as the current SSLEngine object, this can prevent
* garbage collection of this SSLEngine object unless the context
* is unset from the WolfSSLSession.
*
* Protected by ioLock since all I/O operations are dependent on using
* these underlying I/O callbacks.
*
* @throws WolfSSLJNIException on native JNI error
*/
private void setSSLCallbacks() throws WolfSSLJNIException {
synchronized (ioLock) {
if (sendCb == null) {
sendCb = new SendCB();
}
if (recvCb == null) {
recvCb = new RecvCB();
}
ssl.setIORecvByteBuffer(recvCb);
ssl.setIOSendByteBuffer(sendCb);
ssl.setIOReadCtx(this);
ssl.setIOWriteCtx(this);
/* Session ticket callback */
if (sessTicketCb == null) {
sessTicketCb = new SessionTicketCB();
}
ssl.setSessionTicketCb(sessTicketCb, this);
}
}
/**
* Unregister I/O callbacks and contexts with WolfSSLSession and
* native wolfSSL.
*
* Call setSSLCallbacks() to re-register these.
*
* Protected with ioLock since all I/O operations are dependent on
* using these underlying I/O callbacks.
*
* @throws WolfSSLJNIException on native JNI error
*/
private void unsetSSLCallbacks() throws WolfSSLJNIException {
synchronized (ioLock) {
ssl.setIORecvByteBuffer(null);
ssl.setIOSendByteBuffer(null);
ssl.setIOReadCtx(null);
ssl.setIOWriteCtx(null);
ssl.setSessionTicketCb(null, null);
}
}
private void initSSL() throws WolfSSLException, WolfSSLJNIException {
if (sendCb == null) {
sendCb = new SendCB();
}
if (recvCb == null) {
recvCb = new RecvCB();
}
if (sessTicketCb == null) {
sessTicketCb = new SessionTicketCB();
}
/* will throw WolfSSLException if issue creating WOLFSSL */
ssl = new WolfSSLSession(ctx, false);
enableExtraDebug();
enableIODebug();
}
/**
* Copy buffered data to be sent into provided output ByteBuffer.
*
* Data sent will be minimum of either buffered data size or
* destination buffer remaining space.
*
* Returns size of data copied.
*/
private int CopyOutPacket(ByteBuffer out) {
int sendSz = 0;
synchronized (toSendLock) {
if (this.internalIOSendBuf != null) {
sendSz = Math.min(this.internalIOSendBufOffset, out.remaining());
out.put(this.internalIOSendBuf, 0, sendSz);
if (sendSz != this.internalIOSendBufOffset) {
System.arraycopy(this.internalIOSendBuf, sendSz,
this.internalIOSendBuf, 0,
this.internalIOSendBufOffset - sendSz);
this.internalIOSendBufOffset =
this.internalIOSendBufOffset - sendSz;
}
else {
/* reset internalIOSendBufOffset to zero, no data left */
this.internalIOSendBufOffset = 0;
}
}
}
return sendSz;
}
/**
* Helper function, updates internal close_notify alert status
* and inBound/outBoundOpen.
*/
private synchronized void UpdateCloseNotifyStatus() {
int ret;
boolean nativeSent;
boolean nativeReceived;
synchronized (ioLock) {
ret = ssl.getShutdown();
}
nativeSent = ((ret & WolfSSL.SSL_SENT_SHUTDOWN) != 0);
nativeReceived = ((ret & WolfSSL.SSL_RECEIVED_SHUTDOWN) != 0);
/* In SSLEngine mode, native shutdown flags can be set before the
* close_notify bytes are surfaced to Java for wrap(). Map
* closeNotifySent to observable SSLEngine output state and defer
* SENT until data is pending to wrap (or already recorded). */
if (nativeSent && !this.closeNotifySent &&
this.internalIOSendBufOffset == 0) {
nativeSent = false;
}
if (nativeReceived && nativeSent) {
this.closeNotifySent = true;
this.closeNotifyReceived = true;
this.inBoundOpen = false;
if (this.internalIOSendBufOffset == 0) {
/* Don't close outbound if we have a close_notify alert
* send back to peer. Native wolfSSL may have already generated
* it and is reflected in SSL_SENT_SHUTDOWN flag, but we
* might have it cached in our Java SSLEngine object still to
* be sent. */
this.outBoundOpen = false;
}
closed = true;
} else if (nativeReceived) {
this.closeNotifyReceived = true;
this.inBoundOpen = false;
} else if (nativeSent) {
this.closeNotifySent = true;
this.outBoundOpen = false;
}
}
/**
* Returns if current error in WOLFSSL session should be considered
* fatal. Used in ClosingConnection() for detection of storing
* client cache entry.
*
* @param ssl WOLFSSL session to check error on
*
* @return true if error is not fatal, false if fatal
*/
private synchronized boolean sslErrorNotFatal(WolfSSLSession ssl) {
int err;
if (ssl == null) {
return false;
}
err = ssl.getError(0);
if (err == 0 ||
err == WolfSSL.SSL_ERROR_WANT_READ ||
err == WolfSSL.SSL_ERROR_WANT_WRITE) {
return true;
}
return false;
}
/**
* Handles logic during shutdown
*
* @return WolfSSL.SSL_SUCCESS on success, zero or negative on error
* @throws SocketException if ssl.shutdownSSL() encounters a socket error
* @throws SocketTimeoutException if ssl.shutdownSSL() times out
*/
private synchronized int ClosingConnection()
throws SocketException, SocketTimeoutException {
int ret;
/* Save session into WolfSSLAuthStore cache, saves session
* pointer for resumption if on client side. Protected with ioLock
* since underlying get1Session can use I/O with peek.
*
* Only store session if handshake is finished, SSL_get_error() does
* not have an active error state, and the session has not been
* stored previously. */
synchronized (ioLock) {
if (this.handshakeFinished && sslErrorNotFatal(ssl) &&
!this.sessionStored) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "saving WOLFSSL_SESSION into cache");
this.engineHelper.saveSession();
}
else {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "not saving WOLFSSL_SESSION into cache, " +
"handshake not complete or already stored");
}
}
/* get current close_notify state */
UpdateCloseNotifyStatus();
if (this.closeNotifySent && this.closeNotifyReceived) {
return WolfSSL.SSL_SUCCESS;
}
/* send/recv close_notify as needed */
synchronized (ioLock) {
ret = ssl.shutdownSSL();
if (ssl.getError(ret) == WolfSSL.SSL_ERROR_ZERO_RETURN) {
/* got close_notify alert, reset ret to SSL_SUCCESS to continue
* and let corresponding close_notify to be sent */
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "ClosingConnection(), ssl.getError() is ZERO_RETURN");
ret = WolfSSL.SSL_SUCCESS;
}
}
UpdateCloseNotifyStatus();
return ret;
}
/**
* Starts or continues SSL/TLS handshake.
*
* @return WolfSSL.SSL_SUCCESS or WolfSSL.SSL_FAILURE
* @throws SocketException if ssl.connect() or ssl.accept() encounters
* a socket exception.
* @throws SocketTimeoutException if ssl.connect() or ssl.accept()
* times out. This should not happen since infinite timeout is
* being used for these calls.
*/
private synchronized int DoHandshake(boolean fromWrap) throws SSLException {
int ret = WolfSSL.SSL_SUCCESS;
final int tmpRet;
try {
/* If DTLS and calling from wrap() but HandshakeStatus is
* actually NEED_UNWRAP, this is a signal from the application
* that we need to retransmit messages */
if ((this.ssl.dtls() == 1) && fromWrap &&
(this.hs == SSLEngineResult.HandshakeStatus.NEED_UNWRAP)) {
synchronized (ioLock) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Calling wrap() while status is NEED_UNWRAP, " +
"retransmitting DTLS messages");
ret = this.ssl.dtlsGotTimeout();
if (ret == 0) {
ret = WolfSSL.SSL_SUCCESS;
}
}
}
if (ret == WolfSSL.SSL_SUCCESS) {
if (this.getUseClientMode()) {
synchronized (ioLock) {
ret = this.ssl.connect();
lastSSLConnectRet = ret;
}
}
else {
synchronized (ioLock) {
ret = this.ssl.accept();
lastSSLAcceptRet = ret;
}
}
tmpRet = ret;
if (this.getUseClientMode()) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "ssl.connect() ret:err = " + tmpRet + " : " +
ssl.getError(tmpRet));
}
else {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "ssl.accept() ret:err = " + tmpRet + " : " +
ssl.getError(tmpRet));
}
}
} catch (SocketTimeoutException | SocketException e) {
SSLHandshakeException hsException = new SSLHandshakeException(
"Socket error during SSL/TLS handshake: " + e.getMessage());
hsException.initCause(e);
throw hsException;
}
/* Enforce server-side SNIMatchers on the SSLEngine path once SNI
* becomes available during the handshake. */
if (!this.getUseClientMode()) {
if (!this.engineHelper.matchSNI()) {
throw new SSLHandshakeException("Unrecognized Server Name");
}
}
return ret;
}
/**
* Write application data using ssl.write().
*
* Only sends up to maximum app data chunk size
* (SSLSession.getApplicationBufferSize()).
*
* @throws SocketException if ssl.write() encounters a socket error
* @throws SocketTimeoutException if ssl.write() times out. Shouldn't
* happen since this is using an infinite timeout.
* @return bytes sent on success, negative on error
*/
private synchronized int SendAppData(ByteBuffer[] in, int ofst, int len)
throws SocketException, SocketTimeoutException {
int i = 0;
int ret = 0;
int totalIn = 0;
int sendSz = 0;
int inputLeft = 0;
byte[] dataArr;
int[] pos = new int[len]; /* in[] positions */
int[] limit = new int[len]; /* in[] limits */
/* Get total input data size, store input array positions */
for (i = ofst; i < ofst + len; i++) {
totalIn += in[i].remaining();
pos[i - ofst] = in[i].position();
limit[i - ofst] = in[i].limit();
}
/* Allocate static buffer for application data, clear before use */
sendSz = this.engineHelper.getSession().getApplicationBufferSize();
if (this.staticAppDataBuf == null) {
/* allocate static buffer for application data */
this.staticAppDataBuf = ByteBuffer.allocateDirect(sendSz);
}
this.staticAppDataBuf.clear();
/* Only send up to maximum app data size chunk */
sendSz = Math.min(totalIn, sendSz);
/* gather byte array of sendSz bytes from input buffers */
inputLeft = sendSz;
for (i = ofst; i < ofst + len; i++) {
int bufChunk = Math.min(in[i].remaining(), inputLeft);
in[i].limit(in[i].position() + bufChunk); /* set limit */
this.staticAppDataBuf.put(in[i]); /* get data */
inputLeft -= bufChunk;
in[i].limit(limit[i - ofst]); /* reset limit */
if (inputLeft == 0) {
break; /* reached data size needed, stop reading */
}
}
dataArr = new byte[sendSz];
this.staticAppDataBuf.rewind();
this.staticAppDataBuf.get(dataArr);
final int tmpSendSz = sendSz;
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "calling ssl.write() with size: " + tmpSendSz);
synchronized (ioLock) {
ret = this.ssl.write(dataArr, sendSz);
}
if (ret <= 0) {
/* error, reset in[] positions for next call */
for (i = ofst; i < ofst + len; i++) {
in[i].position(pos[i - ofst]);
}
}
final int tmpRet = ret;
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "ssl.write() returning: " + tmpRet);
return ret;
}
@Override
public synchronized SSLEngineResult wrap(ByteBuffer in, ByteBuffer out)
throws SSLException {
if (in == null) {
throw new SSLException("SSLEngine.wrap() bad arguments");
}
return wrap(new ByteBuffer[] { in }, 0, 1, out);
}
@Override
public synchronized SSLEngineResult wrap(ByteBuffer[] in, int ofst, int len,
ByteBuffer out) throws SSLException {
int ret = 0, i;
int produced = 0;
int consumed = 0;
/* Set initial status for SSLEngineResult return */
Status status = SSLEngineResult.Status.OK;
/* Sanity check buffer arguments. */
if (in == null || ofst + len > in.length || out == null) {
throw new SSLException("SSLEngine.wrap() bad arguments");
}
if (ofst < 0 || len < 0) {
throw new IndexOutOfBoundsException();
}
for (i = ofst; i < ofst + len; ++i) {
if (in[i] == null) {
throw new SSLException("SSLEngine.wrap() bad arguments");
}
}
if (out.isReadOnly()) {
throw new ReadOnlyBufferException();
}
if (!this.clientModeSet) {
throw new IllegalStateException(
"setUseClientMode() has not been called on this SSLEngine");
}
if (extraDebugEnabled) {
final Status tmpStatus = status;
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "==== [ entering wrap() ] =============================");
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "setUseClientMode: " +
this.engineHelper.getUseClientMode());
for (i = ofst; i < ofst + len; i++) {
final int idx = i;
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "ByteBuffer in["+idx+"].remaining(): " +
in[idx].remaining());
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "ByteBuffer in["+idx+"].position(): " +
in[idx].position());
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "ByteBuffer in["+idx+"].limit(): " +
in[idx].limit());
}
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "ofst: " + ofst + ", len: " + len);
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "out.remaining(): " + out.remaining());
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "out.position(): " + out.position());
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "out.limit(): " + out.limit());
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "internalIOSendBufOffset: " +
this.internalIOSendBufOffset);
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "closeNotifySent: " + this.closeNotifySent);
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "closeNotifyReceived: " + this.closeNotifyReceived);
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "inBoundOpen: " + this.inBoundOpen);
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "outBoundOpen: " + this.outBoundOpen);
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "status: " + tmpStatus);
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "handshakeStatus: " + hs);
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "handshakeFinished: " + this.handshakeFinished);
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "nativeHandshakeState: " + this.ssl.getStateStringLong());
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "nativeWantsToRead: " + this.nativeWantsToRead);
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "nativeWantsToWrite: " + this.nativeWantsToWrite);
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "=====================================================");
}
/* Set wolfSSL I/O callbacks and context for read/write operations */
try {
setSSLCallbacks();
} catch (WolfSSLJNIException e) {
throw new SSLException(e);
}
/* Wrap in try/finally to ensure we unset callbacks on any exit path */
try {
if (needInit) {
checkAndInitSSLEngine();
}
synchronized (netDataLock) {
this.netData = null;
}
/* Already closed and close_notify flushed, done */
if (!this.outBoundOpen && this.closeNotifySent &&
this.internalIOSendBufOffset == 0) {
return new SSLEngineResult(Status.CLOSED,
SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING, 0, 0);
}
/* Force out buffer to be large enough to hold max packet size */
if (out.remaining() <
this.engineHelper.getSession().getPacketBufferSize()) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "out.remaining() too small (" +
out.remaining() + "), need at least: " +
this.engineHelper.getSession().getPacketBufferSize());
return new SSLEngineResult(Status.BUFFER_OVERFLOW, hs, 0, 0);
}
/* Copy buffered data to be sent into output buffer */
produced = CopyOutPacket(out);
/* Closing down connection if buffered data has been sent and:
* 1. Outbound has been closed (!outBoundOpen)
* 2. Inbound is closed and close_notify has been sent
*/
if (produced >= 0 &&
(!outBoundOpen || (!inBoundOpen && this.closeNotifySent))) {
/* Mark SSLEngine status as CLOSED */
status = SSLEngineResult.Status.CLOSED;
/* Handshake has finished and SSLEngine is closed, release
* global JNI verify callback pointer */
this.engineHelper.unsetVerifyCallback();
try {
ClosingConnection();
} catch (SocketException | SocketTimeoutException e) {
throw new SSLException(e);
}
produced += CopyOutPacket(out);
}
else if ((produced > 0) && !inBoundOpen &&
(!this.closeNotifySent && !this.closeNotifyReceived)) {
/* We had buffered data to send, but inbound was already
* closed. Most likely this is because we needed to send an
* alert to the peer. We should now mark outbound as closed
* since we won't be sending anything after the alert went
* out. */
this.outBoundOpen = false;
this.closed = true;
}
else if (produced == 0) {
/* continue handshake or application data */
if (!this.handshakeFinished) {
ret = DoHandshake(true);
}
else {
try {
ret = SendAppData(in, ofst, len);
if (ret > 0) {
consumed += ret;
}
} catch (SocketException | SocketTimeoutException e) {
throw new SSLException(e);
}
}
/* copy any produced data into output buffer */
produced += CopyOutPacket(out);
}
SetHandshakeStatus(ret);
if (extraDebugEnabled) {
final HandshakeStatus tmpHs = hs;
final Status tmpStatus = status;
final int tmpConsumed = consumed;
final int tmpProduced = produced;
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "==== [ exiting wrap() ] ==========================");
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "setUseClientMode: " +
this.engineHelper.getUseClientMode());
for (i = 0; i < len; i++) {
final int idx = i;
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,