-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathWolfSSLInternalVerifyCb.java
More file actions
619 lines (564 loc) · 26 KB
/
WolfSSLInternalVerifyCb.java
File metadata and controls
619 lines (564 loc) · 26 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
/* WolfSSLInternalVerifyCb.java
*
* Copyright (C) 2006-2026 wolfSSL Inc.
*
* This file is part of wolfSSL.
*
* wolfSSL is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* wolfSSL is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
*/
package com.wolfssl.provider.jsse;
import com.wolfssl.WolfSSL;
import com.wolfssl.WolfSSLDebug;
import com.wolfssl.WolfSSLVerifyCallback;
import com.wolfssl.WolfSSLException;
import com.wolfssl.WolfSSLJNIException;
import com.wolfssl.WolfSSLCertificate;
import com.wolfssl.WolfSSLX509StoreCtx;
import com.wolfssl.provider.jsse.WolfSSLInternalVerifyCb;
import java.security.cert.X509Certificate;
import java.security.cert.CertificateException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;
import javax.net.ssl.X509ExtendedTrustManager;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.nio.charset.StandardCharsets;
import java.util.List;
/**
* Internal verify callback.
* This is used when a user registers a TrustManager which is NOT
* com.wolfssl.provider.jsse.WolfSSLTrustManager. It is used to call
* TrustManager checkClientTrusted() or checkServerTrusted().
* If wolfJSSE TrustManager is used, native wolfSSL does certificate
* verification internally. Used by WolfSSLEngineHelper.
*/
public class WolfSSLInternalVerifyCb implements WolfSSLVerifyCallback {
private X509TrustManager tm = null;
private boolean clientMode;
private WolfSSLParameters params = null;
/* Use WeakReference for SSLSocket and SSLEngine to avoid
* holding back garbage collection of WolfSSLSocket/WolfSSLEngine
* objects */
private WeakReference<SSLSocket> callingSocket = null;
private WeakReference<SSLEngine> callingEngine = null;
/* TrustManager exception for SSLHandshakeException cause chain */
private Exception verifyException = null;
/**
* Create new WolfSSLInternalVerifyCb
*
* @param xtm X509TrustManager to use with this object
* @param client boolean representing if this is client side
* @param socket SSLSocket associated with this callback, or null
* @param engine SSLEngine associated with this callback, or null
* @param params WolfSSLParameters associated with this callback
*/
public WolfSSLInternalVerifyCb(X509TrustManager xtm, boolean client,
SSLSocket socket, SSLEngine engine, WolfSSLParameters params) {
this.tm = xtm;
this.clientMode = client;
this.params = params;
if (socket != null) {
this.callingSocket = new WeakReference<>(socket);
} else {
this.callingSocket = null;
}
if (engine != null) {
this.callingEngine = new WeakReference<>(engine);
} else {
this.callingEngine = null;
}
}
/**
* Reset internal variables back to null/default.
*/
protected void clearInternalVars() {
this.callingSocket = null;
this.callingEngine = null;
this.params = null;
this.tm = null;
this.verifyException = null;
}
/**
* Get the last exception thrown by the TrustManager during
* certificate verification. Returns null if verification succeeded
* or no verification has occurred.
*
* @return Exception from last failed verification, or null
*/
public Exception getVerifyException() {
return this.verifyException;
}
/**
* Verify hostname of provided peer certificate using
* Endpoint Identification Algorithm if set in SSLParameters.
*
* Used by verifyCallback() only for case where internal native wolfSSL
* peer verification is done. Otherwise, hostname is verified as part
* of full cert validation later in verifyCallback().
*
* @param peer peer certificate to use for hostname verification
*
* @return 1 if hostname verification was successful (allows verify
* callback to proceed, otherwise 0 if verification was not
* successful (or not able to do it since Endpoitn Identification
* Algorithm has not been set).
*/
private int verifyHostnameOnly(X509Certificate peer) {
WolfSSLTrustX509 wolfTM = (WolfSSLTrustX509)tm;
try {
SSLSocket sock = (this.callingSocket != null) ?
this.callingSocket.get() : null;
SSLEngine eng = (this.callingEngine != null) ?
this.callingEngine.get() : null;
if (sock != null) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "checking hostname verification using SSLSocket");
/* Throws CertificateException when verify fails */
wolfTM.verifyHostname(peer, sock, null, clientMode);
}
else if (eng != null) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "checking hostname verification using SSLEngine");
/* Throws CertificateException when verify fails */
wolfTM.verifyHostname(peer, null, eng, clientMode);
}
else {
/* SSLSocket/SSLEngine null. Fail if endpoint ID
* is set, otherwise skip hostname verification. */
String eia = null;
if (this.params != null) {
eia = this.params.getEndpointIdentificationAlgorithm();
}
if (eia != null && !eia.isEmpty()) {
throw new CertificateException(
"Both SSLSocket and SSLEngine null, cannot " +
"perform hostname verification for " +
"endpoint identification algorithm: " + eia);
}
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Both SSLSocket and SSLEngine null, skipping " +
"hostname verification (native verify already " +
"passed, no endpoint identification configured)");
}
} catch (CertificateException e) {
this.verifyException = e;
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "X509ExtendedTrustManager hostname verification " +
"failed: " + e.getMessage());
return 0;
}
/* Hostname verification successful */
return 1;
}
/**
* Verify hostname for basic X509TrustManager when Endpoint
* Identification Algorithm is set. Matches SunJSSE behavior.
*
* @param peer peer certificate to verify hostname against
*
* @return 1 if passed or not needed, 0 if failed
*/
private int verifyHostnameForExternalTM(X509Certificate peer) {
String endpointIdAlgo = null;
String peerHost = null;
SSLSession session = null;
/* Get endpoint identification algorithm from params */
if (this.params != null) {
endpointIdAlgo = this.params.getEndpointIdentificationAlgorithm();
}
/* If no endpoint identification algorithm set, skip hostname
* verification - it has not been requested */
if (endpointIdAlgo == null || endpointIdAlgo.isEmpty()) {
return 1;
}
/* Only HTTPS and LDAPS are supported. Fail if endpoint ID was
* explicitly set to something else (typo or unsupported algo). */
if (!endpointIdAlgo.equals("HTTPS") &&
!endpointIdAlgo.equals("LDAPS")) {
final String tmpAlgoUnsup = endpointIdAlgo;
this.verifyException = new CertificateException(
"Unsupported endpoint identification algorithm: " +
endpointIdAlgo);
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Unsupported endpoint identification algorithm: "
+ tmpAlgoUnsup);
return 0;
}
final String tmpAlgo = endpointIdAlgo;
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Provider-level hostname verification, algorithm: " +
tmpAlgo);
/* Get peer host from SSLEngine or SSLSocket handshake session */
try {
SSLEngine eng = (this.callingEngine != null) ?
this.callingEngine.get() : null;
SSLSocket sock = (this.callingSocket != null) ?
this.callingSocket.get() : null;
if (eng != null) {
session = eng.getHandshakeSession();
}
else if (sock != null) {
session = sock.getHandshakeSession();
}
} catch (UnsupportedOperationException e) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "getHandshakeSession() not supported: " + e.getMessage());
CertificateException ce = new CertificateException(
"getHandshakeSession() not supported: " + e.getMessage());
ce.initCause(e);
this.verifyException = ce;
return 0;
}
/* Prefer SNI hostname from SSLParameters over session peer host.
* session.getPeerHost() returns the IP address (e.g. 127.0.0.1),
* but for SNI verification we need the logical hostname the client
* requested (e.g. "something.netty.io"). */
if (this.params != null) {
List<WolfSSLSNIServerName> sniNames =
this.params.getWolfSSLServerNames();
if (sniNames != null && !sniNames.isEmpty()) {
for (WolfSSLSNIServerName sni : sniNames) {
/* Type 0 = host_name (RFC 6066) */
if (sni.getType() == 0) {
byte[] encoded = sni.getEncoded();
if (encoded != null && encoded.length > 0) {
peerHost = new String(encoded,
StandardCharsets.US_ASCII);
}
break;
}
}
}
}
/* Fall back to session peer host if no SNI hostname */
if (peerHost == null || peerHost.isEmpty()) {
if (session != null) {
peerHost = session.getPeerHost();
}
}
if (peerHost == null || peerHost.isEmpty()) {
this.verifyException = new CertificateException(
"No peer host available for hostname verification");
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "No peer host available for hostname verification");
/* No peer host to verify against, fail verification since
* endpoint identification was explicitly requested */
return 0;
}
/* Verify hostname against certificate SAN/CN using native
* wolfSSL X509_check_host() */
final String tmpHost = peerHost;
WolfSSLCertificate wCert = null;
try {
wCert = new WolfSSLCertificate(peer.getEncoded());
int ret = wCert.checkHost(peerHost);
if (ret == WolfSSL.SSL_SUCCESS) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Provider-level hostname verification " +
"passed for: " + tmpHost);
return 1;
} else {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Provider-level hostname verification " +
"FAILED for: " + tmpHost);
this.verifyException = new CertificateException(
"Hostname verification failed for: " + tmpHost);
return 0;
}
} catch (Exception e) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Hostname verification error: " + e.getMessage());
this.verifyException = e;
return 0;
} finally {
if (wCert != null) {
wCert.free();
}
}
}
/**
* Calls registered X509TrustManager / X509ExtendedTrustManager to
* verify certificate chain.
*
* @param certs Peer certificate chain to validate
* @param authType Authentication type
*
* @return true on successful validation, otherwise false on failure
*/
private boolean VerifyCertChainWithTrustManager(X509Certificate[] certs,
String authType) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Verifying peer with X509TrustManager: " + this.tm);
if (this.tm instanceof X509ExtendedTrustManager) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "X509TrustManager of type X509ExtendedTrustManager");
}
else {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "X509TrustManager of type X509TrustManager");
}
try {
/* Call TrustManager to do cert verification, should throw
* CertificateException if verification fails */
SSLSocket sock = (this.callingSocket != null) ?
this.callingSocket.get() : null;
SSLEngine eng = (this.callingEngine != null) ?
this.callingEngine.get() : null;
if (this.clientMode) {
if (this.tm instanceof X509ExtendedTrustManager) {
X509ExtendedTrustManager xtm =
(X509ExtendedTrustManager)this.tm;
if (sock != null) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Calling TrustManager.checkServerTrusted(" +
"SSLSocket)");
xtm.checkServerTrusted(certs, authType, sock);
}
else if (eng != null) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Calling TrustManager.checkServerTrusted(" +
"SSLEngine)");
xtm.checkServerTrusted(certs, authType, eng);
}
else {
/* If we do have access to X509ExtendedTrustManager,
* but don't have SSLSocket/Engine, error out instead
* of falling back to verify without hostname. */
throw new Exception(
"SSLSocket/SSLEngine null during server peer " +
"verification, failed to verify");
}
}
else {
/* Basic X509TrustManager does not support HTTPS
* hostname verification, no SSLSocket/Engine needed */
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Calling TrustManager.checkServerTrusted()");
this.tm.checkServerTrusted(certs, authType);
}
} else {
if (this.tm instanceof X509ExtendedTrustManager) {
X509ExtendedTrustManager xtm =
(X509ExtendedTrustManager)this.tm;
if (sock != null) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Calling TrustManager.checkClientTrusted(" +
"SSLSocket)");
xtm.checkClientTrusted(certs, authType, sock);
}
else if (eng != null) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Calling TrustManager.checkClientTrusted(" +
"SSLEngine)");
xtm.checkClientTrusted(certs, authType, eng);
}
else {
/* If we do have access to X509ExtendedTrustManager,
* but don't have SSLSocket/Engine, error out instead
* of falling back to verify without hostname. */
throw new Exception(
"SSLSocket/SSLEngine null during client peer " +
"verification, failed to verify");
}
}
else {
/* Basic X509TrustManager does not support HTTPS
* hostname verification, no SSLSocket/Engine needed */
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Calling TrustManager.checkClientTrusted()");
this.tm.checkClientTrusted(certs, authType);
}
}
} catch (Exception e) {
/* Store for SSLHandshakeException cause chain */
this.verifyException = e;
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "TrustManager rejected certificates, " +
"verification failed: " + e.getMessage());
return false;
}
return true;
}
/**
* Native wolfSSL verify callback.
*
* @param preverify_ok Will be 1 if native wolfSSL verification
* procedured have passed, otherwise 0.
* @param x509StorePtr Native pointer to WOLFSSL_X509_STORE structure
*
* @return 1 if verification should be considered successful and
* SSL/TLS handshake should continue. Otherwise return 0
* to mark verification failure and stop/abort handshake.
*/
@SuppressWarnings("deprecation")
public int verifyCallback(int preverify_ok, long x509StorePtr) {
WolfSSLCertificate[] certs = null;
String authType = null;
X509Certificate[] x509certs = new X509Certificate[0];
/* Clear any prior callback failure so callers don't see stale causes
* if this callback instance is reused across handshakes. */
this.verifyException = null;
if (preverify_ok == 1) {
/* When using WolfSSLTrustX509 implementation of
* X509TrustManager, we use internal wolfSSL verification logic
* but register this verify callback (always called) so that
* we can do additional hostname verification if user has set
* the Endpoint Identification Algorithm in SSLParameters.
* Note that certificate verification has already been done and
* passed if preverify_ok == 1, so we skip doing it again here
* later on for this case */
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Native wolfSSL peer verification passed (clientMode: " +
this.clientMode + ")");
} else {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "NOTE: Native wolfSSL peer verification failed " +
"(clientMode: " + this.clientMode + ")");
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> " Continuing with X509TrustManager verification");
}
try {
/* Get WolfSSLCertificate[] from x509StorePtr, certs from
* store.getCerts() should be listed in order of peer to root */
WolfSSLX509StoreCtx store =
new WolfSSLX509StoreCtx(x509StorePtr);
certs = store.getCerts();
} catch (WolfSSLException e) {
/* failed to get certs from native, give app null array */
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Failed to get certs from x509StorePtr, certs = null: " +
e.getMessage());
certs = null;
}
if (certs != null && certs.length > 0) {
try {
/* Convert WolfSSLCertificate[] to X509Certificate[] */
x509certs = new X509Certificate[certs.length];
for (int i = 0; i < certs.length; i++) {
x509certs[i] = certs[i].getX509Certificate();
final String tmpName =
x509certs[i].getSubjectDN().getName();
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Peer cert: " + tmpName);
}
} catch (CertificateException | IOException |
WolfSSLJNIException ce) {
/* failed to get cert array, give app empty array */
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Failed to get X509Certificate[] array, set to " +
"empty array: " + ce.getMessage());
x509certs = new X509Certificate[0];
}
/* get authType, use first cert */
String sigType = certs[0].getSignatureType();
if (sigType.contains("RSA")) {
authType = "RSA";
} else if (sigType.contains("ECDSA")) {
authType = "ECDSA";
} else if (sigType.contains("DSA")) {
authType = "DSA";
} else if (sigType.contains("ED25519")) {
authType = "ED25519";
}
final String tmpAuthType = authType;
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Auth type: " + tmpAuthType);
/* Free native WolfSSLCertificate memory. At this
* point x509certs[] is all Java managed memory now. */
for (int i = 0; i < certs.length; i++) {
certs[i].free();
}
}
/* Case where native wolfSSL verification was already done and passed
* and we only want to do hostname verification if needed additionally.
* We do that here and return before going on to additional
* checkServerTrusted/checkClientTrusted() so that we do not
* duplicate verification. */
if ((preverify_ok == 1) && (x509certs.length > 0) &&
(tm instanceof WolfSSLTrustX509)) {
return verifyHostnameOnly(x509certs[0]);
}
/* If server-side application has explicitly disabled client
* authentication (neither needClientAuth nor wantClientAuth set),
* return as success and skip X509TrustManager verification. */
if ((!this.clientMode) && (this.params != null) &&
(!this.params.getNeedClientAuth()) &&
(!this.params.getWantClientAuth())) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Application has disabled client verification " +
"(needClientAuth=false, wantClientAuth=false), " +
"skipping verification");
return 1;
}
else if ((x509certs.length == 0) &&
(!this.clientMode) && (this.params != null) &&
this.params.getWantClientAuth() &&
(!this.params.getNeedClientAuth())) {
/* No peer certificates sent and client authentication is
* optional (wantClientAuth == true, needClientAuth == false).
* Don't call TrustManager with empty certificate chain,
* just consider verification successful. Don't require
* preverify_ok == 1 here since native wolfSSL may report
* failure when no CAs are loaded (foreign TrustManager). */
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "No client cert sent and client auth marked optional, " +
"not calling TrustManager for hostname verification");
}
else if ((!this.clientMode) && (this.params != null) &&
this.params.getWantClientAuth() &&
(!this.params.getNeedClientAuth())) {
/* wantClientAuth is set and client sent a certificate.
* Try to verify via TrustManager, but don't fail the
* handshake if verification fails — matches SunJSSE
* behavior where wantClientAuth is non-fatal. */
if (VerifyCertChainWithTrustManager(x509certs, authType)) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "wantClientAuth: client cert verified successfully");
} else {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "wantClientAuth: client cert verification failed, " +
"continuing handshake (non-fatal)");
}
}
else {
/* Poll X509TrustManager / X509ExtendedTrustManager for certificate
* verification status. Returns 0 if certificates are rejected,
* otherwise 1 on successful verification */
if (VerifyCertChainWithTrustManager(x509certs, authType) == false) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "TrustManager verification failed");
/* Abort handshake, verification failed */
return 0;
}
}
/* Provider-level hostname verify for basic X509TrustManager
* (X509ExtendedTrustManager handles it internally) */
if (!(tm instanceof WolfSSLTrustX509) &&
!(tm instanceof X509ExtendedTrustManager) &&
this.clientMode && x509certs.length > 0) {
if (verifyHostnameForExternalTM(x509certs[0]) == 0) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Provider-level hostname verification failed");
return 0;
}
}
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "TrustManager verification successful");
/* Continue handshake, verification succeeded */
return 1;
}
}