/
SecKey.m
1809 lines (1602 loc) · 76.9 KB
/
SecKey.m
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
/*
* Copyright (c) 2006-2015 Apple Inc. All Rights Reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
/*
* SecKey.m - CoreFoundation based key object
*/
#include <AssertMacros.h>
#include <Security/SecBase.h>
#include <Security/SecKeyInternal.h>
#include <Security/SecItem.h>
#include <Security/SecItemPriv.h>
#include <Security/SecItemShim.h>
#include <Security/SecFramework.h>
#include <Security/SecCertificate.h>
#include <utilities/SecIOFormat.h>
#include <utilities/SecCFWrappers.h>
#include <utilities/array_size.h>
#include <Security/SecKeyPriv.h>
#include "SecRSAKeyPriv.h"
#include "SecECKeyPriv.h"
#include "SecCTKKeyPriv.h"
#include <Security/SecBasePriv.h>
#include <CoreFoundation/CFNumber.h>
#include <CoreFoundation/CFString.h>
#include <CoreFoundation/CFPriv.h>
#include <string.h>
#include <utilities/debugging.h>
#include <utilities/SecCFError.h>
#include <CommonCrypto/CommonDigest.h>
#include <Security/SecAsn1Coder.h>
#include <Security/oidsalg.h>
#include <Security/SecInternal.h>
#include <Security/SecCFAllocator.h>
#include <Security/SecRandom.h>
#include <Security/SecureTransport.h> /* For error codes. */
#include <corecrypto/ccrng.h>
#include <corecrypto/ccsha1.h>
#include <corecrypto/ccsha2.h>
#include <stdlib.h>
#include <os/lock.h>
#include <os/log.h>
#include <libDER/asn1Types.h>
#include <libDER/DER_Keys.h>
#include <libDER/DER_Encode.h>
static os_log_t _SECKEY_LOG(void) {
static dispatch_once_t once;
static os_log_t log;
dispatch_once(&once, ^{ log = os_log_create("com.apple.security", "seckey"); });
return log;
};
#define SECKEY_LOG _SECKEY_LOG()
CFDataRef SecKeyCopyPublicKeyHash(SecKeyRef key)
{
CFDataRef pubKeyDigest = NULL, pubKeyBlob = NULL;
/* encode the public key. */
require_noerr_quiet(SecKeyCopyPublicBytes(key, &pubKeyBlob), errOut);
require_quiet(pubKeyBlob, errOut);
/* Calculate the digest of the public key. */
require_quiet(pubKeyDigest = SecSHA1DigestCreate(CFGetAllocator(key),
CFDataGetBytePtr(pubKeyBlob), CFDataGetLength(pubKeyBlob)),
errOut);
errOut:
CFReleaseNull(pubKeyBlob);
return pubKeyDigest;
}
/*
*/
static CFDictionaryRef SecKeyCopyAttributeDictionaryWithLocalKey(SecKeyRef key,
CFTypeRef keyType,
CFDataRef privateBlob)
{
CFAllocatorRef allocator = CFGetAllocator(key);
DICT_DECLARE(25);
CFDataRef pubKeyDigest = NULL, pubKeyBlob = NULL;
CFDictionaryRef dict = NULL;
size_t sizeValue = SecKeyGetSize(key, kSecKeyKeySizeInBits);
CFNumberRef sizeInBits = CFNumberCreate(allocator, kCFNumberLongType, &sizeValue);
/* encode the public key. */
require_noerr_quiet(SecKeyCopyPublicBytes(key, &pubKeyBlob), errOut);
require_quiet(pubKeyBlob, errOut);
/* Calculate the digest of the public key. */
require_quiet(pubKeyDigest = SecSHA1DigestCreate(allocator,
CFDataGetBytePtr(pubKeyBlob), CFDataGetLength(pubKeyBlob)),
errOut);
DICT_ADDPAIR(kSecClass, kSecClassKey);
DICT_ADDPAIR(kSecAttrKeyClass, privateBlob ? kSecAttrKeyClassPrivate : kSecAttrKeyClassPublic);
DICT_ADDPAIR(kSecAttrApplicationLabel, pubKeyDigest);
DICT_ADDPAIR(kSecAttrIsPermanent, kCFBooleanTrue);
DICT_ADDPAIR(kSecAttrIsPrivate, kCFBooleanTrue);
DICT_ADDPAIR(kSecAttrIsModifiable, kCFBooleanTrue);
DICT_ADDPAIR(kSecAttrKeyType, keyType);
DICT_ADDPAIR(kSecAttrKeySizeInBits, sizeInBits);
DICT_ADDPAIR(kSecAttrEffectiveKeySize, sizeInBits);
DICT_ADDPAIR(kSecAttrIsSensitive, kCFBooleanFalse);
DICT_ADDPAIR(kSecAttrWasAlwaysSensitive, kCFBooleanFalse);
DICT_ADDPAIR(kSecAttrIsExtractable, kCFBooleanTrue);
DICT_ADDPAIR(kSecAttrWasNeverExtractable, kCFBooleanFalse);
DICT_ADDPAIR(kSecAttrCanEncrypt, privateBlob ? kCFBooleanFalse : kCFBooleanTrue);
DICT_ADDPAIR(kSecAttrCanDecrypt, privateBlob ? kCFBooleanTrue : kCFBooleanFalse);
DICT_ADDPAIR(kSecAttrCanDerive, kCFBooleanTrue);
DICT_ADDPAIR(kSecAttrCanSign, privateBlob ? kCFBooleanTrue : kCFBooleanFalse);
DICT_ADDPAIR(kSecAttrCanVerify, privateBlob ? kCFBooleanFalse : kCFBooleanTrue);
DICT_ADDPAIR(kSecAttrCanSignRecover, kCFBooleanFalse);
DICT_ADDPAIR(kSecAttrCanVerifyRecover, kCFBooleanFalse);
DICT_ADDPAIR(kSecAttrCanWrap, privateBlob ? kCFBooleanFalse : kCFBooleanTrue);
DICT_ADDPAIR(kSecAttrCanUnwrap, privateBlob ? kCFBooleanTrue : kCFBooleanFalse);
DICT_ADDPAIR(kSecValueData, privateBlob ? privateBlob : pubKeyBlob);
dict = CFDictionaryCreate(allocator, keys, values, numValues, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
errOut:
// @@@ Zero out key material.
CFReleaseSafe(pubKeyDigest);
CFReleaseSafe(pubKeyBlob);
CFReleaseSafe(sizeInBits);
return dict;
}
CFDictionaryRef SecKeyGeneratePrivateAttributeDictionary(SecKeyRef key,
CFTypeRef keyType,
CFDataRef privateBlob)
{
return SecKeyCopyAttributeDictionaryWithLocalKey(key, keyType, privateBlob);
}
CFDictionaryRef SecKeyGeneratePublicAttributeDictionary(SecKeyRef key, CFTypeRef keyType)
{
return SecKeyCopyAttributeDictionaryWithLocalKey(key, keyType, NULL);
}
static CFStringRef SecKeyCopyDescription(CFTypeRef cf) {
SecKeyRef key = (SecKeyRef)cf;
if(key->key_class->describe)
return key->key_class->describe(key);
else
return CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("<SecKeyRef: %p>"), key);
}
#if TARGET_OS_OSX
static CFMutableDictionaryRef auxilliaryCDSAKeyMap;
static struct os_unfair_lock_s auxilliaryCDSAKeyMapLock = OS_UNFAIR_LOCK_INIT;
static void SecKeyDestroyAuxilliaryCDSAKeyForKey(CFTypeRef cf) {
CFTypeRef keyToDestroy = NULL;
os_unfair_lock_lock(&auxilliaryCDSAKeyMapLock);
if (auxilliaryCDSAKeyMap != NULL) {
keyToDestroy = CFDictionaryGetValue(auxilliaryCDSAKeyMap, cf);
if (keyToDestroy != NULL) {
CFRetain(keyToDestroy);
CFDictionaryRemoveValue(auxilliaryCDSAKeyMap, cf);
}
}
os_unfair_lock_unlock(&auxilliaryCDSAKeyMapLock);
// Actual aux key destruction is performed outside unfair lock to avoid recursive lock.
if (keyToDestroy != NULL) {
CFRelease(keyToDestroy);
}
}
void SecKeySetAuxilliaryCDSAKeyForKey(SecKeyRef cf, SecKeyRef auxKey) {
os_unfair_lock_lock(&auxilliaryCDSAKeyMapLock);
if (auxilliaryCDSAKeyMap == NULL) {
// Allocate map with weak (unretained) keys (which are source SecKeys) but strong values (which are held aux CDSA keys).
auxilliaryCDSAKeyMap = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, NULL, &kCFTypeDictionaryValueCallBacks);
}
CFDictionarySetValue(auxilliaryCDSAKeyMap, cf, auxKey);
os_unfair_lock_unlock(&auxilliaryCDSAKeyMapLock);
}
SecKeyRef SecKeyCopyAuxilliaryCDSAKeyForKey(SecKeyRef cf) {
os_unfair_lock_lock(&auxilliaryCDSAKeyMapLock);
if (auxilliaryCDSAKeyMap == NULL) {
os_unfair_lock_unlock(&auxilliaryCDSAKeyMapLock);
return NULL;
}
SecKeyRef result = (SecKeyRef)CFRetainSafe(CFDictionaryGetValue(auxilliaryCDSAKeyMap, cf));
os_unfair_lock_unlock(&auxilliaryCDSAKeyMapLock);
return result;
}
#endif
static void SecKeyDestroy(CFTypeRef cf) {
SecKeyRef key = (SecKeyRef)cf;
#if TARGET_OS_OSX
SecKeyDestroyAuxilliaryCDSAKeyForKey(cf);
#endif
if (key->key_class->destroy)
key->key_class->destroy(key);
}
static Boolean SecKeyEqual(CFTypeRef cf1, CFTypeRef cf2)
{
SecKeyRef key1 = (SecKeyRef)cf1;
SecKeyRef key2 = (SecKeyRef)cf2;
if (key1 == key2)
return true;
if (!key2 || key1->key_class != key2->key_class)
return false;
if (key1->key_class->version >= 4 && key1->key_class->isEqual)
return key1->key_class->isEqual(key1, key2);
if (key1->key_class->extraBytes)
return !memcmp(key1->key, key2->key, key1->key_class->extraBytes);
/* TODO: Won't work when we get reference keys. */
CFDictionaryRef d1, d2;
d1 = SecKeyCopyAttributeDictionary(key1);
d2 = SecKeyCopyAttributeDictionary(key2);
// Returning NULL is an error; bail out of the equality check
if(!d1 || !d2) {
CFReleaseSafe(d1);
CFReleaseSafe(d2);
return false;
}
Boolean result = CFEqual(d1, d2);
CFReleaseSafe(d1);
CFReleaseSafe(d2);
return result;
}
struct ccrng_state *ccrng_seckey(void)
{
return ccrng(NULL);
}
CFGiblisWithFunctions(SecKey, NULL, NULL, SecKeyDestroy, SecKeyEqual, NULL, NULL, SecKeyCopyDescription, NULL, NULL, NULL)
static bool getBoolForKey(CFDictionaryRef dict, CFStringRef key, bool default_value) {
CFTypeRef value = CFDictionaryGetValue(dict, key);
if (value) {
if (CFGetTypeID(value) == CFBooleanGetTypeID()) {
return CFBooleanGetValue(value);
} else {
os_log_error(SECKEY_LOG, "Value %{public}@ for key %{public}@ is not bool", value, key);
}
}
return default_value;
}
static OSStatus add_key(SecKeyRef key, CFMutableDictionaryRef dict) {
CFDictionarySetValue(dict, kSecValueRef, key);
CFDictionaryRef keyAttributes = SecKeyCopyAttributes(key);
if (keyAttributes != NULL && CFDictionaryContainsKey(keyAttributes, kSecAttrAccessControl)) {
// Avoid overriding ACL from the key with source ACL of the call; ACL of the key might be already processed during key generation and should be preferred to source unprocessed ACL.
CFDictionaryRemoveValue(dict, kSecAttrAccessControl);
}
CFReleaseNull(keyAttributes);
return SecItemAdd(dict, NULL);
}
static void merge_params_applier(const void *key, const void *value,
void *context) {
CFMutableDictionaryRef result = (CFMutableDictionaryRef)context;
CFDictionaryAddValue(result, key, value);
}
/* Create a mutable dictionary that is based on the subdictionary for key
with any attributes from the top level dict merged in. */
static CF_RETURNS_RETAINED CFMutableDictionaryRef merge_params(CFDictionaryRef dict,
CFStringRef key) {
CFDictionaryRef subdict = CFDictionaryGetValue(dict, key);
CFMutableDictionaryRef result;
if (subdict) {
result = CFDictionaryCreateMutableCopy(NULL, 0, subdict);
/* Add everything in dict not already in result to result. */
CFDictionaryApplyFunction(dict, merge_params_applier, result);
} else {
result = CFDictionaryCreateMutableCopy(NULL, 0, dict);
}
/* Remove values that only belong in the top level dict. */
CFDictionaryRemoveValue(result, kSecPublicKeyAttrs);
CFDictionaryRemoveValue(result, kSecPrivateKeyAttrs);
CFDictionaryRemoveValue(result, kSecAttrKeyType);
CFDictionaryRemoveValue(result, kSecAttrKeySizeInBits);
return result;
}
static inline void SecKeyCheck(SecKeyRef key, const char *callerName) {
if (key == NULL) {
os_log_fault(SECKEY_LOG, "%{public}s called with NULL SecKeyRef", callerName);
[NSException raise:NSInvalidArgumentException format:@"%s called with NULL SecKeyRef", callerName];
}
}
CFIndex SecKeyGetAlgorithmId(SecKeyRef key) {
SecKeyCheck(key, __func__);
if (!key->key_class) {
// TBD: somehow, a key can be created with a NULL key_class in the
// SecCertificateCopyPublicKey -> SecKeyCreatePublicFromDER code path
os_log_fault(SECKEY_LOG, "Key with NULL class detected!");
return kSecNullAlgorithmID;
}
/* This method was added to version 1 keys. */
if (key->key_class->version > 0 && key->key_class->getAlgorithmID) {
return key->key_class->getAlgorithmID(key);
}
/* All version 0 keys were RSA. */
return kSecRSAAlgorithmID;
}
/* Generate a private/public keypair. */
OSStatus SecKeyGeneratePair(CFDictionaryRef parameters,
SecKeyRef *publicKey, SecKeyRef *privateKey) {
@autoreleasepool {
OSStatus result = errSecUnsupportedAlgorithm;
SecKeyRef privKey = NULL;
SecKeyRef pubKey = NULL;
CFMutableDictionaryRef pubParams = merge_params(parameters, kSecPublicKeyAttrs),
privParams = merge_params(parameters, kSecPrivateKeyAttrs);
CFStringRef ktype = CFDictionaryGetValue(parameters, kSecAttrKeyType);
CFStringRef tokenID = CFDictionaryGetValue(parameters, kSecAttrTokenID);
require_quiet(ktype, errOut);
if (tokenID != NULL) {
result = SecCTKKeyGeneratePair(parameters, &pubKey, &privKey);
} else if (CFEqual(ktype, kSecAttrKeyTypeECSECPrimeRandom)) {
result = SecECKeyGeneratePair(parameters, &pubKey, &privKey);
} else if (CFEqual(ktype, kSecAttrKeyTypeRSA)) {
result = SecRSAKeyGeneratePair(parameters, &pubKey, &privKey);
}
require_noerr_quiet(result, errOut);
// Store the keys in the keychain if they are marked as permanent. Governed by kSecAttrIsPermanent attribute, with default
// to 'false' (ephemeral keys), except private token-based keys, in which case the default is 'true' (permanent keys).
if (getBoolForKey(pubParams, kSecAttrIsPermanent, false)) {
CFDictionaryRemoveValue(pubParams, kSecAttrTokenID);
require_noerr_quiet(result = add_key(pubKey, pubParams), errOut);
}
if (getBoolForKey(privParams, kSecAttrIsPermanent, CFDictionaryContainsKey(privParams, kSecAttrTokenID))) {
require_noerr_quiet(result = add_key(privKey, privParams), errOut);
}
if (publicKey) {
*publicKey = pubKey;
pubKey = NULL;
}
if (privateKey) {
*privateKey = privKey;
privKey = NULL;
}
errOut:
CFReleaseSafe(pubParams);
CFReleaseSafe(privParams);
CFReleaseSafe(pubKey);
CFReleaseSafe(privKey);
if (result != errSecSuccess) {
os_log_debug(SECKEY_LOG, "SecKeyGeneratePair() failed, error %d", (int)result);
}
return result;
}
}
SecKeyRef SecKeyCreatePublicFromPrivate(SecKeyRef privateKey) {
return SecKeyCopyPublicKey(privateKey);
}
CFDictionaryRef CreatePrivateKeyMatchingQuery(SecKeyRef publicKey, bool returnPersistentRef)
{
const CFTypeRef refType = (returnPersistentRef) ? kSecReturnPersistentRef: kSecReturnRef;
CFDataRef public_key_hash = SecKeyCopyPublicKeyHash(publicKey);
CFDictionaryRef query = CFDictionaryCreateForCFTypes(kCFAllocatorDefault,
kSecClass, kSecClassKey,
kSecAttrKeyClass, kSecAttrKeyClassPrivate,
kSecAttrSynchronizable, kSecAttrSynchronizableAny,
kSecAttrApplicationLabel, public_key_hash,
refType, kCFBooleanTrue,
NULL);
CFReleaseNull(public_key_hash);
return query;
}
CFDataRef SecKeyCreatePersistentRefToMatchingPrivateKey(SecKeyRef publicKey, CFErrorRef *error) {
CFTypeRef persistentRef = NULL;
CFDictionaryRef query = CreatePrivateKeyMatchingQuery(publicKey, true);
require_quiet(SecError(SecItemCopyMatching(query, &persistentRef),error ,
CFSTR("Error finding persistent ref to key from public: %@"), publicKey), fail);
fail:
CFReleaseNull(query);
return (CFDataRef)persistentRef;
}
SecKeyRef SecKeyCopyMatchingPrivateKey(SecKeyRef publicKey, CFErrorRef *error) {
SecKeyRef privateKey = NULL;
CFTypeRef queryResult = NULL;
CFDictionaryRef query = NULL;
require_action_quiet(publicKey != NULL, errOut, SecError(errSecParam, error, CFSTR("Null Public Key")));
query = CreatePrivateKeyMatchingQuery(publicKey, false);
require_quiet(SecError(SecItemCopyMatching(query, &queryResult), error,
CFSTR("Error finding private key from public: %@"), publicKey), errOut);
if (CFGetTypeID(queryResult) == SecKeyGetTypeID()) {
privateKey = (SecKeyRef) queryResult;
queryResult = NULL;
}
errOut:
CFReleaseNull(query);
CFReleaseNull(queryResult);
return privateKey;
}
OSStatus SecKeyGetMatchingPrivateKeyStatus(SecKeyRef publicKey, CFErrorRef *error) {
OSStatus retval = errSecParam;
CFTypeRef private_key = NULL;
CFDictionaryRef query = NULL;
require_action_quiet(publicKey != NULL, errOut, SecError(errSecParam, error, NULL, CFSTR("Null Public Key")));
query = CreatePrivateKeyMatchingQuery(publicKey, false);
retval = SecItemCopyMatching(query, &private_key);
if (!retval && CFGetTypeID(private_key) != SecKeyGetTypeID()) {
retval = errSecInternalComponent;
}
errOut:
CFReleaseNull(query);
CFReleaseNull(private_key);
return retval;
}
SecKeyRef SecKeyCreatePublicFromDER(CFAllocatorRef allocator,
const SecAsn1Oid *oid, const SecAsn1Item *params,
const SecAsn1Item *keyData) {
SecKeyRef publicKey = NULL;
if (SecAsn1OidCompare(oid, &CSSMOID_RSA)) {
/* pkcs1 1 */
/* Note that we call SecKeyCreateRSAPublicKey_ios directly instead of
SecKeyCreateRSAPublicKey, since on OS X the latter function will return
a CSSM SecKeyRef, and we always want an iOS format SecKeyRef here.
*/
publicKey = SecKeyCreateRSAPublicKey_ios(allocator,
keyData->Data, keyData->Length, kSecKeyEncodingPkcs1);
} else if (SecAsn1OidCompare(oid, &CSSMOID_ecPublicKey)) {
SecDERKey derKey = {
.oid = oid->Data,
.oidLength = oid->Length,
.key = keyData->Data,
.keyLength = keyData->Length,
};
if (params) {
derKey.parameters = params->Data;
derKey.parametersLength = params->Length;
}
publicKey = SecKeyCreateECPublicKey(allocator,
(const uint8_t *)&derKey, sizeof(derKey), kSecDERKeyEncoding);
} else {
os_log_debug(SECKEY_LOG, "Unsupported algorithm oid");
}
return publicKey;
}
SecKeyRef SecKeyCreateFromSubjectPublicKeyInfoData(CFAllocatorRef allocator, CFDataRef subjectPublicKeyInfoData)
{
DERReturn drtn;
DERItem subjectPublicKeyInfoDER = {
.data = (uint8_t *)CFDataGetBytePtr(subjectPublicKeyInfoData),
.length = (DERSize)CFDataGetLength(subjectPublicKeyInfoData),
};
DERSubjPubKeyInfo subjectPublicKeyInfo;
DERAlgorithmId algorithmId;
DERItem pubKeyBytes;
drtn = DERParseSequence(&subjectPublicKeyInfoDER,
DERNumSubjPubKeyInfoItemSpecs, DERSubjPubKeyInfoItemSpecs,
&subjectPublicKeyInfo, sizeof(subjectPublicKeyInfo));
require_noerr_quiet(drtn, out);
drtn = DERParseSequenceContent(&subjectPublicKeyInfo.algId,
DERNumAlgorithmIdItemSpecs, DERAlgorithmIdItemSpecs,
&algorithmId, sizeof(algorithmId));
require_noerr_quiet(drtn, out);
DERByte unusedBits;
drtn = DERParseBitString(&subjectPublicKeyInfo.pubKey, &pubKeyBytes, &unusedBits);
require_noerr_quiet(drtn, out);
/* Convert DERItem to SecAsn1Item : */
const SecAsn1Oid oid = { .Data = algorithmId.oid.data, .Length = algorithmId.oid.length };
const SecAsn1Item params = { .Data = algorithmId.params.data, .Length = algorithmId.params.length };
const SecAsn1Item pubKey = { .Data = pubKeyBytes.data, .Length = pubKeyBytes.length };
return SecKeyCreatePublicFromDER(allocator, &oid, ¶ms, &pubKey);
out:
return NULL;
}
static const DERByte oidRSA[] = {
0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00,
};
static const DERByte oidECsecp256[] = {
0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07,
};
static const DERByte oidECsecp384[] = {
0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x22,
};
static const DERByte oidECsecp521[] = {
0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x23,
};
CFDataRef SecKeyCopySubjectPublicKeyInfo(SecKeyRef key)
{
CFMutableDataRef data = NULL;
CFDataRef publicKey = NULL;
CFDataRef dataret = NULL;
DERSubjPubKeyInfo spki;
DERReturn drtn;
size_t zeroPad = 0;
memset(&spki, 0, sizeof(spki));
/* encode the public key. */
require_noerr_quiet(SecKeyCopyPublicBytes(key, &publicKey), errOut);
require_quiet(publicKey, errOut);
require_quiet(CFDataGetLength(publicKey) != 0, errOut);
// Add prefix 00 is needed to avoid creating negative bit strings
if (((uint8_t *)CFDataGetBytePtr(publicKey))[0] & 0x80)
zeroPad = 1;
CFMutableDataRef paddedKey = CFDataCreateMutable(NULL, 0);
/* the bit strings bits used field first */
CFDataAppendBytes(paddedKey, (const UInt8 *)"\x00", 1);
if (zeroPad)
CFDataAppendBytes(paddedKey, (const UInt8 *)"\x00", 1);
CFDataAppendBytes(paddedKey, CFDataGetBytePtr(publicKey), CFDataGetLength(publicKey));
CFTransferRetained(publicKey, paddedKey);
spki.pubKey.data = (DERByte *)CFDataGetBytePtr(publicKey);
spki.pubKey.length = CFDataGetLength(publicKey);
// Encode algId according to algorithm used.
CFIndex algorithm = SecKeyGetAlgorithmId(key);
if (algorithm == kSecRSAAlgorithmID) {
spki.algId.data = (DERByte *)oidRSA;
spki.algId.length = sizeof(oidRSA);
} else if (algorithm == kSecECDSAAlgorithmID) {
SecECNamedCurve curve = SecECKeyGetNamedCurve(key);
switch(curve) {
case kSecECCurveSecp256r1:
spki.algId.data = (DERByte *)oidECsecp256;
spki.algId.length = sizeof(oidECsecp256);
break;
case kSecECCurveSecp384r1:
spki.algId.data = (DERByte *)oidECsecp384;
spki.algId.length = sizeof(oidECsecp384);
break;
case kSecECCurveSecp521r1:
spki.algId.data = (DERByte *)oidECsecp521;
spki.algId.length = sizeof(oidECsecp521);
break;
default:
goto errOut;
}
} else {
goto errOut;
}
DERSize size = DERLengthOfEncodedSequence(ASN1_CONSTR_SEQUENCE, &spki,
DERNumSubjPubKeyInfoItemSpecs, DERSubjPubKeyInfoItemSpecs);
data = CFDataCreateMutable(kCFAllocatorDefault, size);
CFDataSetLength(data, size);
drtn = DEREncodeSequence(ASN1_CONSTR_SEQUENCE, &spki,
DERNumSubjPubKeyInfoItemSpecs,
DERSubjPubKeyInfoItemSpecs,
CFDataGetMutableBytePtr(data), &size);
require_quiet(drtn == DR_Success, errOut);
CFDataSetLength(data, size);
dataret = CFRetain(data);
errOut:
CFReleaseNull(data);
CFReleaseNull(publicKey);
return dataret;
}
SecKeyRef SecKeyCreate(CFAllocatorRef allocator,
const SecKeyDescriptor *key_class, const uint8_t *keyData,
CFIndex keyDataLength, SecKeyEncoding encoding) {
if (key_class == NULL) {
[NSException raise:NSInvalidArgumentException format:@"Attempting to create SecKeyRef with NULL key_class"];
}
size_t size = sizeof(struct __SecKey) + key_class->extraBytes;
SecKeyRef result = (SecKeyRef)_CFRuntimeCreateInstance(allocator,
SecKeyGetTypeID(), size - sizeof(CFRuntimeBase), NULL);
if (result) {
memset((char*)result + sizeof(result->_base), 0, size - sizeof(result->_base));
result->key_class = key_class;
if (key_class->extraBytes) {
/* Make result->key point to the extraBytes we allocated. */
result->key = ((char*)result) + sizeof(*result);
}
if (key_class->init) {
OSStatus status;
status = key_class->init(result, keyData, keyDataLength, encoding);
if (status) {
os_log_error(SECKEY_LOG, "SecKeyCreate init(%{public}s) failed: %d", key_class->name, (int)status);
CFRelease(result);
result = NULL;
}
}
}
return result;
}
// Generic wrapper helper for invoking new-style CFDataRef-based operations with ptr/length arguments
// used by legacy RawSign-style functions.
static OSStatus SecKeyPerformLegacyOperation(SecKeyRef key,
const uint8_t *in1Ptr, size_t in1Len,
const uint8_t *in2Ptr, size_t in2Len,
uint8_t *outPtr, size_t *outLen,
CFTypeRef (^operation)(CFDataRef in1, CFDataRef in2, CFRange *resultRange, CFErrorRef *error)) {
CFErrorRef error = NULL;
OSStatus status = errSecSuccess;
CFDataRef in1 = CFDataCreateWithBytesNoCopy(NULL, in1Ptr, in1Len, kCFAllocatorNull);
CFDataRef in2 = CFDataCreateWithBytesNoCopy(NULL, in2Ptr, in2Len, kCFAllocatorNull);
CFRange range = { 0, -1 };
CFTypeRef output = operation(in1, in2, &range, &error);
require_quiet(output, out);
if (CFGetTypeID(output) == CFDataGetTypeID() && outLen != NULL) {
if (range.length == -1) {
range.length = CFDataGetLength(output);
}
require_action_quiet((size_t)range.length <= *outLen, out,
SecError(errSecParam, &error, CFSTR("buffer too small (required %d, provided %d)"), (int)range.length, (int)*outLen));
*outLen = range.length;
CFDataGetBytes(output, range, outPtr);
}
out:
CFReleaseSafe(in1);
CFReleaseSafe(in2);
CFReleaseSafe(output);
if (error != NULL) {
status = SecErrorGetOSStatus(error);
if (status == errSecVerifyFailed) {
// Legacy functions used errSSLCrypto, while new implementation uses errSecVerifyFailed.
status = errSSLCrypto;
}
CFRelease(error);
}
return status;
}
static SecKeyAlgorithm SecKeyGetSignatureAlgorithmForPadding(SecKeyRef key, SecPadding padding, size_t digestSize) {
switch (SecKeyGetAlgorithmId(key)) {
case kSecRSAAlgorithmID: {
switch (padding) {
case kSecPaddingNone:
return kSecKeyAlgorithmRSASignatureRaw;
case kSecPaddingPKCS1:
return kSecKeyAlgorithmRSASignatureDigestPKCS1v15Raw;
case kSecPaddingPKCS1SHA1:
return kSecKeyAlgorithmRSASignatureDigestPKCS1v15SHA1;
case kSecPaddingPKCS1SHA224:
return kSecKeyAlgorithmRSASignatureDigestPKCS1v15SHA224;
case kSecPaddingPKCS1SHA256:
return kSecKeyAlgorithmRSASignatureDigestPKCS1v15SHA256;
case kSecPaddingPKCS1SHA384:
return kSecKeyAlgorithmRSASignatureDigestPKCS1v15SHA384;
case kSecPaddingPKCS1SHA512:
return kSecKeyAlgorithmRSASignatureDigestPKCS1v15SHA512;
default:
return NULL;
}
}
case kSecECDSAAlgorithmID:
switch (padding) {
case kSecPaddingSigRaw:
return kSecKeyAlgorithmECDSASignatureRFC4754;
case kSecPaddingPKCS1: {
// If digest has known size of some hash function, explicitly encode that hash type in the algorithm.
if (digestSize == ccsha1_di()->output_size) {
return kSecKeyAlgorithmECDSASignatureDigestX962SHA1;
} else if (digestSize == ccsha224_di()->output_size) {
return kSecKeyAlgorithmECDSASignatureDigestX962SHA224;
} else if (digestSize == ccsha256_di()->output_size) {
return kSecKeyAlgorithmECDSASignatureDigestX962SHA256;
} else if (digestSize == ccsha384_di()->output_size) {
return kSecKeyAlgorithmECDSASignatureDigestX962SHA384;
} else if (digestSize == ccsha512_di()->output_size) {
return kSecKeyAlgorithmECDSASignatureDigestX962SHA512;
}
// Fall through to common case, no break here.
}
default:
// Although it is not very logical, previous SecECKey implementation really considered
// anything else than SigRaw (incl. None!) as PKCS1 (i.e. x962), so we keep the behaviour
// for backward compatibility.
return kSecKeyAlgorithmECDSASignatureDigestX962;
}
default:
return NULL;
}
}
#if TARGET_OS_OSX
static SecKeyAlgorithm SecKeyGetSignatureAlgorithmForPadding_macOS(SecKeyRef key, SecPadding padding, size_t digestSize) {
switch (SecKeyGetAlgorithmId(key)) {
case kSecRSAAlgorithmID: {
// On CSSM-based implementation, these functions actually did hash its input,
// so keep doing that for backward compatibility.
switch (padding) {
case kSecPaddingNone:
return kSecKeyAlgorithmRSASignatureRaw;
case kSecPaddingPKCS1:
return kSecKeyAlgorithmRSASignatureDigestPKCS1v15Raw;
case kSecPaddingPKCS1SHA1:
return kSecKeyAlgorithmRSASignatureMessagePKCS1v15SHA1;
case kSecPaddingPKCS1SHA224:
return kSecKeyAlgorithmRSASignatureMessagePKCS1v15SHA224;
case kSecPaddingPKCS1SHA256:
return kSecKeyAlgorithmRSASignatureMessagePKCS1v15SHA256;
case kSecPaddingPKCS1SHA384:
return kSecKeyAlgorithmRSASignatureMessagePKCS1v15SHA384;
case kSecPaddingPKCS1SHA512:
return kSecKeyAlgorithmRSASignatureMessagePKCS1v15SHA512;
default:
return NULL;
}
}
case kSecECDSAAlgorithmID:
switch (padding) {
case kSecPaddingSigRaw:
return kSecKeyAlgorithmECDSASignatureRFC4754;
case kSecPaddingPKCS1: {
// If digest has known size of some hash function, explicitly encode that hash type in the algorithm.
if (digestSize == ccsha1_di()->output_size) {
return kSecKeyAlgorithmECDSASignatureDigestX962SHA1;
} else if (digestSize == ccsha224_di()->output_size) {
return kSecKeyAlgorithmECDSASignatureDigestX962SHA224;
} else if (digestSize == ccsha256_di()->output_size) {
return kSecKeyAlgorithmECDSASignatureDigestX962SHA256;
} else if (digestSize == ccsha384_di()->output_size) {
return kSecKeyAlgorithmECDSASignatureDigestX962SHA384;
} else if (digestSize == ccsha512_di()->output_size) {
return kSecKeyAlgorithmECDSASignatureDigestX962SHA512;
}
// Fall through to common case, no break here.
}
default:
// Although it is not very logical, previous SecECKey implementation really considered
// anything else than SigRaw (incl. None!) as PKCS1 (i.e. x962), so we keep the behaviour
// for backward compatibility.
return kSecKeyAlgorithmECDSASignatureDigestX962;
}
default:
return NULL;
}
}
#endif // TARGET_OS_OSX
#undef SecKeyRawSign
OSStatus SecKeyRawSign(
SecKeyRef key, /* Private key */
SecPadding padding, /* kSecPaddingNone or kSecPaddingPKCS1 */
const uint8_t *dataToSign, /* signature over this data */
size_t dataToSignLen, /* length of dataToSign */
uint8_t *sig, /* signature, RETURNED */
size_t *sigLen) { /* IN/OUT */
SecKeyAlgorithm algorithm = SecKeyGetSignatureAlgorithmForPadding(key, padding, dataToSignLen);
if (algorithm == NULL) {
return errSecParam;
}
return SecKeyPerformLegacyOperation(key, dataToSign, dataToSignLen, NULL, 0, sig, sigLen,
^CFTypeRef(CFDataRef in1, CFDataRef in2, CFRange *range, CFErrorRef *error) {
return SecKeyCreateSignature(key, algorithm, in1, error);
});
}
#if TARGET_OS_OSX
OSStatus SecKeyRawSign_macOS(
SecKeyRef key, /* Private key */
SecPadding padding, /* kSecPaddingNone or kSecPaddingPKCS1 */
const uint8_t *dataToSign, /* signature over this data */
size_t dataToSignLen, /* length of dataToSign */
uint8_t *sig, /* signature, RETURNED */
size_t *sigLen) { /* IN/OUT */
SecKeyAlgorithm algorithm = SecKeyGetSignatureAlgorithmForPadding_macOS(key, padding, dataToSignLen);
if (algorithm == NULL) {
return errSecParam;
}
return SecKeyPerformLegacyOperation(key, dataToSign, dataToSignLen, NULL, 0, sig, sigLen,
^CFTypeRef(CFDataRef in1, CFDataRef in2, CFRange *range, CFErrorRef *error) {
return SecKeyCreateSignature(key, algorithm, in1, error);
});
}
#endif
#undef SecKeyRawVerify
OSStatus SecKeyRawVerify(
SecKeyRef key, /* Public key */
SecPadding padding, /* kSecPaddingNone or kSecPaddingPKCS1 */
const uint8_t *signedData, /* signature over this data */
size_t signedDataLen, /* length of dataToSign */
const uint8_t *sig, /* signature */
size_t sigLen) { /* length of signature */
SecKeyAlgorithm algorithm = SecKeyGetSignatureAlgorithmForPadding(key, padding, signedDataLen);
if (algorithm == NULL) {
return errSecParam;
}
OSStatus status = SecKeyPerformLegacyOperation(key, signedData, signedDataLen, sig, sigLen, NULL, NULL,
^CFTypeRef(CFDataRef in1, CFDataRef in2, CFRange *range, CFErrorRef *error) {
return SecKeyVerifySignature(key, algorithm, in1, in2, error)
? kCFBooleanTrue : NULL;
});
return status;
}
#if TARGET_OS_OSX
OSStatus SecKeyRawVerify_macOS(
SecKeyRef key, /* Public key */
SecPadding padding, /* kSecPaddingNone or kSecPaddingPKCS1 */
const uint8_t *signedData, /* signature over this data */
size_t signedDataLen, /* length of dataToSign */
const uint8_t *sig, /* signature */
size_t sigLen) { /* length of signature */
SecKeyAlgorithm algorithm = SecKeyGetSignatureAlgorithmForPadding_macOS(key, padding, signedDataLen);
if (algorithm == NULL) {
return errSecParam;
}
OSStatus status = SecKeyPerformLegacyOperation(key, signedData, signedDataLen, sig, sigLen, NULL, NULL,
^CFTypeRef(CFDataRef in1, CFDataRef in2, CFRange *range, CFErrorRef *error) {
return SecKeyVerifySignature(key, algorithm, in1, in2, error)
? kCFBooleanTrue : NULL;
});
return status;
}
#endif
static SecKeyAlgorithm SecKeyGetEncryptionAlgorithmForPadding(SecKeyRef key, SecPadding padding) {
switch (SecKeyGetAlgorithmId(key)) {
case kSecRSAAlgorithmID:
switch (padding) {
case kSecPaddingNone:
return kSecKeyAlgorithmRSAEncryptionRaw;
case kSecPaddingPKCS1:
return kSecKeyAlgorithmRSAEncryptionPKCS1;
case kSecPaddingOAEP:
return kSecKeyAlgorithmRSAEncryptionOAEPSHA1;
default:
return NULL;
}
default:
return NULL;
}
}
OSStatus SecKeyEncrypt(
SecKeyRef key, /* Public key */
SecPadding padding, /* kSecPaddingNone, kSecPaddingPKCS1, kSecPaddingOAEP */
const uint8_t *plainText,
size_t plainTextLen, /* length of plainText */
uint8_t *cipherText,
size_t *cipherTextLen) { /* IN/OUT */
SecKeyAlgorithm algorithm = SecKeyGetEncryptionAlgorithmForPadding(key, padding);
if (algorithm == NULL) {
return errSecParam;
}
return SecKeyPerformLegacyOperation(key, plainText, plainTextLen, NULL, 0, cipherText, cipherTextLen,
^CFTypeRef(CFDataRef in1, CFDataRef in2, CFRange *range, CFErrorRef *error) {
return SecKeyCreateEncryptedData(key, algorithm, in1, error);
});
}
OSStatus SecKeyDecrypt(
SecKeyRef key, /* Private key */
SecPadding padding, /* kSecPaddingNone, kSecPaddingPKCS1, kSecPaddingOAEP */
const uint8_t *cipherText,
size_t cipherTextLen, /* length of cipherText */
uint8_t *plainText,
size_t *plainTextLen) { /* IN/OUT */
SecKeyAlgorithm algorithm = SecKeyGetEncryptionAlgorithmForPadding(key, padding);
if (algorithm == NULL) {
return errSecParam;
}
return SecKeyPerformLegacyOperation(key, cipherText, cipherTextLen, NULL, 0, plainText, plainTextLen,
^CFTypeRef(CFDataRef in1, CFDataRef in2, CFRange *range, CFErrorRef *error) {
CFDataRef decrypted = SecKeyCreateDecryptedData(key, algorithm, in1, error);
const UInt8 *data;
if (decrypted != NULL && algorithm == kSecKeyAlgorithmRSAEncryptionRaw &&
*(data = CFDataGetBytePtr(decrypted)) == 0x00) {
// Strip zero-padding from the beginning of the block, as the contract of this
// function says.
range->length = CFDataGetLength(decrypted);
while (*data == 0x00 && range->length > 0) {
range->location++;
range->length--;
data++;
}
}
return decrypted;
});
}
size_t SecKeyGetBlockSize(SecKeyRef key) {
SecKeyCheck(key, __func__);
if (key->key_class->blockSize)
return key->key_class->blockSize(key);
return 0;
}
/* Private API functions. */
CFDictionaryRef SecKeyCopyAttributeDictionary(SecKeyRef key) {
return SecKeyCopyAttributes(key);
}
SecKeyRef SecKeyCreateFromAttributeDictionary(CFDictionaryRef refAttributes) {
CFErrorRef error = NULL;
SecKeyRef key = SecKeyCreateWithData(CFDictionaryGetValue(refAttributes, kSecValueData), refAttributes, &error);
if (key == NULL) {
CFRelease(error);
}
return key;
}
static SecKeyAlgorithm SecKeyGetAlgorithmForSecAsn1AlgId(SecKeyRef key, const SecAsn1AlgId *algId, bool digestData) {
static const struct TableItem {
const SecAsn1Oid *oid1, *oid2;
const SecKeyAlgorithm *algorithms[2];
} translationTableRSA[] = {
{ &CSSMOID_SHA1WithRSA, &CSSMOID_SHA1, {
[false] = &kSecKeyAlgorithmRSASignatureDigestPKCS1v15SHA1,
[true] = &kSecKeyAlgorithmRSASignatureMessagePKCS1v15SHA1,
} },