]> git.saurik.com Git - apple/security.git/blob - SecurityTool/keychain_utilities.c
Security-58286.270.3.0.1.tar.gz
[apple/security.git] / SecurityTool / keychain_utilities.c
1 /*
2 * Copyright (c) 2003-2009,2012,2014 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
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
11 * file.
12 *
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.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 *
23 * keychain_utilities.c
24 */
25
26 #include "keychain_utilities.h"
27 #include "security_tool.h"
28
29 #include <Security/cssmapi.h>
30 #include <Security/SecAccess.h>
31 #include <Security/SecACL.h>
32 #include <Security/SecTrustedApplication.h>
33 #include <Security/SecKeychainItem.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <sys/param.h>
37 #include <libkern/OSByteOrder.h>
38 #include <utilities/SecCFRelease.h>
39
40 #include "readline_cssm.h"
41
42 // SecTrustedApplicationValidateWithPath
43 #include <Security/SecTrustedApplicationPriv.h>
44 #include <Security/SecKeychainPriv.h>
45
46
47 void check_obsolete_keychain(const char *kcName)
48 {
49 if(kcName == NULL) {
50 return;
51 }
52 if(!strcmp(kcName, "/System/Library/Keychains/X509Anchors")) {
53 fprintf(stderr, "***************************************************************\n");
54 fprintf(stderr, " WARNING\n");
55 fprintf(stderr, "\n");
56 fprintf(stderr, "The keychain you are accessing, X509Anchors, is no longer\n");
57 fprintf(stderr, "used by Mac OS X as the system root certificate store.\n");
58 fprintf(stderr, "Please read the security man page for information on the \n");
59 fprintf(stderr, "add-trusted-cert command. New system root certificates should\n");
60 fprintf(stderr, "be added to the Admin Trust Settings domain and to the \n");
61 fprintf(stderr, "System keychain in /Library/Keychains.\n");
62 fprintf(stderr, "***************************************************************\n");
63 }
64 else if(!strcmp(kcName, "/System/Library/Keychains/X509Certificates")) {
65 fprintf(stderr, "***************************************************************\n");
66 fprintf(stderr, " WARNING\n");
67 fprintf(stderr, "\n");
68 fprintf(stderr, "The keychain you are accessing, X509Certificates, is no longer\n");
69 fprintf(stderr, "used by Mac OS X as the system intermediate certificate\n");
70 fprintf(stderr, "store. New system intermediate certificates should be added\n");
71 fprintf(stderr, "to the System keychain in /Library/Keychains.\n");
72 fprintf(stderr, "***************************************************************\n");
73 }
74 }
75
76 SecKeychainRef CF_RETURNS_RETAINED
77 keychain_open(const char *name)
78 {
79 SecKeychainRef keychain = NULL;
80 OSStatus result;
81
82 check_obsolete_keychain(name);
83 if (name && name[0] != '/')
84 {
85 CFArrayRef dynamic = NULL;
86 result = SecKeychainCopyDomainSearchList(
87 kSecPreferencesDomainDynamic, &dynamic);
88 if (result)
89 {
90 sec_error("SecKeychainCopyDomainSearchList %s: %s",
91 name, sec_errstr(result));
92 return NULL;
93 }
94 else
95 {
96 uint32_t i;
97 CFIndex count = dynamic ? CFArrayGetCount(dynamic) : 0;
98
99 for (i = 0; i < count; ++i)
100 {
101 char pathName[MAXPATHLEN];
102 UInt32 ioPathLength = sizeof(pathName);
103 bzero(pathName, ioPathLength);
104 keychain = (SecKeychainRef)CFArrayGetValueAtIndex(dynamic, i);
105 result = SecKeychainGetPath(keychain, &ioPathLength, pathName);
106 if (result)
107 {
108 sec_error("SecKeychainGetPath %s: %s",
109 name, sec_errstr(result));
110 return NULL;
111 }
112 if (!strncmp(pathName, name, ioPathLength))
113 {
114 CFRetain(keychain);
115 CFRelease(dynamic);
116 return keychain;
117 }
118 }
119 CFReleaseNull(dynamic);
120 }
121 }
122
123 if(name) {
124 result = SecKeychainOpen(name, &keychain);
125 } else {
126 result = errSecParam;
127 }
128 if (result)
129 {
130 sec_error("SecKeychainOpen %s: %s", name, sec_errstr(result));
131 }
132
133 return keychain;
134 }
135
136 CFTypeRef
137 keychain_create_array(int argc, char * const *argv)
138 {
139 if (argc == 0)
140 return NULL;
141 else if (argc == 1)
142 return keychain_open(argv[0]);
143 else
144 {
145 CFMutableArrayRef keychains = CFArrayCreateMutable(NULL, argc, &kCFTypeArrayCallBacks);
146 int ix;
147 for (ix = 0; ix < argc; ++ix)
148 {
149 SecKeychainRef keychain = keychain_open(argv[ix]);
150 if (keychain)
151 {
152 CFArrayAppendValue(keychains, keychain);
153 CFRelease(keychain);
154 }
155 }
156
157 return keychains;
158 }
159 }
160
161 int
162 parse_fourcharcode(const char *name, UInt32 *code)
163 {
164 UInt32 cc = 0;
165 size_t len = (name) ? strlen(name) : 0;
166
167 // error check the name
168 if (len != 4)
169 {
170 fprintf(stderr, "Error: four-character types must be exactly 4 characters long.\n");
171 if (len == 3) {
172 fprintf(stderr, "(Try \"%s \" instead of \"%s\")\n", name, name);
173 }
174 return 1;
175 }
176
177 int i;
178 for (i = 0; i < 4; ++i)
179 {
180 cc = (cc << 8) | name[i];
181 }
182
183 *code = cc; // note: this is in host byte order, suitable for passing to APIs
184
185 return 0;
186 }
187
188 int
189 print_keychain_name(FILE *stream, SecKeychainRef keychain)
190 {
191 int result = 0;
192 char pathName[MAXPATHLEN];
193 UInt32 ioPathLength = sizeof(pathName);
194 OSStatus status = SecKeychainGetPath(keychain, &ioPathLength, pathName);
195 if (status)
196 {
197 sec_perror("SecKeychainGetPath", status);
198 result = 1;
199 goto loser;
200 }
201
202 print_buffer(stream, ioPathLength, pathName);
203
204 loser:
205 return result;
206 }
207
208 static int
209 print_keychain_version(FILE* stream, SecKeychainRef keychain)
210 {
211 int result = 0;
212 UInt32 version;
213 OSStatus status = SecKeychainGetKeychainVersion(keychain, &version);
214 if(status) {
215 sec_perror("SecKeychainGetKeychainVersion", status);
216 result = 1;
217 goto loser;
218 }
219
220 fprintf(stream, "%d", (uint32_t) version);
221
222 loser:
223 return result;
224 }
225
226 static void
227 print_cfdata(FILE *stream, CFDataRef data)
228 {
229 if (data)
230 return print_buffer(stream, CFDataGetLength(data), CFDataGetBytePtr(data));
231 else
232 fprintf(stream, "<NULL>");
233 }
234
235 void
236 print_cfstring(FILE *stream, CFStringRef string)
237 {
238 if (!string)
239 fprintf(stream, "<NULL>");
240 else
241 {
242 const char *utf8 = CFStringGetCStringPtr(string, kCFStringEncodingUTF8);
243 if (utf8)
244 fprintf(stream, "%s", utf8);
245 else
246 {
247 CFRange rangeToProcess = CFRangeMake(0, CFStringGetLength(string));
248 while (rangeToProcess.length > 0)
249 {
250 UInt8 localBuffer[256];
251 CFIndex usedBufferLength;
252 CFIndex numChars = CFStringGetBytes(string, rangeToProcess,
253 kCFStringEncodingUTF8, '?', FALSE, localBuffer,
254 sizeof(localBuffer), &usedBufferLength);
255 if (numChars == 0)
256 break; // Failed to convert anything...
257
258 fprintf(stream, "%.*s", (int)usedBufferLength, localBuffer);
259 rangeToProcess.location += numChars;
260 rangeToProcess.length -= numChars;
261 }
262 }
263 }
264 }
265
266 static int
267 print_access(FILE *stream, SecAccessRef access, Boolean interactive)
268 {
269 CFArrayRef aclList = NULL;
270 CFIndex aclix, aclCount;
271 int result = 0;
272 OSStatus status;
273
274 status = SecAccessCopyACLList(access, &aclList);
275 if (status)
276 {
277 sec_perror("SecAccessCopyACLList", status);
278 result = 1;
279 goto loser;
280 }
281
282 aclCount = CFArrayGetCount(aclList);
283 fprintf(stream, "access: %lu entries\n", aclCount);
284 for (aclix = 0; aclix < aclCount; ++aclix)
285 {
286 CFArrayRef applicationList = NULL;
287 CFStringRef description = NULL;
288 CSSM_ACL_KEYCHAIN_PROMPT_SELECTOR promptSelector = {};
289 CFIndex appix, appCount;
290
291 SecACLRef acl = (SecACLRef)CFArrayGetValueAtIndex(aclList, aclix);
292 CSSM_ACL_AUTHORIZATION_TAG tags[64]; // Pick some upper limit
293 uint32 tagix, tagCount = sizeof(tags) / sizeof(*tags);
294 status = SecACLGetAuthorizations(acl, tags, &tagCount);
295 if (status)
296 {
297 sec_perror("SecACLGetAuthorizations", status);
298 result = 1;
299 goto loser;
300 }
301
302 fprintf(stream, " entry %lu:\n authorizations (%lu):", aclix,
303 (unsigned long)tagCount);
304 bool printPartitionIDList = false;
305 for (tagix = 0; tagix < tagCount; ++tagix)
306 {
307 CSSM_ACL_AUTHORIZATION_TAG tag = tags[tagix];
308 switch (tag)
309 {
310 case CSSM_ACL_AUTHORIZATION_ANY:
311 fputs(" any", stream);
312 break;
313 case CSSM_ACL_AUTHORIZATION_LOGIN:
314 fputs(" login", stream);
315 break;
316 case CSSM_ACL_AUTHORIZATION_GENKEY:
317 fputs(" genkey", stream);
318 break;
319 case CSSM_ACL_AUTHORIZATION_DELETE:
320 fputs(" delete", stream);
321 break;
322 case CSSM_ACL_AUTHORIZATION_EXPORT_WRAPPED:
323 fputs(" export_wrapped", stream);
324 break;
325 case CSSM_ACL_AUTHORIZATION_EXPORT_CLEAR:
326 fputs(" export_clear", stream);
327 break;
328 case CSSM_ACL_AUTHORIZATION_IMPORT_WRAPPED:
329 fputs(" import_wrapped", stream);
330 break;
331 case CSSM_ACL_AUTHORIZATION_IMPORT_CLEAR:
332 fputs(" import_clear", stream);
333 break;
334 case CSSM_ACL_AUTHORIZATION_SIGN:
335 fputs(" sign", stream);
336 break;
337 case CSSM_ACL_AUTHORIZATION_ENCRYPT:
338 fputs(" encrypt", stream);
339 break;
340 case CSSM_ACL_AUTHORIZATION_DECRYPT:
341 fputs(" decrypt", stream);
342 break;
343 case CSSM_ACL_AUTHORIZATION_MAC:
344 fputs(" mac", stream);
345 break;
346 case CSSM_ACL_AUTHORIZATION_DERIVE:
347 fputs(" derive", stream);
348 break;
349 case CSSM_ACL_AUTHORIZATION_DBS_CREATE:
350 fputs(" dbs_create", stream);
351 break;
352 case CSSM_ACL_AUTHORIZATION_DBS_DELETE:
353 fputs(" dbs_delete", stream);
354 break;
355 case CSSM_ACL_AUTHORIZATION_DB_READ:
356 fputs(" db_read", stream);
357 break;
358 case CSSM_ACL_AUTHORIZATION_DB_INSERT:
359 fputs(" db_insert", stream);
360 break;
361 case CSSM_ACL_AUTHORIZATION_DB_MODIFY:
362 fputs(" db_modify", stream);
363 break;
364 case CSSM_ACL_AUTHORIZATION_DB_DELETE:
365 fputs(" db_delete", stream);
366 break;
367 case CSSM_ACL_AUTHORIZATION_CHANGE_ACL:
368 fputs(" change_acl", stream);
369 break;
370 case CSSM_ACL_AUTHORIZATION_CHANGE_OWNER:
371 fputs(" change_owner", stream);
372 break;
373 case CSSM_ACL_AUTHORIZATION_INTEGRITY:
374 fputs(" integrity", stream);
375 break;
376 case CSSM_ACL_AUTHORIZATION_PARTITION_ID:
377 fputs(" partition_id", stream);
378 printPartitionIDList = true;
379 break;
380 default:
381 fprintf(stream, " tag=%lu", (unsigned long)tag);
382 break;
383 }
384 }
385 fputc('\n', stream);
386
387 status = SecACLCopySimpleContents(acl, &applicationList, &description, &promptSelector);
388 if (status)
389 {
390 sec_perror("SecACLCopySimpleContents", status);
391 continue;
392 }
393
394 if (promptSelector.flags & CSSM_ACL_KEYCHAIN_PROMPT_REQUIRE_PASSPHRASE)
395 fputs(" require-password\n", stream);
396 else
397 fputs(" don't-require-password\n", stream);
398
399 fputs(" description: ", stream);
400 // special case for Partition IDs
401 if(printPartitionIDList) {
402 print_partition_id_list(stream, description);
403 } else {
404 print_cfstring(stream, description);
405 }
406 fputc('\n', stream);
407
408 if (applicationList)
409 {
410 appCount = CFArrayGetCount(applicationList);
411 fprintf(stream, " applications (%lu):\n", appCount);
412 }
413 else
414 {
415 appCount = 0;
416 fprintf(stream, " applications: <null>\n");
417 }
418
419 for (appix = 0; appix < appCount; ++appix)
420 {
421 const UInt8* bytes;
422 SecTrustedApplicationRef app = (SecTrustedApplicationRef)CFArrayGetValueAtIndex(applicationList, appix);
423 CFDataRef data = NULL;
424 fprintf(stream, " %lu: ", appix);
425 status = SecTrustedApplicationCopyData(app, &data);
426 if (status)
427 {
428 sec_perror("SecTrustedApplicationCopyData", status);
429 continue;
430 }
431
432 bytes = CFDataGetBytePtr(data);
433 if (bytes && bytes[0] == 0x2f) {
434 fprintf(stream, "%s", (const char *)bytes);
435 if ((status = SecTrustedApplicationValidateWithPath(app, (const char *)bytes)) == noErr) {
436 fprintf(stream, " (OK)");
437 } else {
438 fprintf(stream, " (status %d)", (int)status);
439 }
440 fprintf(stream, "\n");
441 } else {
442 print_cfdata(stream, data);
443 fputc('\n', stream);
444 }
445 if (data)
446 CFRelease(data);
447 }
448
449 if (applicationList)
450 CFRelease(applicationList);
451
452 if (description)
453 CFRelease(description);
454
455 if (interactive)
456 {
457 char buffer[10] = {};
458 fprintf(stderr, "Remove this acl? ");
459 if (readline(buffer, sizeof(buffer)) && buffer[0] == 'y')
460 {
461 fprintf(stderr, "removing acl\n");
462 status = SecACLRemove(acl);
463 if (status)
464 {
465 sec_perror("SecACLRemove", status);
466 continue;
467 }
468 }
469 }
470 }
471
472 loser:
473 if (aclList)
474 CFRelease(aclList);
475
476 return result;
477 }
478
479 int
480 print_keychain_item_attributes(FILE *stream, SecKeychainItemRef item, Boolean show_data, Boolean show_raw_data, Boolean show_acl, Boolean interactive)
481 {
482 int result = 0;
483 unsigned int ix;
484 OSStatus status;
485 SecKeychainRef keychain = NULL;
486 SecAccessRef access = NULL;
487 SecItemClass itemClass = 0;
488 UInt32 itemID;
489 SecKeychainAttributeList *attrList = NULL;
490 SecKeychainAttributeInfo *info = NULL;
491 UInt32 length = 0;
492 void *data = NULL;
493
494 status = SecKeychainItemCopyKeychain(item, &keychain);
495 if (status)
496 {
497 sec_perror("SecKeychainItemCopyKeychain", status);
498 result = 1;
499 goto loser;
500 }
501
502 fputs("keychain: ", stream);
503 result = print_keychain_name(stream, keychain);
504 fputc('\n', stream);
505 if (result)
506 goto loser;
507 fputs("version: ", stream);
508 result = print_keychain_version(stream, keychain);
509 fputc('\n', stream);
510 if (result)
511 goto loser;
512
513 /* First find out the item class. */
514 status = SecKeychainItemCopyAttributesAndData(item, NULL, &itemClass, NULL, NULL, NULL);
515 if (status)
516 {
517 sec_perror("SecKeychainItemCopyAttributesAndData", status);
518 result = 1;
519 goto loser;
520 }
521
522 fputs("class: ", stream);
523 char buffer[4];
524 buffer[3] = itemClass & 0xFF;
525 buffer[2] = (itemClass >> 8) & 0xFF;
526 buffer[1] = (itemClass >> 16) & 0xFF;
527 buffer[0] = (itemClass >> 24) & 0xFF;
528
529 print_buffer(stream, 4, buffer);
530 fputs("\nattributes:\n", stream);
531
532 switch (itemClass)
533 {
534 case kSecInternetPasswordItemClass:
535 itemID = CSSM_DL_DB_RECORD_INTERNET_PASSWORD;
536 break;
537 case kSecGenericPasswordItemClass:
538 itemID = CSSM_DL_DB_RECORD_GENERIC_PASSWORD;
539 break;
540 case 'ashp': /* kSecAppleSharePasswordItemClass */
541 itemID = CSSM_DL_DB_RECORD_APPLESHARE_PASSWORD;
542 break;
543 default:
544 itemID = itemClass;
545 break;
546 }
547
548 /* Now get the AttributeInfo for it. */
549 status = SecKeychainAttributeInfoForItemID(keychain, itemID, &info);
550 if (status)
551 {
552 sec_perror("SecKeychainAttributeInfoForItemID", status);
553 result = 1;
554 goto loser;
555 }
556
557 status = SecKeychainItemCopyAttributesAndData(item, info, &itemClass, &attrList,
558 show_data ? &length : NULL,
559 show_data ? &data : NULL);
560 if (status)
561 {
562 sec_perror("SecKeychainItemCopyAttributesAndData", status);
563 result = 1;
564 goto loser;
565 }
566
567 if (info->count != attrList->count)
568 {
569 sec_error("info count: %ld != attribute count: %ld", info->count, attrList->count);
570 result = 1;
571 goto loser;
572 }
573
574 for (ix = 0; ix < info->count; ++ix)
575 {
576 UInt32 tag = info->tag[ix];
577 UInt32 format = info->format[ix];
578 SecKeychainAttribute *attribute = &attrList->attr[ix];
579 if (tag != attribute->tag)
580 {
581 sec_error("attribute %d of %ld info tag: %ld != attribute tag: %ld", ix, info->count, tag, attribute->tag);
582 result = 1;
583 goto loser;
584 }
585
586 fputs(" ", stream);
587 print_uint32(stream, tag);
588 switch (format)
589 {
590 case CSSM_DB_ATTRIBUTE_FORMAT_STRING:
591 fputs("<string>", stream);
592 break;
593 case CSSM_DB_ATTRIBUTE_FORMAT_SINT32:
594 fputs("<sint32>", stream);
595 break;
596 case CSSM_DB_ATTRIBUTE_FORMAT_UINT32:
597 fputs("<uint32>", stream);
598 break;
599 case CSSM_DB_ATTRIBUTE_FORMAT_BIG_NUM:
600 fputs("<bignum>", stream);
601 break;
602 case CSSM_DB_ATTRIBUTE_FORMAT_REAL:
603 fputs("<real>", stream);
604 break;
605 case CSSM_DB_ATTRIBUTE_FORMAT_TIME_DATE:
606 fputs("<timedate>", stream);
607 break;
608 case CSSM_DB_ATTRIBUTE_FORMAT_BLOB:
609 fputs("<blob>", stream);
610 break;
611 case CSSM_DB_ATTRIBUTE_FORMAT_MULTI_UINT32:
612 fputs("<uint32>", stream);
613 break;
614 case CSSM_DB_ATTRIBUTE_FORMAT_COMPLEX:
615 fputs("<complex>", stream);
616 break;
617 default:
618 fprintf(stream, "<format: %d>", (int)format);
619 break;
620 }
621 fputs("=", stream);
622 if (!attribute->length && !attribute->data)
623 fputs("<NULL>", stream);
624 else
625 { switch (format)
626 {
627 case CSSM_DB_ATTRIBUTE_FORMAT_SINT32:
628 case CSSM_DB_ATTRIBUTE_FORMAT_UINT32:
629 {
630 print_uint32(stream, *(UInt32*) attribute->data);
631 break;
632 }
633
634 case CSSM_DB_ATTRIBUTE_FORMAT_MULTI_UINT32:
635 {
636 int n = attribute->length / sizeof(UInt32);
637 UInt32* ptr = (UInt32*) attribute->data;
638
639 while (n--)
640 {
641 print_uint32(stream, *ptr++);
642 }
643 }
644 break;
645
646 default:
647 {
648 print_buffer(stream, attribute->length, attribute->data);
649 }
650 break;
651 }
652 }
653 fputc('\n', stream);
654 }
655
656 if (show_data)
657 {
658 fputs("data:\n", stream);
659 print_buffer(stream, length, data);
660 fputc('\n', stream);
661 }
662
663 if (show_raw_data)
664 {
665 CSSM_DL_DB_HANDLE dldbHandle = {};
666 const CSSM_DB_UNIQUE_RECORD *uniqueRecordID = NULL;
667 CSSM_DATA data = {};
668 status = SecKeychainItemGetDLDBHandle(item, &dldbHandle);
669 if (status)
670 {
671 sec_perror("SecKeychainItemGetDLDBHandle", status);
672 result = 1;
673 goto loser;
674 }
675
676 status = SecKeychainItemGetUniqueRecordID(item, &uniqueRecordID);
677 if (status)
678 {
679 sec_perror("SecKeychainItemGetUniqueRecordID", status);
680 result = 1;
681 goto loser;
682 }
683
684 status = CSSM_DL_DataGetFromUniqueRecordId(dldbHandle, uniqueRecordID, NULL, &data);
685 if (status)
686 {
687 sec_perror("CSSM_DL_DataGetFromUniqueRecordId", status);
688 result = 1;
689 goto loser;
690 }
691
692 fputs("raw data:\n", stream);
693 print_buffer(stream, data.Length, data.Data);
694 fputc('\n', stream);
695
696 /* @@@ Hmm which allocators should we use here? */
697 free(data.Data);
698 }
699
700 if (show_acl)
701 {
702 status = SecKeychainItemCopyAccess(item, &access);
703 if (status == errSecNoAccessForItem)
704 fprintf(stream, "no access control for this item\n");
705 else
706 {
707 if (status)
708 {
709 sec_perror("SecKeychainItemCopyAccess", status);
710 result = 1;
711 goto loser;
712 }
713
714 result = print_access(stream, access, interactive);
715 if (result)
716 goto loser;
717
718 if (interactive)
719 {
720 char buffer[10] = {};
721 fprintf(stderr, "Update access? ");
722 if (readline(buffer, sizeof(buffer)) && buffer[0] == 'y')
723 {
724 fprintf(stderr, "Updating access\n");
725 status = SecKeychainItemSetAccess(item, access);
726 if (status)
727 {
728 sec_perror("SecKeychainItemSetAccess", status);
729 result = 1;
730 goto loser;
731 }
732 }
733 }
734 }
735 }
736
737 loser:
738 if (access)
739 CFRelease(access);
740
741 if (attrList)
742 {
743 status = SecKeychainItemFreeAttributesAndData(attrList, data);
744 if (status)
745 sec_perror("SecKeychainItemFreeAttributesAndData", status);
746 }
747
748 if (info)
749 {
750 status = SecKeychainFreeAttributeInfo(info);
751 if (status)
752 sec_perror("SecKeychainFreeAttributeInfo", status);
753 }
754
755 if (keychain)
756 CFRelease(keychain);
757
758 return result;
759 }
760
761 static void
762 print_buffer_hex(FILE *stream, size_t length, const void *data)
763 {
764 uint8 *p = (uint8 *) data;
765 while (length--)
766 {
767 int ch = *p++;
768 fprintf(stream, "%02X", ch);
769 }
770 }
771
772 static void
773 print_buffer_ascii(FILE *stream, size_t length, const void *data)
774 {
775 uint8 *p = (uint8 *) data;
776 while (length--)
777 {
778 int ch = *p++;
779 if (ch >= ' ' && ch <= '~' && ch != '\\')
780 {
781 fputc(ch, stream);
782 }
783 else
784 {
785 fputc('\\', stream);
786 fputc('0' + ((ch >> 6) & 7), stream);
787 fputc('0' + ((ch >> 3) & 7), stream);
788 fputc('0' + ((ch >> 0) & 7), stream);
789 }
790 }
791 }
792
793 void
794 print_buffer(FILE *stream, size_t length, const void *data)
795 {
796 uint8 *p = (uint8 *) data;
797 Boolean hex = FALSE;
798 Boolean ascii = FALSE;
799 UInt32 ix;
800 for (ix = 0; ix < length; ++ix)
801 {
802 int ch = *p++;
803 if (ch >= ' ' && ch <= '~' && ch != '\\')
804 ascii = TRUE;
805 else
806 hex = TRUE;
807 }
808
809 if (hex)
810 {
811 fputc('0', stream);
812 fputc('x', stream);
813 print_buffer_hex(stream, length, data);
814 if (ascii)
815 fputc(' ', stream);
816 fputc(' ', stream);
817 }
818 if (ascii)
819 {
820 fputc('"', stream);
821 print_buffer_ascii(stream, length, data);
822 fputc('"', stream);
823 }
824 }
825
826 void
827 print_uint32(FILE *stream, uint32 n)
828 {
829 n = OSSwapHostToBigInt32 (n);
830 print_buffer(stream, sizeof(UInt32), &n);
831 }
832
833 unsigned char
834 hexValue(char c)
835 {
836 static const char digits[] = "0123456789abcdef";
837 char *p;
838 if ((p = strchr(digits, tolower(c))))
839 return p - digits;
840 else
841 return 0;
842 }
843
844 void
845 fromHex(const char *hexDigits, CSSM_DATA *data)
846 {
847 size_t bytes = strlen(hexDigits) / 2; // (discards malformed odd end)
848 if (bytes > data->Length)
849 return;
850 // length(bytes); // (will assert if we try to grow it)
851 size_t n;
852 for (n = 0; n < bytes; n++) {
853 data->Data[n] = (uint8)(hexValue(hexDigits[2*n]) << 4 | hexValue(hexDigits[2*n+1]));
854 }
855 }
856
857 CFDataRef CF_RETURNS_RETAINED
858 cfFromHex(CFStringRef hex) {
859 // behavior is undefined if you pass in a non-hex string. Don't do that.
860 char* chex;
861 size_t len;
862
863 GetCStringFromCFString(hex, &chex, &len);
864 if(len == 0) {
865 return NULL;
866 }
867
868 size_t bytes = len/2;
869 CFMutableDataRef bin = CFDataCreateMutable(kCFAllocatorDefault, bytes);
870 CFDataIncreaseLength(bin, bytes);
871
872 if(!bin || (size_t) CFDataGetLength(bin) != bytes) {
873 CFReleaseNull(bin);
874 return NULL;
875 }
876
877 UInt8* data = CFDataGetMutableBytePtr(bin);
878 for(size_t i = 0; i < bytes; i++) {
879 data[i] = (uint8)(hexValue(chex[2*i]) << 4 | hexValue(chex[2*i+1]));
880 }
881
882 return bin;
883 }
884
885 CFStringRef CF_RETURNS_RETAINED cfToHex(CFDataRef bin) {
886 size_t len = CFDataGetLength(bin) * 2;
887 CFMutableStringRef str = CFStringCreateMutable(NULL, len);
888
889 static const char* digits[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
890
891 const uint8_t* data = CFDataGetBytePtr(bin);
892 for (CFIndex i = 0; i < CFDataGetLength(bin); i++) {
893 CFStringAppendCString(str, digits[data[i] >> 4], 1);
894 CFStringAppendCString(str, digits[data[i] & 0xf], 1);
895 }
896 return str;
897 }
898
899 void
900 safe_CFRelease(void *cfTypeRefPtr)
901 {
902 CFTypeRef *obj = (CFTypeRef *)cfTypeRefPtr;
903 if (obj && *obj) {
904 CFRelease(*obj);
905 *obj = NULL;
906 }
907 }
908
909
910 void
911 GetCStringFromCFString(CFStringRef cfstring, char** cstr, size_t* len) {
912 CFIndex strLen = CFStringGetLength(cfstring);
913 CFIndex bufLen = 1 + CFStringGetMaximumSizeForEncoding(strLen, kCFStringEncodingUTF8);
914 *cstr = (char *)malloc(bufLen);
915 if (!CFStringGetCString(cfstring, *cstr, bufLen-1, kCFStringEncodingUTF8)) {
916 (*cstr)[0]=0;
917 }
918 // Handle non-8-bit characters.
919 *len = strnlen(*cstr, strLen);
920 }
921
922 CFDictionaryRef CF_RETURNS_RETAINED makeCFDictionaryFromData(CFDataRef data)
923 {
924 if (data) {
925 CFPropertyListRef plist = CFPropertyListCreateFromXMLData(NULL, data, kCFPropertyListImmutable, NULL);
926 if (plist && CFGetTypeID(plist) != CFDictionaryGetTypeID()) {
927 safe_CFRelease(&plist);
928 return NULL;
929 }
930 return (CFDictionaryRef) plist;
931 } else {
932 return NULL;
933 }
934 }
935
936 void print_partition_id_list(FILE* stream, CFStringRef description) {
937 CFDataRef binary = NULL;
938 CFDictionaryRef partitionList = NULL;
939 CFArrayRef partitionIDs = NULL;
940
941 if(!description) {
942 goto error;
943 }
944 binary = cfFromHex(description);
945 if(!binary) {
946 goto error;
947 }
948 partitionList = makeCFDictionaryFromData(binary);
949 if(!partitionList) {
950 goto error;
951 }
952
953 partitionIDs = CFDictionaryGetValue(partitionList, CFSTR("Partitions"));
954 if(!partitionIDs) {
955 goto error;
956 }
957
958 for(CFIndex i = 0; i < CFArrayGetCount(partitionIDs); i++) {
959 CFStringRef s = CFArrayGetValueAtIndex(partitionIDs, i);
960 if(!s) {
961 goto error;
962 }
963
964 if(i != 0) {
965 fprintf(stream, ", ");
966 }
967 print_cfstring(stream, s);
968 }
969
970 goto cleanup;
971 error:
972 fprintf(stream, "invalid partition ID: ");
973 print_cfstring(stream, description);
974 cleanup:
975 // don't release partitionIDs; it's an element of partitionList
976 safe_CFRelease(&binary);
977 safe_CFRelease(&partitionList);
978
979 return;
980 }
981
982 /*
983 * map a 6-bit binary value to a printable character.
984 */
985 static const
986 unsigned char bintoasc[] =
987 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
988
989 /*
990 * map 6 bits to a printing char
991 */
992 #define ENC(c) (bintoasc[((c) & 0x3f)])
993
994 #define PAD '='
995
996 /*
997 * map one group of up to 3 bytes at inp to 4 bytes at outp.
998 * Count is number of valid bytes in *inp; if less than 3, the
999 * 1 or two extras must be zeros.
1000 */
1001 static void
1002 encChunk(const unsigned char *inp,
1003 unsigned char *outp,
1004 size_t count)
1005 {
1006 unsigned char c1, c2, c3, c4;
1007
1008 c1 = *inp >> 2;
1009 c2 = ((inp[0] << 4) & 0x30) | ((inp[1] >> 4) & 0xf);
1010 c3 = ((inp[1] << 2) & 0x3c) | ((inp[2] >> 6) & 0x3);
1011 c4 = inp[2] & 0x3f;
1012 *outp++ = ENC(c1);
1013 *outp++ = ENC(c2);
1014 if (count == 1) {
1015 *outp++ = PAD;
1016 *outp = PAD;
1017 } else {
1018 *outp++ = ENC(c3);
1019 if (count == 2) {
1020 *outp = PAD;
1021 }
1022 else {
1023 *outp = ENC(c4);
1024 }
1025 }
1026 }
1027
1028 static unsigned char *
1029 malloc_enc64_with_lines(const unsigned char *inbuf,
1030 size_t inlen,
1031 size_t linelen,
1032 unsigned *outlen)
1033 {
1034 unsigned outTextLen;
1035 unsigned len; // to malloc, liberal
1036 unsigned olen = 0; // actual output size
1037 unsigned char *outbuf;
1038 unsigned char endbuf[3];
1039 unsigned i;
1040 unsigned char *outp;
1041 unsigned numLines;
1042 unsigned thisLine;
1043
1044 outTextLen = ((((unsigned)inlen) + 2) / 3) * 4;
1045 if(linelen) {
1046 /*
1047 * linelen must be 0 mod 4 for this to work; round up...
1048 */
1049 if((linelen & 0x03) != 0) {
1050 linelen = (linelen + 3) & 0xfffffffc;
1051 }
1052 numLines = (outTextLen + ((unsigned)linelen) - 1)/ linelen;
1053 }
1054 else {
1055 numLines = 1;
1056 }
1057
1058 /*
1059 * Total output size = encoded text size plus one newline per
1060 * line of output, plus trailing NULL. We always generate newlines
1061 * as \n; when decoding, we tolerate \r\n (Microsoft) or \n.
1062 */
1063 len = outTextLen + (2 * numLines) + 1;
1064 outbuf = (unsigned char*)malloc(len);
1065 outp = outbuf;
1066 thisLine = 0;
1067
1068 while(inlen) {
1069 if(inlen < 3) {
1070 for(i=0; i<3; i++) {
1071 if(i < inlen) {
1072 endbuf[i] = inbuf[i];
1073 }
1074 else {
1075 endbuf[i] = 0;
1076 }
1077 }
1078 encChunk(endbuf, outp, inlen);
1079 inlen = 0;
1080 }
1081 else {
1082 encChunk(inbuf, outp, 3);
1083 inlen -= 3;
1084 inbuf += 3;
1085 }
1086 outp += 4;
1087 thisLine += 4;
1088 olen += 4;
1089 if((linelen != 0) && (thisLine >= linelen) && inlen) {
1090 /*
1091 * last trailing newline added below
1092 * Note we don't split 4-byte output chunks over newlines
1093 */
1094 *outp++ = '\n';
1095 olen++;
1096 thisLine = 0;
1097 }
1098 }
1099 *outp++ = '\n';
1100 olen += 1;
1101 *outlen = olen;
1102 return outbuf;
1103 }
1104
1105 void
1106 print_buffer_pem(FILE *stream, const char *headerString, size_t length, const void *data)
1107 {
1108 unsigned char *buf;
1109 unsigned bufLen;
1110
1111 if (headerString)
1112 fprintf(stream, "-----BEGIN %s-----\n", headerString);
1113 buf = malloc_enc64_with_lines(data, length, 64, &bufLen);
1114 fwrite(buf, bufLen, 1, stream);
1115 free(buf);
1116 if (headerString)
1117 fprintf(stream, "-----END %s-----\n", headerString);
1118 }
1119
1120 char*
1121 prompt_password(const char* keychainName) {
1122 const char *fmt = "password to unlock %s: ";
1123 const char *name = keychainName ? keychainName : "default";
1124 char *prompt = malloc(strlen(fmt) + strlen(name));
1125 sprintf(prompt, fmt, name);
1126 char *password = getpass(prompt);
1127 free(prompt);
1128 return password;
1129 }