2 * Copyright (c) 2003-2004,2006,2012,2014 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
26 #import <Foundation/Foundation.h>
28 #include "keychain_export.h"
29 #include "keychain_utilities.h"
30 #include "security_tool.h"
35 #include <Security/SecImportExport.h>
36 #include <Security/SecKeychainItem.h>
37 #include <Security/SecKeychainSearch.h>
38 #include <Security/SecIdentitySearch.h>
39 #include <Security/SecKey.h>
40 #include <Security/SecKeyPriv.h>
41 #include <Security/SecCertificate.h>
42 #include <Security/SecCertificatePriv.h>
43 #include <Security/SecItem.h>
44 #include <Security/SecAccessControl.h>
45 #include <Security/SecAccessControlPriv.h>
46 #include <security_cdsa_utils/cuFileIo.h>
47 #include <CoreFoundation/CoreFoundation.h>
60 * Add all itmes of specified class from a keychain to an array.
61 * Item class are things like kSecCertificateItemClass, and
62 * CSSM_DL_DB_RECORD_PRIVATE_KEY. Identities are searched separately.
64 static OSStatus addKcItems(
66 SecItemClass itemClass, // kSecCertificateItemClass
67 CFMutableArrayRef outArray,
68 unsigned *numItems) // UPDATED on return
71 SecKeychainSearchRef srchRef;
73 ortn = SecKeychainSearchCreateFromAttributes(kcRef,
78 sec_perror("SecKeychainSearchCreateFromAttributes", ortn);
82 SecKeychainItemRef itemRef;
83 ortn = SecKeychainSearchCopyNext(srchRef, &itemRef);
85 if(ortn == errSecItemNotFound) {
86 /* normal search end */
90 sec_perror("SecIdentitySearchCopyNext", ortn);
94 CFArrayAppendValue(outArray, itemRef);
95 CFRelease(itemRef); // array owns the item
103 * Add all SecIdentityRefs from a keychain into an array.
105 static OSStatus addIdentities(
106 SecKeychainRef kcRef,
107 CFMutableArrayRef outArray,
108 unsigned *numItems) // UPDATED on return
110 /* Search for all identities */
111 SecIdentitySearchRef srchRef;
112 OSStatus ortn = SecIdentitySearchCreate(kcRef,
116 sec_perror("SecIdentitySearchCreate", ortn);
121 SecIdentityRef identity;
122 ortn = SecIdentitySearchCopyNext(srchRef, &identity);
124 if(ortn == errSecItemNotFound) {
125 /* normal search end */
129 sec_perror("SecIdentitySearchCopyNext", ortn);
133 CFArrayAppendValue(outArray, identity);
135 /* the array has the retain count we need */
138 } while(ortn == noErr);
143 static int do_keychain_export(
144 SecKeychainRef kcRef,
145 SecExternalFormat externFormat,
147 const char *passphrase,
149 const char *fileName)
153 unsigned numPrivKeys = 0;
154 unsigned numPubKeys = 0;
155 unsigned numCerts = 0;
156 unsigned numIdents = 0;
158 uint32 expFlags = 0; // SecItemImportExportFlags
159 SecKeyImportExportParameters keyParams;
160 CFStringRef passStr = NULL;
161 CFDataRef outData = NULL;
165 CFMutableArrayRef exportItems = CFArrayCreateMutable(NULL, 0,
166 &kCFTypeArrayCallBacks);
169 ortn = addKcItems(kcRef, kSecCertificateItemClass, exportItems, &numCerts);
177 ortn = addKcItems(kcRef, CSSM_DL_DB_RECORD_PRIVATE_KEY, exportItems,
186 ortn = addKcItems(kcRef, CSSM_DL_DB_RECORD_PUBLIC_KEY, exportItems,
195 ortn = addKcItems(kcRef, CSSM_DL_DB_RECORD_PRIVATE_KEY, exportItems,
201 ortn = addKcItems(kcRef, CSSM_DL_DB_RECORD_PUBLIC_KEY, exportItems,
210 /* No public keys here - PKCS12 doesn't support them */
211 ortn = addKcItems(kcRef, kSecCertificateItemClass, exportItems, &numCerts);
216 ortn = addKcItems(kcRef, CSSM_DL_DB_RECORD_PRIVATE_KEY, exportItems,
225 ortn = addIdentities(kcRef, exportItems, &numIdents);
231 numPrivKeys += numIdents;
232 numCerts += numIdents;
236 sec_error("Internal error parsing item_spec");
241 numItems = CFArrayGetCount(exportItems);
242 if(externFormat == kSecFormatUnknown) {
243 /* Use default export format per set of items */
245 externFormat = kSecFormatPEMSequence;
248 externFormat = kSecFormatX509Cert;
251 externFormat = kSecFormatOpenSSL;
255 expFlags |= kSecItemPemArmour;
259 * Key related arguments, ignored if we're not exporting keys.
260 * Always specify some kind of passphrase - default is secure passkey.
262 memset(&keyParams, 0, sizeof(keyParams));
263 keyParams.version = SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION;
264 if(passphrase != NULL) {
265 passStr = CFStringCreateWithCString(NULL, passphrase, kCFStringEncodingASCII);
266 keyParams.passphrase = passStr;
269 keyParams.flags = kSecKeySecurePassphrase;
273 ortn = SecKeychainItemExport(exportItems, externFormat, expFlags, &keyParams,
276 sec_perror("SecKeychainItemExport", ortn);
281 len = CFDataGetLength(outData);
283 int rtn = writeFileSizet(fileName, CFDataGetBytePtr(outData), len);
286 fprintf(stderr, "...%lu bytes written to %s\n", len, fileName);
290 sec_error("Error writing to %s: %s", fileName, strerror(errno));
295 size_t irtn = write(STDOUT_FILENO, CFDataGetBytePtr(outData), len);
296 if(irtn != (size_t)len) {
302 CFRelease(exportItems);
314 keychain_export(int argc, char * const *argv)
318 char *outFile = NULL;
320 SecKeychainRef kcRef = NULL;
321 SecExternalFormat externFormat = kSecFormatUnknown;
322 ItemSpec itemSpec = IS_All;
325 const char *passphrase = NULL;
327 while ((ch = getopt(argc, argv, "k:o:t:f:P:wph")) != -1)
338 if(!strcmp("certs", optarg)) {
341 else if(!strcmp("allKeys", optarg)) {
342 itemSpec = IS_AllKeys;
344 else if(!strcmp("pubKeys", optarg)) {
345 itemSpec = IS_PubKeys;
347 else if(!strcmp("privKeys", optarg)) {
348 itemSpec = IS_PrivKeys;
350 else if(!strcmp("identities", optarg)) {
351 itemSpec = IS_Identities;
353 else if(!strcmp("all", optarg)) {
357 return SHOW_USAGE_MESSAGE;
361 if(!strcmp("openssl", optarg)) {
362 externFormat = kSecFormatOpenSSL;
364 else if(!strcmp("openssh1", optarg)) {
365 externFormat = kSecFormatSSH;
367 else if(!strcmp("openssh2", optarg)) {
368 externFormat = kSecFormatSSHv2;
370 else if(!strcmp("bsafe", optarg)) {
371 externFormat = kSecFormatBSAFE;
373 else if(!strcmp("raw", optarg)) {
374 externFormat = kSecFormatRawKey;
376 else if(!strcmp("pkcs7", optarg)) {
377 externFormat = kSecFormatPKCS7;
379 else if(!strcmp("pkcs8", optarg)) {
380 externFormat = kSecFormatWrappedPKCS8;
382 else if(!strcmp("pkcs12", optarg)) {
383 externFormat = kSecFormatPKCS12;
385 else if(!strcmp("netscape", optarg)) {
386 externFormat = kSecFormatNetscapeCertSequence;
388 else if(!strcmp("x509", optarg)) {
389 externFormat = kSecFormatX509Cert;
391 else if(!strcmp("pemseq", optarg)) {
392 externFormat = kSecFormatPEMSequence;
395 return SHOW_USAGE_MESSAGE;
409 return SHOW_USAGE_MESSAGE;
414 switch(externFormat) {
415 case kSecFormatOpenSSL:
416 case kSecFormatUnknown: // i.e., use default
417 externFormat = kSecFormatWrappedOpenSSL;
420 externFormat = kSecFormatWrappedSSH;
422 case kSecFormatSSHv2:
423 /* there is no wrappedSSHv2 */
424 externFormat = kSecFormatWrappedOpenSSL;
426 case kSecFormatWrappedPKCS8:
430 sec_error("Don't know how to wrap in specified format/type");
431 return SHOW_USAGE_MESSAGE;
436 kcRef = keychain_open(kcName);
441 result = do_keychain_export(kcRef, externFormat, itemSpec,
442 passphrase, doPem, outFile);
451 CFMutableStringRef str;
452 } ctk_dict2str_context;
456 ctk_obj_to_str(CFTypeRef obj, char *buf, int bufLen, Boolean key);
459 ctk_dict2str(const void *key, const void *value, void *context)
461 char keyBuf[64] = { 0 };
462 ctk_obj_to_str(key, keyBuf, sizeof(keyBuf), true);
464 char valueBuf[1024] = { 0 };
465 ctk_obj_to_str(value, valueBuf, sizeof(valueBuf), false);
467 CFStringRef str = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("\n\t\t\t%s : %s,"), keyBuf, valueBuf);
468 CFStringAppend(((ctk_dict2str_context *)context)->str, str);
473 ctk_obj_to_str(CFTypeRef obj, char *buf, int bufLen, Boolean key)
475 CFStringRef str = NULL;
477 if(CFGetTypeID(obj) == CFStringGetTypeID()) {
478 // CFStringRef - print the string as is (for keys) or quoted (values)
479 str = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, key ? CFSTR("%@") : CFSTR("\"%@\""), obj);
480 } else if(CFGetTypeID(obj) == CFNumberGetTypeID()) {
481 // CFNumber - print the value using current locale
482 CFNumberRef num = (CFNumberRef)obj;
484 CFLocaleRef locale = CFLocaleCopyCurrent();
485 CFNumberFormatterRef fmt = CFNumberFormatterCreate(kCFAllocatorDefault, locale, kCFNumberFormatterDecimalStyle);
488 str = CFNumberFormatterCreateStringWithNumber(kCFAllocatorDefault, fmt, num);
490 } else if(CFGetTypeID(obj) == CFDataGetTypeID()) {
491 // CFData - print the data as <hex bytes>
492 CFDataRef data = (CFDataRef)obj;
494 CFMutableStringRef hexStr = CFStringCreateMutable(kCFAllocatorDefault, CFDataGetLength(data) * 3);
496 for(int i = 0; i < CFDataGetLength(data); i++) {
497 CFStringRef hexByte = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%02x "), *(CFDataGetBytePtr(data) + i));
498 CFStringAppend(hexStr, hexByte);
502 // Get rid of the last excessive space.
503 if(CFDataGetLength(data)) {
504 CFStringDelete(hexStr, CFRangeMake(CFStringGetLength(hexStr) - 1, 1));
507 str = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("<%@>"), hexStr);
509 } else if(CFGetTypeID(obj) == CFBooleanGetTypeID()) {
510 // CFBoolean - print true/false
511 CFBooleanRef cfbool = (CFBooleanRef)obj;
513 str = CFStringCreateWithCString(kCFAllocatorDefault, CFBooleanGetValue(cfbool) ? "true" : "false", kCFStringEncodingUTF8);
514 } else if(CFGetTypeID(obj) == SecAccessControlGetTypeID()) {
515 // SecAccessControlRef - print the constraints dictionary
516 SecAccessControlRef ac = (SecAccessControlRef)obj;
518 CFDictionaryRef constraints = SecAccessControlGetConstraints(ac);
519 CFMutableStringRef constraintsStr = CFStringCreateMutable(kCFAllocatorDefault, 1024);
520 if(constraints && CFDictionaryGetCount(constraints)) {
521 ctk_dict2str_context context;
522 context.str = constraintsStr;
523 CFDictionaryApplyFunction(constraints, ctk_dict2str, &context);
524 CFStringReplace(constraintsStr, CFRangeMake(CFStringGetLength(constraintsStr) - 1, 1), CFSTR("\n\t\t"));
527 CFDictionaryRef protection = SecAccessControlGetProtection(ac);
528 CFMutableStringRef protectionStr = CFStringCreateMutable(kCFAllocatorDefault, 512);
529 if(protection && CFDictionaryGetCount(protection)) {
530 ctk_dict2str_context context;
531 context.str = protectionStr;
532 CFDictionaryApplyFunction(protection, ctk_dict2str, &context);
533 CFStringReplace(protectionStr, CFRangeMake(CFStringGetLength(protectionStr) - 1, 1), CFSTR("\n\t\t"));
536 str = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("constraints: {%@}\n\t\tprotection: {%@}"), constraintsStr, protectionStr);
537 CFRelease(constraintsStr);
538 CFRelease(protectionStr);
541 // Fill the provided buffer with the converted string.
543 Boolean success = CFStringGetCString(str, buf, bufLen, kCFStringEncodingUTF8);
551 // Use object description as fallback...
552 CFStringRef description = CFCopyDescription(obj);
553 if(!CFStringGetCString(description, buf, bufLen, kCFStringEncodingUTF8)) {
554 // ...or else we don't know.
555 strncpy(buf, "<?>", bufLen);
558 CFRelease(description);
567 ctk_dump_item(CFTypeRef item, ctk_print_context *ctx);
570 ctk_print_dict(const void *key, const void *value, void *context)
572 char keyBuf[64] = { 0 };
573 ctk_obj_to_str(key, keyBuf, sizeof(keyBuf), true);
575 char valueBuf[1024] = { 0 };
576 ctk_obj_to_str(value, valueBuf, sizeof(valueBuf), false);
578 printf("\t%s : %s\n", keyBuf, valueBuf);
582 ctk_dump_item_header(ctk_print_context *ctx)
585 printf("==== %s #%d\n", ctx->name.UTF8String, ctx->i);
589 ctk_dump_item_footer(ctk_print_context *ctx)
595 ctk_dump_item(CFTypeRef item, ctk_print_context *ctx)
597 OSStatus stat = errSecSuccess;
599 CFTypeID tid = CFGetTypeID(item);
600 if(tid == CFDictionaryGetTypeID()) {
601 // We expect a dictionary containing item attributes.
602 ctk_dump_item_header(ctx);
603 CFDictionaryApplyFunction((CFDictionaryRef)item, ctk_print_dict, ctx);
604 ctk_dump_item_footer(ctx);
606 stat = errSecInternalComponent;
607 printf("Unexpected item type ID: %lu\n", tid);
614 ctk_dump_items(CFArrayRef items, id secClass, NSString *name)
616 OSStatus stat = errSecSuccess;
618 ctk_print_context ctx = { 1, name };
620 for(CFIndex i = 0; i < CFArrayGetCount(items); i++) {
621 CFTypeRef item = CFArrayGetValueAtIndex(items, i);
622 stat = ctk_dump_item(item, &ctx);
634 exportData(NSData *dataToExport, NSString *fileName, NSString *exportPath, NSString *elementName) {
635 NSMutableString *pem = [NSMutableString new];
636 [pem appendString:[NSString stringWithFormat:@"-----BEGIN %@-----\n", elementName]];
637 NSString *base64Cert = [dataToExport base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength | NSDataBase64EncodingEndLineWithLineFeed];
638 [pem appendString:base64Cert];
639 [pem appendString:[NSString stringWithFormat:@"\n-----END %@-----\n", elementName]];
641 NSString *fullName = [NSString stringWithFormat:@"%@/%@.pem", exportPath, fileName];
643 [pem writeToFile:fullName atomically:YES encoding:NSUTF8StringEncoding error:&error];
645 fprintf(stderr, "%s\n", [NSString stringWithFormat:@"%@", error].UTF8String);
650 ctk_dump(id secClass, NSString *name, NSString *tid, NSString *exportPath)
655 if ([secClass isEqual:(id)kSecClassIdentity] || [secClass isEqual:(id)kSecClassCertificate])
658 NSDictionary *query = @{
659 (id)kSecClass : secClass,
660 (id)kSecMatchLimit : (id)kSecMatchLimitAll,
661 (id)kSecAttrAccessGroup : (id)kSecAttrAccessGroupToken,
662 (id)kSecReturnAttributes : @YES,
663 (id)kSecReturnRef : @(returnRef)
667 NSMutableDictionary *updatedQuery = [NSMutableDictionary dictionaryWithDictionary:query];
668 updatedQuery[(id)kSecAttrTokenID] = tid;
669 query = updatedQuery;
672 OSStatus stat = SecItemCopyMatching((__bridge CFTypeRef)query, (void *)&result);
674 if (stat == errSecItemNotFound) {
675 fprintf(stderr, "No items found.\n");
677 sec_error("SecItemCopyMatching: %x (%d) - %s", stat, stat, sec_errstr(stat));
682 // We expect an array of dictionaries containing item attributes as result.
683 if([result isKindOfClass:[NSArray class]]) {
685 NSMutableArray *updatedResult = [NSMutableArray array];
686 for (NSDictionary *dict in result) {
687 NSMutableDictionary *updatedItem = [NSMutableDictionary dictionaryWithDictionary:dict];
688 id itemRef = updatedItem[(id)kSecValueRef];
689 if ([secClass isEqual:(id)kSecClassIdentity]) {
691 if (SecIdentityCopyCertificate((__bridge SecIdentityRef)itemRef, (void *)&certificateRef) != errSecSuccess)
693 itemRef = certificateRef;
696 NSData *certDigest = (__bridge NSData*)SecCertificateGetSHA1Digest((__bridge SecCertificateRef)itemRef);
697 updatedItem[@"sha1"] = certDigest;
698 [updatedItem removeObjectForKey:(id)kSecValueRef];
699 [updatedResult addObject:updatedItem];
702 NSData *certData = (__bridge_transfer NSData *)SecCertificateCopyData((__bridge SecCertificateRef)itemRef);
703 exportData(certData, updatedItem[(id)kSecAttrLabel], exportPath, @"CERTIFICATE");
704 id publicKey = (__bridge_transfer id)SecCertificateCopyKey((__bridge SecCertificateRef)itemRef);
705 NSData *pubKeyInfo = (__bridge_transfer NSData *)SecKeyCopySubjectPublicKeyInfo((__bridge SecKeyRef)publicKey);
706 exportData(pubKeyInfo, [NSString stringWithFormat:@"Public Key - %@", updatedItem[(id)kSecAttrLabel]], exportPath, @"PUBLIC KEY");
709 result = updatedResult;
713 stat = ctk_dump_items((__bridge CFArrayRef)result, secClass, name);
716 stat = errSecInternalComponent;
722 ctk_export(int argc, char * const *argv)
724 __block OSStatus stat = errSecSuccess;
726 ItemSpec itemSpec = IS_All;
728 NSString *exportPath;
733 while ((ch = getopt(argc, argv, "i:t:e:h")) != -1) {
736 if(!strcmp("certs", optarg)) {
739 else if(!strcmp("privKeys", optarg)) {
740 itemSpec = IS_PrivKeys;
742 else if(!strcmp("identities", optarg)) {
743 itemSpec = IS_Identities;
745 else if(!strcmp("all", optarg)) {
749 return SHOW_USAGE_MESSAGE;
754 tid = [NSString stringWithUTF8String:optarg];
757 exportPath = [NSString stringWithUTF8String:optarg];
764 return SHOW_USAGE_MESSAGE;
769 return SHOW_USAGE_MESSAGE;
772 NSDictionary<id, NSArray *> *classesAndNames = @{ (id)kSecClassCertificate : @[ @"certificate", @(IS_Certs) ],
773 (id)kSecClassKey : @[ @"private key", @(IS_PrivKeys) ],
774 (id)kSecClassIdentity : @[ @"identity", @(IS_Identities) ] };
776 [classesAndNames enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, NSArray * _Nonnull obj, BOOL * _Nonnull stop) {
777 if (itemSpec == IS_All || itemSpec == ((NSNumber *)obj[1]).unsignedIntegerValue) {
778 stat = ctk_dump(key, obj[0], tid, exportPath);