Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/jdk17u
Path: blob/master/src/java.base/macosx/classes/apple/security/KeychainStore.java
67770 views
1
/*
2
* Copyright (c) 2011, 2022, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation. Oracle designates this
8
* particular file as subject to the "Classpath" exception as provided
9
* by Oracle in the LICENSE file that accompanied this code.
10
*
11
* This code is distributed in the hope that it will be useful, but WITHOUT
12
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14
* version 2 for more details (a copy is included in the LICENSE file that
15
* accompanied this code).
16
*
17
* You should have received a copy of the GNU General Public License version
18
* 2 along with this work; if not, write to the Free Software Foundation,
19
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20
*
21
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22
* or visit www.oracle.com if you need additional information or have any
23
* questions.
24
*/
25
26
package apple.security;
27
28
import java.io.*;
29
import java.security.*;
30
import java.security.cert.*;
31
import java.security.cert.Certificate;
32
import java.security.spec.*;
33
import java.util.*;
34
35
import javax.crypto.*;
36
import javax.crypto.spec.*;
37
import javax.security.auth.x500.*;
38
39
import sun.security.pkcs.*;
40
import sun.security.pkcs.EncryptedPrivateKeyInfo;
41
import sun.security.util.*;
42
import sun.security.x509.*;
43
44
/**
45
* This class provides the keystore implementation referred to as "KeychainStore".
46
* It uses the current user's keychain as its backing storage, and does NOT support
47
* a file-based implementation.
48
*/
49
50
public final class KeychainStore extends KeyStoreSpi {
51
52
// Private keys and their supporting certificate chains
53
// If a key came from the keychain it has a SecKeyRef and one or more
54
// SecCertificateRef. When we delete the key we have to delete all of the corresponding
55
// native objects.
56
static class KeyEntry {
57
Date date; // the creation date of this entry
58
byte[] protectedPrivKey;
59
char[] password;
60
long keyRef; // SecKeyRef for this key
61
Certificate chain[];
62
long chainRefs[]; // SecCertificateRefs for this key's chain.
63
};
64
65
// Trusted certificates
66
static class TrustedCertEntry {
67
Date date; // the creation date of this entry
68
69
Certificate cert;
70
long certRef; // SecCertificateRef for this key
71
72
// Each KeyStore.TrustedCertificateEntry have 2 attributes:
73
// 1. "trustSettings" -> trustSettings.toString()
74
// 2. "2.16.840.1.113894.746875.1.1" -> trustedKeyUsageValue
75
// The 1st one is mainly for debugging use. The 2nd one is similar
76
// to the attribute with the same key in a PKCS12KeyStore.
77
78
// The SecTrustSettingsCopyTrustSettings() output for this certificate
79
// inside the KeyChain in its original array of CFDictionaryRef objects
80
// structure with values dumped as strings. For each trust, an extra
81
// entry "SecPolicyOid" is added whose value is the OID for this trust.
82
// The extra entries are used to construct trustedKeyUsageValue.
83
List<Map<String, String>> trustSettings;
84
85
// One or more OIDs defined in http://oidref.com/1.2.840.113635.100.1.
86
// It can also be "2.5.29.37.0" for a self-signed certificate with
87
// an empty trust settings. This value is never empty. When there are
88
// multiple OID values, it takes the form of "[1.1.1, 1.1.2]".
89
String trustedKeyUsageValue;
90
};
91
92
/**
93
* Entries that have been deleted. When something calls engineStore we'll
94
* remove them from the keychain.
95
*/
96
private Hashtable<String, Object> deletedEntries = new Hashtable<>();
97
98
/**
99
* Entries that have been added. When something calls engineStore we'll
100
* add them to the keychain.
101
*/
102
private Hashtable<String, Object> addedEntries = new Hashtable<>();
103
104
/**
105
* Private keys and certificates are stored in a hashtable.
106
* Hash entries are keyed by alias names.
107
*/
108
private Hashtable<String, Object> entries = new Hashtable<>();
109
110
/**
111
* Algorithm identifiers and corresponding OIDs for the contents of the
112
* PKCS12 bag we get from the Keychain.
113
*/
114
private static ObjectIdentifier PKCS8ShroudedKeyBag_OID =
115
ObjectIdentifier.of(KnownOIDs.PKCS8ShroudedKeyBag);
116
private static ObjectIdentifier pbeWithSHAAnd3KeyTripleDESCBC_OID =
117
ObjectIdentifier.of(KnownOIDs.PBEWithSHA1AndDESede);
118
119
/**
120
* Constnats used in PBE decryption.
121
*/
122
private static final int iterationCount = 1024;
123
private static final int SALT_LEN = 20;
124
125
private static final Debug debug = Debug.getInstance("keystore");
126
127
static {
128
jdk.internal.loader.BootLoader.loadLibrary("osxsecurity");
129
}
130
131
private static void permissionCheck() {
132
@SuppressWarnings("removal")
133
SecurityManager sec = System.getSecurityManager();
134
135
if (sec != null) {
136
sec.checkPermission(new RuntimePermission("useKeychainStore"));
137
}
138
}
139
140
141
/**
142
* Verify the Apple provider in the constructor.
143
*
144
* @exception SecurityException if fails to verify
145
* its own integrity
146
*/
147
public KeychainStore() { }
148
149
/**
150
* Returns the key associated with the given alias, using the given
151
* password to recover it.
152
*
153
* @param alias the alias name
154
* @param password the password for recovering the key. This password is
155
* used internally as the key is exported in a PKCS12 format.
156
*
157
* @return the requested key, or null if the given alias does not exist
158
* or does not identify a <i>key entry</i>.
159
*
160
* @exception NoSuchAlgorithmException if the algorithm for recovering the
161
* key cannot be found
162
* @exception UnrecoverableKeyException if the key cannot be recovered
163
* (e.g., the given password is wrong).
164
*/
165
public Key engineGetKey(String alias, char[] password)
166
throws NoSuchAlgorithmException, UnrecoverableKeyException
167
{
168
permissionCheck();
169
170
// An empty password is rejected by MacOS API, no private key data
171
// is exported. If no password is passed (as is the case when
172
// this implementation is used as browser keystore in various
173
// deployment scenarios like Webstart, JFX and applets), create
174
// a dummy password so MacOS API is happy.
175
if (password == null || password.length == 0) {
176
// Must not be a char array with only a 0, as this is an empty
177
// string.
178
if (random == null) {
179
random = new SecureRandom();
180
}
181
password = Long.toString(random.nextLong()).toCharArray();
182
}
183
184
Object entry = entries.get(alias.toLowerCase());
185
186
if (entry == null || !(entry instanceof KeyEntry)) {
187
return null;
188
}
189
190
// This call gives us a PKCS12 bag, with the key inside it.
191
byte[] exportedKeyInfo = _getEncodedKeyData(((KeyEntry)entry).keyRef, password);
192
if (exportedKeyInfo == null) {
193
return null;
194
}
195
196
PrivateKey returnValue = null;
197
198
try {
199
byte[] pkcs8KeyData = fetchPrivateKeyFromBag(exportedKeyInfo);
200
byte[] encryptedKey;
201
AlgorithmParameters algParams;
202
ObjectIdentifier algOid;
203
try {
204
// get the encrypted private key
205
EncryptedPrivateKeyInfo encrInfo = new EncryptedPrivateKeyInfo(pkcs8KeyData);
206
encryptedKey = encrInfo.getEncryptedData();
207
208
// parse Algorithm parameters
209
DerValue val = new DerValue(encrInfo.getAlgorithm().encode());
210
DerInputStream in = val.toDerInputStream();
211
algOid = in.getOID();
212
algParams = parseAlgParameters(in);
213
214
} catch (IOException ioe) {
215
UnrecoverableKeyException uke =
216
new UnrecoverableKeyException("Private key not stored as "
217
+ "PKCS#8 EncryptedPrivateKeyInfo: " + ioe);
218
uke.initCause(ioe);
219
throw uke;
220
}
221
222
// Use JCE to decrypt the data using the supplied password.
223
SecretKey skey = getPBEKey(password);
224
Cipher cipher = Cipher.getInstance(algOid.toString());
225
cipher.init(Cipher.DECRYPT_MODE, skey, algParams);
226
byte[] decryptedPrivateKey = cipher.doFinal(encryptedKey);
227
PKCS8EncodedKeySpec kspec = new PKCS8EncodedKeySpec(decryptedPrivateKey);
228
229
// Parse the key algorithm and then use a JCA key factory to create the private key.
230
DerValue val = new DerValue(decryptedPrivateKey);
231
DerInputStream in = val.toDerInputStream();
232
233
// Ignore this -- version should be 0.
234
int i = in.getInteger();
235
236
// Get the Algorithm ID next
237
DerValue[] value = in.getSequence(2);
238
if (value.length < 1 || value.length > 2) {
239
throw new IOException("Invalid length for AlgorithmIdentifier");
240
}
241
AlgorithmId algId = new AlgorithmId(value[0].getOID());
242
String algName = algId.getName();
243
244
// Get a key factory for this algorithm. It's likely to be 'RSA'.
245
KeyFactory kfac = KeyFactory.getInstance(algName);
246
returnValue = kfac.generatePrivate(kspec);
247
} catch (Exception e) {
248
UnrecoverableKeyException uke =
249
new UnrecoverableKeyException("Get Key failed: " +
250
e.getMessage());
251
uke.initCause(e);
252
throw uke;
253
}
254
255
return returnValue;
256
}
257
258
private native byte[] _getEncodedKeyData(long secKeyRef, char[] password);
259
260
/**
261
* Returns the certificate chain associated with the given alias.
262
*
263
* @param alias the alias name
264
*
265
* @return the certificate chain (ordered with the user's certificate first
266
* and the root certificate authority last), or null if the given alias
267
* does not exist or does not contain a certificate chain (i.e., the given
268
* alias identifies either a <i>trusted certificate entry</i> or a
269
* <i>key entry</i> without a certificate chain).
270
*/
271
public Certificate[] engineGetCertificateChain(String alias) {
272
permissionCheck();
273
274
Object entry = entries.get(alias.toLowerCase());
275
276
if (entry != null && entry instanceof KeyEntry) {
277
if (((KeyEntry)entry).chain == null) {
278
return null;
279
} else {
280
return ((KeyEntry)entry).chain.clone();
281
}
282
} else {
283
return null;
284
}
285
}
286
287
/**
288
* Returns the certificate associated with the given alias.
289
*
290
* <p>If the given alias name identifies a
291
* <i>trusted certificate entry</i>, the certificate associated with that
292
* entry is returned. If the given alias name identifies a
293
* <i>key entry</i>, the first element of the certificate chain of that
294
* entry is returned, or null if that entry does not have a certificate
295
* chain.
296
*
297
* @param alias the alias name
298
*
299
* @return the certificate, or null if the given alias does not exist or
300
* does not contain a certificate.
301
*/
302
public Certificate engineGetCertificate(String alias) {
303
permissionCheck();
304
305
Object entry = entries.get(alias.toLowerCase());
306
307
if (entry != null) {
308
if (entry instanceof TrustedCertEntry) {
309
return ((TrustedCertEntry)entry).cert;
310
} else {
311
KeyEntry ke = (KeyEntry)entry;
312
if (ke.chain == null || ke.chain.length == 0) {
313
return null;
314
}
315
return ke.chain[0];
316
}
317
} else {
318
return null;
319
}
320
}
321
322
private record LocalAttr(String name, String value)
323
implements KeyStore.Entry.Attribute {
324
325
@Override
326
public String getName() {
327
return name;
328
}
329
330
@Override
331
public String getValue() {
332
return value;
333
}
334
}
335
336
@Override
337
public KeyStore.Entry engineGetEntry(String alias, KeyStore.ProtectionParameter protParam)
338
throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException {
339
if (engineIsCertificateEntry(alias)) {
340
Object entry = entries.get(alias.toLowerCase());
341
if (entry instanceof TrustedCertEntry tEntry) {
342
return new KeyStore.TrustedCertificateEntry(
343
tEntry.cert, Set.of(
344
new LocalAttr(KnownOIDs.ORACLE_TrustedKeyUsage.value(), tEntry.trustedKeyUsageValue),
345
new LocalAttr("trustSettings", tEntry.trustSettings.toString())));
346
}
347
}
348
return super.engineGetEntry(alias, protParam);
349
}
350
351
/**
352
* Returns the creation date of the entry identified by the given alias.
353
*
354
* @param alias the alias name
355
*
356
* @return the creation date of this entry, or null if the given alias does
357
* not exist
358
*/
359
public Date engineGetCreationDate(String alias) {
360
permissionCheck();
361
362
Object entry = entries.get(alias.toLowerCase());
363
364
if (entry != null) {
365
if (entry instanceof TrustedCertEntry) {
366
return new Date(((TrustedCertEntry)entry).date.getTime());
367
} else {
368
return new Date(((KeyEntry)entry).date.getTime());
369
}
370
} else {
371
return null;
372
}
373
}
374
375
/**
376
* Assigns the given key to the given alias, protecting it with the given
377
* password.
378
*
379
* <p>If the given key is of type <code>java.security.PrivateKey</code>,
380
* it must be accompanied by a certificate chain certifying the
381
* corresponding public key.
382
*
383
* <p>If the given alias already exists, the keystore information
384
* associated with it is overridden by the given key (and possibly
385
* certificate chain).
386
*
387
* @param alias the alias name
388
* @param key the key to be associated with the alias
389
* @param password the password to protect the key
390
* @param chain the certificate chain for the corresponding public
391
* key (only required if the given key is of type
392
* <code>java.security.PrivateKey</code>).
393
*
394
* @exception KeyStoreException if the given key cannot be protected, or
395
* this operation fails for some other reason
396
*/
397
public void engineSetKeyEntry(String alias, Key key, char[] password,
398
Certificate[] chain)
399
throws KeyStoreException
400
{
401
permissionCheck();
402
403
synchronized(entries) {
404
try {
405
KeyEntry entry = new KeyEntry();
406
entry.date = new Date();
407
408
if (key instanceof PrivateKey) {
409
if ((key.getFormat().equals("PKCS#8")) ||
410
(key.getFormat().equals("PKCS8"))) {
411
entry.protectedPrivKey = encryptPrivateKey(key.getEncoded(), password);
412
entry.password = password.clone();
413
} else {
414
throw new KeyStoreException("Private key is not encoded as PKCS#8");
415
}
416
} else {
417
throw new KeyStoreException("Key is not a PrivateKey");
418
}
419
420
// clone the chain
421
if (chain != null) {
422
if ((chain.length > 1) && !validateChain(chain)) {
423
throw new KeyStoreException("Certificate chain does not validate");
424
}
425
426
entry.chain = chain.clone();
427
entry.chainRefs = new long[entry.chain.length];
428
}
429
430
String lowerAlias = alias.toLowerCase();
431
if (entries.get(lowerAlias) != null) {
432
deletedEntries.put(lowerAlias, entries.get(lowerAlias));
433
}
434
435
entries.put(lowerAlias, entry);
436
addedEntries.put(lowerAlias, entry);
437
} catch (Exception nsae) {
438
KeyStoreException ke = new KeyStoreException("Key protection algorithm not found: " + nsae);
439
ke.initCause(nsae);
440
throw ke;
441
}
442
}
443
}
444
445
/**
446
* Assigns the given key (that has already been protected) to the given
447
* alias.
448
*
449
* <p>If the protected key is of type
450
* <code>java.security.PrivateKey</code>, it must be accompanied by a
451
* certificate chain certifying the corresponding public key. If the
452
* underlying keystore implementation is of type <code>jks</code>,
453
* <code>key</code> must be encoded as an
454
* <code>EncryptedPrivateKeyInfo</code> as defined in the PKCS #8 standard.
455
*
456
* <p>If the given alias already exists, the keystore information
457
* associated with it is overridden by the given key (and possibly
458
* certificate chain).
459
*
460
* @param alias the alias name
461
* @param key the key (in protected format) to be associated with the alias
462
* @param chain the certificate chain for the corresponding public
463
* key (only useful if the protected key is of type
464
* <code>java.security.PrivateKey</code>).
465
*
466
* @exception KeyStoreException if this operation fails.
467
*/
468
public void engineSetKeyEntry(String alias, byte[] key,
469
Certificate[] chain)
470
throws KeyStoreException
471
{
472
permissionCheck();
473
474
synchronized(entries) {
475
// key must be encoded as EncryptedPrivateKeyInfo as defined in
476
// PKCS#8
477
KeyEntry entry = new KeyEntry();
478
try {
479
EncryptedPrivateKeyInfo privateKey = new EncryptedPrivateKeyInfo(key);
480
entry.protectedPrivKey = privateKey.getEncoded();
481
} catch (IOException ioe) {
482
throw new KeyStoreException("key is not encoded as "
483
+ "EncryptedPrivateKeyInfo");
484
}
485
486
entry.date = new Date();
487
488
if ((chain != null) &&
489
(chain.length != 0)) {
490
entry.chain = chain.clone();
491
entry.chainRefs = new long[entry.chain.length];
492
}
493
494
String lowerAlias = alias.toLowerCase();
495
if (entries.get(lowerAlias) != null) {
496
deletedEntries.put(lowerAlias, entries.get(alias));
497
}
498
entries.put(lowerAlias, entry);
499
addedEntries.put(lowerAlias, entry);
500
}
501
}
502
503
/**
504
* Adding trusted certificate entry is not supported.
505
*/
506
public void engineSetCertificateEntry(String alias, Certificate cert)
507
throws KeyStoreException {
508
throw new KeyStoreException("Cannot set trusted certificate entry." +
509
" Use the macOS \"security add-trusted-cert\" command instead.");
510
}
511
512
/**
513
* Deletes the entry identified by the given alias from this keystore.
514
*
515
* @param alias the alias name
516
*
517
* @exception KeyStoreException if the entry cannot be removed.
518
*/
519
public void engineDeleteEntry(String alias)
520
throws KeyStoreException
521
{
522
permissionCheck();
523
524
synchronized(entries) {
525
Object entry = entries.remove(alias.toLowerCase());
526
deletedEntries.put(alias.toLowerCase(), entry);
527
}
528
}
529
530
/**
531
* Lists all the alias names of this keystore.
532
*
533
* @return enumeration of the alias names
534
*/
535
public Enumeration<String> engineAliases() {
536
permissionCheck();
537
return entries.keys();
538
}
539
540
/**
541
* Checks if the given alias exists in this keystore.
542
*
543
* @param alias the alias name
544
*
545
* @return true if the alias exists, false otherwise
546
*/
547
public boolean engineContainsAlias(String alias) {
548
permissionCheck();
549
return entries.containsKey(alias.toLowerCase());
550
}
551
552
/**
553
* Retrieves the number of entries in this keystore.
554
*
555
* @return the number of entries in this keystore
556
*/
557
public int engineSize() {
558
permissionCheck();
559
return entries.size();
560
}
561
562
/**
563
* Returns true if the entry identified by the given alias is a
564
* <i>key entry</i>, and false otherwise.
565
*
566
* @return true if the entry identified by the given alias is a
567
* <i>key entry</i>, false otherwise.
568
*/
569
public boolean engineIsKeyEntry(String alias) {
570
permissionCheck();
571
Object entry = entries.get(alias.toLowerCase());
572
if ((entry != null) && (entry instanceof KeyEntry)) {
573
return true;
574
} else {
575
return false;
576
}
577
}
578
579
/**
580
* Returns true if the entry identified by the given alias is a
581
* <i>trusted certificate entry</i>, and false otherwise.
582
*
583
* @return true if the entry identified by the given alias is a
584
* <i>trusted certificate entry</i>, false otherwise.
585
*/
586
public boolean engineIsCertificateEntry(String alias) {
587
permissionCheck();
588
Object entry = entries.get(alias.toLowerCase());
589
if ((entry != null) && (entry instanceof TrustedCertEntry)) {
590
return true;
591
} else {
592
return false;
593
}
594
}
595
596
/**
597
* Returns the (alias) name of the first keystore entry whose certificate
598
* matches the given certificate.
599
*
600
* <p>This method attempts to match the given certificate with each
601
* keystore entry. If the entry being considered
602
* is a <i>trusted certificate entry</i>, the given certificate is
603
* compared to that entry's certificate. If the entry being considered is
604
* a <i>key entry</i>, the given certificate is compared to the first
605
* element of that entry's certificate chain (if a chain exists).
606
*
607
* @param cert the certificate to match with.
608
*
609
* @return the (alias) name of the first entry with matching certificate,
610
* or null if no such entry exists in this keystore.
611
*/
612
public String engineGetCertificateAlias(Certificate cert) {
613
permissionCheck();
614
Certificate certElem;
615
616
for (Enumeration<String> e = entries.keys(); e.hasMoreElements(); ) {
617
String alias = e.nextElement();
618
Object entry = entries.get(alias);
619
if (entry instanceof TrustedCertEntry) {
620
certElem = ((TrustedCertEntry)entry).cert;
621
} else {
622
KeyEntry ke = (KeyEntry)entry;
623
if (ke.chain == null || ke.chain.length == 0) {
624
continue;
625
}
626
certElem = ke.chain[0];
627
}
628
if (certElem.equals(cert)) {
629
return alias;
630
}
631
}
632
return null;
633
}
634
635
/**
636
* Stores this keystore to the given output stream, and protects its
637
* integrity with the given password.
638
*
639
* @param stream Ignored. the output stream to which this keystore is written.
640
* @param password the password to generate the keystore integrity check
641
*
642
* @exception IOException if there was an I/O problem with data
643
* @exception NoSuchAlgorithmException if the appropriate data integrity
644
* algorithm could not be found
645
* @exception CertificateException if any of the certificates included in
646
* the keystore data could not be stored
647
*/
648
public void engineStore(OutputStream stream, char[] password)
649
throws IOException, NoSuchAlgorithmException, CertificateException
650
{
651
permissionCheck();
652
653
// Delete items that do have a keychain item ref.
654
for (Enumeration<String> e = deletedEntries.keys(); e.hasMoreElements(); ) {
655
String alias = e.nextElement();
656
Object entry = deletedEntries.get(alias);
657
if (entry instanceof TrustedCertEntry) {
658
if (((TrustedCertEntry)entry).certRef != 0) {
659
_removeItemFromKeychain(((TrustedCertEntry)entry).certRef);
660
_releaseKeychainItemRef(((TrustedCertEntry)entry).certRef);
661
}
662
} else {
663
Certificate certElem;
664
KeyEntry keyEntry = (KeyEntry)entry;
665
666
if (keyEntry.chain != null) {
667
for (int i = 0; i < keyEntry.chain.length; i++) {
668
if (keyEntry.chainRefs[i] != 0) {
669
_removeItemFromKeychain(keyEntry.chainRefs[i]);
670
_releaseKeychainItemRef(keyEntry.chainRefs[i]);
671
}
672
}
673
674
if (keyEntry.keyRef != 0) {
675
_removeItemFromKeychain(keyEntry.keyRef);
676
_releaseKeychainItemRef(keyEntry.keyRef);
677
}
678
}
679
}
680
}
681
682
// Add all of the certs or keys in the added entries.
683
// No need to check for 0 refs, as they are in the added list.
684
for (Enumeration<String> e = addedEntries.keys(); e.hasMoreElements(); ) {
685
String alias = e.nextElement();
686
Object entry = addedEntries.get(alias);
687
if (entry instanceof TrustedCertEntry) {
688
// Cannot set trusted certificate entry
689
} else {
690
KeyEntry keyEntry = (KeyEntry)entry;
691
692
if (keyEntry.chain != null) {
693
for (int i = 0; i < keyEntry.chain.length; i++) {
694
keyEntry.chainRefs[i] = addCertificateToKeychain(alias, keyEntry.chain[i]);
695
}
696
697
keyEntry.keyRef = _addItemToKeychain(alias, false, keyEntry.protectedPrivKey, keyEntry.password);
698
}
699
}
700
}
701
702
// Clear the added and deletedEntries hashtables here, now that we're done with the updates.
703
// For the deleted entries, we freed up the native references above.
704
deletedEntries.clear();
705
addedEntries.clear();
706
}
707
708
private long addCertificateToKeychain(String alias, Certificate cert) {
709
byte[] certblob = null;
710
long returnValue = 0;
711
712
try {
713
certblob = cert.getEncoded();
714
returnValue = _addItemToKeychain(alias, true, certblob, null);
715
} catch (Exception e) {
716
e.printStackTrace();
717
}
718
719
return returnValue;
720
}
721
722
private native long _addItemToKeychain(String alias, boolean isCertificate, byte[] datablob, char[] password);
723
private native int _removeItemFromKeychain(long certRef);
724
private native void _releaseKeychainItemRef(long keychainItemRef);
725
726
/**
727
* Loads the keystore from the Keychain.
728
*
729
* @param stream Ignored - here for API compatibility.
730
* @param password Ignored - if user needs to unlock keychain Security
731
* framework will post any dialogs.
732
*
733
* @exception IOException if there is an I/O or format problem with the
734
* keystore data
735
* @exception NoSuchAlgorithmException if the algorithm used to check
736
* the integrity of the keystore cannot be found
737
* @exception CertificateException if any of the certificates in the
738
* keystore could not be loaded
739
*/
740
public void engineLoad(InputStream stream, char[] password)
741
throws IOException, NoSuchAlgorithmException, CertificateException
742
{
743
permissionCheck();
744
745
// Release any stray keychain references before clearing out the entries.
746
synchronized(entries) {
747
for (Enumeration<String> e = entries.keys(); e.hasMoreElements(); ) {
748
String alias = e.nextElement();
749
Object entry = entries.get(alias);
750
if (entry instanceof TrustedCertEntry) {
751
if (((TrustedCertEntry)entry).certRef != 0) {
752
_releaseKeychainItemRef(((TrustedCertEntry)entry).certRef);
753
}
754
} else {
755
KeyEntry keyEntry = (KeyEntry)entry;
756
757
if (keyEntry.chain != null) {
758
for (int i = 0; i < keyEntry.chain.length; i++) {
759
if (keyEntry.chainRefs[i] != 0) {
760
_releaseKeychainItemRef(keyEntry.chainRefs[i]);
761
}
762
}
763
764
if (keyEntry.keyRef != 0) {
765
_releaseKeychainItemRef(keyEntry.keyRef);
766
}
767
}
768
}
769
}
770
771
entries.clear();
772
_scanKeychain();
773
if (debug != null) {
774
debug.println("KeychainStore load entry count: " +
775
entries.size());
776
}
777
}
778
}
779
780
private native void _scanKeychain();
781
782
/**
783
* Callback method from _scanKeychain. If a trusted certificate is found,
784
* this method will be called.
785
*
786
* inputTrust is a list of strings in groups. Each group contains key/value
787
* pairs for one trust setting and ends with a null. Thus the size of the
788
* whole list is (2 * s_1 + 1) + (2 * s_2 + 1) + ... + (2 * s_n + 1),
789
* where s_i is the size of mapping for the i'th trust setting,
790
* and n is the number of trust settings. Ex:
791
*
792
* key1 for trust1
793
* value1 for trust1
794
* ..
795
* null (end of trust1)
796
* key1 for trust2
797
* value1 for trust2
798
* ...
799
* null (end of trust2)
800
* ...
801
* null (end if trust_n)
802
*/
803
private void createTrustedCertEntry(String alias, List<String> inputTrust,
804
long keychainItemRef, long creationDate, byte[] derStream) {
805
TrustedCertEntry tce = new TrustedCertEntry();
806
807
try {
808
CertificateFactory cf = CertificateFactory.getInstance("X.509");
809
InputStream input = new ByteArrayInputStream(derStream);
810
X509Certificate cert = (X509Certificate) cf.generateCertificate(input);
811
input.close();
812
tce.cert = cert;
813
tce.certRef = keychainItemRef;
814
815
tce.trustSettings = new ArrayList<>();
816
Map<String,String> tmpMap = new LinkedHashMap<>();
817
for (int i = 0; i < inputTrust.size(); i++) {
818
if (inputTrust.get(i) == null) {
819
tce.trustSettings.add(tmpMap);
820
if (i < inputTrust.size() - 1) {
821
// Prepare an empty map for the next trust setting.
822
// Do not just clear(), must be a new object.
823
// Only create if not at end of list.
824
tmpMap = new LinkedHashMap<>();
825
}
826
} else {
827
tmpMap.put(inputTrust.get(i), inputTrust.get(i+1));
828
i++;
829
}
830
}
831
832
boolean isSelfSigned;
833
try {
834
cert.verify(cert.getPublicKey());
835
isSelfSigned = true;
836
} catch (Exception e) {
837
isSelfSigned = false;
838
}
839
if (tce.trustSettings.isEmpty()) {
840
if (isSelfSigned) {
841
// If a self-signed certificate has an empty trust settings,
842
// trust it for all purposes
843
tce.trustedKeyUsageValue = KnownOIDs.anyExtendedKeyUsage.value();
844
} else {
845
// Otherwise, return immediately. The certificate is not
846
// added into entries.
847
return;
848
}
849
} else {
850
List<String> values = new ArrayList<>();
851
for (var oneTrust : tce.trustSettings) {
852
var result = oneTrust.get("kSecTrustSettingsResult");
853
// https://developer.apple.com/documentation/security/sectrustsettingsresult?language=objc
854
// 1 = kSecTrustSettingsResultTrustRoot, 2 = kSecTrustSettingsResultTrustAsRoot
855
// If missing, a default value of kSecTrustSettingsResultTrustRoot is assumed
856
// for self-signed certificates (see doc for SecTrustSettingsCopyTrustSettings).
857
// Note that the same SecPolicyOid can appear in multiple trust settings
858
// for different kSecTrustSettingsAllowedError and/or kSecTrustSettingsPolicyString.
859
if ((result == null && isSelfSigned)
860
|| "1".equals(result) || "2".equals(result)) {
861
// When no kSecTrustSettingsPolicy, it means everything
862
String oid = oneTrust.getOrDefault("SecPolicyOid",
863
KnownOIDs.anyExtendedKeyUsage.value());
864
if (!values.contains(oid)) {
865
values.add(oid);
866
}
867
}
868
}
869
if (values.isEmpty()) {
870
return;
871
}
872
if (values.size() == 1) {
873
tce.trustedKeyUsageValue = values.get(0);
874
} else {
875
tce.trustedKeyUsageValue = values.toString();
876
}
877
}
878
// Make a creation date.
879
if (creationDate != 0)
880
tce.date = new Date(creationDate);
881
else
882
tce.date = new Date();
883
884
int uniqueVal = 1;
885
String originalAlias = alias;
886
887
while (entries.containsKey(alias.toLowerCase())) {
888
alias = originalAlias + " " + uniqueVal;
889
uniqueVal++;
890
}
891
892
entries.put(alias.toLowerCase(), tce);
893
} catch (Exception e) {
894
// The certificate will be skipped.
895
System.err.println("KeychainStore Ignored Exception: " + e);
896
}
897
}
898
899
/**
900
* Callback method from _scanKeychain. If an identity is found, this method will be called to create Java certificate
901
* and private key objects from the keychain data.
902
*/
903
private void createKeyEntry(String alias, long creationDate, long secKeyRef,
904
long[] secCertificateRefs, byte[][] rawCertData) {
905
KeyEntry ke = new KeyEntry();
906
907
// First, store off the private key information. This is the easy part.
908
ke.protectedPrivKey = null;
909
ke.keyRef = secKeyRef;
910
911
// Make a creation date.
912
if (creationDate != 0)
913
ke.date = new Date(creationDate);
914
else
915
ke.date = new Date();
916
917
// Next, create X.509 Certificate objects from the raw data. This is complicated
918
// because a certificate's public key may be too long for Java's default encryption strength.
919
List<CertKeychainItemPair> createdCerts = new ArrayList<>();
920
921
try {
922
CertificateFactory cf = CertificateFactory.getInstance("X.509");
923
924
for (int i = 0; i < rawCertData.length; i++) {
925
try {
926
InputStream input = new ByteArrayInputStream(rawCertData[i]);
927
X509Certificate cert = (X509Certificate) cf.generateCertificate(input);
928
input.close();
929
930
// We successfully created the certificate, so track it and its corresponding SecCertificateRef.
931
createdCerts.add(new CertKeychainItemPair(secCertificateRefs[i], cert));
932
} catch (CertificateException e) {
933
// The certificate will be skipped.
934
System.err.println("KeychainStore Ignored Exception: " + e);
935
}
936
}
937
} catch (CertificateException e) {
938
e.printStackTrace();
939
} catch (IOException ioe) {
940
ioe.printStackTrace(); // How would this happen?
941
}
942
943
// We have our certificates in the List, so now extract them into an array of
944
// Certificates and SecCertificateRefs.
945
CertKeychainItemPair[] objArray = createdCerts.toArray(new CertKeychainItemPair[0]);
946
Certificate[] certArray = new Certificate[objArray.length];
947
long[] certRefArray = new long[objArray.length];
948
949
for (int i = 0; i < objArray.length; i++) {
950
CertKeychainItemPair addedItem = objArray[i];
951
certArray[i] = addedItem.mCert;
952
certRefArray[i] = addedItem.mCertificateRef;
953
}
954
955
ke.chain = certArray;
956
ke.chainRefs = certRefArray;
957
958
// If we don't have already have an item with this item's alias
959
// create a new one for it.
960
int uniqueVal = 1;
961
String originalAlias = alias;
962
963
while (entries.containsKey(alias.toLowerCase())) {
964
alias = originalAlias + " " + uniqueVal;
965
uniqueVal++;
966
}
967
968
entries.put(alias.toLowerCase(), ke);
969
}
970
971
private static class CertKeychainItemPair {
972
long mCertificateRef;
973
Certificate mCert;
974
975
CertKeychainItemPair(long inCertRef, Certificate cert) {
976
mCertificateRef = inCertRef;
977
mCert = cert;
978
}
979
}
980
981
/*
982
* Validate Certificate Chain
983
*/
984
private boolean validateChain(Certificate[] certChain)
985
{
986
for (int i = 0; i < certChain.length-1; i++) {
987
X500Principal issuerDN =
988
((X509Certificate)certChain[i]).getIssuerX500Principal();
989
X500Principal subjectDN =
990
((X509Certificate)certChain[i+1]).getSubjectX500Principal();
991
if (!(issuerDN.equals(subjectDN)))
992
return false;
993
}
994
return true;
995
}
996
997
private byte[] fetchPrivateKeyFromBag(byte[] privateKeyInfo) throws IOException, NoSuchAlgorithmException, CertificateException
998
{
999
byte[] returnValue = null;
1000
DerValue val = new DerValue(new ByteArrayInputStream(privateKeyInfo));
1001
DerInputStream s = val.toDerInputStream();
1002
int version = s.getInteger();
1003
1004
if (version != 3) {
1005
throw new IOException("PKCS12 keystore not in version 3 format");
1006
}
1007
1008
/*
1009
* Read the authSafe.
1010
*/
1011
byte[] authSafeData;
1012
ContentInfo authSafe = new ContentInfo(s);
1013
ObjectIdentifier contentType = authSafe.getContentType();
1014
1015
if (contentType.equals(ContentInfo.DATA_OID)) {
1016
authSafeData = authSafe.getData();
1017
} else /* signed data */ {
1018
throw new IOException("public key protected PKCS12 not supported");
1019
}
1020
1021
DerInputStream as = new DerInputStream(authSafeData);
1022
DerValue[] safeContentsArray = as.getSequence(2);
1023
int count = safeContentsArray.length;
1024
1025
/*
1026
* Spin over the ContentInfos.
1027
*/
1028
for (int i = 0; i < count; i++) {
1029
byte[] safeContentsData;
1030
ContentInfo safeContents;
1031
DerInputStream sci;
1032
byte[] eAlgId = null;
1033
1034
sci = new DerInputStream(safeContentsArray[i].toByteArray());
1035
safeContents = new ContentInfo(sci);
1036
contentType = safeContents.getContentType();
1037
safeContentsData = null;
1038
1039
if (contentType.equals(ContentInfo.DATA_OID)) {
1040
safeContentsData = safeContents.getData();
1041
} else if (contentType.equals(ContentInfo.ENCRYPTED_DATA_OID)) {
1042
// The password was used to export the private key from the keychain.
1043
// The Keychain won't export the key with encrypted data, so we don't need
1044
// to worry about it.
1045
continue;
1046
} else {
1047
throw new IOException("public key protected PKCS12" +
1048
" not supported");
1049
}
1050
DerInputStream sc = new DerInputStream(safeContentsData);
1051
returnValue = extractKeyData(sc);
1052
}
1053
1054
return returnValue;
1055
}
1056
1057
private byte[] extractKeyData(DerInputStream stream)
1058
throws IOException, NoSuchAlgorithmException, CertificateException
1059
{
1060
byte[] returnValue = null;
1061
DerValue[] safeBags = stream.getSequence(2);
1062
int count = safeBags.length;
1063
1064
/*
1065
* Spin over the SafeBags.
1066
*/
1067
for (int i = 0; i < count; i++) {
1068
ObjectIdentifier bagId;
1069
DerInputStream sbi;
1070
DerValue bagValue;
1071
Object bagItem = null;
1072
1073
sbi = safeBags[i].toDerInputStream();
1074
bagId = sbi.getOID();
1075
bagValue = sbi.getDerValue();
1076
if (!bagValue.isContextSpecific((byte)0)) {
1077
throw new IOException("unsupported PKCS12 bag value type "
1078
+ bagValue.tag);
1079
}
1080
bagValue = bagValue.data.getDerValue();
1081
if (bagId.equals(PKCS8ShroudedKeyBag_OID)) {
1082
// got what we were looking for. Return it.
1083
returnValue = bagValue.toByteArray();
1084
} else {
1085
// log error message for "unsupported PKCS12 bag type"
1086
System.out.println("Unsupported bag type '" + bagId + "'");
1087
}
1088
}
1089
1090
return returnValue;
1091
}
1092
1093
/*
1094
* Generate PBE Algorithm Parameters
1095
*/
1096
private AlgorithmParameters getAlgorithmParameters(String algorithm)
1097
throws IOException
1098
{
1099
AlgorithmParameters algParams = null;
1100
1101
// create PBE parameters from salt and iteration count
1102
PBEParameterSpec paramSpec =
1103
new PBEParameterSpec(getSalt(), iterationCount);
1104
try {
1105
algParams = AlgorithmParameters.getInstance(algorithm);
1106
algParams.init(paramSpec);
1107
} catch (Exception e) {
1108
IOException ioe =
1109
new IOException("getAlgorithmParameters failed: " +
1110
e.getMessage());
1111
ioe.initCause(e);
1112
throw ioe;
1113
}
1114
return algParams;
1115
}
1116
1117
// the source of randomness
1118
private SecureRandom random;
1119
1120
/*
1121
* Generate random salt
1122
*/
1123
private byte[] getSalt()
1124
{
1125
// Generate a random salt.
1126
byte[] salt = new byte[SALT_LEN];
1127
if (random == null) {
1128
random = new SecureRandom();
1129
}
1130
random.nextBytes(salt);
1131
return salt;
1132
}
1133
1134
/*
1135
* parse Algorithm Parameters
1136
*/
1137
private AlgorithmParameters parseAlgParameters(DerInputStream in)
1138
throws IOException
1139
{
1140
AlgorithmParameters algParams = null;
1141
try {
1142
DerValue params;
1143
if (in.available() == 0) {
1144
params = null;
1145
} else {
1146
params = in.getDerValue();
1147
if (params.tag == DerValue.tag_Null) {
1148
params = null;
1149
}
1150
}
1151
if (params != null) {
1152
algParams = AlgorithmParameters.getInstance("PBE");
1153
algParams.init(params.toByteArray());
1154
}
1155
} catch (Exception e) {
1156
IOException ioe =
1157
new IOException("parseAlgParameters failed: " +
1158
e.getMessage());
1159
ioe.initCause(e);
1160
throw ioe;
1161
}
1162
return algParams;
1163
}
1164
1165
/*
1166
* Generate PBE key
1167
*/
1168
private SecretKey getPBEKey(char[] password) throws IOException
1169
{
1170
SecretKey skey = null;
1171
1172
try {
1173
PBEKeySpec keySpec = new PBEKeySpec(password);
1174
SecretKeyFactory skFac = SecretKeyFactory.getInstance("PBE");
1175
skey = skFac.generateSecret(keySpec);
1176
} catch (Exception e) {
1177
IOException ioe = new IOException("getSecretKey failed: " +
1178
e.getMessage());
1179
ioe.initCause(e);
1180
throw ioe;
1181
}
1182
return skey;
1183
}
1184
1185
/*
1186
* Encrypt private key using Password-based encryption (PBE)
1187
* as defined in PKCS#5.
1188
*
1189
* NOTE: Currently pbeWithSHAAnd3-KeyTripleDES-CBC algorithmID is
1190
* used to derive the key and IV.
1191
*
1192
* @return encrypted private key encoded as EncryptedPrivateKeyInfo
1193
*/
1194
private byte[] encryptPrivateKey(byte[] data, char[] password)
1195
throws IOException, NoSuchAlgorithmException, UnrecoverableKeyException
1196
{
1197
byte[] key = null;
1198
1199
try {
1200
// create AlgorithmParameters
1201
AlgorithmParameters algParams =
1202
getAlgorithmParameters("PBEWithSHA1AndDESede");
1203
1204
// Use JCE
1205
SecretKey skey = getPBEKey(password);
1206
Cipher cipher = Cipher.getInstance("PBEWithSHA1AndDESede");
1207
cipher.init(Cipher.ENCRYPT_MODE, skey, algParams);
1208
byte[] encryptedKey = cipher.doFinal(data);
1209
1210
// wrap encrypted private key in EncryptedPrivateKeyInfo
1211
// as defined in PKCS#8
1212
AlgorithmId algid =
1213
new AlgorithmId(pbeWithSHAAnd3KeyTripleDESCBC_OID, algParams);
1214
EncryptedPrivateKeyInfo encrInfo =
1215
new EncryptedPrivateKeyInfo(algid, encryptedKey);
1216
key = encrInfo.getEncoded();
1217
} catch (Exception e) {
1218
UnrecoverableKeyException uke =
1219
new UnrecoverableKeyException("Encrypt Private Key failed: "
1220
+ e.getMessage());
1221
uke.initCause(e);
1222
throw uke;
1223
}
1224
1225
return key;
1226
}
1227
1228
1229
}
1230
1231
1232