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/SecCertificate.h>
41 #include <Security/SecCertificatePriv.h>
42 #include <Security/SecItem.h>
43 #include <Security/SecAccessControl.h>
44 #include <Security/SecAccessControlPriv.h>
45 #include <security_cdsa_utils/cuFileIo.h>
46 #include <CoreFoundation/CoreFoundation.h>
59 * Add all itmes of specified class from a keychain to an array.
60 * Item class are things like kSecCertificateItemClass, and
61 * CSSM_DL_DB_RECORD_PRIVATE_KEY. Identities are searched separately.
63 static OSStatus addKcItems(
65 SecItemClass itemClass, // kSecCertificateItemClass
66 CFMutableArrayRef outArray,
67 unsigned *numItems) // UPDATED on return
70 SecKeychainSearchRef srchRef;
72 ortn = SecKeychainSearchCreateFromAttributes(kcRef,
77 sec_perror("SecKeychainSearchCreateFromAttributes", ortn);
81 SecKeychainItemRef itemRef;
82 ortn = SecKeychainSearchCopyNext(srchRef, &itemRef);
84 if(ortn == errSecItemNotFound) {
85 /* normal search end */
89 sec_perror("SecIdentitySearchCopyNext", ortn);
93 CFArrayAppendValue(outArray, itemRef);
94 CFRelease(itemRef); // array owns the item
102 * Add all SecIdentityRefs from a keychain into an array.
104 static OSStatus addIdentities(
105 SecKeychainRef kcRef,
106 CFMutableArrayRef outArray,
107 unsigned *numItems) // UPDATED on return
109 /* Search for all identities */
110 SecIdentitySearchRef srchRef;
111 OSStatus ortn = SecIdentitySearchCreate(kcRef,
115 sec_perror("SecIdentitySearchCreate", ortn);
120 SecIdentityRef identity;
121 ortn = SecIdentitySearchCopyNext(srchRef, &identity);
123 if(ortn == errSecItemNotFound) {
124 /* normal search end */
128 sec_perror("SecIdentitySearchCopyNext", ortn);
132 CFArrayAppendValue(outArray, identity);
134 /* the array has the retain count we need */
137 } while(ortn == noErr);
142 static int do_keychain_export(
143 SecKeychainRef kcRef,
144 SecExternalFormat externFormat,
146 const char *passphrase,
148 const char *fileName)
152 unsigned numPrivKeys = 0;
153 unsigned numPubKeys = 0;
154 unsigned numCerts = 0;
155 unsigned numIdents = 0;
157 uint32 expFlags = 0; // SecItemImportExportFlags
158 SecKeyImportExportParameters keyParams;
159 CFStringRef passStr = NULL;
160 CFDataRef outData = NULL;
164 CFMutableArrayRef exportItems = CFArrayCreateMutable(NULL, 0,
165 &kCFTypeArrayCallBacks);
168 ortn = addKcItems(kcRef, kSecCertificateItemClass, exportItems, &numCerts);
176 ortn = addKcItems(kcRef, CSSM_DL_DB_RECORD_PRIVATE_KEY, exportItems,
185 ortn = addKcItems(kcRef, CSSM_DL_DB_RECORD_PUBLIC_KEY, exportItems,
194 ortn = addKcItems(kcRef, CSSM_DL_DB_RECORD_PRIVATE_KEY, exportItems,
200 ortn = addKcItems(kcRef, CSSM_DL_DB_RECORD_PUBLIC_KEY, exportItems,
209 /* No public keys here - PKCS12 doesn't support them */
210 ortn = addKcItems(kcRef, kSecCertificateItemClass, exportItems, &numCerts);
215 ortn = addKcItems(kcRef, CSSM_DL_DB_RECORD_PRIVATE_KEY, exportItems,
224 ortn = addIdentities(kcRef, exportItems, &numIdents);
230 numPrivKeys += numIdents;
231 numCerts += numIdents;
235 sec_error("Internal error parsing item_spec");
240 numItems = CFArrayGetCount(exportItems);
241 if(externFormat == kSecFormatUnknown) {
242 /* Use default export format per set of items */
244 externFormat = kSecFormatPEMSequence;
247 externFormat = kSecFormatX509Cert;
250 externFormat = kSecFormatOpenSSL;
254 expFlags |= kSecItemPemArmour;
258 * Key related arguments, ignored if we're not exporting keys.
259 * Always specify some kind of passphrase - default is secure passkey.
261 memset(&keyParams, 0, sizeof(keyParams));
262 keyParams.version = SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION;
263 if(passphrase != NULL) {
264 passStr = CFStringCreateWithCString(NULL, passphrase, kCFStringEncodingASCII);
265 keyParams.passphrase = passStr;
268 keyParams.flags = kSecKeySecurePassphrase;
272 ortn = SecKeychainItemExport(exportItems, externFormat, expFlags, &keyParams,
275 sec_perror("SecKeychainItemExport", ortn);
280 len = CFDataGetLength(outData);
282 int rtn = writeFileSizet(fileName, CFDataGetBytePtr(outData), len);
285 fprintf(stderr, "...%lu bytes written to %s\n", len, fileName);
289 sec_error("Error writing to %s: %s", fileName, strerror(errno));
294 size_t irtn = write(STDOUT_FILENO, CFDataGetBytePtr(outData), len);
295 if(irtn != (size_t)len) {
301 CFRelease(exportItems);
313 keychain_export(int argc, char * const *argv)
317 char *outFile = NULL;
319 SecKeychainRef kcRef = NULL;
320 SecExternalFormat externFormat = kSecFormatUnknown;
321 ItemSpec itemSpec = IS_All;
324 const char *passphrase = NULL;
326 while ((ch = getopt(argc, argv, "k:o:t:f:P:wph")) != -1)
337 if(!strcmp("certs", optarg)) {
340 else if(!strcmp("allKeys", optarg)) {
341 itemSpec = IS_AllKeys;
343 else if(!strcmp("pubKeys", optarg)) {
344 itemSpec = IS_PubKeys;
346 else if(!strcmp("privKeys", optarg)) {
347 itemSpec = IS_PrivKeys;
349 else if(!strcmp("identities", optarg)) {
350 itemSpec = IS_Identities;
352 else if(!strcmp("all", optarg)) {
356 return SHOW_USAGE_MESSAGE;
360 if(!strcmp("openssl", optarg)) {
361 externFormat = kSecFormatOpenSSL;
363 else if(!strcmp("openssh1", optarg)) {
364 externFormat = kSecFormatSSH;
366 else if(!strcmp("openssh2", optarg)) {
367 externFormat = kSecFormatSSHv2;
369 else if(!strcmp("bsafe", optarg)) {
370 externFormat = kSecFormatBSAFE;
372 else if(!strcmp("raw", optarg)) {
373 externFormat = kSecFormatRawKey;
375 else if(!strcmp("pkcs7", optarg)) {
376 externFormat = kSecFormatPKCS7;
378 else if(!strcmp("pkcs8", optarg)) {
379 externFormat = kSecFormatWrappedPKCS8;
381 else if(!strcmp("pkcs12", optarg)) {
382 externFormat = kSecFormatPKCS12;
384 else if(!strcmp("netscape", optarg)) {
385 externFormat = kSecFormatNetscapeCertSequence;
387 else if(!strcmp("x509", optarg)) {
388 externFormat = kSecFormatX509Cert;
390 else if(!strcmp("pemseq", optarg)) {
391 externFormat = kSecFormatPEMSequence;
394 return SHOW_USAGE_MESSAGE;
408 return SHOW_USAGE_MESSAGE;
413 switch(externFormat) {
414 case kSecFormatOpenSSL:
415 case kSecFormatUnknown: // i.e., use default
416 externFormat = kSecFormatWrappedOpenSSL;
419 externFormat = kSecFormatWrappedSSH;
421 case kSecFormatSSHv2:
422 /* there is no wrappedSSHv2 */
423 externFormat = kSecFormatWrappedOpenSSL;
425 case kSecFormatWrappedPKCS8:
429 sec_error("Don't know how to wrap in specified format/type");
430 return SHOW_USAGE_MESSAGE;
435 kcRef = keychain_open(kcName);
440 result = do_keychain_export(kcRef, externFormat, itemSpec,
441 passphrase, doPem, outFile);
450 CFMutableStringRef str;
451 } ctk_dict2str_context;
455 ctk_obj_to_str(CFTypeRef obj, char *buf, int bufLen, Boolean key);
458 ctk_dict2str(const void *key, const void *value, void *context)
460 char keyBuf[64] = { 0 };
461 ctk_obj_to_str(key, keyBuf, sizeof(keyBuf), true);
463 char valueBuf[1024] = { 0 };
464 ctk_obj_to_str(value, valueBuf, sizeof(valueBuf), false);
466 CFStringRef str = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("\n\t\t\t%s : %s,"), keyBuf, valueBuf);
467 CFStringAppend(((ctk_dict2str_context *)context)->str, str);
472 ctk_obj_to_str(CFTypeRef obj, char *buf, int bufLen, Boolean key)
474 CFStringRef str = NULL;
476 if(CFGetTypeID(obj) == CFStringGetTypeID()) {
477 // CFStringRef - print the string as is (for keys) or quoted (values)
478 str = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, key ? CFSTR("%@") : CFSTR("\"%@\""), obj);
479 } else if(CFGetTypeID(obj) == CFNumberGetTypeID()) {
480 // CFNumber - print the value using current locale
481 CFNumberRef num = (CFNumberRef)obj;
483 CFLocaleRef locale = CFLocaleCopyCurrent();
484 CFNumberFormatterRef fmt = CFNumberFormatterCreate(kCFAllocatorDefault, locale, kCFNumberFormatterDecimalStyle);
487 str = CFNumberFormatterCreateStringWithNumber(kCFAllocatorDefault, fmt, num);
489 } else if(CFGetTypeID(obj) == CFDataGetTypeID()) {
490 // CFData - print the data as <hex bytes>
491 CFDataRef data = (CFDataRef)obj;
493 CFMutableStringRef hexStr = CFStringCreateMutable(kCFAllocatorDefault, CFDataGetLength(data) * 3);
495 for(int i = 0; i < CFDataGetLength(data); i++) {
496 CFStringRef hexByte = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%02x "), *(CFDataGetBytePtr(data) + i));
497 CFStringAppend(hexStr, hexByte);
501 // Get rid of the last excessive space.
502 if(CFDataGetLength(data)) {
503 CFStringDelete(hexStr, CFRangeMake(CFStringGetLength(hexStr) - 1, 1));
506 str = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("<%@>"), hexStr);
508 } else if(CFGetTypeID(obj) == CFBooleanGetTypeID()) {
509 // CFBoolean - print true/false
510 CFBooleanRef cfbool = (CFBooleanRef)obj;
512 str = CFStringCreateWithCString(kCFAllocatorDefault, CFBooleanGetValue(cfbool) ? "true" : "false", kCFStringEncodingUTF8);
513 } else if(CFGetTypeID(obj) == SecAccessControlGetTypeID()) {
514 // SecAccessControlRef - print the constraints dictionary
515 SecAccessControlRef ac = (SecAccessControlRef)obj;
517 CFDictionaryRef constraints = SecAccessControlGetConstraints(ac);
518 CFMutableStringRef constraintsStr = CFStringCreateMutable(kCFAllocatorDefault, 1024);
519 if(constraints && CFDictionaryGetCount(constraints)) {
520 ctk_dict2str_context context;
521 context.str = constraintsStr;
522 CFDictionaryApplyFunction(constraints, ctk_dict2str, &context);
523 CFStringReplace(constraintsStr, CFRangeMake(CFStringGetLength(constraintsStr) - 1, 1), CFSTR("\n\t\t"));
526 CFDictionaryRef protection = SecAccessControlGetProtection(ac);
527 CFMutableStringRef protectionStr = CFStringCreateMutable(kCFAllocatorDefault, 512);
528 if(protection && CFDictionaryGetCount(protection)) {
529 ctk_dict2str_context context;
530 context.str = protectionStr;
531 CFDictionaryApplyFunction(protection, ctk_dict2str, &context);
532 CFStringReplace(protectionStr, CFRangeMake(CFStringGetLength(protectionStr) - 1, 1), CFSTR("\n\t\t"));
535 str = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("constraints: {%@}\n\t\tprotection: {%@}"), constraintsStr, protectionStr);
536 CFRelease(constraintsStr);
537 CFRelease(protectionStr);
540 // Fill the provided buffer with the converted string.
542 Boolean success = CFStringGetCString(str, buf, bufLen, kCFStringEncodingUTF8);
550 // Use object description as fallback...
551 CFStringRef description = CFCopyDescription(obj);
552 if(!CFStringGetCString(description, buf, bufLen, kCFStringEncodingUTF8)) {
553 // ...or else we don't know.
554 strncpy(buf, "<?>", bufLen);
557 CFRelease(description);
566 ctk_dump_item(CFTypeRef item, ctk_print_context *ctx);
569 ctk_print_dict(const void *key, const void *value, void *context)
571 char keyBuf[64] = { 0 };
572 ctk_obj_to_str(key, keyBuf, sizeof(keyBuf), true);
574 char valueBuf[1024] = { 0 };
575 ctk_obj_to_str(value, valueBuf, sizeof(valueBuf), false);
577 printf("\t%s : %s\n", keyBuf, valueBuf);
581 ctk_dump_item_header(ctk_print_context *ctx)
584 printf("==== %s #%d\n", ctx->name, ctx->i);
588 ctk_dump_item_footer(ctk_print_context *ctx)
594 ctk_dump_item(CFTypeRef item, ctk_print_context *ctx)
596 OSStatus stat = errSecSuccess;
598 CFTypeID tid = CFGetTypeID(item);
599 if(tid == CFDictionaryGetTypeID()) {
600 // We expect a dictionary containing item attributes.
601 ctk_dump_item_header(ctx);
602 CFDictionaryApplyFunction((CFDictionaryRef)item, ctk_print_dict, ctx);
603 ctk_dump_item_footer(ctx);
605 stat = errSecInternalComponent;
606 printf("Unexpected item type ID: %lu\n", tid);
613 ctk_dump_items(CFArrayRef items, CFTypeRef secClass, const char *name)
615 OSStatus stat = errSecSuccess;
617 ctk_print_context ctx = { 1, name };
619 for(CFIndex i = 0; i < CFArrayGetCount(items); i++) {
620 CFTypeRef item = CFArrayGetValueAtIndex(items, i);
621 stat = ctk_dump_item(item, &ctx);
633 ctk_dump(CFTypeRef secClass, const char *name, const char *tid)
638 if ([(__bridge id)secClass isEqual:(id)kSecClassIdentity] || [(__bridge id)secClass isEqual:(id)kSecClassCertificate])
641 NSDictionary *query = @{
642 (id)kSecClass : (__bridge id)secClass,
643 (id)kSecMatchLimit : (id)kSecMatchLimitAll,
644 (id)kSecAttrAccessGroup : (id)kSecAttrAccessGroupToken,
645 (id)kSecReturnAttributes : @YES,
646 (id)kSecReturnRef : @(returnRef)
650 NSMutableDictionary *updatedQuery = [NSMutableDictionary dictionaryWithDictionary:query];
651 updatedQuery[(id)kSecAttrTokenID] = [NSString stringWithUTF8String:tid];
652 query = updatedQuery;
655 OSStatus stat = SecItemCopyMatching((__bridge CFTypeRef)query, (void *)&result);
657 if (stat == errSecItemNotFound) {
658 fprintf(stderr, "No items found.\n");
660 sec_error("SecItemCopyMatching: %x (%d) - %s", stat, stat, sec_errstr(stat));
665 // We expect an array of dictionaries containing item attributes as result.
666 if([result isKindOfClass:[NSArray class]]) {
668 NSMutableArray *updatedResult = [NSMutableArray array];
669 for (NSDictionary *dict in result) {
670 NSMutableDictionary *updatedItem = [NSMutableDictionary dictionaryWithDictionary:dict];
671 id itemRef = updatedItem[(id)kSecValueRef];
672 if ([(__bridge id)secClass isEqual:(id)kSecClassIdentity]) {
674 if (SecIdentityCopyCertificate((__bridge SecIdentityRef)itemRef, (void *)&certificateRef) != errSecSuccess)
676 itemRef = certificateRef;
679 NSData *certDigest = (__bridge NSData*)SecCertificateGetSHA1Digest((__bridge SecCertificateRef)itemRef);
680 updatedItem[@"sha1"] = certDigest;
681 [updatedItem removeObjectForKey:(id)kSecValueRef];
682 [updatedResult addObject:updatedItem];
684 result = updatedResult;
687 stat = ctk_dump_items((__bridge CFArrayRef)result, secClass, name);
689 stat = errSecInternalComponent;
695 ctk_export(int argc, char * const *argv)
697 OSStatus stat = errSecSuccess;
699 ItemSpec itemSpec = IS_All;
700 const char *tid = NULL;
703 while ((ch = getopt(argc, argv, "i:t:h")) != -1) {
706 if(!strcmp("certs", optarg)) {
709 else if(!strcmp("privKeys", optarg)) {
710 itemSpec = IS_PrivKeys;
712 else if(!strcmp("identities", optarg)) {
713 itemSpec = IS_Identities;
715 else if(!strcmp("all", optarg)) {
719 return SHOW_USAGE_MESSAGE;
728 return SHOW_USAGE_MESSAGE;
732 CFTypeRef classes[] = { kSecClassCertificate, kSecClassKey, kSecClassIdentity };
733 const char* names[] = { "certificate", "private key", "identity" };
734 ItemSpec specs[] = { IS_Certs, IS_PrivKeys, IS_Identities };
736 for(size_t i = 0; i < sizeof(classes)/sizeof(classes[0]); i++) {
737 if(specs[i] == itemSpec || itemSpec == IS_All) {
738 stat = ctk_dump(classes[i], names[i], tid);