2 * Copyright (c) 2003-2010,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 "identity_find.h"
29 #include "keychain_utilities.h"
30 #include "trusted_cert_utils.h"
31 #include "security_tool.h"
37 #include <Security/cssmtype.h>
38 #include <Security/oidsalg.h>
39 #include <Security/SecCertificate.h>
40 #include <Security/SecIdentity.h>
41 #include <Security/SecIdentitySearch.h>
42 #include <Security/SecPolicySearch.h>
43 #include <Security/SecTrust.h>
44 #include <Security/SecItem.h>
45 #include <Security/SecItemPriv.h>
46 #include <utilities/SecCFWrappers.h>
49 #include <Security/SecBasePriv.h>
50 // SecCertificateInferLabel, SecDigestGetData
51 #include <Security/SecCertificatePriv.h>
52 // SecIdentitySearchCreateWithPolicy
53 #include <Security/SecIdentitySearchPriv.h>
55 static bool checkKeyUsageOperation(CSSM_KEYUSE keyUse, CSSM_KEYUSE keyOp, NSDictionary *keyAttrs, id secKeyOp) {
57 return [keyAttrs[secKeyOp] isEqual:@YES];
62 static bool checkKeyUsage(CSSM_KEYUSE keyUse, NSDictionary *keyAttrs) {
63 CSSM_KEYUSE keyOps[] = { CSSM_KEYUSE_ENCRYPT, CSSM_KEYUSE_DECRYPT, CSSM_KEYUSE_SIGN, CSSM_KEYUSE_VERIFY, CSSM_KEYUSE_SIGN_RECOVER, CSSM_KEYUSE_VERIFY_RECOVER, CSSM_KEYUSE_WRAP, CSSM_KEYUSE_UNWRAP, CSSM_KEYUSE_DERIVE };
64 id secKeyOps[] = { (id)kSecAttrCanEncrypt, (id)kSecAttrCanDecrypt, (id)kSecAttrCanSign, (id)kSecAttrCanVerify, (id)kSecAttrCanSignRecover, (id)kSecAttrCanVerifyRecover, (id)kSecAttrCanWrap, (id)kSecAttrCanUnwrap, (id)kSecAttrCanDerive };
66 if (keyUse & CSSM_KEYUSE_ANY) {
67 for (size_t i = 0; i < sizeof(keyOps) / sizeof(CSSM_KEYUSE); ++i) {
71 for (size_t i = 0; i < sizeof(keyOps) / sizeof(CSSM_KEYUSE); ++i) {
72 if (!checkKeyUsageOperation(keyUse, keyOps[i], keyAttrs, secKeyOps[i]))
79 CopyMatchingIdentity(CFTypeRef keychainOrArray,
85 // check input hash string and convert to data
88 hashData = (__bridge_transfer NSData *)CFDataCreateFromHexString(kCFAllocatorDefault, (__bridge CFStringRef)[NSString stringWithUTF8String:hash]);
91 // filter candidates against the hash (or the name, if no hash provided)
92 NSString *matchName = (identity) ? [NSString stringWithUTF8String:identity] : nil;
93 Boolean exactMatch = FALSE;
96 if (keychainOrArray) {
98 if (![(__bridge id)keychainOrArray isKindOfClass:[NSArray class]]) {
99 keychainArray = @[(__bridge id)keychainOrArray];
101 keychainArray = (__bridge id)keychainOrArray;
103 query = @{ (id)kSecClass : (id)kSecClassIdentity,
104 (id)kSecMatchLimit : (id)kSecMatchLimitAll,
105 (id)kSecMatchSearchList : keychainArray,
106 (id)kSecReturnRef : @YES };
108 query = @{ (id)kSecClass : (id)kSecClassIdentity,
109 (id)kSecMatchLimit : (id)kSecMatchLimitAll,
110 (id)kSecReturnRef : @YES };
113 if (SecItemCopyMatching((CFDictionaryRef)query, (void *)&identities) != errSecSuccess) {
117 for (id candidate in identities) {
119 if (SecIdentityCopyCertificate((__bridge SecIdentityRef)candidate, (void *)&cert) != errSecSuccess)
122 NSData *pubKeyHash = (__bridge_transfer NSData*)SecCertificateCopyPublicKeySHA1Digest((__bridge SecCertificateRef)cert);
123 NSDictionary *keyAttrs;
124 if (SecItemCopyMatching((__bridge CFDictionaryRef)@{ (id)kSecClass : (id)kSecClassKey, (id)kSecAttrApplicationLabel : pubKeyHash, (id)kSecReturnAttributes : @YES }, (void *)&keyAttrs) != errSecSuccess)
126 if (!(checkKeyUsage(keyUsage, keyAttrs))) {
131 NSData *certDataHash = (__bridge NSData *)SecCertificateGetSHA1Digest((__bridge SecCertificateRef)cert);
132 if ([hashData isEqual:certDataHash]) {
133 identityRef = candidate;
137 // copy certificate name
138 NSString *commonName;
139 if ((SecCertificateCopyCommonName((__bridge SecCertificateRef)cert, (void *)&commonName) != errSecSuccess) || commonName == nil) {
140 continue; // no name, so no match is possible
143 if (identity && !strcmp(identity, "*")) { // special case: means "just take the first one"
144 sec_error("Using identity \"%s\"", [commonName UTF8String]);
145 identityRef = candidate;
148 CFRange find = { kCFNotFound, 0 };
149 if (commonName && matchName)
150 find = CFStringFind((__bridge CFStringRef)commonName, (__bridge CFStringRef)matchName, kCFCompareCaseInsensitive | kCFCompareNonliteral);
151 Boolean isExact = (find.location == 0 && find.length == (CFIndex)commonName.length);
152 if (find.location == kCFNotFound) {
153 continue; // no match
155 if (identityRef) { // got two matches
156 if (exactMatch && !isExact) { // prior is better; ignore this one
159 if (exactMatch == isExact) { // same class of match
160 if ([identityRef isEqual:candidate]) { // identities have same cert
163 // ambiguity - must fail
164 sec_error("\"%s\" is ambiguous, matches more than one certificate", identity);
169 identityRef = candidate;
170 exactMatch = isExact;
174 return identityRef?(__bridge_retained SecIdentityRef)identityRef:NULL;
177 static void printIdentity(SecIdentityRef identity, SecPolicyRef policy, int ordinalValue)
180 Boolean printHash = TRUE, printName = TRUE;
181 SecCertificateRef cert = NULL;
183 status = SecIdentityCopyCertificate(identity, &cert);
186 CSSM_DATA certData = { 0, nil };
187 (void) SecCertificateGetData(cert, &certData);
188 fprintf(stdout, "%3d) ", ordinalValue);
192 digest.Length = sizeof(sha1_hash);
193 digest.Data = sha1_hash;
194 if (SecDigestGetData(CSSM_ALGID_SHA1, &digest, &certData) == CSSM_OK) {
196 size_t len = digest.Length;
197 uint8 *cp = digest.Data;
198 for(i=0; i<len; i++) {
199 fprintf(stdout, "%02X", ((unsigned char *)cp)[i]);
202 fprintf(stdout, "!----- unable to get SHA-1 digest -----!");
206 char *nameBuf = NULL;
207 CFStringRef nameRef = NULL;
208 status = SecCertificateInferLabel(cert, &nameRef);
209 CFIndex nameLen = (nameRef) ? CFStringGetLength(nameRef) : 0;
211 CFIndex bufLen = 1 + CFStringGetMaximumSizeForEncoding(nameLen, kCFStringEncodingUTF8);
212 nameBuf = (char *)malloc(bufLen);
213 if (!CFStringGetCString(nameRef, nameBuf, bufLen-1, kCFStringEncodingUTF8))
216 fprintf(stdout, " \"%s\"", (nameBuf && nameBuf[0] != 0) ? nameBuf : "<unknown>");
219 safe_CFRelease(&nameRef);
222 // Default to X.509 Basic if no policy was specified
224 SecPolicySearchRef policySearch = NULL;
225 if (SecPolicySearchCreate(CSSM_CERT_X_509v3, &CSSMOID_APPLE_X509_BASIC, NULL, &policySearch)==noErr) {
226 SecPolicySearchCopyNext(policySearch, &policy);
228 safe_CFRelease(&policySearch);
233 // Create the trust reference, given policy and certificates
234 SecTrustRef trust = nil;
235 SecTrustResultType trustResult = kSecTrustResultInvalid;
236 OSStatus trustResultCode = noErr;
237 CFMutableArrayRef certificates = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
239 CFArrayAppendValue(certificates, cert);
241 status = SecTrustCreateWithCertificates((CFArrayRef)certificates, policy, &trust);
243 status = SecTrustEvaluate(trust, &trustResult);
245 if (trustResult != kSecTrustResultInvalid) {
246 status = SecTrustGetCssmResultCode(trust, &trustResultCode);
248 if (trustResultCode != noErr) {
249 fprintf(stdout, " (%s)\n", cssmErrorString(trustResultCode));
251 fprintf(stdout, "\n");
253 safe_CFRelease(&trust);
254 safe_CFRelease(&policy);
255 safe_CFRelease(&certificates);
257 safe_CFRelease(&cert);
262 do_identity_search_with_policy(CFTypeRef keychainOrArray,
264 const CSSM_OID* oidPtr,
265 CSSM_KEYUSE keyUsage,
269 // set up SMIME options with provided data
270 CE_KeyUsage ceKeyUsage = 0;
271 if (keyUsage & CSSM_KEYUSE_SIGN) ceKeyUsage |= CE_KU_DigitalSignature;
272 if (keyUsage & CSSM_KEYUSE_ENCRYPT) ceKeyUsage |= CE_KU_KeyEncipherment;
273 CSSM_APPLE_TP_SMIME_OPTIONS smimeOpts = {
274 CSSM_APPLE_TP_SMIME_OPTS_VERSION, // Version
275 ceKeyUsage, // IntendedUsage
276 name ? (uint32) strlen(name) : 0, // SenderEmailLen
279 CSSM_DATA smimeValue = { sizeof(smimeOpts), (uint8*)&smimeOpts };
281 // set up SSL options with provided data
282 CSSM_APPLE_TP_SSL_OPTIONS sslOpts = {
283 CSSM_APPLE_TP_SSL_OPTS_VERSION, // Version
284 (name && !client) ? (uint32) strlen(name) : 0, // ServerNameLen
285 (client) ? NULL : name, // ServerName
286 (client) ? CSSM_APPLE_TP_SSL_CLIENT : 0 // Flags
288 CSSM_DATA sslValue = { sizeof(sslOpts), (uint8*)&sslOpts };
290 // get a policy ref for the specified policy OID
291 OSStatus status = noErr;
292 SecPolicyRef policy = NULL;
293 SecPolicySearchRef policySearch = NULL;
294 status = SecPolicySearchCreate(CSSM_CERT_X_509v3, oidPtr, NULL, &policySearch);
296 status = SecPolicySearchCopyNext(policySearch, &policy);
298 CSSM_DATA *policyValue = NULL;
299 const char *policyName = "<unknown>";
301 if (compareOids(oidPtr, &CSSMOID_APPLE_TP_SMIME)) {
302 policyName = "S/MIME";
303 policyValue = &smimeValue;
305 else if (compareOids(oidPtr, &CSSMOID_APPLE_TP_SSL)) {
307 policyName = "SSL (client)";
309 policyName = "SSL (server)";
310 policyValue = &sslValue;
312 else if (compareOids(oidPtr, &CSSMOID_APPLE_TP_EAP)) {
315 else if (compareOids(oidPtr, &CSSMOID_APPLE_TP_IP_SEC)) {
316 policyName = "IPsec";
318 else if (compareOids(oidPtr, &CSSMOID_APPLE_TP_ICHAT)) {
319 policyName = "iChat";
321 else if (compareOids(oidPtr, &CSSMOID_APPLE_TP_CODE_SIGNING)) {
322 policyName = "Code Signing";
324 else if (compareOids(oidPtr, &CSSMOID_APPLE_X509_BASIC)) {
325 policyName = "X.509 Basic";
327 else if (compareOids(oidPtr, &CSSMOID_APPLE_TP_MACAPPSTORE_RECEIPT)) {
328 policyName = "Mac App Store Receipt";
330 else if (compareOids(oidPtr, &CSSMOID_APPLE_TP_APPLEID_SHARING)) {
331 policyName = "AppleID Sharing";
334 // set the policy's value, if there is one (this is specific to certain policies)
335 if (policy && policyValue)
336 status = SecPolicySetValue(policy, policyValue);
338 CFStringRef idStr = (name) ? CFStringCreateWithCStringNoCopy(NULL, name, kCFStringEncodingUTF8, kCFAllocatorNull) : NULL;
339 SecIdentitySearchRef searchRef = NULL;
340 int identityCount = 0;
343 // create an identity search, specifying all identities (i.e. returnOnlyValidIdentities=FALSE)
344 // this should return all identities which match the policy and key usage, regardless of validity
345 fprintf(stdout, "\nPolicy: %s\n", policyName);
346 fprintf(stdout, " Matching identities\n");
347 status = SecIdentitySearchCreateWithPolicy(policy, idStr, keyUsage, keychainOrArray, FALSE, &searchRef);
350 SecIdentityRef identityRef = NULL;
351 while (SecIdentitySearchCopyNext(searchRef, &identityRef) == noErr)
354 printIdentity(identityRef, policy, identityCount);
355 safe_CFRelease(&identityRef);
357 safe_CFRelease(&searchRef);
359 fprintf(stdout, " %d identities found\n\n", identityCount);
362 // create a second identity search, specifying only valid identities (i.e. returnOnlyValidIdentities=TRUE)
363 // this should return only valid identities for the policy.
366 fprintf(stdout, " Valid identities only\n");
368 status = SecIdentitySearchCreateWithPolicy(policy, idStr, keyUsage, keychainOrArray, TRUE, &searchRef);
371 SecIdentityRef identityRef = NULL;
372 while (SecIdentitySearchCopyNext(searchRef, &identityRef) == noErr)
375 printIdentity(identityRef, policy, identityCount);
376 safe_CFRelease(&identityRef);
378 safe_CFRelease(&searchRef);
380 fprintf(stdout, " %d valid identities found\n", identityCount);
382 safe_CFRelease(&idStr);
383 safe_CFRelease(&policy);
384 safe_CFRelease(policySearch);
388 do_system_identity_search(CFStringRef domain)
390 SecIdentityRef identity = NULL;
391 OSStatus status = SecIdentityCopySystemIdentity(domain, &identity, NULL);
392 if (CFEqual(domain, kSecIdentityDomainDefault)) {
393 fprintf(stdout, "\n System default identity\n");
394 } else if (CFEqual(domain, kSecIdentityDomainKerberosKDC)) {
395 fprintf(stdout, "\n System Kerberos KDC identity\n");
397 if (!status && identity) {
398 SecPolicyRef policy = NULL;
399 SecPolicySearchRef policySearch = NULL;
400 if (SecPolicySearchCreate(CSSM_CERT_X_509v3, &CSSMOID_APPLE_X509_BASIC, NULL, &policySearch) == noErr) {
401 if (SecPolicySearchCopyNext(policySearch, &policy) == noErr) {
402 printIdentity(identity, policy, 1);
405 safe_CFRelease(&policySearch);
407 safe_CFRelease(&identity);
412 do_find_identities(CFTypeRef keychainOrArray, const char *name, unsigned int policyFlags, Boolean validOnly)
417 fprintf(stdout, "Looking for identities matching \"%s\"\n", name);
419 if (policyFlags & (1 << 0))
420 do_identity_search_with_policy(keychainOrArray, name, &CSSMOID_APPLE_TP_SSL, CSSM_KEYUSE_SIGN, TRUE, validOnly);
421 if (policyFlags & (1 << 1))
422 do_identity_search_with_policy(keychainOrArray, name, &CSSMOID_APPLE_TP_SSL, CSSM_KEYUSE_SIGN, FALSE, validOnly);
423 if (policyFlags & (1 << 2))
424 do_identity_search_with_policy(keychainOrArray, name, &CSSMOID_APPLE_TP_SMIME, CSSM_KEYUSE_SIGN, TRUE, validOnly);
425 if (policyFlags & (1 << 3))
426 do_identity_search_with_policy(keychainOrArray, name, &CSSMOID_APPLE_TP_EAP, CSSM_KEYUSE_SIGN, TRUE, validOnly);
427 if (policyFlags & (1 << 4))
428 do_identity_search_with_policy(keychainOrArray, name, &CSSMOID_APPLE_TP_IP_SEC, CSSM_KEYUSE_SIGN, TRUE, validOnly);
429 if (policyFlags & (1 << 5))
430 do_identity_search_with_policy(keychainOrArray, name, &CSSMOID_APPLE_TP_ICHAT, CSSM_KEYUSE_SIGN, TRUE, validOnly);
431 if (policyFlags & (1 << 6))
432 do_identity_search_with_policy(keychainOrArray, name, &CSSMOID_APPLE_TP_CODE_SIGNING, CSSM_KEYUSE_SIGN, TRUE, validOnly);
433 if (policyFlags & (1 << 7))
434 do_identity_search_with_policy(keychainOrArray, name, &CSSMOID_APPLE_X509_BASIC, CSSM_KEYUSE_SIGN, TRUE, validOnly);
436 if (policyFlags & (1 << 8))
437 do_system_identity_search(kSecIdentityDomainDefault);
438 if (policyFlags & (1 << 9))
439 do_system_identity_search(kSecIdentityDomainKerberosKDC);
440 if (policyFlags & (1 << 10))
441 do_identity_search_with_policy(keychainOrArray, name, &CSSMOID_APPLE_TP_APPLEID_SHARING, CSSM_KEYUSE_SIGN, FALSE, validOnly);
442 if (policyFlags & (1 << 11))
443 do_identity_search_with_policy(keychainOrArray, name, &CSSMOID_APPLE_TP_MACAPPSTORE_RECEIPT, CSSM_KEYUSE_SIGN, TRUE, validOnly);
449 keychain_find_identity(int argc, char * const *argv)
452 unsigned int policyFlags = 0;
453 const char *name = NULL;
454 Boolean validOnly = FALSE;
455 CFTypeRef keychainOrArray = NULL;
458 * " -p Specify policy to evaluate (multiple -p options are allowed)\n"
459 * " -s Specify optional policy-specific string (e.g. a DNS hostname for SSL,\n"
460 * " or RFC822 email address for S/MIME)\n"
461 * " -v Show valid identities only (default is to show all identities)\n"
464 while ((ch = getopt(argc, argv, "hp:s:v")) != -1)
469 if (optarg != NULL) {
470 if (!strcmp(optarg, "ssl-client"))
471 policyFlags |= 1 << 0;
472 else if (!strcmp(optarg, "ssl-server"))
473 policyFlags |= 1 << 1;
474 else if (!strcmp(optarg, "smime"))
475 policyFlags |= 1 << 2;
476 else if (!strcmp(optarg, "eap"))
477 policyFlags |= 1 << 3;
478 else if (!strcmp(optarg, "ipsec"))
479 policyFlags |= 1 << 4;
480 else if (!strcmp(optarg, "ichat"))
481 policyFlags |= 1 << 5;
482 else if (!strcmp(optarg, "codesigning"))
483 policyFlags |= 1 << 6;
484 else if (!strcmp(optarg, "basic"))
485 policyFlags |= 1 << 7;
486 else if (!strcmp(optarg, "sys-default"))
487 policyFlags |= 1 << 8;
488 else if (!strcmp(optarg, "sys-kerberos-kdc"))
489 policyFlags |= 1 << 9;
490 else if (!strcmp(optarg, "appleID"))
491 policyFlags |= 1 << 10;
492 else if (!strcmp(optarg, "macappstore"))
493 policyFlags |= 1 << 11;
495 result = SHOW_USAGE_MESSAGE;
508 result = 2; /* @@@ Return 2 triggers usage message. */
514 policyFlags |= 1 << 7; /* default to basic policy if none specified */
519 keychainOrArray = keychain_create_array(argc, argv);
521 result = do_find_identities(keychainOrArray, name, policyFlags, validOnly);
524 safe_CFRelease(&keychainOrArray);