]> git.saurik.com Git - apple/security.git/blob - SecurityTool/macOS/keychain_utilities.c
Security-59306.11.20.tar.gz
[apple/security.git] / SecurityTool / macOS / keychain_utilities.c
1 /*
2 * Copyright (c) 2003-2009,2012,2014-2019 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 // Returns base16 value of input hexadecimal character.
834 // If the input character is not valid hex, output error flag is set.
835 //
836 unsigned char
837 hexToValue(char c, char *error)
838 {
839 static const char digits[] = "0123456789abcdef";
840 char *p = strchr(digits, tolower(c));
841 if (p) { return p - digits; }
842 if (error) { *error = 1; }
843 return 0;
844 }
845
846 unsigned char
847 hexValue(char c)
848 {
849 return hexToValue(c, NULL);
850 }
851
852 // Returns true if we can convert the supplied hex string to data,
853 // with pointer to the allocated data and its length as optional output.
854 // This function will zero-pad an odd number of nibbles in hexString,
855 // e.g. an input of 'FFF' is treated as 0x0FFF.
856 // If outData is supplied, caller must free returned value.
857 //
858 bool
859 convertHex(const char *hexString, uint8_t **outData, size_t *outLength)
860 {
861 if (!hexString) { return false; }
862
863 size_t num_nibbles = strlen(hexString);
864 uint8_t zero_pad = ((num_nibbles % 2) != 0) ? 1 : 0;
865 size_t num_bytes = (num_nibbles / 2) + zero_pad;
866 uint8_t *data = calloc(num_bytes, sizeof(*data));
867 char error = 0;
868 if (zero_pad) {
869 data[0] = hexToValue(hexString[0], &error);
870 }
871 for (size_t n = zero_pad; n < num_bytes; n++) {
872 data[n] = hexToValue(hexString[2*n], &error) << 4 | hexToValue(hexString[2*n+1], &error);
873 }
874 if (error) {
875 free(data);
876 return false;
877 }
878 if (outData) {
879 *outData = data;
880 } else {
881 memset(data, 0, num_bytes);
882 free(data);
883 }
884 if (outLength) {
885 *outLength = num_bytes;
886 }
887 return true;
888 }
889
890 void
891 fromHex(const char *hexDigits, CSSM_DATA *data)
892 {
893 size_t bytes = strlen(hexDigits) / 2; // (discards malformed odd end)
894 if (bytes > data->Length)
895 return;
896 // length(bytes); // (will assert if we try to grow it)
897 size_t n;
898 for (n = 0; n < bytes; n++) {
899 data->Data[n] = (uint8)(hexValue(hexDigits[2*n]) << 4 | hexValue(hexDigits[2*n+1]));
900 }
901 }
902
903 CFDataRef CF_RETURNS_RETAINED
904 cfFromHex(CFStringRef hex) {
905 // behavior is undefined if you pass in a non-hex string. Don't do that.
906 char* chex;
907 size_t len;
908
909 GetCStringFromCFString(hex, &chex, &len);
910 if(len == 0) {
911 return NULL;
912 }
913
914 size_t bytes = len/2;
915 CFMutableDataRef bin = CFDataCreateMutable(kCFAllocatorDefault, bytes);
916 CFDataIncreaseLength(bin, bytes);
917
918 if(!bin || (size_t) CFDataGetLength(bin) != bytes) {
919 CFReleaseNull(bin);
920 return NULL;
921 }
922
923 UInt8* data = CFDataGetMutableBytePtr(bin);
924 for(size_t i = 0; i < bytes; i++) {
925 data[i] = (uint8)(hexValue(chex[2*i]) << 4 | hexValue(chex[2*i+1]));
926 }
927
928 return bin;
929 }
930
931 CFStringRef CF_RETURNS_RETAINED cfToHex(CFDataRef bin) {
932 size_t len = CFDataGetLength(bin) * 2;
933 CFMutableStringRef str = CFStringCreateMutable(NULL, len);
934
935 static const char* digits[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
936
937 const uint8_t* data = CFDataGetBytePtr(bin);
938 for (CFIndex i = 0; i < CFDataGetLength(bin); i++) {
939 CFStringAppendCString(str, digits[data[i] >> 4], 1);
940 CFStringAppendCString(str, digits[data[i] & 0xf], 1);
941 }
942 return str;
943 }
944
945 void
946 safe_CFRelease(void *cfTypeRefPtr)
947 {
948 CFTypeRef *obj = (CFTypeRef *)cfTypeRefPtr;
949 if (obj && *obj) {
950 CFRelease(*obj);
951 *obj = NULL;
952 }
953 }
954
955
956 void
957 GetCStringFromCFString(CFStringRef cfstring, char** cstr, size_t* len) {
958 CFIndex strLen = CFStringGetLength(cfstring);
959 CFIndex bufLen = 1 + CFStringGetMaximumSizeForEncoding(strLen, kCFStringEncodingUTF8);
960 *cstr = (char *)malloc(bufLen);
961 if (!CFStringGetCString(cfstring, *cstr, bufLen-1, kCFStringEncodingUTF8)) {
962 (*cstr)[0]=0;
963 }
964 // Handle non-8-bit characters.
965 *len = strnlen(*cstr, strLen);
966 }
967
968 CFDictionaryRef CF_RETURNS_RETAINED makeCFDictionaryFromData(CFDataRef data)
969 {
970 if (data) {
971 CFPropertyListRef plist = CFPropertyListCreateFromXMLData(NULL, data, kCFPropertyListImmutable, NULL);
972 if (plist && CFGetTypeID(plist) != CFDictionaryGetTypeID()) {
973 safe_CFRelease(&plist);
974 return NULL;
975 }
976 return (CFDictionaryRef) plist;
977 } else {
978 return NULL;
979 }
980 }
981
982 void print_partition_id_list(FILE* stream, CFStringRef description) {
983 CFDataRef binary = NULL;
984 CFDictionaryRef partitionList = NULL;
985 CFArrayRef partitionIDs = NULL;
986
987 if(!description) {
988 goto error;
989 }
990 binary = cfFromHex(description);
991 if(!binary) {
992 goto error;
993 }
994 partitionList = makeCFDictionaryFromData(binary);
995 if(!partitionList) {
996 goto error;
997 }
998
999 partitionIDs = CFDictionaryGetValue(partitionList, CFSTR("Partitions"));
1000 if(!partitionIDs) {
1001 goto error;
1002 }
1003
1004 for(CFIndex i = 0; i < CFArrayGetCount(partitionIDs); i++) {
1005 CFStringRef s = CFArrayGetValueAtIndex(partitionIDs, i);
1006 if(!s) {
1007 goto error;
1008 }
1009
1010 if(i != 0) {
1011 fprintf(stream, ", ");
1012 }
1013 print_cfstring(stream, s);
1014 }
1015
1016 goto cleanup;
1017 error:
1018 fprintf(stream, "invalid partition ID: ");
1019 print_cfstring(stream, description);
1020 cleanup:
1021 // don't release partitionIDs; it's an element of partitionList
1022 safe_CFRelease(&binary);
1023 safe_CFRelease(&partitionList);
1024
1025 return;
1026 }
1027
1028 /*
1029 * map a 6-bit binary value to a printable character.
1030 */
1031 static const
1032 unsigned char bintoasc[] =
1033 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1034
1035 /*
1036 * map 6 bits to a printing char
1037 */
1038 #define ENC(c) (bintoasc[((c) & 0x3f)])
1039
1040 #define PAD '='
1041
1042 /*
1043 * map one group of up to 3 bytes at inp to 4 bytes at outp.
1044 * Count is number of valid bytes in *inp; if less than 3, the
1045 * 1 or two extras must be zeros.
1046 */
1047 static void
1048 encChunk(const unsigned char *inp,
1049 unsigned char *outp,
1050 size_t count)
1051 {
1052 unsigned char c1, c2, c3, c4;
1053
1054 c1 = *inp >> 2;
1055 c2 = ((inp[0] << 4) & 0x30) | ((inp[1] >> 4) & 0xf);
1056 c3 = ((inp[1] << 2) & 0x3c) | ((inp[2] >> 6) & 0x3);
1057 c4 = inp[2] & 0x3f;
1058 *outp++ = ENC(c1);
1059 *outp++ = ENC(c2);
1060 if (count == 1) {
1061 *outp++ = PAD;
1062 *outp = PAD;
1063 } else {
1064 *outp++ = ENC(c3);
1065 if (count == 2) {
1066 *outp = PAD;
1067 }
1068 else {
1069 *outp = ENC(c4);
1070 }
1071 }
1072 }
1073
1074 static unsigned char *
1075 malloc_enc64_with_lines(const unsigned char *inbuf,
1076 size_t inlen,
1077 size_t linelen,
1078 unsigned *outlen)
1079 {
1080 unsigned outTextLen;
1081 unsigned len; // to malloc, liberal
1082 unsigned olen = 0; // actual output size
1083 unsigned char *outbuf;
1084 unsigned char endbuf[3];
1085 unsigned i;
1086 unsigned char *outp;
1087 unsigned numLines;
1088 unsigned thisLine;
1089
1090 outTextLen = ((((unsigned)inlen) + 2) / 3) * 4;
1091 if(linelen) {
1092 /*
1093 * linelen must be 0 mod 4 for this to work; round up...
1094 */
1095 if((linelen & 0x03) != 0) {
1096 linelen = (linelen + 3) & 0xfffffffc;
1097 }
1098 numLines = (outTextLen + ((unsigned)linelen) - 1)/ linelen;
1099 }
1100 else {
1101 numLines = 1;
1102 }
1103
1104 /*
1105 * Total output size = encoded text size plus one newline per
1106 * line of output, plus trailing NULL. We always generate newlines
1107 * as \n; when decoding, we tolerate \r\n (Microsoft) or \n.
1108 */
1109 len = outTextLen + (2 * numLines) + 1;
1110 outbuf = (unsigned char*)malloc(len);
1111 outp = outbuf;
1112 thisLine = 0;
1113
1114 while(inlen) {
1115 if(inlen < 3) {
1116 for(i=0; i<3; i++) {
1117 if(i < inlen) {
1118 endbuf[i] = inbuf[i];
1119 }
1120 else {
1121 endbuf[i] = 0;
1122 }
1123 }
1124 encChunk(endbuf, outp, inlen);
1125 inlen = 0;
1126 }
1127 else {
1128 encChunk(inbuf, outp, 3);
1129 inlen -= 3;
1130 inbuf += 3;
1131 }
1132 outp += 4;
1133 thisLine += 4;
1134 olen += 4;
1135 if((linelen != 0) && (thisLine >= linelen) && inlen) {
1136 /*
1137 * last trailing newline added below
1138 * Note we don't split 4-byte output chunks over newlines
1139 */
1140 *outp++ = '\n';
1141 olen++;
1142 thisLine = 0;
1143 }
1144 }
1145 *outp++ = '\n';
1146 olen += 1;
1147 *outlen = olen;
1148 return outbuf;
1149 }
1150
1151 void
1152 print_buffer_pem(FILE *stream, const char *headerString, size_t length, const void *data)
1153 {
1154 unsigned char *buf;
1155 unsigned bufLen;
1156
1157 if (headerString)
1158 fprintf(stream, "-----BEGIN %s-----\n", headerString);
1159 buf = malloc_enc64_with_lines(data, length, 64, &bufLen);
1160 fwrite(buf, bufLen, 1, stream);
1161 free(buf);
1162 if (headerString)
1163 fprintf(stream, "-----END %s-----\n", headerString);
1164 }
1165
1166 char*
1167 prompt_password(const char* keychainName) {
1168 const char *fmt = "password to unlock %s: ";
1169 const char *name = keychainName ? keychainName : "default";
1170 char *prompt = malloc(strlen(fmt) + strlen(name));
1171 sprintf(prompt, fmt, name);
1172 char *password = getpass(prompt);
1173 free(prompt);
1174 return password;
1175 }