-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathWolfSSLTrustX509.java
More file actions
1349 lines (1176 loc) · 53.7 KB
/
WolfSSLTrustX509.java
File metadata and controls
1349 lines (1176 loc) · 53.7 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
/* WolfSSLTrustX509.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 java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Enumeration;
import java.net.Socket;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSession;
import javax.net.ssl.ExtendedSSLSession;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SNIServerName;
import javax.net.ssl.SNIHostName;
import javax.net.ssl.StandardConstants;
import javax.net.ssl.X509ExtendedTrustManager;
import javax.security.auth.x500.X500Principal;
import com.wolfssl.WolfSSLDebug;
import com.wolfssl.WolfSSLCertificate;
import com.wolfssl.WolfSSLCertManager;
import com.wolfssl.WolfSSLException;
import java.security.cert.Certificate;
/**
* wolfSSL implementation of X509TrustManager, extends
* X509ExtendedTrustManager for additional hostname verification for
* HTTPS (RFC 2818) and LDAPS (RFC 2830).
*
* @author wolfSSL
*/
public final class WolfSSLTrustX509 extends X509ExtendedTrustManager {
private KeyStore store = null;
/** X509ExtendedTrustManager hostname type HTTPS */
private static int HOSTNAME_TYPE_HTTPS = 1;
/** X509ExtendedTrustManager hostname type LDAPS */
private static int HOSTNAME_TYPE_LDAPS = 2;
/**
* Create new WolfSSLTrustX509 object
*
* @param in KeyStore to use with this X509TrustManager
*/
public WolfSSLTrustX509(KeyStore in) {
this.store = in;
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "created new WolfSSLTrustX509");
}
/**
* Sort provided certificate chain by subject and issuer.
*
* Begin with leaf cert, end with last most intermediate cert. Current
* routine assumes that peer cert will be first in the provided certs
* array, and will use that as a base/starting point to sort intermediate
* certs going up the chain.
*
* @param certs Peer certificate chain, assuming leaf/peer is first
*
* @return List of X509Certifiates representing peer cert chain, sorted
* from leaf to last intermediate. Not including root CA.
* @throws CertificateException if error occurs while building chain.
*/
private X509Certificate[] sortCertChainBySubjectIssuer(
X509Certificate[] certs) throws CertificateException {
int i, curr, next;
int leafIdx = -1;
boolean nextFound = false;
final X509Certificate[] chain;
X509Certificate[] retChain = null;
if (certs == null) {
throw new CertificateException("Input cert chain null");
}
/* If certs array is only one cert (peer), just return copy of it */
if (certs.length == 1) {
return certs.clone();
}
/* Make copy of peer cert chain, so we don't change original */
chain = certs.clone();
/* Print out chain for debugging */
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "sorting peer chain (" + chain.length + " certs):");
for (i = 0; i < chain.length; i++) {
final int tmpI = i;
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "\t[" + tmpI + "]: subject: " +
chain[tmpI].getSubjectX500Principal().getName());
}
/* Find the leaf certificate using BasicConstraints extension.
* Per RFC 5280, leaf/end-entity certs have getBasicConstraints()
* return -1, while CA certs return >= 0. */
for (i = 0; i < chain.length; i++) {
if (chain[i].getBasicConstraints() == -1) {
leafIdx = i;
final int tmpLeaf = i;
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Identified leaf cert at index " + tmpLeaf +
" (BasicConstraints CA=false)");
break;
}
}
/* If we couldn't identify leaf cert by BasicConstraints, default
* to treat the first cert as peer */
if (leafIdx == -1) {
final int tmpLeaf = 0;
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Could not identify leaf cert by BasicConstraints, " +
"assuming index " + tmpLeaf);
leafIdx = 0;
}
/* Move leaf cert to position 0 if not already there */
if (leafIdx != 0) {
X509Certificate tmp = chain[0];
chain[0] = chain[leafIdx];
chain[leafIdx] = tmp;
}
/* Now build chain from leaf to root */
for (curr = 0; curr < chain.length; curr++) {
nextFound = false;
for (next = curr + 1; next < chain.length; next++) {
/* check if next subject matches curr issuer */
if (chain[curr].getIssuerX500Principal().equals(
chain[next].getSubjectX500Principal())) {
/* if next not directly after curr, swap */
if (next != curr + 1) {
X509Certificate tmp = chain[next];
chain[next] = chain[curr + 1];
chain[curr + 1] = tmp;
}
nextFound = true;
break;
}
}
/* if next not found, stop building chain */
if (nextFound == false) {
break;
}
}
/* Print out sorted peer chain for debugging */
final int tmpCurr = curr;
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "sorted peer chain (" + (tmpCurr + 1) + " certs):");
for (i = 0; i <= curr; i++) {
final int tmpI = i;
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "\t[" + tmpI + "]: subject: " +
chain[tmpI].getSubjectX500Principal().getName());
}
/* If chain is now shorter, return adjusted size array */
if (chain.length > (curr + 1)) {
retChain = Arrays.copyOf(chain, curr + 1);
} else {
retChain = chain;
}
return retChain;
}
/**
* Finds and returns X509Certificate matching the root CA that will
* verify the given leaf/intermediate certificate.
*
* This will search through the provided KeyStore for the approproate
* root CA that correctly verifies the given certificate.
*
* @param cert Certificate for which to find verifying root CA
* @param ks KeyStore to search in for root CA
*
* @return X509Certificate representing root CA which will verify cert
* @throws CertificateException on error/failure getting root CA.
*/
private X509Certificate findRootCAFromKeyStoreForCert(X509Certificate cert,
KeyStore ks) throws CertificateException {
int i = 0;
int ret;
int verifiedRootIdx = -1;
WolfSSLCertManager cm = null;
List<X509Certificate> possibleCerts = new ArrayList<X509Certificate>();
byte[] encodedRoot = null;
byte[] encodedCert = null;
boolean rootFound = false;
if (cert == null || ks == null) {
throw new CertificateException("Certificate or KeyStore is null");
}
/* Issuer name we need to match */
X500Principal issuer = cert.getIssuerX500Principal();
if (issuer == null) {
throw new CertificateException("Unable to get expected issuer");
}
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Searching KeyStore for root CA matching: " +
issuer.getName());
/* Find all issuers that match needed issuer name */
try {
Enumeration<String> aliases = ks.aliases();
while (aliases.hasMoreElements()) {
String name = aliases.nextElement();
X509Certificate root = null;
if (ks.isKeyEntry(name)) {
Certificate[] chain = ks.getCertificateChain(name);
if (chain != null) {
root = (X509Certificate) chain[0];
}
} else {
root = (X509Certificate) ks.getCertificate(name);
}
if (root != null && root.getBasicConstraints() >= 0) {
if (root.getSubjectX500Principal().equals(issuer)) {
/* Found correct CN, add to possible roots list */
possibleCerts.add(root);
}
}
}
} catch (KeyStoreException ex) {
throw new CertificateException(ex);
}
if (possibleCerts.size() == 0) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "No root CA found in KeyStore to validate certificate");
return null;
}
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Found " + possibleCerts.size() +
" possible root CAs, testing");
/* Use wolfSSL Cert Manager to make sure root verifies input cert */
try {
cm = new WolfSSLCertManager();
} catch (WolfSSLException e) {
throw new CertificateException(
"Failed to create native WolfSSLCertManager");
}
for (i = 0; i < possibleCerts.size(); i++) {
final int tmpI = i;
/* load candidate root CA as trusted */
encodedRoot = possibleCerts.get(tmpI).getEncoded();
ret = cm.CertManagerLoadCABuffer(encodedRoot, encodedRoot.length,
WolfSSL.SSL_FILETYPE_ASN1);
if (ret != WolfSSL.SSL_SUCCESS) {
cm.free();
throw new CertificateException(
"Failed to load root CA DER into wolfSSL cert manager");
}
/* try to verify input cert */
encodedCert = cert.getEncoded();
ret = cm.CertManagerVerifyBuffer(encodedCert, encodedCert.length,
WolfSSL.SSL_FILETYPE_ASN1);
if (ret != WolfSSL.SSL_SUCCESS) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Potential root " + tmpI + " did not verify cert");
} else {
rootFound = true;
verifiedRootIdx = tmpI;
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Found valid root: " +
possibleCerts.get(tmpI).getSubjectX500Principal().getName());
}
/* unload CAs from WolfSSLCertManager */
ret = cm.CertManagerUnloadCAs();
if (ret != WolfSSL.SSL_SUCCESS) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Error unloading root CAs from WolfSSLCertManager");
cm.free();
throw new CertificateException("Failed to unload root CA " +
"from WolfSSLCertManager");
}
if (rootFound == true) {
break;
}
}
/* Free native WolfSSLCertManager resources */
cm.free();
if (rootFound == true) {
return possibleCerts.get(verifiedRootIdx);
}
return null;
}
/**
* Find the actual issuer of a certificate from the KeyStore by checking
* both subject DN match and signature verification. This handles the case
* where multiple CA certificates share the same subject DN (e.g.,
* cross-signed roots with the same CN but different key pairs).
*
* @param cert Certificate whose issuer we want to find
* @param ks KeyStore containing trusted CA certificates
*
* @return The CA certificate that actually signed cert, or null if not
* found
*/
private X509Certificate findIssuerBySignature(X509Certificate cert,
KeyStore ks) {
if (cert == null || ks == null) {
return null;
}
X500Principal issuerDN = cert.getIssuerX500Principal();
if (issuerDN == null) {
return null;
}
try {
Enumeration<String> aliases = ks.aliases();
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
X509Certificate candidate = null;
if (ks.isKeyEntry(alias)) {
java.security.cert.Certificate[] chain =
ks.getCertificateChain(alias);
if (chain != null && chain.length > 0) {
candidate = (X509Certificate) chain[0];
}
} else {
java.security.cert.Certificate c = ks.getCertificate(alias);
if (c instanceof X509Certificate) {
candidate = (X509Certificate) c;
}
}
if (candidate == null) {
continue;
}
/* Check subject DN matches cert's issuer DN */
if (!candidate.getSubjectX500Principal().equals(issuerDN)) {
continue;
}
/* Verify the signature to confirm this is the actual issuer,
* not just a CA with the same subject DN */
try {
cert.verify(candidate.getPublicKey());
return candidate;
} catch (Exception e) {
/* Signature didn't match, try next candidate */
}
}
} catch (KeyStoreException e) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "KeyStoreException in findIssuerBySignature: " +
e.getMessage());
}
return null;
}
/**
* Verify cert chain using WolfSSLCertManager.
* Do all loading and verification in one function to avoid holding native
* resources at the object/class level.
*
* @param certs Certificate chain to validate
* @param type Authentication type
* @param returnChain Boolean (true/false), return validation chain or not
*
* @return Complete chain used for validation, including root CA, if
* returnChain is true. Otherwise, if returnChain is false return NULL
* @throws CertificateException on verification error/failure
*/
private List<X509Certificate> certManagerVerify(
X509Certificate[] certs, String type, boolean returnChain)
throws CertificateException {
int ret;
WolfSSLCertManager cm = null;
final X509Certificate[] sortedCerts;
X509Certificate rootCA = null;
List<X509Certificate> fullChain = null;
if (certs == null || certs.length == 0 ||
type == null || type.length() == 0) {
throw new CertificateException();
}
/* create new WolfSSLCertManager */
try {
cm = new WolfSSLCertManager();
} catch (WolfSSLException e) {
throw new CertificateException(
"Failed to create native WolfSSLCertManager");
}
/* load trusted certs from KeyStore */
try {
ret = cm.CertManagerLoadCAKeyStore(this.store);
if (ret != WolfSSL.SSL_SUCCESS) {
throw new CertificateException(
"Failed to load trusted certs into WolfSSLCertManager");
}
} catch (WolfSSLException e) {
cm.free();
throw new CertificateException(
"Failed to load trusted certs into WolfSSLCertManager");
}
/* Sort cert chain in order from peer to last intermedate. We
* assume cert chain starts with peer certificate (certs[0]). */
sortedCerts = sortCertChainBySubjectIssuer(certs);
/* If requested to return full chain, initialize new list and add
* peer cert first. Intermediate and root CAs added as verified. */
if (returnChain) {
fullChain = new ArrayList<X509Certificate>();
fullChain.add(sortedCerts[0]); /* Add peer cert */
}
/* Walk backwards down list of intermediate CA certs, verify each one
* based on trusted certs we already have loaded in the CertManager,
* then once verified load the intermediate into the CertManager
* as a root that can be used to verify our peer cert.
*
* Similarly to native wolfSSL WOLFSSL_ALT_CERT_CHAINS behavior: if a CA
* certificate cannot be verified, we skip it and continue building
* the chain through other certificates. This allows handling of
* cross-signed certificates and extra certificates in the chain.
*
* When verification fails for a CA cert, we also try to find its
* actual issuer in the KeyStore by signature verification. This
* handles the case where multiple CAs share the same subject DN
* (e.g., cross-signed roots) and the native CA lookup returns the
* wrong one first. */
for (int i = sortedCerts.length-1; i > 0; i--) {
final int tmpI = i;
/* Verify chain cert */
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Verifying intermediate chain cert: " +
sortedCerts[tmpI].getSubjectX500Principal().getName());
byte[] encoded = sortedCerts[tmpI].getEncoded();
ret = cm.CertManagerVerifyBuffer(encoded, encoded.length,
WolfSSL.SSL_FILETYPE_ASN1);
if (ret != WolfSSL.SSL_SUCCESS) {
/* Verification failed. If this is a CA cert, try to find
* and load its actual issuer from the KeyStore. This handles
* cross-signed certs where multiple CAs share the same
* subject DN but have different keys. */
if (sortedCerts[tmpI].getBasicConstraints() != -1) {
X509Certificate issuer = findIssuerBySignature(
sortedCerts[tmpI], this.store);
if (issuer != null) {
/* Found the actual issuer, load it and retry */
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Found issuer by signature for: " +
sortedCerts[tmpI].getSubjectX500Principal()
.getName());
try {
byte[] issuerEnc = issuer.getEncoded();
cm.CertManagerLoadCABuffer(issuerEnc,
issuerEnc.length, WolfSSL.SSL_FILETYPE_ASN1);
} catch (Exception e) {
/* If loading issuer fails, fall through to
* skip logic below */
}
/* Retry verification after loading issuer */
ret = cm.CertManagerVerifyBuffer(encoded,
encoded.length, WolfSSL.SSL_FILETYPE_ASN1);
}
}
if (ret != WolfSSL.SSL_SUCCESS) {
if (sortedCerts[tmpI].getBasicConstraints() != -1) {
/* This is a CA certificate, skip it and continue.
* Do not add it to the certificate manager. */
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Using alternate cert chain " +
"(skipping CA): " +
sortedCerts[tmpI].getSubjectX500Principal()
.getName());
continue;
}
/* Non-CA certificates must verify successfully */
cm.free();
throw new CertificateException(
"Failed to verify intermediate chain cert");
}
}
/* Load chain cert as trusted CA */
ret = cm.CertManagerLoadCABuffer(encoded, encoded.length,
WolfSSL.SSL_FILETYPE_ASN1);
if (ret != WolfSSL.SSL_SUCCESS) {
cm.free();
throw new CertificateException("Failed to load intermediate " +
"CA certificate as trusted root");
}
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Loaded intermediate CA: " +
sortedCerts[tmpI].getSubjectX500Principal().getName());
/* Chain cert verified successfully, add to fullChain if requested.
* Inserting at position 1 maintains peer to root order and shifts
* all other certs in the list down a position. */
if (returnChain) {
fullChain.add(1, sortedCerts[tmpI]);
}
}
/* Verify peer certificate */
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Verifying peer certificate: " +
sortedCerts[0].getSubjectX500Principal().getName());
byte[] peer = sortedCerts[0].getEncoded();
if (peer == null) {
cm.free();
throw new CertificateException("Failed to get encoded peer cert");
}
ret = cm.CertManagerVerifyBuffer(peer, peer.length,
WolfSSL.SSL_FILETYPE_ASN1);
if (ret != WolfSSL.SSL_SUCCESS) {
/* Native CA lookup by subject hash may return wrong issuer
* for cross-signed certs. Find correct one by signature,
* reload it, and retry. */
X509Certificate issuer = findIssuerBySignature(
sortedCerts[0], this.store);
if (issuer != null) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Found issuer by signature for peer: " +
sortedCerts[0].getSubjectX500Principal().getName());
try {
cm.CertManagerUnloadCAs();
byte[] issuerEnc = issuer.getEncoded();
cm.CertManagerLoadCABuffer(issuerEnc,
issuerEnc.length, WolfSSL.SSL_FILETYPE_ASN1);
} catch (Exception e) {
/* Fall through to failure below */
}
ret = cm.CertManagerVerifyBuffer(peer, peer.length,
WolfSSL.SSL_FILETYPE_ASN1);
}
if (ret != WolfSSL.SSL_SUCCESS) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Failed to verify peer certificate");
cm.free();
throw new CertificateException(
"Failed to verify peer certificate");
}
}
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Verified peer certificate: " +
sortedCerts[0].getSubjectX500Principal().getName());
cm.free();
if (returnChain) {
/* Find root CA from KeyStore to append to chain. Use the last
* cert in fullChain (last verified intermediate) to find its
* issuer root CA. */
rootCA = findRootCAFromKeyStoreForCert(
fullChain.get(fullChain.size() - 1), this.store);
if (rootCA == null) {
throw new CertificateException("Unable to find root CA " +
"in KeyStore to append to chain list");
}
/* Append root CA if not already present */
if (!fullChain.contains(rootCA)) {
fullChain.add(rootCA);
}
}
else {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Not returning cert chain from verify, not requested");
}
return fullChain;
}
/**
* Verify hostname using HTTPS or LDAPS verification method.
*
* For HTTPS hostname verification (RFC 2818):
*
* - If SNI name has been received during TLS handshake, try to
* first verify peer certificate against that. Skip this step when
* on server side verifying the client, since server does not set
* an SNI for the client.
* - Otherwise, try to verify certificate against SSLSocket or SSLEngine
* hostname (getHandshakeSession().getHostName()).
* - If both of the above fail, fail hostname verification.
* - Hostname matching rules for HTTPS come from RFC 2818
*
* For LDAPS hostname verification (RFC 2830):
*
* - Try to verify certificate against hostname used to create
* the SSLSocket or SSLEngine, obtained via
* getHandshakeSession().getPeerHost().
* - Hostname matching rules for LDAPS come from RFC 2830
*
* @param cert peer certificate
* @param socket SSLSocket associated with connection to peer. Only one
* of socket or engine params should be used. The other should
* be set to null.
* @param engine SSLEngine associated with connection to peer. Either/or
* between this and socket param. Other should be set to
* null.
* @param isClient true if we are calling this from client side, otherwise
* false if calling from server side.
* @param type type of hostname to verify, options are
* HOSTNAME_TYPE_HTTPS or HOSTNAME_TYPE_LDAPS
* @throws CertificateException if hostname cannot be verified
*/
private void verifyHostnameByType(X509Certificate cert, SSLSocket socket,
SSLEngine engine, boolean isClient, int type)
throws CertificateException {
final String peerHost;
List<SNIServerName> sniNames = null;
String sniHostName = null;
SSLSession session = null;
final WolfSSLCertificate peerCert;
int ret = WolfSSL.SSL_FAILURE;
if (type == HOSTNAME_TYPE_HTTPS) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "verifying hostname type HTTPS");
} else if (type == HOSTNAME_TYPE_LDAPS) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "verifying hostname type LDAPS");
} else {
throw new CertificateException("Unsupported hostname type, " +
"HTTPS and LDAPS only supported currently: " + type);
}
/* Get session associated with SSLSocket or SSLEngine */
try {
if (socket != null) {
session = socket.getHandshakeSession();
}
else if (engine != null) {
session = engine.getHandshakeSession();
}
} catch (UnsupportedOperationException e) {
e.printStackTrace();
throw new CertificateException(e);
}
/* Get peer host from SSLSocket */
if (session != null) {
peerHost = session.getPeerHost();
} else {
peerHost = null;
}
/* Get SNI name if SSLSocket/SSLEngine has received that from peer.
* Only check this when on the client side and verifying a server since
* SNI holding expected server name is available on client-side but not
* vice-versa. Also only checked for HTTPS type, not LDAPS. As per
* RFC 2830, the client MUST use the server hostname it used to open
* the LDAP connection. */
if ((session != null) && isClient &&
(session instanceof ExtendedSSLSession) &&
(type == HOSTNAME_TYPE_HTTPS)) {
sniNames = ((ExtendedSSLSession)session).getRequestedServerNames();
for (SNIServerName name : sniNames) {
if (name.getType() == StandardConstants.SNI_HOST_NAME) {
SNIHostName tmpName = new SNIHostName(name.getEncoded());
if (tmpName != null) {
/* Get SNI name as ASCII string for comparison */
sniHostName = tmpName.getAsciiName();
}
}
}
}
/* Create new WolfSSLCertificate (WOLFSSL_X509) from
* DER encoding of peer certificate */
try {
peerCert = new WolfSSLCertificate(cert.getEncoded());
if (peerCert == null) {
throw new CertificateException(
"Unable to create WolfSSLCertificate from peer cert");
}
} catch (WolfSSLException e) {
throw new CertificateException(e);
}
/* Try verifying hostname against SNI name, if HTTPS type */
if (isClient && (type == HOSTNAME_TYPE_HTTPS)) {
if (sniHostName != null) {
final String tmpSniName = sniHostName;
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "trying hostname verification against SNI: " +
tmpSniName);
ret = peerCert.checkHost(sniHostName);
if (ret == WolfSSL.SSL_SUCCESS) {
/* Hostname successfully verified against SNI name */
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "successfully verified X509 hostname using " +
"SNI name");
return;
}
else {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "hostname match with SNI failed");
}
}
else {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "no provided SNI name found");
}
}
/* Try verifying hostname against peerHost from SSLSocket/SSLEngine */
if (peerHost != null) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "trying hostname verification against peer host: " +
peerHost);
if (type == HOSTNAME_TYPE_LDAPS) {
/* LDAPS requires wildcard left-most matching only */
ret = peerCert.checkHost(peerHost,
WolfSSL.WOLFSSL_LEFT_MOST_WILDCARD_ONLY);
} else {
ret = peerCert.checkHost(peerHost);
}
if (ret == WolfSSL.SSL_SUCCESS) {
/* Hostname successfully verified against peer host name */
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "successfully verified X509 hostname using " +
"SSLSession getPeerHost()");
return;
}
}
final String tmpSniName = sniHostName;
final String tmpPeerHost = peerHost;
if (isClient) {
if (type == HOSTNAME_TYPE_HTTPS) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "hostname verification failed for server peer " +
"cert, tried SNI (" + tmpSniName + "), peer host (" +
tmpPeerHost + ")\n" + peerCert);
} else {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "hostname verification failed for server peer " +
"cert, peer host (" + tmpPeerHost + ")\n" + peerCert);
}
} else {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "hostname verification failed for client peer cert, " +
"tried peer host (" + tmpPeerHost + ")\n" + peerCert);
}
throw new CertificateException("Hostname verification failed");
}
/**
* Verify hostname of certificate.
*
* @param cert peer certificate
* @param socket SSLSocket associated with connection to peer. Only one
* of socket or engine params should be used. The other should
* be set to null.
* @param engine SSLEngine associated with connection to peer. Either/or
* between this and socket param. Other should be set to
* null.
* @param isClient true if we are calling this from client side, otherwise
* false if calling from server side.
* @throws CertificateException if hostname cannot be verified
*/
protected void verifyHostname(X509Certificate cert,
Socket socket, SSLEngine engine, boolean isClient)
throws CertificateException {
String endpointIdAlgo = null;
SSLParameters sslParams = null;
/* Hostname verification on Socket done only if Socket is of SSLSocket,
* not null, and connected */
if ((socket != null) && (socket instanceof SSLSocket) &&
(socket.isConnected())) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "entered verifyHostname, using SSLSocket for host info");
sslParams = ((SSLSocket)socket).getSSLParameters();
if (sslParams == null) {
throw new CertificateException(
"SSLParameters in SSLSocket is null");
}
endpointIdAlgo = sslParams.getEndpointIdentificationAlgorithm();
/* If endpoint ID algo is null or empty, skips hostname verify */
if (endpointIdAlgo != null && !endpointIdAlgo.isEmpty()) {
if (endpointIdAlgo.equals("HTTPS")) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "verifying hostname, endpoint identification " +
"algorithm = HTTPS");
verifyHostnameByType(cert, (SSLSocket)socket,
null, isClient, HOSTNAME_TYPE_HTTPS);
}
else if (endpointIdAlgo.equals("LDAPS")) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "verifying hostname, endpoint identification " +
"algorithm = LDAPS");
verifyHostnameByType(cert, (SSLSocket)socket,
null, isClient, HOSTNAME_TYPE_LDAPS);
}
else {
throw new CertificateException(
"Unsupported Endpoint Identification Algorithm: " +
endpointIdAlgo);
}
}
else {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "endpoint Identification algo is null or empty, " +
"skipping hostname verification");
}
}
else if (engine != null) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "entered verifyHostname, using SSLEngine for host info");
sslParams = engine.getSSLParameters();
if (sslParams == null) {
throw new CertificateException(
"SSLParameters in SSLEngine is null");
}
endpointIdAlgo = sslParams.getEndpointIdentificationAlgorithm();
/* If endpoint ID algo is null or empty, skips hostname verify */
if (endpointIdAlgo != null && !endpointIdAlgo.isEmpty()) {
if (endpointIdAlgo.equals("HTTPS")) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "verifying hostname, endpoint identification " +
"algorithm = HTTPS");
verifyHostnameByType(cert, null, engine, isClient,
HOSTNAME_TYPE_HTTPS);
}
else if (endpointIdAlgo.equals("LDAPS")) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "verifying hostname, endpoint identification " +
"algorithm = LDAPS");
verifyHostnameByType(cert, null, engine, isClient,
HOSTNAME_TYPE_LDAPS);
}
else {
throw new CertificateException(
"Unsupported Endpoint Identification Algorithm: " +
endpointIdAlgo);
}
}
else {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "endpoint Identification algo is null or empty, " +
"skipping hostname verification");
}
}
else {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Socket is null, not connected, or not SSLSocket. " +
"SSLEngine is also null. Skipping hostname verification " +
"in ExtendedX509TrustManager");
}
}
/**
* Try to build and validate the client certificate chain based on the
* provided certificates and authentication type.
*
* Does not do hostname verification internally. Calling applications are
* responsible for checking hostname for accuracy if desired. To use
* internal hostname verification use X509ExtendedTrustManager APIs
* (for HTTPS verification).
*
* @param certs peer certificate chain
* @param type authentication type based on the client certificate
* @throws CertificateException if certificate chain is not trusted
*/
@Override
public void checkClientTrusted(X509Certificate[] certs, String type)
throws CertificateException, IllegalArgumentException {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "entered checkClientTrusted()");
if (certs == null) {
throw new IllegalArgumentException("Input cert chain null");
}
if (type == null || type.length() == 0) {
throw new IllegalArgumentException("Input auth type null");
}
/* Verify cert chain, throw CertificateException if not valid */
certManagerVerify(certs, type, false);
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "leaving checkClientTrusted(), success");
}
/**
* Try to build and validate the client certificate chain based on the
* provided certificates and authentication type.
*
* Does hostname verification internally if Endpoint Identification
* Algorithm has been set by application in SSLParameters, and that
* Algorithm matches "HTTPS" or "LDAPS". If "HTTPS" is set, hostname
* verification is done using SNI first then peer host value.
*
* Other Endpoint Identification Algorithms besides "HTTPS" and "LDAPS"
* are not currently supported.
*
* @param certs peer certificate chain
* @param type authentication type based on the client certificate
* @throws CertificateException if certificate chain is not trusted
*/
@Override
public void checkClientTrusted(X509Certificate[] certs, String type,
Socket socket) throws CertificateException, IllegalArgumentException {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "entered checkClientTrusted() with Socket");
if (certs == null) {
throw new IllegalArgumentException("Input cert chain null");
}
if (type == null || type.length() == 0) {
throw new IllegalArgumentException("Input auth type null");
}
/* Verify cert chain, throw CertificateException if not valid */
certManagerVerify(certs, type, false);
/* Verify hostname if right criteria matches */
verifyHostname(certs[0], socket, null, false);