-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathWolfSSLKeyStore.java
More file actions
3475 lines (2995 loc) · 123 KB
/
WolfSSLKeyStore.java
File metadata and controls
3475 lines (2995 loc) · 123 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
/* WolfSSLKeyStore.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.jce;
import java.util.Date;
import java.util.Enumeration;
import java.util.Arrays;
import java.util.Map;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.security.Key;
import java.security.KeyStoreSpi;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.KeyFactory;
import java.security.Security;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.KeyStoreException;
import java.security.NoSuchProviderException;
import java.security.InvalidKeyException;
import java.security.InvalidAlgorithmParameterException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.CertificateException;
import java.security.cert.CertificateEncodingException;
import java.security.MessageDigest;
import java.util.concurrent.ConcurrentHashMap;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.BadPaddingException;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.security.auth.DestroyFailedException;
import com.wolfssl.wolfcrypt.Asn;
import com.wolfssl.wolfcrypt.Aes;
import com.wolfssl.wolfcrypt.Pwdbased;
import com.wolfssl.wolfcrypt.WolfCrypt;
import com.wolfssl.wolfcrypt.WolfSSLCertManager;
import com.wolfssl.wolfcrypt.WolfCryptException;
/**
* wolfSSL KeyStore implementation (WKS).
*
* This KeyStore has been designed to be compatible with wolfCrypt
* FIPS 140-2 and 140-3, using algorithms and modes inside the wolfCrypt FIPS
* module boundary.
*
* Private keys are protected inside this KeyStore implementation using
* PKCS#5 PBKDF2 and AES-CBC with HMAC-SHA512, specifically:
*
* 1. PKCS#5 PBKDF2 derives an encryption key from provided user password
* + Password is converted from char[] to byte[] using UTF-8
* + Salt size = 16 bytes, Iteration count = 210,000
* + Iterations can be customized using wolfjce.wks.iterationCount
* Security property in a java.security file
*
* 2. AES-CBC encrypts the private key using derived password
* + IV length = 16 bytes
* + Key length = 32 bytes (256 bits)
*
* 3. HMAC-SHA512 is calculated over the encrypted key and associated
* parameters (Encrypt-then-MAC).
*
* When this KeyStore is stored (engineStore()), the following format is used.
* There is an HMAC-SHA512 stored at the end which is calculated over the
* entire HEADER + ENTRIES + PBKDF2 SALT LEN/SALT + PBKDF2 iterations, which
* is used to check the KeyStore integrity when loaded back in (engineLoad())
* to detect corrupt or tampered KeyStores.
*
* HEADER:
* magicNumber (int / 7)
* keystoreVersion (int)
* entryCount (int)
* ENTRIES (can be any of below, depending on type)
* [WKSPrivateKey]
* entryId (int / 1)
* alias (UTF String)
* creationDate.getTime() (long)
* kdfSalt.length (int)
* kdfSalt (byte[])
* kdfIterations (int)
* iv.length (int)
* iv (byte[])
* encryptedKey.length (int)
* encryptedKey (byte[])
* chain.length (int)
* FOR EACH CERT:
* chain[i].getType() (UTF String)
* chain[i].getEncoded().length (int)
* chain[i].getEncoced() (byte[])
* hmac.length (int)
* hmac (HMAC-SHA512) (byte[])
* [WKSSecretKey]
* entryId (int / 3)
* alias (UTF String)
* creationDate.getTime() (long)
* key.getAlgorithm() (UTF String)
* kdfSalt.length (int)
* kdfIterations (int)
* kdfSalt (byte[])
* iv.length (int)
* iv (byte[])
* encryptedKey.length (int)
* encryptedKey (byte[])
* hmac.length (int)
* hmac (HMAC-SHA512) (byte[])
* [WKSCertificate]
* entryId (int / 2)
* alias (UTF String)
* creationDate.getTime() (long)
* cert.getType() (UTF String)
* cert.getEncoded().length (int)
* cert.getEncoced() (byte[])
* HMAC PBKDF2 salt length int
* HMAC PBKDF2 salt (byte[])
* HMAC PBKDF2 iterations int
* HMAC length int
* HMAC (HMAC-SHA512) (byte[])
*
* When loading a KeyStore (engineLoad()), the password is optional. If a
* password is provided, we recalculate the HMAC over the input KeyStore and
* check against the HMAC encoded in the KeyStore bytes to detect if the
* stored KeyStore has been tampered with. If a password is not provided,
* the integrity check will be skipped. This is consistent with existing
* (ie: JKS) KeyStore implementation behavior and allows for consistent use of
* system KeyStores (ex: cacerts) where users do not normally have/use the
* password when loading the KeyStore.
*
* Each PrivateKey and SecretKey entry includes a separate HMAC-SHA512.
* That HMAC is loaded together with the entry and verified against the
* provided password when the entry is retrieved by the user. This is
* independent of the entire KeyStore integrity HMAC verification.
*
* KEK Caching for Performance
*
* Repeated calls to {@code getKey()} can be slow due to PBKDF2 key derivation.
* This design is on purpose for security of private keys. An optional KEK
* (Key Encryption Key) cache can be enabled to improve performance by caching
* derived keys in memory.
*
* Security properties controlling KEK caching:
*
* {@code wolfjce.keystore.kekCacheEnabled} - Set to "true" to enable
* caching (default: false/disabled)
*
* {@code wolfjce.keystore.kekCacheTtlSec} - Cache TTL in seconds
* (default: 300 = 5 minutes)
*
* Security Note: Enabling the cache keeps derived keys in memory for the TTL
* duration. Only enable in trusted environments where the performance benefit
* outweighs the increased memory exposure window.
*/
public class WolfSSLKeyStore extends KeyStoreSpi {
/* RNG used for generating random IVs and salts */
private SecureRandom rand = null;
private static final Object randLock = new Object();
/* PBKDF2 parameters:
* [salt]: NIST SP 800-132 recommends salts should be at least 128 bits
* [iterations]: OWASP PBKDF2 guidance recommends 210,000 iterations
* of PBKDF2-HMAC-SHA512. HMAC-SHA512 was chosen since significantly
* fewer iterations are required as compared to HMAC-SHA256 (requires
* 600,000 iterations to match OWASP recommendations). Iterations
* can be customized using Java Security property
* 'wolfjce.wks.iterationCount' in java.security. Minimum iterations
* allowed is 10,000.
* [type]: SHA-512 (WolfCrypt.WC_HASH_TYPE_SHA512) */
private static final int WKS_PBKDF2_SALT_SIZE = 16;
private static final int WKS_PBKDF2_MIN_ITERATIONS = 10000;
private static final int WKS_PBKDF2_DEFAULT_ITERATIONS = 210000;
private static final int WKS_PBKDF2_ITERATION_COUNT;
private static final int WKS_PBKDF2_TYPE = WolfCrypt.WC_HASH_TYPE_SHA512;
/* AES-CBC parameters (bytes) */
private static final int WKS_ENC_IV_LENGTH = 16;
private static final int WKS_ENC_KEY_LENGTH = Aes.KEY_SIZE_256;
/* HMAC parameters:
* 64-bytes (512-bit) to match usage with HMAC-SHA512 */
private static final int WKS_HMAC_KEY_LENGTH = 64;
/* Max cert chain length, used in sanity check when loading a KeyStore.
* Can be customized via 'wolfjce.wks.maxCertChainLength' Java Security
* property in java.security file */
private static final int WKS_DEFAULT_MAX_CHAIN_COUNT = 100;
private static final int WKS_MAX_CHAIN_COUNT;
/* WKS magic number, used when storing KeyStore to OutputStream */
private static final int WKS_MAGIC_NUMBER = 7;
/* WKS KeyStore version (may increment in future if behavior changes) */
private static final int WKS_STORE_VERSION = 1;
/* WKS entry IDs, used when storing/loading KeyStore */
private static final int WKS_ENTRY_ID_PRIVATE_KEY = 1;
private static final int WKS_ENTRY_ID_CERTIFICATE = 2;
private static final int WKS_ENTRY_ID_SECRET_KEY = 3;
/* Security property name to enable KEK cache (disabled by default) */
private static final String KEK_CACHE_ENABLED_PROPERTY =
"wolfjce.keystore.kekCacheEnabled";
/* Security property name for KEK cache TTL in seconds */
private static final String KEK_CACHE_TTL_PROPERTY =
"wolfjce.keystore.kekCacheTtlSec";
/* Default TTL: 5 minutes in milliseconds */
private static final long KEK_CACHE_DEFAULT_TTL_MS = 300000;
/**
* KeyStore entries as ConcurrentHashMap.
* Entry values are objects of one of the following types:
* WKSPrivateKey, WKSCertificate, WKSSecretKey. Keys are Strings which
* represent an alias name.
*/
private ConcurrentHashMap<String, Object> entries =
new ConcurrentHashMap<>();
private enum EntryType {
PRIVATE_KEY, /* WKSPrivateKey */
CERTIFICATE, /* WKSCertificate */
SECRET_KEY /* WKSSecretKey */
};
/**
* Cache for derived KEK keys, keyed by SHA-256(passwordHash + kdfSalt +
* kdfIterations). Used to avoid repeated PBKDF2 derivations for the same
* password/salt combination if enabled via Security property.
*/
private final Map<ByteArrayWrapper, KekCacheEntry> kekCache =
new ConcurrentHashMap<>();
/* Lock for cache operations */
private final Object cacheLock = new Object();
/**
* KEK cache entry holding derived KEK key and metadata.
*/
private static class KekCacheEntry {
byte[] derivedKey; /* cached KEK + HMAC key */
byte[] passHash; /* SHA-256 hash of password */
long expiryTime; /* System.currentTimeMillis() when entry expires */
KekCacheEntry(byte[] derivedKey, byte[] passHash, long expiryTime) {
this.derivedKey = derivedKey.clone();
this.passHash = passHash.clone();
this.expiryTime = expiryTime;
}
synchronized void wipe() {
if (derivedKey != null) {
Arrays.fill(derivedKey, (byte)0);
derivedKey = null;
}
if (passHash != null) {
Arrays.fill(passHash, (byte)0);
passHash = null;
}
expiryTime = 0;
}
}
/**
* Wrapper for byte arrays to use as kekCache map keys.
*/
private static class ByteArrayWrapper {
private final byte[] data;
ByteArrayWrapper(byte[] data) {
this.data = data.clone();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if ((obj == null) || (getClass() != obj.getClass())) {
return false;
}
ByteArrayWrapper that = (ByteArrayWrapper)obj;
return Arrays.equals(data, that.data);
}
@Override
public int hashCode() {
return Arrays.hashCode(data);
}
void wipe() {
if (data != null) {
Arrays.fill(data, (byte)0);
}
}
}
static {
int iCount = WKS_PBKDF2_DEFAULT_ITERATIONS;
int cLength = WKS_DEFAULT_MAX_CHAIN_COUNT;
String iterations = null;
String chainCount = null;
/* Set PBKDF2 iteration count, using default or one set by
* user in 'wolfjce.wks.iterationCount' Security property in
* java.security file */
iterations = Security.getProperty("wolfjce.wks.iterationCount");
if (iterations != null && !iterations.isEmpty()) {
try {
iCount = Integer.parseInt(iterations);
if (iCount < WKS_PBKDF2_MIN_ITERATIONS) {
log("wolfjce.wks.iterationCount (" + iCount + ") lower " +
"than min allowed (" + WKS_PBKDF2_MIN_ITERATIONS +
")");
iCount = WKS_PBKDF2_DEFAULT_ITERATIONS;
}
} catch (NumberFormatException e) {
/* Error parsing property, fall back to default */
log("error parsing wolfjce.wks.iterationCount property, " +
"using default instead");
}
}
log("setting PBKDF2 iterations: " + iCount);
WKS_PBKDF2_ITERATION_COUNT = iCount;
/* Set max certificate chain length limitation, using default or one
* set with `wolfjce.wks.maxCertChainLength` Security property in
* java.security file */
chainCount = Security.getProperty("wolfjce.wks.maxCertChainLength");
if (chainCount != null && !chainCount.isEmpty()) {
try {
cLength = Integer.parseInt(chainCount);
if (cLength <= 0) {
log("wolfjce.wks.maxCertChainLength (" + cLength +
") lower than 0, using default");
cLength = WKS_DEFAULT_MAX_CHAIN_COUNT;
}
} catch (NumberFormatException e) {
/* Error parsing property, fall back to default */
log("error parsing wolfjce.wks.maxCertChainLength property, " +
"using default instead");
}
}
log("setting max cert chain length: " + cLength);
WKS_MAX_CHAIN_COUNT = cLength;
}
/**
* Create new WolfSSLKeyStore object
*/
public WolfSSLKeyStore() {
log("created new KeyStore: type WKS (version: " +
WKS_STORE_VERSION + ")");
}
/**
* Clear all KEK cache entries.
*
* This method removes all cached derived keys. Should be called when:
* - KeyStore instance is no longer needed
* - Want to ensure cached keys are removed from memory
* - Security policy requires explicit cache clearing
*
* The cache will also be cleared automatically when this KeyStore is
* garbage collected. But calling this method explicitly provides
* deterministic cleanup.
*
* This method is safe to call multiple times and has no effect
* if the cache is already empty.
*/
public void clearCache() {
clearKekCache();
}
/**
* Cleanup method to wipe KEK cache when KeyStore is garbage collected.
*/
@SuppressWarnings({"deprecation", "removal"})
@Override
protected void finalize() throws Throwable {
try {
/* Ensure KEK cache is cleared */
clearCache();
} finally {
super.finalize();
}
}
/**
* Native JNI method that calls wolfSSL_X509_check_private_key()
* to confirm that the provided X.509 certificate matches the given
* private key.
*
* @param derCert X.509 certificate encoded as DER byte array
* @param pkcs8PrivKey Private key encoded as PKCS#8 byte array
*
* @return true if matches, otherwise false if no match
*
* @throws WolfCryptException on native wolfSSL error
*/
private native boolean X509CheckPrivateKey(
byte[] derCert, byte[] pkcs8PrivKey) throws WolfCryptException;
/**
* Check if KEK caching is enabled via Security property.
*
* @return true if cache is enabled, false otherwise
*/
private boolean isKekCacheEnabled() {
String enabled = Security.getProperty(KEK_CACHE_ENABLED_PROPERTY);
if (enabled != null && enabled.equalsIgnoreCase("true")) {
return true;
}
return false;
}
/**
* Get KEK cache TTL from Security property, convert to ms and return.
*
* @return TTL in milliseconds
*/
private long getKekCacheTtlMs() {
long ttlSec;
String ttlStr = Security.getProperty(KEK_CACHE_TTL_PROPERTY);
if (ttlStr != null) {
try {
ttlSec = Long.parseLong(ttlStr.trim());
if (ttlSec > 0) {
/* Convert from sec to ms, checking for overflow */
if (ttlSec > Long.MAX_VALUE / 1000) {
/* Overflow would occur, return Long.MAX_VALUE */
return Long.MAX_VALUE;
}
return ttlSec * 1000;
}
} catch (NumberFormatException e) {
log("error parsing " + KEK_CACHE_TTL_PROPERTY +
" property, using default TTL instead");
}
}
return KEK_CACHE_DEFAULT_TTL_MS;
}
/**
* Hash password using SHA-256.
*
* Converts char[] to byte[] without creating an intermediate String.
*
* @param password password to hash
*
* @return SHA-256 hash of password
*
* @throws NoSuchAlgorithmException if SHA-256 not available
*/
private byte[] hashPassword(char[] password)
throws NoSuchAlgorithmException {
byte[] passBytes = null;
ByteBuffer byteBuffer = null;
CharBuffer charBuffer = null;
MessageDigest md = null;
try {
/* Convert char[] to byte[] */
charBuffer = CharBuffer.wrap(password);
byteBuffer = StandardCharsets.UTF_8.encode(charBuffer);
passBytes = new byte[byteBuffer.remaining()];
byteBuffer.get(passBytes);
md = MessageDigest.getInstance("SHA-256");
return md.digest(passBytes);
} finally {
if (passBytes != null) {
Arrays.fill(passBytes, (byte)0);
}
if (byteBuffer != null && byteBuffer.hasArray()) {
Arrays.fill(byteBuffer.array(), (byte)0);
}
}
}
/**
* Generate cache key by hashing: password hash, salt, and iteration count.
*
* Including iteration count ensures entries with different PBKDF2
* iterations have different cache keys, even if they share the same
* password and salt.
*
* @param passwordHash SHA-256 hash of password
* @param kdfSalt PBKDF2 salt from the entry
* @param kdfIterations PBKDF2 iteration count from the entry
*
* @return SHA-256 hash to use as cache key
*
* @throws NoSuchAlgorithmException if SHA-256 not available
*/
private byte[] generateCacheKey(byte[] passwordHash, byte[] kdfSalt,
int kdfIterations) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(passwordHash);
md.update(kdfSalt);
/* Include iteration count as 4 bytes (big-endian) */
md.update((byte)(kdfIterations >> 24));
md.update((byte)(kdfIterations >> 16));
md.update((byte)(kdfIterations >> 8));
md.update((byte)(kdfIterations));
return md.digest();
}
/**
* Retrieve cached derived key for given password, salt, and iterations.
*
* @param password password used for key derivation
* @param kdfSalt PBKDF2 salt from the entry
* @param kdfIterations PBKDF2 iteration count from the entry
*
* @return cached derived key if found and valid, null otherwise
*/
private byte[] getCachedDerivedKey(char[] password, byte[] kdfSalt,
int kdfIterations) {
long now;
byte[] passHash = null;
byte[] cacheKeyBytes = null;
ByteArrayWrapper lookupKey = null;
KekCacheEntry entryValue = null;
/* Return null if caching is disabled */
if (!isKekCacheEnabled()) {
return null;
}
try {
/* Compute password hash and cache key */
passHash = hashPassword(password);
cacheKeyBytes = generateCacheKey(passHash, kdfSalt, kdfIterations);
lookupKey = new ByteArrayWrapper(cacheKeyBytes);
synchronized (cacheLock) {
entryValue = kekCache.get(lookupKey);
if (entryValue != null) {
/* If cache entry expired, remove and return null */
now = System.currentTimeMillis();
if (now >= entryValue.expiryTime) {
/* Wipe both key and value, then remove from cache */
kekCache.computeIfPresent(lookupKey, (key, value) -> {
value.wipe();
key.wipe();
return null; /* Remove entry */
});
log("Cache entry expired, removed from cache");
return null;
}
/* Verify password hash matches */
if (!MessageDigest.isEqual(passHash, entryValue.passHash)) {
/* Password mismatch - don't use cache */
return null;
}
/* Cache hit - return copy of derived key */
log("Using cached PBKDF2 derived key");
return entryValue.derivedKey.clone();
}
}
return null;
} catch (NoSuchAlgorithmException e) {
/* If MessageDigest SHA-256 is not available, return null */
return null;
} finally {
if (passHash != null) {
Arrays.fill(passHash, (byte)0);
}
if (cacheKeyBytes != null) {
Arrays.fill(cacheKeyBytes, (byte)0);
}
if (lookupKey != null) {
lookupKey.wipe();
}
}
}
/**
* Store derived KEK key in cache.
*
* @param password password used for key derivation
* @param kdfSalt PBKDF2 salt from the entry
* @param kdfIterations PBKDF2 iteration count from the entry
* @param derivedKey derived key to cache (KEK + HMAC key)
*/
private void cacheDerivedKey(char[] password, byte[] kdfSalt,
int kdfIterations, byte[] derivedKey) {
long expiryTime, now, ttl;
byte[] passHash = null;
byte[] cacheKeyBytes = null;
KekCacheEntry entry = null;
KekCacheEntry oldEntry = null;
ByteArrayWrapper mapKey = null;
/* Return if cache is disabled */
if (!isKekCacheEnabled()) {
return;
}
try {
/* Compute password hash and cache key */
passHash = hashPassword(password);
cacheKeyBytes = generateCacheKey(passHash, kdfSalt, kdfIterations);
/* Calculate expiry time, checking for overflow */
now = System.currentTimeMillis();
ttl = getKekCacheTtlMs();
if (ttl > Long.MAX_VALUE - now) {
/* Overflow would occur - set to Long.MAX_VALUE */
expiryTime = Long.MAX_VALUE;
} else {
expiryTime = now + ttl;
}
entry = new KekCacheEntry(derivedKey, passHash, expiryTime);
mapKey = new ByteArrayWrapper(cacheKeyBytes);
synchronized (cacheLock) {
/* Check for old entry, remove/wipe if found */
oldEntry = kekCache.get(mapKey);
if (oldEntry != null) {
/* Find and wipe old key, then remove entry */
for (Map.Entry<ByteArrayWrapper, KekCacheEntry> mapEntry :
kekCache.entrySet()) {
if (mapEntry.getKey().equals(mapKey)) {
ByteArrayWrapper oldKey = mapEntry.getKey();
kekCache.remove(oldKey);
oldEntry.wipe();
oldKey.wipe();
break;
}
}
}
/* Insert new entry */
kekCache.put(mapKey, entry);
}
log("Cached PBKDF2 derived key");
} catch (NoSuchAlgorithmException e) {
log("Error caching derived key: SHA-256 not available");
} finally {
if (passHash != null) {
Arrays.fill(passHash, (byte)0);
}
if (cacheKeyBytes != null) {
Arrays.fill(cacheKeyBytes, (byte)0);
}
}
}
/**
* Remove specific cache entry on HMAC verification failure.
*
* @param password password used for key derivation
* @param kdfSalt PBKDF2 salt from the entry
* @param kdfIterations PBKDF2 iteration count from the entry
*/
private void invalidateCacheEntry(char[] password, byte[] kdfSalt,
int kdfIterations) {
byte[] passHash = null;
byte[] cacheKeyBytes = null;
ByteArrayWrapper lookupKey = null;
KekCacheEntry entryValue = null;
/* Do nothing if caching is disabled */
if (!isKekCacheEnabled()) {
return;
}
try {
/* Compute password hash and cache key */
passHash = hashPassword(password);
cacheKeyBytes = generateCacheKey(passHash, kdfSalt, kdfIterations);
lookupKey = new ByteArrayWrapper(cacheKeyBytes);
synchronized (cacheLock) {
entryValue = kekCache.get(lookupKey);
if (entryValue != null) {
/* Wipe both key and value, then remove from cache */
kekCache.computeIfPresent(lookupKey, (key, value) -> {
value.wipe();
key.wipe();
return null; /* Remove entry */
});
log("Invalidated cache entry due to HMAC failure");
}
}
} catch (NoSuchAlgorithmException e) {
log("Error invalidating cache entry: SHA-256 not available");
} finally {
if (passHash != null) {
Arrays.fill(passHash, (byte)0);
}
if (cacheKeyBytes != null) {
Arrays.fill(cacheKeyBytes, (byte)0);
}
if (lookupKey != null) {
lookupKey.wipe();
}
}
}
/**
* Clear all entries from the KEK cache.
*/
private void clearKekCache() {
synchronized (cacheLock) {
int count = kekCache.size();
for (Map.Entry<ByteArrayWrapper, KekCacheEntry> entry :
kekCache.entrySet()) {
entry.getValue().wipe();
entry.getKey().wipe();
}
kekCache.clear();
if (count > 0) {
log("Cleared KEK cache (" + count + " entries wiped)");
}
}
}
/**
* Return entry from internal map that matches alias and type.
*
* @param alias Alias for entry to retrieve
* @param type type of entry that should be returned, either
* EntryType.PRIVATE_KEY, EntryType.CERTIFICATE, or
* EntryType.SECRET_KEY
*
* @return entry Object if found, otherwise null if not found or entry
* for given alias does not match type requested
*/
private Object getEntryFromAlias(String alias, EntryType type) {
Object entry = null;
if (alias == null || alias.isEmpty()) {
return null;
}
entry = entries.get(alias);
if (entry == null) {
return null;
}
switch (type) {
case PRIVATE_KEY:
if (entry instanceof WKSPrivateKey) {
return entry;
}
break;
case CERTIFICATE:
if (entry instanceof WKSCertificate) {
return entry;
}
break;
case SECRET_KEY:
if (entry instanceof WKSSecretKey) {
return entry;
}
break;
default:
break;
}
return null;
}
/**
* Derive encryption and authentication keys from password using PBKDF2.
*
* @param pass password to use for key protection
* @param salt salt for PBKDF2 derivation
* @param iterations iterations for PBKDF2 derivation
* @param kLen key length to generate
*
* @return byte array continaing derived key of specified length
*
* @throws KeyStoreException on error deriving key
*/
private static byte[] deriveKeyFromPassword(char[] pass,
byte[] salt, int iterations, int kLen) throws KeyStoreException {
byte[] kek = null;
if (pass == null || pass.length == 0 || salt == null ||
salt.length == 0 || iterations <= 0 || kLen <= 0) {
throw new KeyStoreException(
"Invalid arguments when deriving key from password");
}
try {
kek = Pwdbased.PBKDF2(
WolfCryptSecretKeyFactory.passwordToByteArray(pass),
salt, iterations, kLen, WKS_PBKDF2_TYPE);
if (kek == null) {
throw new KeyStoreException(
"Error deriving key encryption key with PBKDF2");
}
} catch (WolfCryptException e) {
if (kek != null) {
Arrays.fill(kek, (byte)0);
}
throw new KeyStoreException(e);
}
return kek;
}
/**
* Generate HMAC over data using provided key.
*
* @param key HMAC key to be used
* @param data data to be used as input for HMAC
*
* @return generated HMAC value on success, null on error
*
* @throws KeyStoreException on error generating HMAC
*/
private static byte[] generateHmac(byte[] key, byte[] data)
throws KeyStoreException {
byte[] hmac = null;
SecretKeySpec spec = null;
Mac mac = null;
if (key == null || key.length == 0 ||
data == null || data.length == 0) {
throw new KeyStoreException(
"HMAC key or data null or zero length when generating");
}
try {
mac = Mac.getInstance("HmacSHA512", "wolfJCE");
spec = new SecretKeySpec(key, "SHA512");
/* Generate HMAC-SHA512 */
mac.init(spec);
mac.update(data);
hmac = mac.doFinal();
} catch (NoSuchAlgorithmException e) {
throw new KeyStoreException(
"HmacSHA512 not available in wolfJCE Mac service", e);
} catch (NoSuchProviderException e) {
throw new KeyStoreException(
"WolfSSLKeyStore must currently use wolfJCE for " +
"HmacSHA512", e);
} catch (IllegalStateException e) {
throw new KeyStoreException(
"Error initializing Mac object", e);
} catch (InvalidKeyException e) {
throw new KeyStoreException(
"Invalid SecretKeySpec passed to Mac.init()");
} finally {
if (spec != null) {
try {
spec.destroy();
} catch (DestroyFailedException e) {
log("SecretKeySpec.destroy() failed in generateHmac()");
}
}
}
return hmac;
}
/**
* Encrypt plaintext key using AES-CBC.
*
* AES-CBC encryption uses Cipher.AES/CBC/PKCS5Padding mode.
*
* @param plainKey plaintext key to be encrypted/protected
* @param kek key encryption key, used to encrypt plaintext key
* @param pass password to use for key protection
* @param iv initialization vector (IV) for encryption operation
*
* @return byte array containing encrypted/protected key
*
* @throws KeyStoreException on error encrypting key
*/
private static byte[] encryptKey(byte[] plainKey, byte[] kek,
byte[] iv) throws KeyStoreException {
Cipher enc = null;
SecretKeySpec keySpec = null;
IvParameterSpec ivSpec = null;
byte[] encrypted = null;
if (plainKey == null || plainKey.length == 0 || kek == null ||
kek.length != WKS_ENC_KEY_LENGTH || iv == null ||
iv.length != Aes.BLOCK_SIZE) {
throw new KeyStoreException(
"Invalid arguments not allowed when encrypting key");
}
try {
try {
enc = Cipher.getInstance("AES/CBC/PKCS5Padding", "wolfJCE");
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
throw new KeyStoreException(
"AES/CBC/PKCS5Padding not available in wolfJCE Cipher", e);
} catch (NoSuchProviderException e) {
throw new KeyStoreException(
"WolfSSLKeyStore must currently use wolfJCE for AES", e);
}
keySpec = new SecretKeySpec(kek, "AES");
ivSpec = new IvParameterSpec(iv);
try {
enc.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
} catch (InvalidKeyException e) {
throw new KeyStoreException(
"Invalid AES key used for private key encryption", e);
} catch (InvalidAlgorithmParameterException e) {
throw new KeyStoreException(
"Invalid params used for private key encryption", e);
}