forked from wolfSSL/wolfssljni
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWolfSSLSession.java
More file actions
5682 lines (4870 loc) · 219 KB
/
WolfSSLSession.java
File metadata and controls
5682 lines (4870 loc) · 219 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
/* WolfSSLSession.java
*
* Copyright (C) 2006-2025 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;
import java.util.Arrays;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.lang.StringBuilder;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.security.Security;
/**
* Wraps a native WolfSSL session object and contains methods directly related
* to the SSL/TLS session.
*
* @author wolfSSL
*/
public class WolfSSLSession {
/* Internal pointer to native WOLFSSL object. Access to this pointer
* should be protected in this class with synchronization on the
* this.sslLock lock. */
private long sslPtr;
private Object ioReadCtx;
private Object ioWriteCtx;
private Object genCookieCtx;
private Object macEncryptCtx;
private Object decryptVerifyCtx;
private Object verifyDecryptCtx;
private Object eccSignCtx;
private Object eccVerifyCtx;
private Object eccSharedSecretCtx;
private Object rsaSignCtx;
private Object rsaVerifyCtx;
private Object rsaEncCtx;
private Object rsaDecCtx;
private Object alpnSelectArg;
private Object tls13SecretCtx;
private Object sessionTicketCtx;
/* reference to the associated WolfSSLContext */
private WolfSSLContext ctx = null;
/* user-registered PSK callbacks, also at WolfSSLContext level */
private WolfSSLPskClientCallback internPskClientCb = null;
private WolfSSLPskServerCallback internPskServerCb = null;
/* User-registerd I/O callbacks:
*
* These are called by internal WolfSSLSession I/O callback. This is done
* in order to pass references to WolfSSLSession object. There are two sets
* of I/O callbacks here, one set that will use byte[] and one that will
* use ByteBuffer. Only one send and one recv callback can be set at a time
* between the two. Native JNI code will give preference to using the
* ByteBuffer variants for performance if set, since this will avoid an
* extra native allocation (NewByteArray()). The ByteBuffer variant will
* wrap the pre-allocated wolfSSL array in a Java direct ByteBuffer
* to pass back up to Java. */
private WolfSSLIORecvCallback internRecvSSLCb_array;
private WolfSSLIOSendCallback internSendSSLCb_array;
private WolfSSLByteBufferIORecvCallback internRecvSSLCb_BB;
private WolfSSLByteBufferIOSendCallback internSendSSLCb_BB;
/* user-registered ALPN select callback, called by internal WolfSSLSession
* ALPN select callback */
private WolfSSLALPNSelectCallback internAlpnSelectCb;
/* user-registered TLS 1.3 secret callback, called by internal
* WolfSSLSession TLS 1.3 secret callback */
private WolfSSLTls13SecretCallback internTls13SecretCb;
/* user-registered session ticket callback, called by internal
* WolfSSLSession session ticket callback */
private WolfSSLSessionTicketCallback internSessionTicketCb;
/* have session tickets been enabled for this session? Default to false. */
private boolean sessionTicketsEnabled = false;
/* is this context active, or has it been freed? */
private boolean active = false;
/* lock around active state */
private final Object stateLock = new Object();
/* lock around native WOLFSSL pointer use */
private final Object sslLock = new Object();
/* Is static direct ByteBuffer pool enabled for read/write() calls */
private boolean byteBufferPoolEnabled = true;
/* Maximum direct ByteBuffer pool size */
private static int MAX_POOL_SIZE = 16;
/* Size of each direct ByteBuffer in the pool. This is set to 17KB, which
* is slightly larger than the maximum SSL record size (16KB). This
* allows for some overhead (SSL record header, etc) */
private static int BUFFER_SIZE = 17 * 1024;
/* Thread-local direct ByteBuffer pool for optimized JNI direct memory
* access. Passing byte[] and offset down to JNI, on some systems this
* will cause unaligned memory access, with pointer addition
* (buffer + offset). Unaligned memory access can be considerably slower
* (ex: Aarch64). To avoid this, we use a thread-local pool of ByteBuffers
* here so native JNI does not do unaligned memory access and to eliminate
* cross-thread contention. */
private static final ThreadLocal<ConcurrentLinkedQueue<ByteBuffer>> directBufferPool =
ThreadLocal.withInitial(() -> new ConcurrentLinkedQueue<>());
/**
* Check if static direct ByteBuffer pool has been disabled for
* use in read/write() methods.
*
* The pool is enabled by default, unless explicitly disabled by setting
* the "wolfssl.readWriteByteBufferPool.disabled" property to "true".
*
* @return true if disabled, otherwise false
*/
private boolean readWritePoolDisabled() {
String disabled =
Security.getProperty("wolfssl.readWriteByteBufferPool.disabled");
if (disabled == null || disabled.isEmpty()) {
return false;
}
if (disabled.equalsIgnoreCase("true")) {
return true;
}
return false;
}
/**
* Check if the maximum size of the static per-thread direct
* ByteBuffer pool has been adjusted by setting of the
* "wolfssl.readWriteByteBufferPool.size" Security property.
*
* @return the size set, or the current default
* (MAX_POOL_SIZE) if not.
*/
private int readWritePoolGetMaxSizeFromProperty() {
int maxSize = MAX_POOL_SIZE;
String sizeProp =
Security.getProperty("wolfssl.readWriteByteBufferPool.size");
if (sizeProp == null || sizeProp.isEmpty()) {
return maxSize;
}
try {
int size = Integer.parseInt(sizeProp);
if (size > 0) {
maxSize = size;
}
} catch (NumberFormatException e) {
WolfSSLDebug.log(getClass(),
WolfSSLDebug.Component.JNI, WolfSSLDebug.ERROR, 0,
() -> "Invalid value for " +
"wolfssl.readWriteByteBufferPool.size: " + sizeProp);
}
return maxSize;
}
/**
* Check if the size of the ByteBuffers in the static per-thread
* pool has been adjusted by setting of the
* "wolfssl.readWriteByteBufferPool.bufferSize" Security property.
*
* @return the size set, or the current default (BUFFER_SIZE) if not.
*/
private int readWritePoolGetBufferSizeFromProperty() {
int bufferSize = BUFFER_SIZE;
String sizeProp =
Security.getProperty("wolfssl.readWriteByteBufferPool.bufferSize");
if (sizeProp == null || sizeProp.isEmpty()) {
return bufferSize;
}
try {
int size = Integer.parseInt(sizeProp);
if (size > 0) {
bufferSize = size;
}
} catch (NumberFormatException e) {
WolfSSLDebug.log(getClass(),
WolfSSLDebug.Component.JNI, WolfSSLDebug.ERROR, 0,
() -> "Invalid value for " +
"wolfssl.readWriteByteBufferPool.bufferSize: " + sizeProp);
}
return bufferSize;
}
/**
* Read current values of relevant Security properties and set
* internal behavior.
*/
private void detectSecurityPropertySettings() {
/* Re-use sslLock for synchronization here */
synchronized (sslLock) {
/* Check if static direct ByteBuffer pool has been disabled
* with the "wolfssl.readWriteByteBufferPool.disabled"
* Security property. */
if (readWritePoolDisabled()) {
this.byteBufferPoolEnabled = false;
}
/* Check if the maximum size of the static per-thread direct
* ByteBuffer pool has been adjusted by setting of the
* "wolfssl.readWriteByteBufferPool.size" Security property. */
WolfSSLSession.MAX_POOL_SIZE =
readWritePoolGetMaxSizeFromProperty();
/* Check if the size of the ByteBuffers in the static per-thread
* pool has been adjusted by setting of the
* "wolfssl.readWriteByteBufferPool.bufferSize" Security property. */
WolfSSLSession.BUFFER_SIZE =
readWritePoolGetBufferSizeFromProperty();
}
}
/**
* Get a DirectByteBuffer from the thread-local pool or allocate a new one
* if the pool is empty.
*
* @return a direct ByteBuffer ready to use
*/
private static synchronized ByteBuffer acquireDirectBuffer() {
ConcurrentLinkedQueue<ByteBuffer> threadPool = directBufferPool.get();
ByteBuffer buffer = threadPool.poll();
if (buffer == null) {
WolfSSLDebug.log(WolfSSLSession.class, WolfSSLDebug.Component.JNI,
WolfSSLDebug.INFO, 0,
() -> "Thread-local DirectByteBuffer pool empty, " +
"allocating new buffer");
buffer = ByteBuffer.allocateDirect(BUFFER_SIZE);
} else {
WolfSSLDebug.log(WolfSSLSession.class, WolfSSLDebug.Component.JNI,
WolfSSLDebug.INFO, 0,
() -> "Reusing DirectByteBuffer from thread-local pool, " +
"pool size: " + threadPool.size());
buffer.clear();
}
return buffer;
}
/**
* Return a DirectByteBuffer to the thread-local pool for reuse.
*
* If the pool is full, the ByteBuffer will be garbage collected.
*
* @param buffer the buffer to return to the pool
*/
private static synchronized void releaseDirectBuffer(ByteBuffer buffer) {
if (buffer != null && buffer.isDirect()) {
buffer.clear();
ConcurrentLinkedQueue<ByteBuffer> threadPool =
directBufferPool.get();
if (threadPool.size() < MAX_POOL_SIZE) {
WolfSSLDebug.log(WolfSSLSession.class,
WolfSSLDebug.Component.JNI, WolfSSLDebug.INFO, 0,
() -> "Returning DirectByteBuffer to thread-local pool, " +
"pool size: " + threadPool.size());
threadPool.offer(buffer);
}
}
}
/* SNI requested by this WolfSSLSession if client side and useSNI()
* was called successfully. */
private byte[] clientSNIRequested = null;
/**
* Creates a new SSL/TLS session.
*
* Native session created also creates JNI SSLAppData for usage
* internal to wolfSSL JNI. This constructor creates a default
* pipe() to use for interrupting threads waiting in select()/poll()
* when close() is called. To skip creation of this pipe() use
* the WolfSSLSession(WolfSSLContext ctx, boolean setupIOPipe)
* constructor with 'setupIOPipe' set to false.
*
* @param ctx WolfSSLContext object used to create SSL session.
*
* @throws com.wolfssl.WolfSSLException if session object creation
* failed.
*/
public WolfSSLSession(WolfSSLContext ctx) throws WolfSSLException {
sslPtr = newSSL(ctx.getContextPtr(), true);
if (sslPtr == 0) {
throw new WolfSSLException("Failed to create SSL Object");
}
WolfSSLDebug.log(getClass(), WolfSSLDebug.Component.JNI,
WolfSSLDebug.INFO, sslPtr,
() -> "creating new WolfSSLSession (with I/O pipe)");
detectSecurityPropertySettings();
synchronized (stateLock) {
this.active = true;
}
/* save context reference for I/O callbacks from JNI */
this.ctx = ctx;
}
/**
* Creates a new SSL/TLS session.
*
* Native session created also creates JNI SSLAppData for usage
* internal to wolfSSL JNI. A pipe() can be created internally to wolfSSL
* JNI to use for interrupting threads waiting in select()/poll()
* when close() is called. To skip creation of this pipe(), set
* 'setupIOPipe' to false.
*
* It is generally recommended to have wolfSSL JNI create the native
* pipe(), unless you will be operating over non-Socket I/O. For example,
* when this WolfSSLSession is being created from the JSSE level
* SSLEngine class.
*
* @param ctx WolfSSLContext object used to create SSL session.
* @param setupIOPipe true to create internal IO pipe(), otherwise
* false
*
* @throws com.wolfssl.WolfSSLException if session object creation
* failed.
*/
public WolfSSLSession(WolfSSLContext ctx, boolean setupIOPipe)
throws WolfSSLException {
sslPtr = newSSL(ctx.getContextPtr(), false);
if (sslPtr == 0) {
throw new WolfSSLException("Failed to create SSL Object");
}
if (setupIOPipe) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.Component.JNI,
WolfSSLDebug.INFO, sslPtr,
() -> "creating new WolfSSLSession (with I/O pipe)");
} else {
WolfSSLDebug.log(getClass(), WolfSSLDebug.Component.JNI,
WolfSSLDebug.INFO, sslPtr,
() -> "creating new WolfSSLSession (without I/O pipe)");
}
detectSecurityPropertySettings();
synchronized (stateLock) {
this.active = true;
}
/* save context reference for I/O callbacks from JNI */
this.ctx = ctx;
}
/* ------------------- private/protected methods -------------------- */
/* used from JNI code */
synchronized WolfSSLContext getAssociatedContextPtr() {
return ctx;
}
synchronized Object getGenCookieCtx() {
return this.genCookieCtx;
}
synchronized Object getMacEncryptCtx() {
return this.macEncryptCtx;
}
synchronized Object getDecryptVerifyCtx() {
return this.decryptVerifyCtx;
}
synchronized Object getVerifyDecryptCtx() {
return this.verifyDecryptCtx;
}
synchronized Object getEccSignCtx() {
return this.eccSignCtx;
}
synchronized Object getEccVerifyCtx() {
return this.eccVerifyCtx;
}
synchronized Object getEccSharedSecretCtx() {
return this.eccSharedSecretCtx;
}
synchronized Object getRsaSignCtx() {
return this.rsaSignCtx;
}
synchronized Object getRsaVerifyCtx() {
return this.rsaVerifyCtx;
}
synchronized Object getRsaEncCtx() {
return this.rsaEncCtx;
}
synchronized Object getRsaDecCtx() {
return this.rsaDecCtx;
}
/* Methods to detect which I/O callback variants have been set */
private boolean isArrayIOSendCallbackSet() {
return (internSendSSLCb_array != null);
}
private boolean isByteBufferIOSendCallbackSet() {
return (internSendSSLCb_BB != null);
}
private boolean isArrayIORecvCallbackSet() {
return (internRecvSSLCb_array != null);
}
private boolean isByteBufferIORecvCallbackSet() {
return (internRecvSSLCb_BB != null);
}
/* These callbacks will be registered with native wolfSSL library */
/**
* Internal wolfSSL I/O receive callback, using byte array.
*/
private int internalIOSSLRecvCallback(WolfSSLSession ssl,
byte[] buf, int sz)
{
/* call user-registered recv method */
return internRecvSSLCb_array.receiveCallback(ssl, buf, sz,
ssl.getIOReadCtx());
}
/**
* Internal wolfSSL I/O receive callback, using ByteBuffer.
*/
private int internalIOSSLRecvCallback(WolfSSLSession ssl,
ByteBuffer buf, int sz)
{
/* call user-registered recv method */
return internRecvSSLCb_BB.receiveCallback(ssl, buf, sz,
ssl.getIOReadCtx());
}
/**
* Internal wolfSSL I/O send callback, using byte array.
*/
private int internalIOSSLSendCallback(WolfSSLSession ssl,
byte[] buf, int sz)
{
/* call user-registered recv method */
return internSendSSLCb_array.sendCallback(ssl, buf, sz,
ssl.getIOWriteCtx());
}
/**
* Internal wolfSSL I/O send callback, using ByteBuffer.
*/
private int internalIOSSLSendCallback(WolfSSLSession ssl,
ByteBuffer buf, int sz)
{
/* call user-registered recv method */
return internSendSSLCb_BB.sendCallback(ssl, buf, sz,
ssl.getIOWriteCtx());
}
private long internalPskClientCallback(WolfSSLSession ssl, String hint,
StringBuffer identity, long idMaxLen, byte[] key,
long keyMaxLen)
{
/* call user-registered PSK client callback method */
return internPskClientCb.pskClientCallback(ssl, hint, identity,
idMaxLen, key, keyMaxLen);
}
private long internalPskServerCallback(WolfSSLSession ssl,
String identity, byte[] key, long keyMaxLen)
{
/* call user-registered PSK server callback method */
return internPskServerCb.pskServerCallback(ssl, identity,
key, keyMaxLen);
}
private int internalAlpnSelectCallback(WolfSSLSession ssl, String[] out,
String[] in)
{
/* call user-registered ALPN select callback */
return internAlpnSelectCb.alpnSelectCallback(ssl, out, in,
this.alpnSelectArg);
}
private int internalTls13SecretCallback(WolfSSLSession ssl, int id,
byte[] secret)
{
/* call user-registered TLS 1.3 secret callback */
return internTls13SecretCb.tls13SecretCallback(ssl, id, secret,
this.tls13SecretCtx);
}
private int internalSessionTicketCallback(WolfSSLSession ssl, byte[] ticket)
{
/* call user-registered session ticket callback */
return internSessionTicketCb.sessionTicketCallback(ssl, ticket,
this.sessionTicketCtx);
}
/**
* Verifies that the current WolfSSLSession object is active.
*
* @throws IllegalStateException if object has been freed
*/
private synchronized void confirmObjectIsActive()
throws IllegalStateException {
synchronized (stateLock) {
if (this.active == false) {
throw new IllegalStateException(
"WolfSSLSession object has been freed");
}
}
}
/* ------------------ native method declarations -------------------- */
private native long newSSL(long ctx, boolean withIOPipe);
private native int setFd(long ssl, Socket sd, int type);
private native int setFd(long ssl, DatagramSocket sd, int type);
private native int useCertificateFile(long ssl, String file, int format);
private native int usePrivateKeyFile(long ssl, String file, int format);
private native int useCertificateChainFile(long ssl, String file);
private native void setUsingNonblock(long ssl, int nonblock);
private native int getUsingNonblock(long ssl);
private native int getFd(long ssl);
private native int connect(long ssl, int timeout);
private native int write(long ssl, byte[] data, int offset, int length,
int timeout);
private native int write(long ssl, ByteBuffer data, final int position,
final int limit, boolean hasArray, int sz, int timeout)
throws WolfSSLException;
private native int read(long ssl, byte[] data, int offset, int sz,
int timeout);
private native int read(long ssl, ByteBuffer data, final int position,
final int limit, boolean hasArray, int sz, int timeout)
throws WolfSSLException;
private native int pending(long ssl);
private native int accept(long ssl, int timeout);
private native void freeSSL(long ssl);
private native int shutdownSSL(long ssl, int timeout);
private native int getError(long ssl, int ret);
private native int setSession(long ssl, long session);
private native long getSession(long ssl);
private native long get1Session(long ssl);
private static native int wolfsslSessionIsSetup(long ssl);
private static native int wolfsslSessionIsResumable(long ssl);
private static native long wolfsslSessionDup(long session);
private static native String wolfsslSessionCipherGetName(long ssl);
private static native void freeNativeSession(long session);
private native byte[] getSessionID(long session);
private native int setServerID(long ssl, byte[] id, int len, int newSess);
private native int setTimeout(long ssl, long t);
private native long getTimeout(long ssl);
private native int setSessTimeout(long session, long t);
private native long getSessTimeout(long session);
private native int setCipherList(long ssl, String list);
private native int dtlsGetCurrentTimeout(long ssl);
private native int dtlsGotTimeout(long ssl);
private native int dtlsRetransmit(long ssl);
private native int dtls(long ssl);
private native int dtlsSetPeer(long ssl, InetSocketAddress peer);
private native int sendHrrCookie(long ssl, byte[] secret);
private native long getDtlsMacDropCount(long ssl);
private native long getDtlsReplayDropCount(long ssl);
private native InetSocketAddress dtlsGetPeer(long ssl);
private native int sessionReused(long ssl);
private native long getPeerCertificate(long ssl);
private native String getPeerX509Issuer(long ssl, long x509);
private native String getPeerX509Subject(long ssl, long x509);
private native String getPeerX509AltName(long ssl, long x509);
private native String getVersion(long ssl);
private native long getCurrentCipher(long ssl);
private native int checkDomainName(long ssl, String dn);
private native int setTmpDH(long ssl, byte[] p, int pSz, byte[] g, int gSz);
private native int setTmpDHFile(long ssl, String fname, int format);
private native int useCertificateBuffer(long ssl, byte[] in, long sz,
int format);
private native int usePrivateKeyBuffer(long ssl, byte[] in, long sz,
int format);
private native int useCertificateChainBuffer(long ssl, byte[] in,
long sz);
private native int useCertificateChainBufferFormat(
long ssl, byte[] in, long sz, int format);
private native int setGroupMessages(long ssl);
private native int enableCRL(long ssl, int options);
private native int disableCRL(long ssl);
private native int loadCRL(long ssl, String path, int type, int monitor);
private native int setCRLCb(long ssl, WolfSSLMissingCRLCallback cb);
private native String cipherGetName(long ssl);
private native byte[] getMacSecret(long ssl, int verify);
private native byte[] getClientWriteKey(long ssl);
private native byte[] getClientWriteIV(long ssl);
private native byte[] getServerWriteKey(long ssl);
private native byte[] getServerWriteIV(long ssl);
private native int getKeySize(long ssl);
private native int getSide(long ssl);
private native int isTLSv1_1(long ssl);
private native int getBulkCipher(long ssl);
private native int getCipherBlockSize(long ssl);
private native int getAeadMacSize(long ssl);
private native int getHmacSize(long ssl);
private native int getHmacType(long ssl);
private native int getCipherType(long ssl);
private native int setTlsHmacInner(long ssl, byte[] inner, long sz,
int content, int verify);
private native void setEccSignCtx(long ssl);
private native void setEccVerifyCtx(long ssl);
private native void setEccSharedSecretCtx(long ssl);
private native void setRsaSignCtx(long ssl);
private native void setRsaVerifyCtx(long ssl);
private native void setRsaEncCtx(long ssl);
private native void setRsaDecCtx(long ssl);
private native void setPskClientCb(long ctx);
private native void setPskServerCb(long ctx);
private native String getPskIdentityHint(long ssl);
private native String getPskIdentity(long ssl);
private native int usePskIdentityHint(long ssl, String hint);
private native boolean handshakeDone(long ssl);
private native void setConnectState(long ssl);
private native void setAcceptState(long ssl);
private native void setVerify(long ssl, int mode, WolfSSLVerifyCallback vc);
private native long setOptions(long ssl, long op);
private native long getOptions(long ssl);
private native int getShutdown(long ssl);
private native void setSSLIORecv(long ssl);
private native void setSSLIOSend(long ssl);
private native int useSNI(long ssl, byte type, byte[] data);
private native byte[] getSNIRequest(long ssl, byte type);
private native int useSessionTicket(long ssl);
private native byte[] getSessionTicket(long ssl);
private native int setSessionTicket(long ssl, byte[] ticket);
private native int gotCloseNotify(long ssl);
private native int sslSetAlpnProtos(long ssl, byte[] alpnProtos);
private native byte[] sslGet0AlpnSelected(long ssl);
private native int useALPN(long ssl, String protocols, int options);
private native int setALPNSelectCb(long ssl);
private native int setTls13SecretCb(long ssl);
private native int setSessionTicketCb(long ssl);
private native void keepArrays(long ssl);
private native byte[] getClientRandom(long ssl);
private native int useSecureRenegotiation(long ssl);
private native int rehandshake(long ssl);
private native int set1SigAlgsList(long ssl, String list);
private native int useSupportedCurve(long ssl, int name);
private native int disableExtendedMasterSecret(long ssl);
private native int hasTicket(long session);
private native int useClientSuites(long ssl);
private native int interruptBlockedIO(long ssl);
private native int getThreadsBlockedInPoll(long ssl);
private native int setMTU(long ssl, int mtu);
private native String stateStringLong(long ssl);
private native int getMaxOutputSize(long ssl);
/* ------------------- session-specific methods --------------------- */
/**
* Loads a certificate file into the SSL session object.
* This file is provided by the <b>file</b> parameter. The <b>format</b>
* paramenter specifies the format type of the file - either
* <b>SSL_FILETYPE_ASN1</b> or <b>SSL_FILETYPE_PEM</b>. Please see the
* wolfSSL examples for proper usage.
*
* @param file a file containing the certificate to be loaded into
* the wolfSSL SSL session object.
* @param format format of the certificates pointed to by <code>file
* </code>. Possible options are <b>SSL_FILETYPE_ASN1</b>,
* for DER-encoded certificates, or <b>SSL_FILETYPE_PEM
* </b> for PEM-encoded certificates.
* @return <code>SSL_SUCCESS</code> upon success,
* <code>SSL_BAD_FILE</code> upon bad input file,
* otherwise <code>SSL_FAILURE</code>. Possible failure
* causes may be that the file is in the wrong format, the
* format argument was given incorrectly, the file
* doesn't exist, can't be read, or is corrupted,
* an out of memory condition occurs, or the Base16
* decoding fails on the file.
* @throws IllegalStateException WolfSSLContext has been freed
* @see WolfSSLContext#useCertificateFile(String, int)
*/
public int useCertificateFile(String file, int format)
throws IllegalStateException {
confirmObjectIsActive();
synchronized (sslLock) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.Component.JNI,
WolfSSLDebug.INFO, this.sslPtr,
() -> "entered useCertificateFile(" + file + ", " +
format + ")");
return useCertificateFile(this.sslPtr, file, format);
}
}
/**
* Loads a private key file into the SSL session object.
* This file is provided by the <b>file</b> parameter. The <b>format</b>
* paramenter specifies the format type of the file - either
* <b>SSL_FILETYPE_ASN1</b> or <b>SSL_FILETYPE_PEM</b>. Please see the
* wolfSSL examples for proper usage.
*
* @param file a file containing the private key to be loaded into
* the wolfSSL SSL session.
* @param format format of the private key pointed to by <code>file
* </code>. Possible options are <b>SSL_FILETYPE_ASN1</b>,
* for a DER-encoded key, or <b>SSL_FILETYPE_PEM
* </b> for a PEM-encoded key.
* @return <code>SSL_SUCCESS</code> upon success,
* <code>SSL_BAD_FILE</code> upon bad input file, otherwise
* <code>SSL_FAILURE</code>. Possible failure causes
* may be that the file is in the wrong format, the
* format argument was given incorrectly, the file
* doesn't exist, can't be read, or is corrupted,
* an out of memory condition occurs, the Base16
* decoding fails on the file, or the key file is
* encrypted but no password is provided.
* @throws IllegalStateException WolfSSLContext has been freed
* @see WolfSSLContext#usePrivateKeyFile(String, int)
*/
public int usePrivateKeyFile(String file, int format)
throws IllegalStateException {
confirmObjectIsActive();
synchronized (sslLock) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.Component.JNI,
WolfSSLDebug.INFO, this.sslPtr,
() -> "entered usePrivateKeyFile(" + file + ", " +
format + ")");
return usePrivateKeyFile(this.sslPtr, file, format);
}
}
/**
* Loads a chain of certificates into the SSL session object.
* The file containing the certificate chain is provided by the <b>file</b>
* parameter and must contain PEM-formatted certificates. This function
* will process up to <code>MAX_CHAIN_DEPTH</code> (default = 9, defined
* in internal.h) certificates, plus the subject cert.
*
* @param file path to the file containing the chain of certificates
* to be loaded into the wolfSSL SSL session. Certificates
* must be in PEM format.
* @return <code>SSL_SUCCESS</code> on success,
* <code>SSL_BAD_FILE</code> upon bad input file, otherwise
* <code>SSL_FAILURE</code>. If the function call fails,
* possible causes might include: the file is in the wrong
* format, the file doesn't exist, can't be read, or is
* corrupted, or an out of memory condition occurs.
* @throws IllegalStateException WolfSSLContext has been freed
* @see WolfSSLContext#useCertificateFile(String, int)
* @see #useCertificateFile(String, int)
*/
public int useCertificateChainFile(String file)
throws IllegalStateException {
confirmObjectIsActive();
synchronized (sslLock) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.Component.JNI,
WolfSSLDebug.INFO, this.sslPtr,
() -> "entered useCertificateChainFile(" + file + ")");
return useCertificateChainFile(this.sslPtr, file);
}
}
/**
* Assigns a Socket file descriptor as the input/output facility for the
* SSL connection.
*
* @param sd Socket to be used as input/output facility.
* @return <code>SSL_SUCCESS</code> on success, otherwise
* <code>SSL_FAILURE</code>.
* @throws IllegalStateException WolfSSLContext has been freed
* @see #getFd()
*/
public int setFd(Socket sd) throws IllegalStateException {
int ret;
confirmObjectIsActive();
synchronized (sslLock) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.Component.JNI,
WolfSSLDebug.INFO, this.sslPtr,
() -> "entered setFd(" + sd + ")");
ret = setFd(this.sslPtr, sd, 1);
if (ret == WolfSSL.SSL_SUCCESS) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.Component.JNI,
WolfSSLDebug.INFO, this.sslPtr,
() -> "native fd set to: " + getFd(this.sslPtr));
}
return ret;
}
}
/**
* Assigns a DatagramSocket file descriptor as the input/output facility
* for the SSL connection.
* This can be used when using DatagramSocket objects with DTLS.
*
* @param sd Socket to be used as input/output facility.
* @return <code>SSL_SUCCESS</code> on success, otherwise
* <code>SSL_FAILURE</code>.
* @throws IllegalStateException WolfSSLContext has been freed
* @see #getFd()
*/
public int setFd(DatagramSocket sd) throws IllegalStateException {
confirmObjectIsActive();
synchronized (sslLock) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.Component.JNI,
WolfSSLDebug.INFO, this.sslPtr,
() -> "entered setFd(" + sd + ")");
return setFd(this.sslPtr, sd, 2);
}
}
/**
* Informs wolfSSL session that the underlying I/O is non-blocking.
* After an application creates a SSL session (native WOLFSSL object),
* if it will be used with a non-blocking socket, this method should
* be called. This lets the SSL session know that receiving EWOULDBLOCK
* means that the recvfrom call would block rather than that it timed out.
*
* @param nonblock value used to set non-blocking flag on the SSL
* session. Use <b>1</b> to specify non-blocking,
* otherwise <b>0</b>.
* @throws IllegalStateException WolfSSLContext has been freed
* @throws WolfSSLJNIException Internal JNI error
* @see #getUsingNonblock()
* @see #dtlsGotTimeout()
* @see #dtlsGetCurrentTimeout()
*/
public void setUsingNonblock(int nonblock)
throws IllegalStateException, WolfSSLJNIException {
confirmObjectIsActive();
synchronized (sslLock) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.Component.JNI,
WolfSSLDebug.INFO, this.sslPtr,
() -> "entered setUsingNonblock(" + nonblock + ")");
setUsingNonblock(this.sslPtr, nonblock);
}
}
/**
* Allows the application to determine if wolfSSL is using non-blocking
* I/O.
* After an application created an SSL session object, if it will be used
* with a non-blocking socket, call <code>setUsingNonblock()</code> on it.
* This lets the SSL session object know that receiving EWOULDBLOCK means
* that the recvfrom call would block rather than that it timed out.
*
* @return <b>1</b> if the underlying I/O is non-blocking, otherwise
* <b>0</b> if blocking.
* @throws IllegalStateException WolfSSLContext has been freed
* @throws WolfSSLJNIException Internal JNI error
* @see #setUsingNonblock(int)
* @see #setSession(long)
*/
public int getUsingNonblock()
throws IllegalStateException, WolfSSLJNIException {
confirmObjectIsActive();
synchronized (sslLock) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.Component.JNI,
WolfSSLDebug.INFO, this.sslPtr,
() -> "entered getUsingNonblock()");
return getUsingNonblock(this.sslPtr);
}
}
/**
* Returns the file descriptor used as the input/output facility for the
* SSL connection.
* Typically this will be a socket file descriptor.
*
* @return SSL session file descriptor
* @throws IllegalStateException WolfSSLContext has been freed
* @throws WolfSSLJNIException Internal JNI error
* @see #setFd(Socket)
*/
public int getFd()
throws IllegalStateException, WolfSSLJNIException {
final int fd;
confirmObjectIsActive();
synchronized (sslLock) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.Component.JNI,
WolfSSLDebug.INFO, this.sslPtr, () -> "entered getFd()");
fd = getFd(this.sslPtr);
WolfSSLDebug.log(getClass(), WolfSSLDebug.Component.JNI,
WolfSSLDebug.INFO, this.sslPtr, () -> "returning fd: " + fd);
}
return fd;
}
/**
* Helper method to throw appropriate exception based on native
* result of poll()/select() from API that does I/O.
*/
private static void throwExceptionFromIOReturnValue(
int ret, String nativeFunc)
throws SocketTimeoutException, SocketException {
if (ret == WolfSSL.WOLFJNI_IO_EVENT_TIMEOUT) {
throw new SocketTimeoutException(
"Native socket timed out during " + nativeFunc);
}
else if (ret == WolfSSL.WOLFJNI_IO_EVENT_FD_CLOSED) {
throw new SocketException("Socket fd closed during poll(), " +
"errno = " + WolfSSL.getErrno());
}
else if (ret == WolfSSL.WOLFJNI_IO_EVENT_ERROR) {
throw new SocketException("Socket fd poll() exceptional error, " +
"errno = " + WolfSSL.getErrno());
}
else if (ret == WolfSSL.WOLFJNI_IO_EVENT_POLLHUP) {
throw new SocketException("Socket disconnected during poll(), " +
"errno = " + WolfSSL.getErrno());
}
else if (ret == WolfSSL.WOLFJNI_IO_EVENT_FAIL) {
throw new SocketException("Socket select/poll() failed, " +
"errno = " + WolfSSL.getErrno());
}
}
/**
* Initializes an SSL/TLS handshake with a server.
* This function is called on the client side. When called, the underlying
* communication channel should already be set up.
* <p>
* <code>connect()</code> works with both blocking and non-blocking I/O.