-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathWolfSSLEngineHelper.java
More file actions
1989 lines (1742 loc) · 74.1 KB
/
WolfSSLEngineHelper.java
File metadata and controls
1989 lines (1742 loc) · 74.1 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
/* WolfSSLEngineHelper.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 java.util.Arrays;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SNIMatcher;
import javax.net.ssl.SNIServerName;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLException;
import javax.net.ssl.X509TrustManager;
import javax.net.ssl.X509KeyManager;
import javax.net.ssl.X509ExtendedKeyManager;
import javax.net.ssl.SSLHandshakeException;
import java.security.Security;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.security.cert.CertificateEncodingException;
import com.wolfssl.WolfSSL;
import com.wolfssl.WolfSSLDebug;
import com.wolfssl.WolfSSLSession;
import com.wolfssl.WolfSSLException;
import com.wolfssl.WolfSSLJNIException;
import com.wolfssl.WolfSSLPskClientCallback;
import com.wolfssl.WolfSSLPskServerCallback;
import java.nio.charset.StandardCharsets;
/**
* This is a helper class to account for similar methods between SSLSocket
* and SSLEngine.
*
* This class wraps a new WOLFSSL object that is created (inside
* WolfSSLSession). All methods are protected or private because this class
* should only be used internally to wolfJSSE.
*
* @author wolfSSL
*/
public class WolfSSLEngineHelper {
/* Cache system and security properties to reduce thread contention */
private boolean jsseEnableSniExtension;
private boolean jdkTlsTrustNameService;
private boolean wolfjsseAutoSni;
private volatile WolfSSLSession ssl = null;
private WolfSSLImplementSSLSession session = null;
private WolfSSLParameters params = null;
/* Peer hostname, used for session cache lookup (combined with port),
* and SNI as secondary if user has not set via SSLParameters */
private String hostname = null;
/* Peer port, used for session cache lookup (combined with hostname) */
private int port;
/* Peer InetAddress, may be set when creating SSLSocket, otherwise
* will be null if String host constructor was used instead.
* If hostname above is null, and user has not set SSLParameters,
* if 'jdk.tls.trustNameService' property has been set will try to set
* SNI based on this using peerAddr.getHostName() */
private InetAddress peerAddr = null;
/* Reference to WolfSSLAuthStore, comes from WolfSSLContext */
private WolfSSLAuthStore authStore = null;
/* Is this client side (true) or server (false) */
private boolean clientMode;
/* Is session creation allowed for this object */
private boolean sessionCreation = true;
/* Has setUseClientMode() been called on this object */
private boolean modeSet = false;
/* wolfSSL verification mode, set inside setLocalAuth() */
private int verifyMask = WolfSSL.SSL_VERIFY_PEER;
/* Internal Java verify callback, used when user/app is not using
* com.wolfssl.provider.jsse.WolfSSLTrustX509 and instead using their
* own TrustManager to perform verification via checkClientTrusted()
* and/or checkServerTrusted().
*
* This object is stored at the native level as a global reference
* created in Java_com_wolfssl_WolfSSLSession_setVerify()
* of com_wolfssl_WolfSSLSession.c and deleted in native
* Java_com_wolfssl_WolfSSLSession_freeSSL(). Deleting the native
* global reference allows the Java object to be garbage collected. */
private WolfSSLInternalVerifyCb wicb = null;
/**
* Private helper method to get System and Security properties.
* Called once up front by constructor.
*/
private void getSystemAndSecurityProperties() {
this.jsseEnableSniExtension =
checkBooleanProperty("jsse.enableSNIExtension", true);
this.jdkTlsTrustNameService =
checkBooleanProperty("jdk.tls.trustNameService", false);
this.wolfjsseAutoSni =
checkBooleanProperty("wolfjsse.autoSNI", false);
}
/**
* Always creates a new session
* @param ssl WOLFSSL session
* @param store main auth store holding session tables and managers
* @param params default parameters to use on connection
* @throws WolfSSLException if an exception happens during session creation
*/
protected WolfSSLEngineHelper(WolfSSLSession ssl, WolfSSLAuthStore store,
WolfSSLParameters params) throws WolfSSLException {
if (params == null || ssl == null || store == null) {
throw new WolfSSLException("Bad argument");
}
getSystemAndSecurityProperties();
this.ssl = ssl;
this.params = params;
this.authStore = store;
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "created new WolfSSLEngineHelper()");
}
/**
* Allows for new session and resume session by default
* @param ssl WOLFSSL session
* @param store main auth store holding session tables and managers
* @param params default parameters to use on connection
* @param port port number as hint for resume
* @param hostname hostname as hint for resume and for default SNI
* @throws WolfSSLException if an exception happens during session resume
*/
protected WolfSSLEngineHelper(WolfSSLSession ssl, WolfSSLAuthStore store,
WolfSSLParameters params, int port, String hostname)
throws WolfSSLException {
/* SSLEngine(host, -1) is a valid JSSE/Netty unknown-port hint. */
if (params == null || ssl == null || store == null || port < -1) {
throw new WolfSSLException("Bad argument");
}
getSystemAndSecurityProperties();
this.ssl = ssl;
this.params = params;
this.port = port;
this.hostname = hostname;
this.authStore = store;
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "created new WolfSSLEngineHelper(peer port: " + port +
", peer hostname: " + hostname + ")");
}
/**
* Allows for new session and resume session by default
* @param ssl WOLFSSL session
* @param store main auth store holding session tables and managers
* @param params default parameters to use on connection
* @param port port number as hint for resume
* @param peerAddr InetAddress of peer, used for session resumption and
* SNI if system property is set
* @throws WolfSSLException if an exception happens during session resume
*/
protected WolfSSLEngineHelper(WolfSSLSession ssl, WolfSSLAuthStore store,
WolfSSLParameters params, int port, InetAddress peerAddr)
throws WolfSSLException {
if (params == null || ssl == null || store == null ||
peerAddr == null || port < -1) {
throw new WolfSSLException("Bad argument");
}
getSystemAndSecurityProperties();
this.ssl = ssl;
this.params = params;
this.port = port;
this.peerAddr = peerAddr;
this.authStore = store;
this.session = new WolfSSLImplementSSLSession(store);
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "created new WolfSSLEngineHelper(peer port: " + port +
", peer IP: " + peerAddr.getHostAddress() + ")");
}
/**
* Get the alias from the X509KeyManager to use for finding and loading
* the private key and certificate chain for this endpoint.
*
* @param km X509KeyManager or X509ExtendedKeyManager to poll for
* client/server alias name
* @param socket Socket or SSLSocket from which this peer is being
* created, may be null if engine is being used instead
* @param engine SSLEngine from which this peer is being created, may be
* null if socket is being used instead
*
* @return alias String, or null if none found
*/
private String GetKeyAndCertChainAlias(X509KeyManager km, Socket sock,
SSLEngine engine) {
String alias = null;
String javaVersion = System.getProperty("java.version");
if (sock == null && engine == null) {
return null;
}
/* If javaVersion is null, set to empty string */
if (javaVersion == null) {
javaVersion = "";
}
/* We only load keys from algorithms enabled in native wolfSSL,
* and in the priority order of ECC first, then RSA. JDK 1.7.0_201
* and 1.7.0_171 have a bug that causes PrivateKey.getEncoded() to
* fail for EC keys. This has been fixed in later JDK versions,
* but skip adding EC here if we're running on those versions . */
ArrayList<String> keyAlgos = new ArrayList<String>();
if (WolfSSL.EccEnabled() &&
(!javaVersion.equals("1.7.0_201") &&
!javaVersion.equals("1.7.0_171"))) {
keyAlgos.add("EC");
}
if (WolfSSL.RsaEnabled()) {
keyAlgos.add("RSA");
if (WolfSSL.RsaPssEnabled()) {
keyAlgos.add("RSASSA-PSS");
}
}
String[] keyTypes = new String[keyAlgos.size()];
keyTypes = keyAlgos.toArray(keyTypes);
if (clientMode) {
if (sock != null) {
alias = km.chooseClientAlias(keyTypes, null, sock);
}
else if (engine != null) {
if (km instanceof X509ExtendedKeyManager) {
alias = ((X509ExtendedKeyManager)km).
chooseEngineClientAlias(keyTypes, null, engine);
}
else {
alias = km.chooseClientAlias(keyTypes, null, null);
}
}
}
else {
if (engine instanceof WolfSSLEngine) {
((WolfSSLEngine)engine).cacheRequestedServerNamesFromNetData();
}
/* Loop through available key types until we find an alias
* that works, or none that do and return null */
for (String type : keyTypes) {
if (sock != null) {
alias = km.chooseServerAlias(type, null, sock);
}
else if (engine != null) {
if (km instanceof X509ExtendedKeyManager) {
alias = ((X509ExtendedKeyManager)km).
chooseEngineServerAlias(type, null, engine);
}
else {
alias = km.chooseServerAlias(type, null, null);
}
}
if (alias != null) {
break;
}
}
}
return alias;
}
/**
* Loads the private key and certificate chain for this
* SSLSocket/SSLEngine to be used for performing authentication of
* this peer during the handshake.
*
* If there is no X509KeyManager in our WolfSSLAuthStore, skips loading
* private key and certificate. This means SSLContext.init() was
* initialized with a null KeyManager.
*
* @param sock Socket or SSLSocket associated with this connection, may
* be null if engine is used instead
* @param engine SSLEngine associated with this connection, may be null
* if sock used instead
*
* @throws WolfSSLException if private key is not correct format,
* WolfSSLAuthStore is null, or native error when loading
* private key or certificate.
* @throws CertificateEncodingException on error getting Certificate
* encoding before loading into native WOLFSSL
* @throws IOException on error concatenating certificate chain into
* single byte array
*/
protected synchronized void loadKeyAndCertChain(
Socket sock, SSLEngine engine)
throws WolfSSLException, CertificateEncodingException, IOException {
int ret;
int offset;
final String alias; /* KeyStore alias holding private key */
X509KeyManager km = null; /* X509KeyManager from KeyStore */
if (this.authStore == null) {
throw new WolfSSLException("WolfSSLAuthStore is null");
}
km = this.authStore.getX509KeyManager();
if (km == null) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.ERROR,
() -> "internal KeyManager is null, no cert/key to load");
return;
}
/* Ask X509KeyManager to choose correct client alias from which
* to load private key / cert chain */
alias = GetKeyAndCertChainAlias(km, sock, engine);
authStore.setCertAlias(alias);
/* Load private key into WOLFSSL session */
PrivateKey privKey = km.getPrivateKey(alias);
if (privKey != null) {
byte[] privKeyEncoded = privKey.getEncoded();
byte[] privKeyTraditional = null;
try {
if (!privKey.getFormat().equals("PKCS#8")) {
throw new WolfSSLException(
"Private key is not in PKCS#8 format");
}
/* Skip past PKCS#8 offset */
offset = WolfSSL.getPkcs8TraditionalOffset(privKeyEncoded, 0,
privKeyEncoded.length);
privKeyTraditional = Arrays.copyOfRange(privKeyEncoded,
offset, privKeyEncoded.length);
try {
ret = this.ssl.usePrivateKeyBuffer(privKeyTraditional,
privKeyTraditional.length, WolfSSL.SSL_FILETYPE_ASN1);
} catch (WolfSSLJNIException e) {
throw new WolfSSLException(e);
}
if (ret != WolfSSL.SSL_SUCCESS) {
throw new WolfSSLException("Failed to load private key " +
"buffer into WOLFSSL, err = " + ret);
}
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "loaded private key from X509KeyManager (alias: " +
alias + ")");
} finally {
if (privKeyEncoded != null) {
Arrays.fill(privKeyEncoded, (byte)0);
}
if (privKeyTraditional != null) {
Arrays.fill(privKeyTraditional, (byte)0);
}
}
} else {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "no private key found in X509KeyManager " +
"(alias: " + alias + "), skipped loading");
}
/* Load certificate chain */
X509Certificate[] cert = km.getCertificateChain(alias);
if (cert != null) {
ByteArrayOutputStream certStream = new ByteArrayOutputStream();
int chainLength = 0;
for (int i = 0; i < cert.length; i++) {
/* concatenate certs into single byte array */
certStream.write(cert[i].getEncoded());
chainLength++;
}
byte[] certChain = certStream.toByteArray();
certStream.close();
try {
ret = this.ssl.useCertificateChainBufferFormat(certChain,
certChain.length, WolfSSL.SSL_FILETYPE_ASN1);
} catch (WolfSSLJNIException e) {
throw new WolfSSLException(e);
}
if (ret != WolfSSL.SSL_SUCCESS) {
throw new WolfSSLException("Failed to load certificate " +
"chain buffer into WOLFSSL, err = " + ret);
}
final int tmpChainLength = chainLength;
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "loaded certificate chain from KeyManager (alias: " +
alias + ", length: " +
tmpChainLength + ")");
} else {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "no certificate or chain found " +
"(alias: " + alias + "), skipped loading");
}
}
/**
* Set hostname and port
* Used internally by SSLSocket.connect(SocketAddress)
*
* @param hostname peer hostname String
* @param port peer port number
*/
protected synchronized void setHostAndPort(String hostname, int port) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "entered setHostAndPort()");
this.hostname = hostname;
this.port = port;
}
/**
* Set peer InetAddress.
* Used by SSLSocket.connect() when InetAddress is passed in from user.
*
* @param peerAddr InetAddress of peer
*/
protected synchronized void setPeerAddress(InetAddress peerAddr) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "entered setPeerAddress()");
this.peerAddr = peerAddr;
}
/**
* Get the com.wolfssl.WolfSSLSession for this object
*
* @return com.wolfssl.WolfSSLSession for this object
*/
protected synchronized WolfSSLSession getWolfSSLSession() {
return ssl;
}
/**
* Get WolfSSLImplementSession for this object
*
* @return WolfSSLImplementSession for this object
*/
protected synchronized WolfSSLImplementSSLSession getSession() {
if (this.session == null) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "this.session is null, creating new " +
"WolfSSLImplementSSLSession");
this.session = new WolfSSLImplementSSLSession(authStore);
}
return this.session;
}
/**
* Get the last exception from TrustManager certificate verification.
* Delegates to the internal verify callback if available.
*
* @return Exception from last failed verification, or null
*/
protected synchronized Exception getLastVerifyException() {
if (this.wicb != null) {
return this.wicb.getVerifyException();
}
return null;
}
/**
* Get all supported cipher suites in native wolfSSL library, which
* are also allowed by "wolfjsse.enabledCipherSuites" system Security
* property, if set. Does not auto-filter out anon suites, since this
* returns all supported suites in native wolfSSL.
*
* @return String array of all supported cipher suites
*/
protected static synchronized String[] getAllCiphers() {
return WolfSSLUtil.sanitizeSuites(WolfSSL.getCiphersIana(), false);
}
/**
* Get all enabled cipher suites, filtered by
* wolfjsse.enabledCipherSuites system Security property (if set). Does
* not auto-filter out anon suites, since this returns all enabled suites in
* native wolfSSL.
*
* @return String array of all enabled cipher suites
*/
protected synchronized String[] getCiphers() {
return WolfSSLUtil.sanitizeSuites(this.params.getCipherSuites(), false);
}
/**
* Set cipher suites enabled in WolfSSLParameters.
*
* Validates input array against supported cipher suites but does
* not filter anonymous suites, allowing applications to explicitly
* enable them if needed.
*
* @param suites String array of cipher suites to be enabled
*
* @throws IllegalArgumentException if input array contains invalid
* cipher suites, input array is null, or input array has length
* zero
*/
protected synchronized void setCiphers(String[] suites)
throws IllegalArgumentException {
if (suites == null) {
throw new IllegalArgumentException("input array is null");
}
if (suites.length == 0) {
throw new IllegalArgumentException("input array has length zero");
}
/* sanitize cipher array for unsupported strings */
List<String> supported = Arrays.asList(getAllCiphers());
for (int i = 0; i < suites.length; i++) {
if (!supported.contains(suites[i])) {
throw new IllegalArgumentException("Unsupported CipherSuite: " +
suites[i] + "(Supported: " +
Arrays.toString(getAllCiphers()) + ")");
}
}
this.params.setCipherSuites(WolfSSLUtil.sanitizeSuites(suites, false));
if (this.ssl != null && !this.ssl.handshakeDone()) {
String[] protocols = WolfSSLUtil.sanitizeProtocols(
this.params.getProtocols(), WolfSSL.TLS_VERSION.INVALID);
if (protocols != null && protocols.length > 0) {
applyConfiguredCipherProtocolSettingsFromSetter();
}
}
}
/**
* Set protocols enabled in WolfSSLParameters
*
* Sanitizes protocol array for invalid protocols
*
* @param p String array of SSL/TLS protocols to be enabled
*
* @throws IllegalArgumentException if input array is null or
* contains invalid/unsupported protocols
*/
protected synchronized void setProtocols(String[] p)
throws IllegalArgumentException {
if (p == null) {
throw new IllegalArgumentException("input array is null");
}
if (p.length == 0) {
/* Empty array is valid, store empty set */
this.params.setProtocols(new String[0]);
return;
}
/* sanitize protocol array for unsupported strings */
List<String> supported = Arrays.asList(getAllProtocols());
for (int i = 0; i < p.length; i++) {
if (!supported.contains(p[i])) {
throw new IllegalArgumentException("Unsupported protocol: " +
p[i]);
}
}
this.params.setProtocols(
WolfSSLUtil.sanitizeProtocols(p, WolfSSL.TLS_VERSION.INVALID));
if (this.ssl != null && !this.ssl.handshakeDone()) {
String[] protocols = WolfSSLUtil.sanitizeProtocols(
this.params.getProtocols(), WolfSSL.TLS_VERSION.INVALID);
if (protocols != null && protocols.length > 0) {
applyConfiguredCipherProtocolSettingsFromSetter();
}
}
}
/**
* Get enabled SSL/TLS protocols from WolfSSLParameters
*
* @return String array of enabled SSL/TLS protocols
*/
protected synchronized String[] getProtocols() {
return WolfSSLUtil.sanitizeProtocols(
this.params.getProtocols(), WolfSSL.TLS_VERSION.INVALID);
}
/**
* Get all supported SSL/TLS protocols in native wolfSSL library,
* which are also allowed by 'jdk.tls.client.protocols' or
* 'jdk.tls.server.protocols' if set.
*
* @return String array of supported protocols
*/
protected static synchronized String[] getAllProtocols() {
return WolfSSLUtil.sanitizeProtocols(
WolfSSL.getProtocols(), WolfSSL.TLS_VERSION.INVALID);
}
/**
* Set client mode for associated WOLFSSL session
*
* @param mode client mode (true/false)
*
* @throws IllegalArgumentException if called after SSL/TLS handshake
* has been completed. Only allowed before.
*/
protected synchronized void setUseClientMode(boolean mode)
throws IllegalArgumentException {
if (this.ssl.handshakeDone()) {
throw new IllegalArgumentException("setUseClientMode() not " +
"allowed after handshake is completed");
}
this.clientMode = mode;
if (this.clientMode) {
this.ssl.setConnectState();
}
else {
this.ssl.setAcceptState();
}
this.modeSet = true;
}
/**
* Get clientMode for associated session
*
* @return boolean value of clientMode set for this session
*/
protected synchronized boolean getUseClientMode() {
return this.clientMode;
}
/**
* Set if session needs client authentication
*
* @param need boolean if session needs client authentication
*/
protected synchronized void setNeedClientAuth(boolean need) {
this.params.setNeedClientAuth(need);
}
/**
* Get value of needClientAuth for this session
*
* @return boolean value for needClientAuth
*/
protected synchronized boolean getNeedClientAuth() {
return this.params.getNeedClientAuth();
}
/**
* Set value of wantClientAuth for this session
*
* @param want boolean value of wantClientAuth for this session
*/
protected synchronized void setWantClientAuth(boolean want) {
this.params.setWantClientAuth(want);
}
/**
* Get value of wantClientAuth for this session
*
* @return boolean value for wantClientAuth
*/
protected synchronized boolean getWantClientAuth() {
return this.params.getWantClientAuth();
}
/**
* Set ability to create sessions
*
* @param flag boolean to set enable session creation
*/
protected synchronized void setEnableSessionCreation(boolean flag) {
this.sessionCreation = flag;
}
/**
* Get boolean if session creation is allowed
*
* @return boolean value for enableSessionCreation
*/
protected synchronized boolean getEnableSessionCreation() {
return this.sessionCreation;
}
/**
* Enable use of session tickets
*
* @param flag boolean to enable/disable session tickets
*/
protected synchronized void setUseSessionTickets(boolean flag) {
this.params.setUseSessionTickets(flag);
}
/**
* Set ALPN protocols
*
* @param alpnProtos encoded byte array of ALPN protocols
*/
protected synchronized void setAlpnProtocols(byte[] alpnProtos) {
this.params.setAlpnProtocols(alpnProtos);
}
/**
* Get selected ALPN protocol
*
* Used by some versions of Android, non-standard ALPN API.
*
* @return encoded byte array for selected ALPN protocol or null if
* handshake has not finished
*/
protected synchronized byte[] getAlpnSelectedProtocol() {
if (this.ssl.handshakeDone()) {
return ssl.getAlpnSelected();
}
return null;
}
/**
* Get selected ALPN protocol string
*
* @return String representation of selected ALPN protocol, null
* if protocol is not available yet, or empty String if
* ALPN will not be used for this connection.
*/
protected synchronized String getAlpnSelectedProtocolString() {
String proto = ssl.getAlpnSelectedString();
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "selected ALPN protocol = " + proto);
if (proto == null && this.ssl.handshakeDone()) {
/* ALPN not used if proto is null and handshake is done */
return "";
}
return proto;
}
/********** Calls to transfer over parameter to wolfSSL before connection */
/*transfer over cipher suites right before establishing a connection */
private void setLocalCiphers(String[] suites)
throws IllegalArgumentException {
try {
String list;
StringBuilder sb = new StringBuilder();
if (suites == null || suites.length == 0) {
/* use default cipher suites */
return;
}
for (String s : suites) {
sb.append(s);
sb.append(":");
}
if (sb.length() > 0) {
/* remove last : */
sb.deleteCharAt(sb.length() - 1);
list = sb.toString();
if (this.ssl.setCipherList(list) != WolfSSL.SSL_SUCCESS) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "error setting cipher list " + list);
}
}
if (this.ssl.getSide() == WolfSSL.WOLFSSL_SERVER_END &&
!this.params.getUseCipherSuitesOrder()) {
this.ssl.useClientSuites();
}
} catch (IllegalStateException e) {
throw new IllegalArgumentException(e);
}
}
/* sets the protocol to use with WOLFSSL connections */
private void setLocalProtocol(String[] p)
throws SSLException {
int i;
long mask = 0;
boolean[] set = new boolean[5];
Arrays.fill(set, false);
if (p == null) {
/* if null then just use wolfSSL default */
return;
}
if (p.length == 0) {
throw new SSLException("No protocols enabled or available");
}
for (i = 0; i < p.length; i++) {
/* TLS 1.3 needs to be enabled for DTLS 1.3 */
if (p[i].equals("TLSv1.3") || p[i].equals("DTLSv1.3")) {
set[0] = true;
}
/* TLS 1.2 needs to be enabled for DTLS 1.2 */
if (p[i].equals("TLSv1.2") || p[i].equals("DTLSv1.2")) {
set[1] = true;
}
if (p[i].equals("TLSv1.1")) {
set[2] = true;
}
if (p[i].equals("TLSv1")) {
set[3] = true;
}
if (p[i].equals("SSLv3")) {
set[4] = true;
}
}
/* Note: No SSL_OP_NO_* for DTLS in native wolfSSL */
if (set[0] == false) {
mask |= WolfSSL.SSL_OP_NO_TLSv1_3;
}
if (set[1] == false) {
mask |= WolfSSL.SSL_OP_NO_TLSv1_2;
}
if (set[2] == false) {
mask |= WolfSSL.SSL_OP_NO_TLSv1_1;
}
if (set[3] == false) {
mask |= WolfSSL.SSL_OP_NO_TLSv1;
}
if (set[4] == false) {
mask |= WolfSSL.SSL_OP_NO_SSLv3;
}
this.ssl.setOptions(mask);
}
private boolean isTls13CipherSuite(String suite) {
if (suite == null) {
return false;
}
return suite.startsWith("TLS_AES_") ||
suite.startsWith("TLS_CHACHA20_") || suite.startsWith("TLS_SM4_");
}
private String[] getEffectiveProtocolsForCiphers(String[] protocols,
String[] suites) {
boolean hasTls13Proto = false;
boolean hasLegacyProto = false;
boolean hasTls13Suite = false;
boolean hasLegacySuite = false;
ArrayList<String> filtered;
if (protocols == null || suites == null || suites.length == 0) {
return protocols;
}
for (String proto : protocols) {
if ("TLSv1.3".equals(proto) || "DTLSv1.3".equals(proto)) {
hasTls13Proto = true;
}
else if ("TLSv1.2".equals(proto) || "DTLSv1.2".equals(proto) ||
"TLSv1.1".equals(proto) || "TLSv1".equals(proto) ||
"SSLv3".equals(proto)) {
hasLegacyProto = true;
}
}
if (!hasTls13Proto) {
return protocols;
}
for (String suite : suites) {
if (isTls13CipherSuite(suite)) {
hasTls13Suite = true;
}
else {
hasLegacySuite = true;
}
}
if (!hasTls13Suite) {
filtered = new ArrayList<String>();
for (String proto : protocols) {
if (!"TLSv1.3".equals(proto) && !"DTLSv1.3".equals(proto)) {
filtered.add(proto);
}
}
if (filtered.isEmpty()) {
return protocols;
}
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "disabling TLSv1.3 since no TLSv1.3 cipher suites " +
"are enabled");
return filtered.toArray(new String[filtered.size()]);
}
if (!hasLegacySuite && hasLegacyProto) {
filtered = new ArrayList<String>();
for (String proto : protocols) {
if ("TLSv1.3".equals(proto) || "DTLSv1.3".equals(proto)) {
filtered.add(proto);
}
}
if (filtered.isEmpty()) {
return protocols;
}
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "disabling pre-TLSv1.3 protocols since only TLSv1.3 " +
"cipher suites are enabled");
return filtered.toArray(new String[filtered.size()]);
}
return protocols;
}
private void applyConfiguredCipherProtocolSettings() throws SSLException {
String[] suites;
String[] protocols;
suites = WolfSSLUtil.sanitizeSuites(
this.params.getCipherSuites(), false);
protocols = WolfSSLUtil.sanitizeProtocols(
this.params.getProtocols(), WolfSSL.TLS_VERSION.INVALID);
protocols = getEffectiveProtocolsForCiphers(protocols, suites);
this.setLocalCiphers(suites);
this.setLocalProtocol(protocols);
}
private void applyConfiguredCipherProtocolSettingsFromSetter()
throws IllegalArgumentException {
try {
applyConfiguredCipherProtocolSettings();
} catch (SSLException e) {
throw new IllegalArgumentException(e);
}
}
/* sets client auth on or off if needed / wanted */
private void setLocalAuth(SSLSocket socket, SSLEngine engine) {
int mask = WolfSSL.SSL_VERIFY_NONE;