+static CF_RETURNS_RETAINED CFTypeRef CERT_FindItemInAllAvailableKeychains(CFDictionaryRef query) {
+ CFTypeRef item = NULL;
+ CFMutableDictionaryRef q = NULL;
+ CFDictionaryRef whoAmI = NULL;
+ CFErrorRef error = NULL;
+ CFDataRef musr = NULL;
+ const uint8_t activeUserUuid[16] = "\xA7\x5A\x3A\x35\xA5\x57\x4B\x10\xBE\x2E\x83\x94\x7E\x4A\x34\x72";
+
+ /* Do the standard keychain query */
+ require_quiet(errSecItemNotFound == SecItemCopyMatching(query, &item), out);
+
+ /* No item found. Can caller use the system keychain? */
+ whoAmI = _SecSecuritydCopyWhoAmI(&error);
+ require_quiet(NULL == error && whoAmI && CFDictionaryGetValue(whoAmI, CFSTR("status")), out);
+ musr = CFDictionaryGetValue(whoAmI, CFSTR("musr"));
+ /* Caller has system-keychain entitlement, is in multi-user mode, and is an active user. */
+ if (CFDictionaryGetValue(whoAmI, CFSTR("system-keychain")) && musr &&
+ (16 == CFDataGetLength(musr)) && (0 == memcmp(activeUserUuid,CFDataGetBytePtr(musr),12))) {
+ q = CFDictionaryCreateMutableCopy(NULL, CFDictionaryGetCount(query) + 1, query);
+ CFDictionaryAddValue(q, kSecUseSystemKeychain, kCFBooleanTrue);
+ SecItemCopyMatching(q, &item);
+ }
+
+out:
+ if (q)
+ CFRelease(q);
+ if (whoAmI)
+ CFRelease(whoAmI);
+ if (error)
+ CFRelease(error);
+
+ return item;
+}