-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathWolfSSLKeyX509.java
More file actions
611 lines (508 loc) · 20.8 KB
/
WolfSSLKeyX509.java
File metadata and controls
611 lines (508 loc) · 20.8 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
/* WolfSSLKeyX509.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.net.Socket;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.PrivilegedAction;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.Arrays;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.X509ExtendedKeyManager;
import com.wolfssl.WolfSSLDebug;
/**
* wolfSSL implementation of X509KeyManager, extends X509ExtendedKeyManager
* for implementation of chooseEngineClientAlias() and
* chooseEngineServerAlias().
*
* @author wolfSSL
*/
public class WolfSSLKeyX509 extends X509ExtendedKeyManager {
/* Security property to control caching behavior. When set to "true",
* disables KeyStore entry caching and reverts to calling KeyStore
* methods directly for each operation. */
private static final String DISABLE_CACHE_PROPERTY =
"wolfjsse.X509KeyManager.disableCache";
/* Reference to original KeyStore for non-cached operations */
private final KeyStore keyStore;
private final char[] keyStorePassword;
/* Cache behavior determined once at construction time */
private final boolean cacheDisabled;
/* Cache for KeyStore entries to avoid concurrent access issues. Prior
* to the addition of these caches, WolfSSLKeyX509 called down directly
* to the underlying KeyStore for each operation. Since the KeyStore
* operations are synchronized, concurrent threads accessing this
* KeyManager can queue up in that scenario and hurt performance.
* These caches are only used if caching has not been disabled via
* Security property. */
private final Map<String, X509Certificate> certificateCache;
private final Map<String, X509Certificate[]> certificateChainCache;
private final Map<String, PrivateKey> privateKeyCache;
private final Set<String> aliasSet;
/**
* Create new WolfSSLKeyX509 object
*
* @param store input KeyStore to cache entries from
* @param password input KeyStore password
* @throws KeyStoreException if unable to populate cache from KeyStore
*/
public WolfSSLKeyX509(KeyStore store, char[] password)
throws KeyStoreException {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "creating new WolfSSLKeyX509 object");
/* Check Security property once at construction time.
* Use doPrivileged for SecurityManager compatibility.
* AccessController used via FQN to avoid import-line removal
* warning on JDK 17+. */
@SuppressWarnings("removal")
String disableCacheValue = java.security.AccessController.doPrivileged(
new PrivilegedAction<String>() {
public String run() {
return Security.getProperty(DISABLE_CACHE_PROPERTY);
}
}
);
this.cacheDisabled = "true".equalsIgnoreCase(disableCacheValue);
if (this.cacheDisabled) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "KeyStore caching disabled via " +
DISABLE_CACHE_PROPERTY + " Security property, " +
"using direct KeyStore access");
this.keyStore = store;
this.keyStorePassword =
(password != null) ? password.clone() : null;
this.certificateCache = null;
this.certificateChainCache = null;
this.privateKeyCache = null;
this.aliasSet = null;
} else {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "KeyStore caching enabled, populating caches");
this.keyStore = null;
this.keyStorePassword = null;
/* Initialize cache data structures */
this.certificateCache = new HashMap<String, X509Certificate>();
this.certificateChainCache =
new HashMap<String, X509Certificate[]>();
this.privateKeyCache = new HashMap<String, PrivateKey>();
this.aliasSet = new LinkedHashSet<String>();
/* Populate caches from KeyStore */
populateCache(store, password);
}
}
/**
* Populate internal caches with all entries from KeyStore
*
* @param store KeyStore to read entries from
* @param password KeyStore password to access private keys
* @throws KeyStoreException if unable to read from KeyStore
*/
private void populateCache(KeyStore store, char[] password)
throws KeyStoreException {
if (store == null) {
return;
}
Enumeration<String> aliases = store.aliases();
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
aliasSet.add(alias);
try {
/* Cache individual certificate */
Certificate cert = store.getCertificate(alias);
if (cert instanceof X509Certificate) {
certificateCache.put(alias, (X509Certificate)cert);
}
/* Cache certificate chain */
Certificate[] certChain = store.getCertificateChain(alias);
if (certChain != null) {
int x509Cnt = 0;
/* Count X509Certificate entries */
for (int i = 0; i < certChain.length; i++) {
if (certChain[i] instanceof X509Certificate) {
x509Cnt++;
}
}
/* Store X509Certificate chain */
if (x509Cnt > 0) {
int idx = 0;
X509Certificate[] x509Chain =
new X509Certificate[x509Cnt];
for (int i = 0; i < certChain.length; i++) {
if (certChain[i] instanceof X509Certificate) {
x509Chain[idx++] = (X509Certificate)certChain[i];
}
}
certificateChainCache.put(alias, x509Chain);
}
}
/* Cache private key */
PrivateKey key = (PrivateKey)store.getKey(alias, password);
if (key != null) {
privateKeyCache.put(alias, key);
}
} catch (Exception e) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.ERROR,
() -> "Error caching entry for alias: " + alias + ", " + e);
/* Continue processing other aliases */
}
}
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Cached " + aliasSet.size() + " aliases from KeyStore");
}
/**
* Return array of aliases from KeyStore that matches provided
* type and issuers array (non-cached version).
*
* Returns:
* null - if no alias matches found in KeyStore.
* String[] - aliases, if found that match type and/or issuers
*/
@SuppressWarnings("deprecation")
private String[] getAliasesFromKeyStore(String type, Principal[] issuers)
throws KeyStoreException {
int i;
ArrayList<String> ret = new ArrayList<String>();
if (keyStore == null) {
return null;
}
Enumeration<String> aliases = keyStore.aliases();
/* loop through each KeyStore alias */
while (aliases.hasMoreElements()) {
String current = aliases.nextElement();
Certificate cert = keyStore.getCertificate(current);
if (!(cert instanceof X509Certificate)) {
continue;
}
X509Certificate x509cert = (X509Certificate)cert;
if (type != null &&
!x509cert.getPublicKey().getAlgorithm().equals(type)) {
/* different public key type, skip */
continue;
}
/* if issuers is null then it does not matter which issuer */
if (issuers == null) {
ret.add(current);
}
else {
/* search through issuers for matching issuer name */
for (i = 0; i < issuers.length; i++) {
String certIssuer = x509cert.getIssuerDN().getName();
String issuerName = issuers[i].getName();
/* normalize spaces after commas, needed on some JDKs */
certIssuer = certIssuer.replaceAll(", ", ",");
issuerName = issuerName.replaceAll(", ", ",");
if (certIssuer.equals(issuerName)) {
/* matched issuer, add alias and continue on */
ret.add(current);
break;
}
}
}
}
if (ret.size() == 0) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "No aliases found in KeyStore that match type " +
"and/or issuer");
return null;
}
return ret.toArray(new String[0]);
}
/**
* Return array of aliases that matches provided type and issuers array.
* Uses either cached entries or direct KeyStore access based on Security
* property configuration.
*
* Returns:
* null - if no alias matches found.
* String[] - aliases, if found that match type and/or issuers
*/
@SuppressWarnings("deprecation")
private String[] getAliases(String type, Principal[] issuers) {
/* Check if caching is disabled, use direct KeyStore access */
if (this.cacheDisabled) {
try {
return getAliasesFromKeyStore(type, issuers);
} catch (KeyStoreException e) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.ERROR,
() -> "Error accessing KeyStore directly: " +
e.getMessage());
return null;
}
}
/* Use cached entries */
int i;
ArrayList<String> ret = new ArrayList<String>();
/* loop through each cached alias */
for (String current : aliasSet) {
X509Certificate cert = certificateCache.get(current);
if (type != null && cert != null &&
!cert.getPublicKey().getAlgorithm().equals(type)) {
/* different public key type, skip */
continue;
}
/* if issuers is null then it does not matter which issuer */
if (issuers == null) {
ret.add(current);
}
else {
if (cert != null) {
/* search through issuers for matching issuer name */
for (i = 0; i < issuers.length; i++) {
String certIssuer = cert.getIssuerDN().getName();
String issuerName = issuers[i].getName();
/* normalize spaces after commas, needed on some JDKs */
certIssuer = certIssuer.replaceAll(", ", ",");
issuerName = issuerName.replaceAll(", ", ",");
if (certIssuer.equals(issuerName)) {
/* matched issuer, add alias and continue on */
ret.add(current);
break;
}
}
}
}
}
if (ret.size() == 0) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "No aliases found in cache that match type " +
"and/or issuer");
return null;
}
return ret.toArray(new String[0]);
}
@Override
public String[] getClientAliases(String type, Principal[] issuers) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "entered getClientAliases()");
return getAliases(type, issuers);
}
/* Note: Socket argument not used by wolfJSSE to choose aliases */
@Override
public String chooseClientAlias(String[] type, Principal[] issuers,
Socket sock) {
int i;
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "entered chooseClientAlias()");
if (type == null) {
return null;
}
for (i = 0; i < type.length; i++) {
String[] all = getAliases(type[i], issuers);
if (all != null) {
/* Find first alias that has a private key, skip cert-only
* entries (trustedCertEntry) which have no private key */
for (String alias : all) {
PrivateKey key = getPrivateKey(alias);
if (key != null) {
final String selectedAlias = alias;
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "chooseClientAlias() returning alias " +
"with private key: " + selectedAlias);
return alias;
}
}
}
}
return null;
}
/* Note: Engine argument not yet used by wolfJSSE to choose aliases */
@Override
public String chooseEngineClientAlias(String[] type, Principal[] issuers,
SSLEngine engine) {
int i;
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "entered chooseEngineClientAlias()");
if (type == null) {
return null;
}
for (i = 0; i < type.length; i++) {
String[] all = getAliases(type[i], issuers);
if (all != null) {
/* Find first alias that has a private key, skip cert-only
* entries (trustedCertEntry) which have no private key */
for (String alias : all) {
PrivateKey key = getPrivateKey(alias);
if (key != null) {
final String selectedAlias = alias;
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "chooseEngineClientAlias() returning " +
"alias with private key: " + selectedAlias);
return alias;
}
}
}
}
return null;
}
@Override
public String[] getServerAliases(String type, Principal[] issuers) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "entered getServerAliases(), type: " + type);
return getAliases(type, issuers);
}
@Override
public String chooseServerAlias(String type, Principal[] issuers,
Socket sock) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "entered chooseServerAlias(), type: " + type);
if (type == null || type.isEmpty()) {
return null;
}
/* For now using same behavior as chooseClientAlias() */
return chooseClientAlias(new String[] {type}, issuers, sock);
}
@Override
public String chooseEngineServerAlias(String type, Principal[] issuers,
SSLEngine engine) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "entered chooseEngineServerAlias(), type: " + type);
if (type == null || type.isEmpty()) {
return null;
}
/* For now, using same behavior as chooseEngineClientAlias() */
return chooseEngineClientAlias(new String[] {type}, issuers, engine);
}
@Override
public X509Certificate[] getCertificateChain(String alias) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "entered getCertificateChain(), alias: " + alias);
if (alias == null) {
return null;
}
/* Check if caching is disabled, use direct KeyStore access */
if (this.cacheDisabled) {
try {
if (keyStore == null) {
return null;
}
Certificate[] certChain = keyStore.getCertificateChain(alias);
if (certChain == null) {
return null;
}
/* Convert to X509Certificate array */
int x509Cnt = 0;
for (int i = 0; i < certChain.length; i++) {
if (certChain[i] instanceof X509Certificate) {
x509Cnt++;
}
}
if (x509Cnt == 0) {
return null;
}
X509Certificate[] x509Chain = new X509Certificate[x509Cnt];
int idx = 0;
for (int i = 0; i < certChain.length; i++) {
if (certChain[i] instanceof X509Certificate) {
x509Chain[idx++] = (X509Certificate)certChain[i];
}
}
return x509Chain;
} catch (KeyStoreException e) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.ERROR,
() -> "Error accessing certificate chain from KeyStore: " +
e.getMessage());
return null;
}
}
/* Return cached certificate chain */
return certificateChainCache.get(alias);
}
@Override
public PrivateKey getPrivateKey(String alias) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "entered getPrivateKey(), alias: " + alias);
if (alias == null) {
return null;
}
/* Check if caching is disabled, use direct KeyStore access */
if (this.cacheDisabled) {
try {
if (keyStore == null || keyStorePassword == null) {
return null;
}
return (PrivateKey)keyStore.getKey(alias, keyStorePassword);
} catch (Exception e) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.ERROR,
() -> "Error accessing private key from KeyStore: " +
e.getMessage());
return null;
}
}
/* Return cached private key */
return privateKeyCache.get(alias);
}
/**
* Clear sensitive data when object is garbage collected
*/
@SuppressWarnings({"deprecation", "removal"})
@Override
protected void finalize() throws Throwable {
try {
/* Clear KeyStore password if present */
if (keyStorePassword != null) {
Arrays.fill(keyStorePassword, (char)0);
}
/* Clear cached private keys */
if (privateKeyCache != null) {
privateKeyCache.clear();
}
/* Free WolfSSLX509 certificates if present */
if (certificateCache != null) {
for (X509Certificate cert : certificateCache.values()) {
if (cert instanceof WolfSSLX509) {
((WolfSSLX509)cert).free();
}
}
certificateCache.clear();
}
/* Free WolfSSLX509 certificate chains if present */
if (certificateChainCache != null) {
for (X509Certificate[] chain : certificateChainCache.values()) {
if (chain != null) {
for (X509Certificate cert : chain) {
if (cert instanceof WolfSSLX509) {
((WolfSSLX509)cert).free();
}
}
}
}
certificateChainCache.clear();
}
if (aliasSet != null) {
aliasSet.clear();
}
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "WolfSSLKeyX509 finalized, sensitive data cleared");
} finally {
super.finalize();
}
}
}