Debian Codegraph @

crt/aws-c-io/source/darwin/darwin_pki_utils.c

raw symbols SCIP
1 /**
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0.
4 */
5 #include <aws/io/private/pki_utils.h>
6
7 #include <aws/common/mutex.h>
8 #include <aws/common/string.h>
9 #include <aws/io/logging.h>
10 #include <aws/io/pem.h>
11 #include <aws/io/tls_channel_handler.h>
12
13 #include <Security/SecCertificate.h>
14 #include <Security/SecKey.h>
15 #include <Security/Security.h>
16
17 /* SecureTransport is not thread-safe during identity import */
18 /* https://developer.apple.com/documentation/security/certificate_key_and_trust_services/working_with_concurrency */
19 static struct aws_mutex s_sec_mutex = AWS_MUTEX_INIT;
20
21 #if !defined(AWS_OS_IOS)
22
23 /*
24 * Helper function to import ECC private key in PEM format into `import_keychain`. Return
25 * AWS_OP_SUCCESS if successfully imported a private key or find a duplicate key in the
26 * `import_keychain`, otherwise return AWS_OP_ERR.
27 * `private_key`: UTF-8 key data in PEM format. If the key file contains multiple key sections,
28 * the function will only import the first valid key.
29 * `import_keychain`: The keychain to be imported to. `import_keychain` should not be NULL.
30 */
31 int aws_import_ecc_key_into_keychain(
32 struct aws_allocator *alloc,
33 CFAllocatorRef cf_alloc,
34 const struct aws_byte_cursor *private_key,
35 SecKeychainRef import_keychain) {
36 // Ensure imported_keychain is not NULL
37 AWS_PRECONDITION(import_keychain != NULL);
38 AWS_PRECONDITION(private_key != NULL);
39
40 int result = AWS_OP_ERR;
41 struct aws_array_list decoded_key_buffer_list;
42
43 /* Decode PEM format file to DER format */
44 if (aws_pem_objects_init_from_file_contents(&decoded_key_buffer_list, alloc, *private_key)) {
45 AWS_LOGF_ERROR(AWS_LS_IO_PKI, "static: Failed to decode PEM private key to DER format.");
46 goto ecc_import_cleanup;
47 }
48 AWS_ASSERT(aws_array_list_is_valid(&decoded_key_buffer_list));
49
50 // A PEM file could contains multiple PEM data section. Try importing each PEM section until find the first
51 // succeed key.
52 for (size_t index = 0; index < aws_array_list_length(&decoded_key_buffer_list); index++) {
53 struct aws_pem_object *pem_object_ptr = NULL;
54 /* We only check the first pem section. Currently, we dont support key with multiple pem section. */
55 aws_array_list_get_at_ptr(&decoded_key_buffer_list, (void **)&pem_object_ptr, index);
56 AWS_ASSERT(pem_object_ptr);
57 CFDataRef key_data = CFDataCreate(cf_alloc, pem_object_ptr->data.buffer, pem_object_ptr->data.len);
58 if (!key_data) {
59 AWS_LOGF_ERROR(AWS_LS_IO_PKI, "static: error in creating ECC key data system call.");
60 continue;
61 }
62
63 /* Import ECC key data into keychain. */
64 SecExternalFormat format = kSecFormatOpenSSL;
65 SecExternalItemType item_type = kSecItemTypePrivateKey;
66 SecItemImportExportKeyParameters import_params;
67 AWS_ZERO_STRUCT(import_params);
68 import_params.version = SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION;
69 import_params.passphrase = CFSTR("");
70
71 OSStatus key_status =
72 SecItemImport(key_data, NULL, &format, &item_type, 0, &import_params, import_keychain, NULL);
73
74 /* Clean up key buffer */
75 CFRelease(key_data);
76
77 // As long as we found an imported key, ignore the rest of keys
78 if (key_status == errSecSuccess || key_status == errSecDuplicateItem) {
79 result = AWS_OP_SUCCESS;
80 break;
81 } else {
82 // Log the error code for key importing
83 AWS_LOGF_ERROR(AWS_LS_IO_PKI, "static: error importing ECC private key with OSStatus %d", (int)key_status);
84 }
85 }
86
87 ecc_import_cleanup:
88 // Zero out the array list and release it
89 aws_pem_objects_clean_up(&decoded_key_buffer_list);
90 return result;
91 }
92
93 int aws_import_public_and_private_keys_to_identity(
94 struct aws_allocator *alloc,
95 CFAllocatorRef cf_alloc,
96 const struct aws_byte_cursor *public_cert_chain,
97 const struct aws_byte_cursor *private_key,
98 CFArrayRef *identity,
99 const struct aws_string *keychain_path) {
100 AWS_PRECONDITION(public_cert_chain != NULL);
101 AWS_PRECONDITION(private_key != NULL);
102
103 int result = AWS_OP_ERR;
104
105 CFDataRef cert_data = NULL;
106 CFDataRef key_data = NULL;
107
108 CFArrayRef cert_import_output = NULL;
109 CFArrayRef key_import_output = NULL;
110 SecExternalFormat format = kSecFormatUnknown;
111 SecExternalItemType item_type = kSecItemTypeCertificate;
112
113 SecItemImportExportKeyParameters import_params;
114 AWS_ZERO_STRUCT(import_params);
115 import_params.version = SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION;
116 import_params.passphrase = CFSTR("");
117
118 struct aws_array_list cert_chain_list;
119 AWS_ZERO_STRUCT(cert_chain_list);
120 CFDataRef root_cert_data = NULL;
121 SecCertificateRef certificate_ref = NULL;
122 SecKeychainRef import_keychain = NULL;
123
124 cert_data = CFDataCreate(cf_alloc, public_cert_chain->ptr, public_cert_chain->len);
125 if (!cert_data) {
126 AWS_LOGF_ERROR(AWS_LS_IO_PKI, "static: failed creating public cert chain data.");
127 result = aws_raise_error(AWS_ERROR_SYS_CALL_FAILURE);
128 goto done;
129 }
130
131 key_data = CFDataCreate(cf_alloc, private_key->ptr, private_key->len);
132 if (!key_data) {
133 AWS_LOGF_ERROR(AWS_LS_IO_PKI, "static: failed creating private key data.");
134 result = aws_raise_error(AWS_ERROR_SYS_CALL_FAILURE);
135 goto done;
136 }
137
138 # pragma clang diagnostic push
139 # pragma clang diagnostic ignored "-Wdeprecated-declarations"
140 /* SecKeychain functions are marked as deprecated.
141 * Disable compiler warnings for now, but consider removing support for keychain altogether */
142
143 if (keychain_path) {
144 OSStatus keychain_status = SecKeychainOpen(aws_string_c_str(keychain_path), &import_keychain);
145 if (keychain_status != errSecSuccess) {
146 AWS_LOGF_ERROR(
147 AWS_LS_IO_PKI,
148 "static: error opening keychain \"%s\" with OSStatus %d",
149 aws_string_c_str(keychain_path),
150 keychain_status);
151 result = aws_raise_error(AWS_ERROR_SYS_CALL_FAILURE);
152 goto done;
153 }
154 keychain_status = SecKeychainUnlock(import_keychain, 0, "", true);
155 if (keychain_status != errSecSuccess) {
156 AWS_LOGF_ERROR(
157 AWS_LS_IO_PKI,
158 "static: error unlocking keychain \"%s\" with OSStatus %d",
159 aws_string_c_str(keychain_path),
160 keychain_status);
161 result = aws_raise_error(AWS_ERROR_SYS_CALL_FAILURE);
162 goto done;
163 }
164 } else {
165 OSStatus keychain_status = SecKeychainCopyDefault(&import_keychain);
166 if (keychain_status != errSecSuccess) {
167 AWS_LOGF_ERROR(
168 AWS_LS_IO_PKI, "static: error opening the default keychain with OSStatus %d", keychain_status);
169 result = aws_raise_error(AWS_ERROR_SYS_CALL_FAILURE);
170 goto done;
171 }
172 }
173
174 # pragma clang diagnostic pop
175
176 aws_mutex_lock(&s_sec_mutex);
177
178 /* import certificate */
179 OSStatus cert_status =
180 SecItemImport(cert_data, NULL, &format, &item_type, 0, &import_params, import_keychain, &cert_import_output);
181
182 /* import private key */
183 format = kSecFormatUnknown;
184 item_type = kSecItemTypePrivateKey;
185 OSStatus key_status =
186 SecItemImport(key_data, NULL, &format, &item_type, 0, &import_params, import_keychain, &key_import_output);
187
188 if (cert_status != errSecSuccess && cert_status != errSecDuplicateItem) {
189 AWS_LOGF_ERROR(AWS_LS_IO_PKI, "static: error importing certificate with OSStatus %d", (int)cert_status);
190 result = aws_raise_error(AWS_IO_FILE_VALIDATION_FAILURE);
191 goto done;
192 }
193
194 /*
195 * If the key format is unknown, we tried to decode the key into DER format import it.
196 * The PEM file might contains multiple key sections, we will only add the first succeed key into the keychain.
197 */
198 if (key_status == errSecUnknownFormat) {
199 AWS_LOGF_TRACE(AWS_LS_IO_PKI, "static: error reading private key format, try ECC key format.");
200 if (aws_import_ecc_key_into_keychain(alloc, cf_alloc, private_key, import_keychain)) {
201 result = aws_raise_error(AWS_IO_FILE_VALIDATION_FAILURE);
202 goto done;
203 }
204 } else if (key_status != errSecSuccess && key_status != errSecDuplicateItem) {
205 AWS_LOGF_ERROR(AWS_LS_IO_PKI, "static: error importing private key with OSStatus %d", (int)key_status);
206 result = aws_raise_error(AWS_IO_FILE_VALIDATION_FAILURE);
207 goto done;
208 }
209
210 /* if it's already there, just convert this over to a cert and then let the keychain give it back to us. */
211 if (cert_status == errSecDuplicateItem) {
212 /* The text for this log is also in the README for each CRT and v2 IoT SDK. If changed, please also change
213 * where it is referenced. */
214 AWS_LOGF_INFO(
215 AWS_LS_IO_PKI,
216 "static: certificate has an existing certificate-key pair that was previously imported into the Keychain. "
217 "Using key from Keychain instead of the one provided.");
218 if (aws_pem_objects_init_from_file_contents(&cert_chain_list, alloc, *public_cert_chain)) {
219 AWS_LOGF_ERROR(AWS_LS_IO_PKI, "static: decoding certificate PEM failed.");
220 result = AWS_OP_ERR;
221 goto done;
222 }
223
224 struct aws_pem_object *root_cert_ptr = NULL;
225 aws_array_list_get_at_ptr(&cert_chain_list, (void **)&root_cert_ptr, 0);
226 AWS_ASSERT(root_cert_ptr);
227 root_cert_data = CFDataCreate(cf_alloc, root_cert_ptr->data.buffer, root_cert_ptr->data.len);
228 if (!root_cert_data) {
229 AWS_LOGF_ERROR(AWS_LS_IO_PKI, "static: failed creating root cert data.");
230 result = aws_raise_error(AWS_ERROR_SYS_CALL_FAILURE);
231 goto done;
232 }
233
234 certificate_ref = SecCertificateCreateWithData(cf_alloc, root_cert_data);
235 if (!certificate_ref) {
236 AWS_LOGF_ERROR(AWS_LS_IO_PKI, "static: failed to create certificate.");
237 result = aws_raise_error(AWS_IO_FILE_VALIDATION_FAILURE);
238 goto done;
239 }
240 } else {
241 certificate_ref = (SecCertificateRef)CFArrayGetValueAtIndex(cert_import_output, 0);
242 /* SecCertificateCreateWithData returns an object with +1 retain, so we need to match that behavior here */
243 CFRetain(certificate_ref);
244 }
245
246 /* we got a cert one way or the other, create the identity and return it */
247 AWS_ASSERT(certificate_ref);
248 SecIdentityRef identity_output;
249 OSStatus status = SecIdentityCreateWithCertificate(import_keychain, certificate_ref, &identity_output);
250 if (status != errSecSuccess) {
251 AWS_LOGF_ERROR(AWS_LS_IO_PKI, "static: error creating identity with OSStatus %d", key_status);
252 result = aws_raise_error(AWS_ERROR_SYS_CALL_FAILURE);
253 goto done;
254 }
255
256 CFTypeRef certs[] = {identity_output};
257 *identity = CFArrayCreate(cf_alloc, (const void **)certs, 1L, &kCFTypeArrayCallBacks);
258 result = AWS_OP_SUCCESS;
259
260 done:
261 aws_mutex_unlock(&s_sec_mutex);
262 if (certificate_ref) {
263 CFRelease(certificate_ref);
264 }
265 if (root_cert_data) {
266 CFRelease(root_cert_data);
267 }
268 if (cert_import_output) {
269 CFRelease(cert_import_output);
270 }
271 if (key_import_output) {
272 CFRelease(key_import_output);
273 }
274 if (import_keychain) {
275 CFRelease(import_keychain);
276 }
277 if (cert_data) {
278 CFRelease(cert_data);
279 }
280 if (key_data) {
281 CFRelease(key_data);
282 }
283 aws_pem_objects_clean_up(&cert_chain_list);
284
285 return result;
286 }
287
288 #else /* !AWS_OS_IOS */
289
290 int aws_import_public_and_private_keys_to_identity(
291 struct aws_allocator *alloc,
292 CFAllocatorRef cf_alloc,
293 const struct aws_byte_cursor *public_cert_chain,
294 const struct aws_byte_cursor *private_key,
295 CFArrayRef *identity,
296 const struct aws_string *keychain_path) {
297 (void)alloc;
298 (void)cf_alloc;
299 (void)public_cert_chain;
300 (void)private_key;
301 (void)identity;
302 (void)keychain_path;
303 /* This should not be reached when using iOS */
304 AWS_FATAL_ASSERT(false);
305 }
306
307 #endif
308
309 int aws_import_pkcs12_to_identity(
310 CFAllocatorRef cf_alloc,
311 const struct aws_byte_cursor *pkcs12_cursor,
312 const struct aws_byte_cursor *password,
313 CFArrayRef *identity) {
314 CFDataRef pkcs12_data = CFDataCreate(cf_alloc, pkcs12_cursor->ptr, pkcs12_cursor->len);
315 CFArrayRef items = NULL;
316
317 CFMutableDictionaryRef dictionary = CFDictionaryCreateMutable(cf_alloc, 0, NULL, NULL);
318
319 CFStringRef password_ref = CFSTR("");
320
321 if (password->len) {
322 password_ref = CFStringCreateWithBytes(cf_alloc, password->ptr, password->len, kCFStringEncodingUTF8, false);
323 }
324
325 CFDictionaryAddValue(dictionary, kSecImportExportPassphrase, password_ref);
326
327 aws_mutex_lock(&s_sec_mutex);
328 OSStatus status = SecPKCS12Import(pkcs12_data, dictionary, &items);
329 aws_mutex_unlock(&s_sec_mutex);
330 CFRelease(pkcs12_data);
331
332 if (password_ref) {
333 CFRelease(password_ref);
334 }
335
336 CFRelease(dictionary);
337
338 if (status == errSecSuccess) {
339 CFTypeRef item = (CFTypeRef)CFArrayGetValueAtIndex(items, 0);
340
341 CFTypeRef identity_ref = (CFTypeRef)CFDictionaryGetValue((CFDictionaryRef)item, kSecImportItemIdentity);
342 if (identity_ref) {
343 *identity = CFArrayCreate(cf_alloc, &identity_ref, 1L, &kCFTypeArrayCallBacks);
344 }
345
346 CFRelease(items);
347 return AWS_OP_SUCCESS;
348 }
349
350 AWS_LOGF_ERROR(AWS_LS_IO_PKI, "static: error importing pkcs#12 certificate OSStatus %d", (int)status);
351
352 return AWS_OP_ERR;
353 }
354
355 /*
356 * Apple Network framework and SecItem API's use of the data protection keychain is currently only implemented
357 * for iOS and tvOS. We may add support for MacOS at a later date.
358 */
359
360 void aws_cf_release(CFTypeRef obj) {
361 if (obj != NULL) {
362 CFRelease(obj);
363 }
364 }
365
366 static int s_aws_secitem_add_certificate_to_keychain(
367 CFAllocatorRef cf_alloc,
368 SecCertificateRef cert_ref,
369 CFDataRef serial_data,
370 CFStringRef label) {
371
372 int result = AWS_OP_ERR;
373 OSStatus status;
374
375 CFMutableDictionaryRef add_attributes = NULL;
376 CFMutableDictionaryRef delete_query = NULL;
377
378 add_attributes =
379 CFDictionaryCreateMutable(cf_alloc, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
380 CFDictionaryAddValue(add_attributes, kSecClass, kSecClassCertificate);
381 CFDictionaryAddValue(add_attributes, kSecAttrSerialNumber, serial_data);
382 CFDictionaryAddValue(add_attributes, kSecAttrLabel, label);
383 CFDictionaryAddValue(add_attributes, kSecValueRef, cert_ref);
384
385 // Initial attempt to add certificate to keychain.
386 status = SecItemAdd(add_attributes, NULL);
387
388 // A duplicate item is handled. All other errors are unhandled.
389 if (status != errSecSuccess && status != errSecDuplicateItem) {
390 switch (status) {
391 case errSecMissingEntitlement:
392 AWS_LOGF_ERROR(
393 AWS_LS_IO_PKI,
394 "SecItemAdd certificate failed with OSStatus %d : errSecMissingEntitlement. The process attempting "
395 "to access the keychain is missing the necessary entitlements.",
396 (int)status);
397 break;
398 default:
399 AWS_LOGF_ERROR(AWS_LS_IO_PKI, "SecItemAdd certificate failed with OSStatus %d", (int)status);
400 aws_raise_error(AWS_ERROR_SYS_CALL_FAILURE);
401 break;
402 }
403 goto done;
404 }
405
406 /* A duplicate item error indicates the certificate already exists in the keychain. We delete the
407 * existing certificate and re-add the certificate in case there are differences that need to be applied.
408 *
409 * query should be made up of primary keys only. Optional/non-unique attributes in the query
410 * can result in not finding the matching certificate and cause the update operation to fail.
411 *
412 * Certificate item primary keys used for the query:
413 * kSecAttrSerialNumber: (CFStringRef) value indicates the item's serial number
414 * - We explicity set this value, extracted from the certificate itself as our primary method of determining
415 * uniqueness of the certificate.
416 *
417 * Certificate primary keys we do not use for the query:
418 * These can be added in the future if we require a more specified search query.
419 * kSecAttrCertificateType: (CFNumberRef) value indicates the item's certificate type
420 * - values see the CSSM_CERT_TYPE enumeration in cssmtype.h
421 * https://opensource.apple.com/source/Security/Security-55471/libsecurity_cssm/lib/cssmtype.h.auto.html
422 * - default will try to add common value such as X.509. We do not pass this attribute and allow default value
423 * to be used. If we decide to support other types of certificates, we should set and use this value explicitly.
424 * kSecAttrIssuer: (CFStringRef) value indicates the item's issuer
425 * - default will try to extract issuer from the certificate itself.
426 * We will not set this attribute and allow default value to be used.
427 */
428 if (status == errSecDuplicateItem) {
429 AWS_LOGF_INFO(
430 AWS_LS_IO_PKI,
431 "static: Keychain contains existing certificate that was previously imported into the Keychain. "
432 "Deleting existing certificate in keychain.");
433
434 delete_query =
435 CFDictionaryCreateMutable(cf_alloc, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
436 CFDictionaryAddValue(delete_query, kSecClass, kSecClassCertificate);
437 CFDictionaryAddValue(delete_query, kSecAttrSerialNumber, serial_data);
438
439 // delete the existing certificate from keychain
440 status = SecItemDelete(delete_query);
441 if (status != errSecSuccess) {
442 AWS_LOGF_ERROR(AWS_LS_IO_PKI, "SecItemDelete certificate failed with OSStatus %d", (int)status);
443 aws_raise_error(AWS_ERROR_SYS_CALL_FAILURE);
444 goto done;
445 }
446
447 // now try adding it again
448 status = SecItemAdd(add_attributes, NULL);
449 if (status != errSecSuccess) {
450 AWS_LOGF_ERROR(AWS_LS_IO_PKI, "SecItemAdd certificate failed with OSStatus %d", (int)status);
451 aws_raise_error(AWS_ERROR_SYS_CALL_FAILURE);
452 goto done;
453 }
454 }
455
456 AWS_LOGF_INFO(AWS_LS_IO_PKI, "static: Successfully imported certificate into SecItem keychain.");
457
458 result = AWS_OP_SUCCESS;
459
460 done:
461 // cleanup
462 aws_cf_release(add_attributes);
463 aws_cf_release(delete_query);
464 return result;
465 }
466
467 static int s_aws_secitem_add_private_key_to_keychain(
468 CFAllocatorRef cf_alloc,
469 SecKeyRef key_ref,
470 CFStringRef label,
471 CFDataRef application_label) {
472
473 int result = AWS_OP_ERR;
474 OSStatus status;
475
476 CFMutableDictionaryRef add_attributes = NULL;
477 CFMutableDictionaryRef delete_query = NULL;
478
479 add_attributes =
480 CFDictionaryCreateMutable(cf_alloc, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
481 CFDictionaryAddValue(add_attributes, kSecClass, kSecClassKey);
482 CFDictionaryAddValue(add_attributes, kSecAttrKeyClass, kSecAttrKeyClassPrivate);
483 CFDictionaryAddValue(add_attributes, kSecAttrApplicationLabel, application_label);
484 CFDictionaryAddValue(add_attributes, kSecAttrLabel, label);
485 CFDictionaryAddValue(add_attributes, kSecValueRef, key_ref);
486
487 // Initial attempt to add private key to keychain.
488 status = SecItemAdd(add_attributes, NULL);
489
490 // A duplicate item is handled. All other errors are unhandled.
491 if (status != errSecSuccess && status != errSecDuplicateItem) {
492 switch (status) {
493 case errSecMissingEntitlement:
494 AWS_LOGF_ERROR(
495 AWS_LS_IO_PKI,
496 "SecItemAdd private key failed with OSStatus %d : errSecMissingEntitlement. The process attempting "
497 "to access the keychain is missing the necessary entitlements.",
498 (int)status);
499 break;
500 default:
501 AWS_LOGF_ERROR(AWS_LS_IO_PKI, "SecItemAdd private key failed with OSStatus %d", (int)status);
502 aws_raise_error(AWS_ERROR_SYS_CALL_FAILURE);
503 break;
504 }
505 goto done;
506 }
507
508 /* A duplicate item error indicates the private key already exists in the keychain. We delete the
509 * existing private key and re-add the private-key in case there are differences that need to be applied.
510 *
511 * query should be made up of primary keys only. Optional/non-unique attributes in the query
512 * can result in not finding the matching private key and cause the update operation to fail.
513 *
514 * Private Key item primary keys we use for the query:
515 * kSecAttrKeyClass: (CFTypeRef) value indicates item's cryptographic key class
516 * - We explicitly set this value to kSecAttrKeyClassPrivate
517 * kSecAttrApplicationLabel: (CFStringRef) value indicates item's application label.
518 * - We pull this value out of the SecKeyRef. It's the hash of the public key stored within.
519 *
520 * Private Key primary keys we do not use for the query:
521 * These can be added in the future if we require a more specified search query.
522 * kSecAttrApplicationTag: (CFDataRef) value indicates the item's private tag.
523 * kSecAttrKeySizeInBits: (CFNumberRef) value indicates the number of bits in a cryptographic key.
524 * kSecAttrEffectiveKeySize: (CFNumberRef) value indicates the effective number of bits in a crytographic key.
525 */
526
527 if (status == errSecDuplicateItem) {
528 AWS_LOGF_INFO(
529 AWS_LS_IO_PKI,
530 "static: Keychain contains existing private key that was previously imported into the Keychain. "
531 "Deleting private key in keychain.");
532
533 delete_query =
534 CFDictionaryCreateMutable(cf_alloc, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
535 CFDictionaryAddValue(delete_query, kSecClass, kSecClassKey);
536 CFDictionaryAddValue(delete_query, kSecAttrKeyClass, kSecAttrKeyClassPrivate);
537 CFDictionaryAddValue(delete_query, kSecAttrApplicationLabel, application_label);
538
539 // delete the existing private key from keychain
540 status = SecItemDelete(delete_query);
541 if (status != errSecSuccess) {
542 AWS_LOGF_ERROR(AWS_LS_IO_PKI, "SecItemDelete private key failed with OSStatus %d", (int)status);
543 aws_raise_error(AWS_ERROR_SYS_CALL_FAILURE);
544 goto done;
545 }
546
547 // now try adding it again
548 status = SecItemAdd(add_attributes, NULL);
549 if (status != errSecSuccess) {
550 AWS_LOGF_ERROR(AWS_LS_IO_PKI, "SecItemAdd private key failed with OSStatus %d", (int)status);
551 aws_raise_error(AWS_ERROR_SYS_CALL_FAILURE);
552 goto done;
553 }
554 }
555
556 AWS_LOGF_INFO(AWS_LS_IO_PKI, "static: Successfully imported private key into SecItem keychain.");
557
558 result = AWS_OP_SUCCESS;
559
560 done:
561 // cleanup
562 aws_cf_release(add_attributes);
563 aws_cf_release(delete_query);
564
565 return result;
566 }
567
568 static int s_aws_secitem_get_identity(CFAllocatorRef cf_alloc, CFDataRef serial_data, sec_identity_t *out_identity) {
569
570 int result = AWS_OP_ERR;
571 OSStatus status;
572 CFMutableDictionaryRef search_query = NULL;
573 SecIdentityRef sec_identity_ref = NULL;
574
575 /*
576 * SecItem identity is created when a certificate matches a private key in the keychain.
577 * Since a private key may be associated with multiple certificates, searching for the
578 * identity using a unique attribute of the certificate is required. This is why we use
579 * the serial_data from the certificate as the search parameter.
580 */
581 search_query =
582 CFDictionaryCreateMutable(cf_alloc, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
583 CFDictionaryAddValue(search_query, kSecClass, kSecClassIdentity);
584 CFDictionaryAddValue(search_query, kSecAttrSerialNumber, serial_data);
585 CFDictionaryAddValue(search_query, kSecReturnRef, kCFBooleanTrue);
586
587 /*
588 * Copied or created CF items must have CFRelease called on them or you leak memory. This identity needs to
589 * have CFRelease called on it at some point or it will leak.
590 */
591 status = SecItemCopyMatching(search_query, (CFTypeRef *)&sec_identity_ref);
592
593 if (status != errSecSuccess) {
594 AWS_LOGF_ERROR(AWS_LS_IO_PKI, "SecItemCopyMatching identity failed with OSStatus %d", (int)status);
595 aws_raise_error(AWS_ERROR_SYS_CALL_FAILURE);
596 goto done;
597 }
598
599 *out_identity = sec_identity_create(sec_identity_ref);
600 if (*out_identity == NULL) {
601 AWS_LOGF_ERROR(
602 AWS_LS_IO_PKI, "sec_identity_create failed to create a sec_identity_t from provided SecIdentityRef.");
603 aws_raise_error(AWS_ERROR_SYS_CALL_FAILURE);
604 goto done;
605 }
606
607 AWS_LOGF_INFO(AWS_LS_IO_PKI, "static: Successfully retrieved identity from keychain.");
608
609 result = AWS_OP_SUCCESS;
610
611 done:
612 // cleanup
613 aws_cf_release(search_query);
614 aws_cf_release(sec_identity_ref);
615
616 return result;
617 }
618
619 int aws_secitem_import_cert_and_key(
620 struct aws_allocator *alloc,
621 CFAllocatorRef cf_alloc,
622 const struct aws_byte_cursor *public_cert_chain,
623 const struct aws_byte_cursor *private_key,
624 sec_identity_t *secitem_identity,
625 const struct aws_secitem_options *secitem_options) {
626
627 AWS_PRECONDITION(public_cert_chain != NULL);
628 AWS_PRECONDITION(private_key != NULL);
629
630 int result = AWS_OP_ERR;
631
632 CFErrorRef error = NULL;
633
634 CFDataRef cert_data = NULL;
635 SecCertificateRef cert_ref = NULL;
636 CFDataRef cert_serial_data = NULL;
637 CFStringRef cert_label_ref = NULL;
638
639 CFMutableDictionaryRef key_attributes = NULL;
640 CFDictionaryRef key_copied_attributes = NULL;
641 CFDataRef key_data = NULL;
642 SecKeyRef key_ref = NULL;
643 CFStringRef key_type = NULL;
644 CFStringRef key_label_ref = NULL;
645 CFDataRef application_label_ref = NULL;
646
647 struct aws_array_list decoded_cert_buffer_list;
648 AWS_ZERO_STRUCT(decoded_cert_buffer_list);
649 struct aws_array_list decoded_key_buffer_list;
650 AWS_ZERO_STRUCT(decoded_key_buffer_list);
651
652 /*
653 * iOS SecItem requires DER encoded files so we first convert the provided PEM encoded
654 * cert and key into a list of aws_pem_object that strips headers/footers and Base64 decodes
655 * the data into a byte buf.
656 */
657 if (aws_pem_objects_init_from_file_contents(&decoded_cert_buffer_list, alloc, *public_cert_chain)) {
658 AWS_LOGF_ERROR(AWS_LS_IO_PKI, "static: Failed to decode PEM certificate to DER format.");
659 goto done;
660 }
661 AWS_ASSERT(aws_array_list_is_valid(&decoded_cert_buffer_list));
662
663 if (aws_pem_objects_init_from_file_contents(&decoded_key_buffer_list, alloc, *private_key)) {
664 AWS_LOGF_ERROR(AWS_LS_IO_PKI, "static: Failed to decode PEM private key to DER format.");
665 goto done;
666 }
667 AWS_ASSERT(aws_array_list_is_valid(&decoded_key_buffer_list));
668
669 /*
670 * A PEM certificate file could contains multiple PEM data sections. We currently decode and
671 * use the first certificate data only. Certificate chaining support could be added in the future.
672 */
673 if (aws_array_list_length(&decoded_cert_buffer_list) > 1) {
674 AWS_LOGF_ERROR(AWS_LS_IO_PKI, "Certificate chains not currently supported on iOS.");
675 result = aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
676 goto done;
677 }
678
679 /* Convert the DER encoded files to the CFDataRef type required for import into keychain */
680 struct aws_pem_object *pem_cert_ptr = NULL;
681 aws_array_list_get_at_ptr(&decoded_cert_buffer_list, (void **)&pem_cert_ptr, 0);
682 AWS_ASSERT(pem_cert_ptr);
683
684 struct aws_pem_object *pem_key_ptr = NULL;
685 aws_array_list_get_at_ptr(&decoded_key_buffer_list, (void **)&pem_key_ptr, 0);
686 AWS_ASSERT(pem_key_ptr);
687
688 cert_data = CFDataCreate(cf_alloc, pem_cert_ptr->data.buffer, pem_cert_ptr->data.len);
689 if (!cert_data) {
690 AWS_LOGF_ERROR(AWS_LS_IO_PKI, "Error creating certificate data system call.");
691 aws_raise_error(AWS_ERROR_SYS_CALL_FAILURE);
692 goto done;
693 }
694
695 key_data = CFDataCreate(cf_alloc, pem_key_ptr->data.buffer, pem_key_ptr->data.len);
696 if (!key_data) {
697 AWS_LOGF_ERROR(AWS_LS_IO_PKI, "Error creating private key data system call.");
698 aws_raise_error(AWS_ERROR_SYS_CALL_FAILURE);
699 goto done;
700 }
701
702 /*
703 * The aws_pem_object preserves the type of encoding found in the PEM file. We use the type_string member to set the
704 * appropriate CFStringRef key_type attribute.
705 */
706 switch (pem_key_ptr->type) {
707 case AWS_PEM_TYPE_PRIVATE_RSA_PKCS1:
708 key_type = kSecAttrKeyTypeRSA;
709 break;
710
711 case AWS_PEM_TYPE_EC_PRIVATE:
712 key_type = kSecAttrKeyTypeEC;
713 break;
714
715 case AWS_PEM_TYPE_PRIVATE_PKCS8:
716 /*
717 * PKCS8 is not supported on iOS/tvOS (the framework doesn't allow it) and is currently NOT supported by us
718 * on macOS PKCS8 support for macOS using SecItem can be added later for macOS only but will require a
719 * different import strategy than the currently shared one.
720 */
721 key_type = kSecAttrKeyTypeRSA;
722 AWS_LOGF_ERROR(
723 AWS_LS_IO_PKI, "The PKCS8 private key format is currently unsupported for use with SecItem.");
724 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
725 goto done;
726 break;
727
728 case AWS_PEM_TYPE_UNKNOWN:
729 default:
730 AWS_LOGF_ERROR(AWS_LS_IO_PKI, "Unsupported private key format.");
731 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
732 goto done;
733 }
734
735 /* Attributes used for query and adding of cert/key SecItems */
736
737 /*
738 * We create a SecCertificateRef here to use with the kSecValueRef key as well as to extract the serial number for
739 * use as a unique identifier when storing the certificate in the keychain. The serial number is also used as the
740 * identifier when retrieving the identity
741 */
742 cert_ref = SecCertificateCreateWithData(cf_alloc, cert_data);
743 if (!cert_ref) {
744 AWS_LOGF_ERROR(AWS_LS_IO_PKI, "Failed creating SecCertificateRef from cert_data.");
745 aws_raise_error(AWS_ERROR_SYS_CALL_FAILURE);
746 goto done;
747 }
748
749 cert_serial_data = SecCertificateCopySerialNumberData(cert_ref, &error);
750 if (error) {
751 AWS_LOGF_ERROR(AWS_LS_IO_PKI, "Failed extracting serial number data from cert_ref.");
752 aws_raise_error(AWS_ERROR_SYS_CALL_FAILURE);
753 goto done;
754 }
755
756 cert_label_ref = CFStringCreateWithBytes(
757 cf_alloc,
758 (const UInt8 *)aws_string_bytes(secitem_options->cert_label),
759 secitem_options->cert_label->len,
760 kCFStringEncodingUTF8,
761 false);
762 if (!cert_label_ref) {
763 AWS_LOGF_ERROR(AWS_LS_IO_PKI, "Failed creating certificate label.");
764 aws_raise_error(AWS_ERROR_SYS_CALL_FAILURE);
765 goto done;
766 }
767
768 /*
769 * We create a SecKeyRef (key_ref) here using the key_data for the purpose of extracting the public key hash from
770 * the private key. We need the public key hash (application_label_ref) to use as a unique identifier when importing
771 * the private key into the keychain.
772 */
773 key_attributes =
774 CFDictionaryCreateMutable(cf_alloc, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
775 CFDictionaryAddValue(key_attributes, kSecAttrKeyClass, kSecAttrKeyClassPrivate);
776 CFDictionaryAddValue(key_attributes, kSecAttrKeyType, key_type);
777 key_ref = SecKeyCreateWithData(key_data, key_attributes, &error);
778
779 // Get the hash of the public key stored within the private key by extracting it from the key_ref's attributes
780 key_copied_attributes = SecKeyCopyAttributes(key_ref);
781 // application_label_ref does not need to be released. It gets released when key_copied_attributes is released.
782 application_label_ref = (CFDataRef)CFDictionaryGetValue(key_copied_attributes, kSecAttrApplicationLabel);
783 if (!application_label_ref) {
784 AWS_LOGF_ERROR(AWS_LS_IO_PKI, "Failed creating private key application label.");
785 aws_raise_error(AWS_ERROR_SYS_CALL_FAILURE);
786 goto done;
787 }
788
789 key_label_ref = CFStringCreateWithBytes(
790 cf_alloc,
791 (const UInt8 *)aws_string_bytes(secitem_options->key_label),
792 secitem_options->key_label->len,
793 kCFStringEncodingUTF8,
794 false);
795 if (!key_label_ref) {
796 AWS_LOGF_ERROR(AWS_LS_IO_PKI, "Failed creating private key label.");
797 aws_raise_error(AWS_ERROR_SYS_CALL_FAILURE);
798 goto done;
799 }
800
801 // Add the certificate and private key to keychain then retrieve identity
802
803 if (s_aws_secitem_add_certificate_to_keychain(cf_alloc, cert_ref, cert_serial_data, cert_label_ref)) {
804 goto done;
805 }
806
807 if (s_aws_secitem_add_private_key_to_keychain(cf_alloc, key_ref, key_label_ref, application_label_ref)) {
808 goto done;
809 }
810
811 if (s_aws_secitem_get_identity(cf_alloc, cert_serial_data, secitem_identity)) {
812 goto done;
813 }
814
815 result = AWS_OP_SUCCESS;
816
817 done:
818 // cleanup
819 aws_cf_release(error);
820 aws_cf_release(cert_data);
821 aws_cf_release(cert_ref);
822 aws_cf_release(cert_serial_data);
823 aws_cf_release(cert_label_ref);
824 aws_cf_release(key_attributes);
825 aws_cf_release(key_copied_attributes);
826 aws_cf_release(key_data);
827 aws_cf_release(key_ref);
828 aws_cf_release(key_type);
829 aws_cf_release(key_label_ref);
830
831 // Zero out the array list and release it
832 aws_pem_objects_clean_up(&decoded_cert_buffer_list);
833 aws_pem_objects_clean_up(&decoded_key_buffer_list);
834
835 return result;
836 }
837
838 int aws_secitem_import_pkcs12(
839 CFAllocatorRef cf_alloc,
840 const struct aws_byte_cursor *pkcs12_cursor,
841 const struct aws_byte_cursor *password,
842 sec_identity_t *out_identity) {
843
844 int result = AWS_OP_ERR;
845 CFArrayRef items = NULL;
846 CFDataRef pkcs12_data = NULL;
847 CFMutableDictionaryRef dictionary = NULL;
848 SecIdentityRef sec_identity_ref = NULL;
849 CFStringRef password_ref = NULL;
850
851 pkcs12_data = CFDataCreate(cf_alloc, pkcs12_cursor->ptr, pkcs12_cursor->len);
852 if (!pkcs12_data) {
853 AWS_LOGF_ERROR(AWS_LS_IO_PKI, "Error creating pkcs12 data system call.");
854 aws_raise_error(AWS_ERROR_SYS_CALL_FAILURE);
855 goto done;
856 }
857
858 if (password->len) {
859 password_ref = CFStringCreateWithBytes(cf_alloc, password->ptr, password->len, kCFStringEncodingUTF8, false);
860 } else {
861 password_ref = CFStringCreateWithCString(cf_alloc, "", kCFStringEncodingUTF8);
862 }
863
864 dictionary = CFDictionaryCreateMutable(cf_alloc, 0, NULL, NULL);
865 CFDictionaryAddValue(dictionary, kSecImportExportPassphrase, password_ref);
866
867 OSStatus status = SecPKCS12Import(pkcs12_data, dictionary, &items);
868
869 if (status != errSecSuccess || CFArrayGetCount(items) == 0) {
870 AWS_LOGF_ERROR(AWS_LS_IO_PKI, "Failed to import PKCS#12 file with OSStatus:%d", (int)status);
871 aws_raise_error(AWS_ERROR_SYS_CALL_FAILURE);
872 goto done;
873 }
874
875 // Extract the identity from the first item in the array
876 // identity_and_trust does not need to be released as it is not a copy or created CF object.
877 CFDictionaryRef identity_and_trust = CFArrayGetValueAtIndex(items, 0);
878 sec_identity_ref = (SecIdentityRef)CFDictionaryGetValue(identity_and_trust, kSecImportItemIdentity);
879
880 if (sec_identity_ref != NULL) {
881 AWS_LOGF_INFO(
882 AWS_LS_IO_PKI, "static: Successfully imported PKCS#12 file into keychain and retrieved identity.");
883 } else {
884 status = errSecItemNotFound;
885 AWS_LOGF_ERROR(AWS_LS_IO_PKI, "Failed to retrieve identity from PKCS#12 with OSStatus %d", (int)status);
886 goto done;
887 }
888
889 *out_identity = sec_identity_create(sec_identity_ref);
890
891 result = AWS_OP_SUCCESS;
892
893 done:
894 // cleanup
895 aws_cf_release(pkcs12_data);
896 aws_cf_release(dictionary);
897 aws_cf_release(password_ref);
898 aws_cf_release(items);
899 return result;
900 }
901
902 int aws_import_trusted_certificates(
903 struct aws_allocator *alloc,
904 CFAllocatorRef cf_alloc,
905 const struct aws_byte_cursor *certificates_blob,
906 CFArrayRef *certs) {
907 AWS_PRECONDITION(certificates_blob != NULL);
908
909 struct aws_array_list certificates;
910
911 if (aws_pem_objects_init_from_file_contents(&certificates, alloc, *certificates_blob)) {
912 AWS_LOGF_ERROR(AWS_LS_IO_PKI, "static: decoding CA PEM failed.");
913 aws_array_list_clean_up(&certificates);
914 return AWS_OP_ERR;
915 }
916
917 size_t cert_count = aws_array_list_length(&certificates);
918 CFMutableArrayRef temp_cert_array = CFArrayCreateMutable(cf_alloc, cert_count, &kCFTypeArrayCallBacks);
919
920 int err = AWS_OP_SUCCESS;
921 aws_mutex_lock(&s_sec_mutex);
922 for (size_t i = 0; i < cert_count; ++i) {
923 struct aws_pem_object *pem_object_ptr = NULL;
924 aws_array_list_get_at_ptr(&certificates, (void **)&pem_object_ptr, i);
925
926 CFDataRef cert_blob = CFDataCreate(cf_alloc, pem_object_ptr->data.buffer, pem_object_ptr->data.len);
927
928 if (cert_blob) {
929 SecCertificateRef certificate_ref = SecCertificateCreateWithData(cf_alloc, cert_blob);
930 CFArrayAppendValue(temp_cert_array, certificate_ref);
931 CFRelease(certificate_ref);
932 CFRelease(cert_blob);
933 } else {
934 err = AWS_OP_SUCCESS;
935 }
936 }
937 aws_mutex_unlock(&s_sec_mutex);
938
939 *certs = temp_cert_array;
940 aws_pem_objects_clean_up(&certificates);
941 aws_array_list_clean_up(&certificates);
942 return err;
943 }