]> git.saurik.com Git - apple/security.git/blob - libsecurity_keychain/lib/Certificate.cpp
93eb0aa1a42c0f04cea2bc68c091099d37d53fa8
[apple/security.git] / libsecurity_keychain / lib / Certificate.cpp
1 /*
2 * Copyright (c) 2002-2007,2012 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
24 //
25 // Certificate.cpp
26 //
27 #include <security_keychain/Certificate.h>
28 #include <security_cdsa_utilities/Schema.h>
29 #include <Security/oidscert.h>
30 #include <Security/oidsattr.h>
31 #include <Security/SecCertificate.h>
32 #include <Security/SecCertificatePriv.h>
33 #include <security_cdsa_client/cspclient.h>
34 #include <security_keychain/KeyItem.h>
35 #include <security_keychain/KCCursor.h>
36 #include <vector>
37 #include <CommonCrypto/CommonDigestSPI.h>
38 #include <SecBase.h>
39
40 using namespace KeychainCore;
41
42 CL
43 Certificate::clForType(CSSM_CERT_TYPE type)
44 {
45 return CL(gGuidAppleX509CL);
46 }
47
48 Certificate::Certificate(const CSSM_DATA &data, CSSM_CERT_TYPE type, CSSM_CERT_ENCODING encoding) :
49 ItemImpl(CSSM_DL_DB_RECORD_X509_CERTIFICATE, reinterpret_cast<SecKeychainAttributeList *>(NULL), UInt32(data.Length), reinterpret_cast<const void *>(data.Data)),
50 mHaveTypeAndEncoding(true),
51 mPopulated(false),
52 mType(type),
53 mEncoding(encoding),
54 mCL(clForType(type)),
55 mCertHandle(0),
56 mV1SubjectPublicKeyCStructValue(NULL),
57 mV1SubjectNameCStructValue(NULL),
58 mV1IssuerNameCStructValue(NULL),
59 mSha1Hash(NULL)
60 {
61 if (data.Length == 0 || data.Data == NULL)
62 MacOSError::throwMe(errSecParam);
63 }
64
65 // db item constructor
66 Certificate::Certificate(const Keychain &keychain, const PrimaryKey &primaryKey, const CssmClient::DbUniqueRecord &uniqueId) :
67 ItemImpl(keychain, primaryKey, uniqueId),
68 mHaveTypeAndEncoding(false),
69 mPopulated(false),
70 mCL(NULL),
71 mCertHandle(0),
72 mV1SubjectPublicKeyCStructValue(NULL),
73 mV1SubjectNameCStructValue(NULL),
74 mV1IssuerNameCStructValue(NULL),
75 mSha1Hash(NULL)
76 {
77 }
78
79
80
81 Certificate* Certificate::make(const Keychain &keychain, const PrimaryKey &primaryKey, const CssmClient::DbUniqueRecord &uniqueId)
82 {
83 Certificate* c = new Certificate(keychain, primaryKey, uniqueId);
84 keychain->addItem(primaryKey, c);
85 return c;
86 }
87
88
89
90 Certificate* Certificate::make(const Keychain &keychain, const PrimaryKey &primaryKey)
91 {
92 Certificate* c = new Certificate(keychain, primaryKey);
93 keychain->addItem(primaryKey, c);
94 return c;
95 }
96
97
98
99
100 // PrimaryKey item constructor
101 Certificate::Certificate(const Keychain &keychain, const PrimaryKey &primaryKey) :
102 ItemImpl(keychain, primaryKey),
103 mHaveTypeAndEncoding(false),
104 mPopulated(false),
105 mCL(NULL),
106 mCertHandle(0),
107 mV1SubjectPublicKeyCStructValue(NULL),
108 mV1SubjectNameCStructValue(NULL),
109 mV1IssuerNameCStructValue(NULL),
110 mSha1Hash(NULL)
111 {
112 // @@@ In this case we don't know the type...
113 }
114
115 Certificate::Certificate(Certificate &certificate) :
116 ItemImpl(certificate),
117 mHaveTypeAndEncoding(certificate.mHaveTypeAndEncoding),
118 mPopulated(false /* certificate.mPopulated */),
119 mType(certificate.mType),
120 mEncoding(certificate.mEncoding),
121 mCL(certificate.mCL),
122 mCertHandle(0),
123 mV1SubjectPublicKeyCStructValue(NULL),
124 mV1SubjectNameCStructValue(NULL),
125 mV1IssuerNameCStructValue(NULL),
126 mSha1Hash(NULL)
127 {
128 }
129
130 Certificate::~Certificate()
131 try
132 {
133 if (mV1SubjectPublicKeyCStructValue)
134 releaseFieldValue(CSSMOID_X509V1SubjectPublicKeyCStruct, mV1SubjectPublicKeyCStructValue);
135
136 if (mCertHandle && mCL)
137 CSSM_CL_CertAbortCache(mCL->handle(), mCertHandle);
138
139 if (mV1SubjectNameCStructValue)
140 releaseFieldValue(CSSMOID_X509V1SubjectNameCStruct, mV1SubjectNameCStructValue);
141
142 if (mV1IssuerNameCStructValue)
143 releaseFieldValue(CSSMOID_X509V1IssuerNameCStruct, mV1IssuerNameCStructValue);
144
145 if (mSha1Hash)
146 CFRelease(mSha1Hash);
147 }
148 catch (...)
149 {
150 }
151
152 CSSM_HANDLE
153 Certificate::certHandle()
154 {
155 StLock<Mutex>_(mMutex);
156 const CSSM_DATA *cert = &data();
157 if (!mCertHandle)
158 {
159 if (CSSM_RETURN retval = CSSM_CL_CertCache(clHandle(), cert, &mCertHandle))
160 CssmError::throwMe(retval);
161 }
162
163 return mCertHandle;
164 }
165
166 /* Return a zero terminated list of CSSM_DATA_PTR's with the values of the field specified by field. Caller must call releaseFieldValues to free the storage allocated by this call. */
167 CSSM_DATA_PTR *
168 Certificate::copyFieldValues(const CSSM_OID &field)
169 {
170 StLock<Mutex>_(mMutex);
171 CSSM_CL_HANDLE clh = clHandle();
172 CSSM_DATA_PTR fieldValue, *fieldValues;
173 CSSM_HANDLE resultsHandle = 0;
174 uint32 numberOfFields = 0;
175 CSSM_RETURN result;
176
177 result = CSSM_CL_CertGetFirstCachedFieldValue(clh, certHandle(), &field, &resultsHandle, &numberOfFields, &fieldValue);
178 if (result)
179 {
180 if (result == CSSMERR_CL_NO_FIELD_VALUES)
181 return NULL;
182
183 CssmError::throwMe(result);
184 }
185
186 fieldValues = new CSSM_DATA_PTR[numberOfFields + 1];
187 fieldValues[0] = fieldValue;
188 fieldValues[numberOfFields] = NULL;
189
190 for (uint32 value = 1; value < numberOfFields; ++value)
191 {
192 CSSM_RETURN cresult = CSSM_CL_CertGetNextCachedFieldValue(clh, resultsHandle, &fieldValues[value]);
193 if (cresult)
194 {
195 fieldValues[value] = NULL;
196 result = cresult;
197 break; // No point in continuing really.
198 }
199 }
200
201 CSSM_CL_CertAbortQuery(clh, resultsHandle);
202
203 if (result)
204 {
205 releaseFieldValues(field, fieldValues);
206 CssmError::throwMe(result);
207 }
208
209 return fieldValues;
210 }
211
212 void
213 Certificate::releaseFieldValues(const CSSM_OID &field, CSSM_DATA_PTR *fieldValues)
214 {
215 StLock<Mutex>_(mMutex);
216 if (fieldValues)
217 {
218 CSSM_CL_HANDLE clh = clHandle();
219
220 for (int ix = 0; fieldValues[ix]; ++ix)
221 CSSM_CL_FreeFieldValue(clh, &field, fieldValues[ix]);
222
223 delete[] fieldValues;
224 }
225 }
226
227 void
228 Certificate::addParsedAttribute(const CSSM_DB_ATTRIBUTE_INFO &info, const CSSM_OID &field)
229 {
230 StLock<Mutex>_(mMutex);
231 CSSM_DATA_PTR *fieldValues = copyFieldValues(field);
232 if (fieldValues)
233 {
234 CssmDbAttributeData &anAttr = mDbAttributes->add(info);
235 for (int ix = 0; fieldValues[ix]; ++ix)
236 anAttr.add(*fieldValues[ix], *mDbAttributes);
237
238 releaseFieldValues(field, fieldValues);
239 }
240 }
241
242 void
243 Certificate::addSubjectKeyIdentifier()
244 {
245 StLock<Mutex>_(mMutex);
246 const CSSM_DB_ATTRIBUTE_INFO &info = Schema::attributeInfo(kSecSubjectKeyIdentifierItemAttr);
247 const CSSM_OID &field = CSSMOID_SubjectKeyIdentifier;
248
249 CSSM_DATA_PTR *fieldValues = copyFieldValues(field);
250 if (fieldValues)
251 {
252 CssmDbAttributeData &anAttr = mDbAttributes->add(info);
253 for (int ix = 0; fieldValues[ix]; ++ix)
254 {
255 const CSSM_X509_EXTENSION *extension = reinterpret_cast<const CSSM_X509_EXTENSION *>(fieldValues[ix]->Data);
256 if (extension == NULL || fieldValues[ix]->Length != sizeof(CSSM_X509_EXTENSION))
257 {
258 assert(extension != NULL && fieldValues[ix]->Length == sizeof(CSSM_X509_EXTENSION));
259 continue;
260 }
261 const CE_SubjectKeyID *skid = reinterpret_cast<CE_SubjectKeyID *>(extension->value.parsedValue);
262 if (skid == NULL)
263 {
264 assert(skid != NULL);
265 continue;
266 }
267 anAttr.add(*skid, *mDbAttributes);
268 }
269
270 releaseFieldValues(field, fieldValues);
271 }
272 }
273
274 /* Return a CSSM_DATA_PTR with the value of the first field specified by field. Caller must call releaseFieldValue to free the storage allocated by this call. */
275 CSSM_DATA_PTR
276 Certificate::copyFirstFieldValue(const CSSM_OID &field)
277 {
278 StLock<Mutex>_(mMutex);
279 CSSM_CL_HANDLE clh = clHandle();
280 CSSM_DATA_PTR fieldValue;
281 CSSM_HANDLE resultsHandle = 0;
282 uint32 numberOfFields = 0;
283 CSSM_RETURN result;
284
285 result = CSSM_CL_CertGetFirstCachedFieldValue(clh, certHandle(), &field, &resultsHandle, &numberOfFields, &fieldValue);
286 if (result)
287 {
288 if (result == CSSMERR_CL_NO_FIELD_VALUES)
289 return NULL;
290
291 CssmError::throwMe(result);
292 }
293
294 result = CSSM_CL_CertAbortQuery(clh, resultsHandle);
295
296 if (result)
297 {
298 releaseFieldValue(field, fieldValue);
299 CssmError::throwMe(result);
300 }
301
302 return fieldValue;
303 }
304
305 void
306 Certificate::releaseFieldValue(const CSSM_OID &field, CSSM_DATA_PTR fieldValue)
307 {
308 StLock<Mutex>_(mMutex);
309 if (fieldValue)
310 {
311 CSSM_CL_HANDLE clh = clHandle();
312 CSSM_CL_FreeFieldValue(clh, &field, fieldValue);
313 }
314 }
315
316
317
318 /*
319 This method computes the keyIdentifier for the public key in the cert as
320 described below:
321
322 The keyIdentifier is composed of the 160-bit SHA-1 hash of the
323 value of the BIT STRING subjectPublicKey (excluding the tag,
324 length, and number of unused bits).
325 */
326 const CssmData &
327 Certificate::publicKeyHash()
328 {
329 StLock<Mutex>_(mMutex);
330 if (mPublicKeyHash.Length)
331 return mPublicKeyHash;
332
333 CSSM_DATA_PTR keyPtr = copyFirstFieldValue(CSSMOID_CSSMKeyStruct);
334 if (keyPtr && keyPtr->Data)
335 {
336 CssmClient::CSP csp(gGuidAppleCSP);
337 CssmClient::PassThrough passThrough(csp);
338 CSSM_KEY *key = reinterpret_cast<CSSM_KEY *>(keyPtr->Data);
339 void *outData;
340 CssmData *cssmData;
341
342 /* Given a CSSM_KEY_PTR in any format, obtain the SHA-1 hash of the
343 * associated key blob.
344 * Key is specified in CSSM_CSP_CreatePassThroughContext.
345 * Hash is allocated by the CSP, in the App's memory, and returned
346 * in *outData. */
347 passThrough.key(key);
348 passThrough(CSSM_APPLECSP_KEYDIGEST, NULL, &outData);
349 cssmData = reinterpret_cast<CssmData *>(outData);
350
351 assert(cssmData->Length <= sizeof(mPublicKeyHashBytes));
352 mPublicKeyHash.Data = mPublicKeyHashBytes;
353 mPublicKeyHash.Length = cssmData->Length;
354 memcpy(mPublicKeyHash.Data, cssmData->Data, cssmData->Length);
355 csp.allocator().free(cssmData->Data);
356 csp.allocator().free(cssmData);
357 }
358
359 releaseFieldValue(CSSMOID_CSSMKeyStruct, keyPtr);
360
361 return mPublicKeyHash;
362 }
363
364 const CssmData &
365 Certificate::subjectKeyIdentifier()
366 {
367 StLock<Mutex>_(mMutex);
368 if (mSubjectKeyID.Length)
369 return mSubjectKeyID;
370
371 CSSM_DATA_PTR fieldValue = copyFirstFieldValue(CSSMOID_SubjectKeyIdentifier);
372 if (fieldValue && fieldValue->Data && fieldValue->Length == sizeof(CSSM_X509_EXTENSION))
373 {
374 const CSSM_X509_EXTENSION *extension = reinterpret_cast<const CSSM_X509_EXTENSION *>(fieldValue->Data);
375 const CE_SubjectKeyID *skid = reinterpret_cast<CE_SubjectKeyID *>(extension->value.parsedValue); // CSSM_DATA
376
377 if (skid->Length <= sizeof(mSubjectKeyIDBytes))
378 {
379 mSubjectKeyID.Data = mSubjectKeyIDBytes;
380 mSubjectKeyID.Length = skid->Length;
381 memcpy(mSubjectKeyID.Data, skid->Data, skid->Length);
382 }
383 else
384 mSubjectKeyID.Length = 0;
385 }
386
387 releaseFieldValue(CSSMOID_SubjectKeyIdentifier, fieldValue);
388
389 return mSubjectKeyID;
390 }
391
392
393 /*
394 * Given an CSSM_X509_NAME, Find the first (or last) name/value pair with
395 * a printable value which matches the specified OID (e.g., CSSMOID_CommonName).
396 * Returns the CFString-style encoding associated with name component's BER tag.
397 * Returns NULL if none found.
398 */
399 static const CSSM_DATA *
400 findPrintableField(
401 const CSSM_X509_NAME &x509Name,
402 const CSSM_OID *tvpType, // NULL means "any printable field"
403 bool lastInstance, // false means return first instance
404 CFStringBuiltInEncodings *encoding) // RETURNED
405 {
406 const CSSM_DATA *result = NULL;
407 for(uint32 rdnDex=0; rdnDex<x509Name.numberOfRDNs; rdnDex++) {
408 const CSSM_X509_RDN *rdnPtr =
409 &x509Name.RelativeDistinguishedName[rdnDex];
410 for(uint32 tvpDex=0; tvpDex<rdnPtr->numberOfPairs; tvpDex++) {
411 const CSSM_X509_TYPE_VALUE_PAIR *tvpPtr =
412 &rdnPtr->AttributeTypeAndValue[tvpDex];
413
414 /* type/value pair: match caller's specified type? */
415 if(tvpType != NULL && tvpType->Data != NULL) {
416 if(tvpPtr->type.Length != tvpType->Length) {
417 continue;
418 }
419 if(memcmp(tvpPtr->type.Data, tvpType->Data, tvpType->Length)) {
420 /* If we don't have a match but the requested OID is CSSMOID_UserID,
421 * look for a matching X.500 UserID OID: (0.9.2342.19200300.100.1.1) */
422 const char cssm_userid_oid[] = { 0x09,0x49,0x86,0x49,0x1f,0x12,0x8c,0xe4,0x81,0x81 };
423 const char x500_userid_oid[] = { 0x09,0x92,0x26,0x89,0x93,0xF2,0x2C,0x64,0x01,0x01 };
424 if(!(tvpType->Length == sizeof(cssm_userid_oid) &&
425 !memcmp(tvpPtr->type.Data, x500_userid_oid, sizeof(x500_userid_oid)) &&
426 !memcmp(tvpType->Data, cssm_userid_oid, sizeof(cssm_userid_oid)))) {
427 continue;
428 }
429 }
430 }
431
432 /* printable? */
433 switch(tvpPtr->valueType) {
434 case BER_TAG_PRINTABLE_STRING:
435 case BER_TAG_IA5_STRING:
436 *encoding = kCFStringEncodingASCII;
437 result = &tvpPtr->value;
438 break;
439 case BER_TAG_PKIX_UTF8_STRING:
440 case BER_TAG_GENERAL_STRING:
441 case BER_TAG_PKIX_UNIVERSAL_STRING:
442 *encoding = kCFStringEncodingUTF8;
443 result = &tvpPtr->value;
444 break;
445 case BER_TAG_T61_STRING:
446 case BER_TAG_VIDEOTEX_STRING:
447 case BER_TAG_ISO646_STRING:
448 *encoding = kCFStringEncodingISOLatin1;
449 result = &tvpPtr->value;
450 break;
451 case BER_TAG_PKIX_BMP_STRING:
452 *encoding = kCFStringEncodingUnicode;
453 result = &tvpPtr->value;
454 break;
455 default:
456 /* not printable */
457 break;
458 }
459 /* if we found a result and we want the first instance, return it now. */
460 if(result && !lastInstance) {
461 return result;
462 }
463
464 } /* for each pair */
465 } /* for each RDN */
466
467 /* result is NULL if no printable component was found */
468 return result;
469 }
470
471 /*
472 * Infer printable label for a given CSSM_X509_NAME. Returns NULL
473 * if no appropriate printable name found. Returns the CFString-style
474 * encoding associated with name component's BER tag. Also optionally
475 * returns Description component and its encoding if present and the
476 * returned name component was one we explicitly requested.
477 */
478 static const CSSM_DATA *inferLabelFromX509Name(
479 const CSSM_X509_NAME *x509Name,
480 CFStringBuiltInEncodings *encoding, // RETURNED
481 const CSSM_DATA **description, // optionally RETURNED
482 CFStringBuiltInEncodings *descrEncoding) // RETURNED if description != NULL
483 {
484 const CSSM_DATA *printValue;
485 if(description != NULL) {
486 *description = findPrintableField(*x509Name, &CSSMOID_Description, false, descrEncoding);
487 }
488 /*
489 * Search order (take the first one found with a printable
490 * value):
491 * -- common name
492 * -- Organizational Unit
493 * -- Organization
494 * -- email address
495 * -- field of any kind
496 */
497 printValue = findPrintableField(*x509Name, &CSSMOID_CommonName, true, encoding);
498 if(printValue != NULL) {
499 return printValue;
500 }
501 printValue = findPrintableField(*x509Name, &CSSMOID_OrganizationalUnitName, false, encoding);
502 if(printValue != NULL) {
503 return printValue;
504 }
505 printValue = findPrintableField(*x509Name, &CSSMOID_OrganizationName, false, encoding);
506 if(printValue != NULL) {
507 return printValue;
508 }
509 printValue = findPrintableField(*x509Name, &CSSMOID_EmailAddress, false, encoding);
510 if(printValue != NULL) {
511 return printValue;
512 }
513 /* if we didn't get one of the above names, don't append description */
514 if(description != NULL) {
515 *description = NULL;
516 }
517 /* take anything */
518 return findPrintableField(*x509Name, NULL, false, encoding);
519 }
520
521 /*
522 * Infer printable label for a given an CSSM_X509_NAME. Returns NULL
523 * if no appropriate printable name found.
524 */
525 const CSSM_DATA *SecInferLabelFromX509Name(
526 const CSSM_X509_NAME *x509Name)
527 {
528 /* callees of this routine don't care about the encoding */
529 CFStringBuiltInEncodings encoding = kCFStringEncodingASCII;
530 return inferLabelFromX509Name(x509Name, &encoding, NULL, &encoding);
531 }
532
533
534 void
535 Certificate::inferLabel(bool addLabel, CFStringRef *rtnString)
536 {
537 StLock<Mutex>_(mMutex);
538 // Set PrintName and optionally the Alias attribute for this certificate, based on the
539 // X509 SubjectAltName and SubjectName.
540 const CSSM_DATA *printName = NULL;
541 const CSSM_DATA *description = NULL;
542 std::vector<CssmData> emailAddresses;
543 CSSM_DATA puntData;
544 CssmAutoData printPlusDescr(Allocator::standard());
545 CssmData printPlusDescData;
546 CFStringBuiltInEncodings printEncoding = kCFStringEncodingUTF8;
547 CFStringBuiltInEncodings descrEncoding = kCFStringEncodingUTF8;
548
549 // Find the SubjectAltName fields, if any, and extract all the GNT_RFC822Name entries from all of them
550 const CSSM_OID &sanOid = CSSMOID_SubjectAltName;
551 CSSM_DATA_PTR *sanValues = copyFieldValues(sanOid);
552 const CSSM_OID &snOid = CSSMOID_X509V1SubjectNameCStruct;
553 CSSM_DATA_PTR snValue = copyFirstFieldValue(snOid);
554
555 getEmailAddresses(sanValues, snValue, emailAddresses);
556
557 if (snValue && snValue->Data)
558 {
559 const CSSM_X509_NAME &x509Name = *(const CSSM_X509_NAME *)snValue->Data;
560 printName = inferLabelFromX509Name(&x509Name, &printEncoding,
561 &description, &descrEncoding);
562 if (printName)
563 {
564 /* Don't ever use "Thawte Freemail Member" as the label for a cert. Instead force
565 a fall back on the email address. */
566 const char tfm[] = "Thawte Freemail Member";
567 if ( (printName->Length == sizeof(tfm) - 1) &&
568 !memcmp(printName->Data, tfm, sizeof(tfm) - 1)) {
569 printName = NULL;
570 }
571 }
572 }
573
574 /* Do a check to see if a '\0' was at the end of printName and strip it. */
575 CssmData cleanedUpPrintName;
576 if((printName != NULL) &&
577 (printName->Length != 0) &&
578 (printEncoding != kCFStringEncodingISOLatin1) &&
579 (printEncoding != kCFStringEncodingUnicode) &&
580 (printName->Data[printName->Length - 1] == '\0')) {
581 cleanedUpPrintName.Data = printName->Data;
582 cleanedUpPrintName.Length = printName->Length - 1;
583 printName = &cleanedUpPrintName;
584 }
585
586 if((printName != NULL) && (description != NULL) && (description->Length != 0))
587 {
588 /*
589 * Munge Print Name (which in this case is the CommonName) and Description
590 * together with the Description in parentheses. We convert from whatever
591 * format Print Name and Description are in to UTF8 here.
592 */
593 CFRef<CFMutableStringRef> combo(CFStringCreateMutable(NULL, 0));
594 CFRef<CFStringRef> cfPrint(CFStringCreateWithBytes(NULL, printName->Data,
595 (CFIndex)printName->Length, printEncoding, true));
596 CssmData cleanedUpDescr(description->Data, description->Length);
597 if ((cleanedUpDescr.Data[cleanedUpDescr.Length - 1] == '\0') &&
598 (descrEncoding != kCFStringEncodingISOLatin1) &&
599 (descrEncoding != kCFStringEncodingUnicode)) {
600 cleanedUpDescr.Length--;
601 }
602 CFRef<CFStringRef> cfDesc(CFStringCreateWithBytes(NULL, cleanedUpDescr.Data,
603 (CFIndex)cleanedUpDescr.Length, descrEncoding, true));
604 CFStringAppend(combo, cfPrint);
605 CFStringAppendCString(combo, " (", kCFStringEncodingASCII);
606 CFStringAppend(combo, cfDesc);
607 CFStringAppendCString(combo, ")", kCFStringEncodingASCII);
608 CFRef<CFDataRef> comboData(CFStringCreateExternalRepresentation(NULL, combo,
609 kCFStringEncodingUTF8, 0));
610 printPlusDescr.copy(CFDataGetBytePtr(comboData), CFDataGetLength(comboData));
611 printPlusDescData = printPlusDescr;
612 printName = &printPlusDescData;
613 printEncoding = kCFStringEncodingUTF8;
614 }
615
616 if (printName == NULL)
617 {
618 /* If the we couldn't find a label use the emailAddress instead. */
619 if (!emailAddresses.empty())
620 printName = &emailAddresses[0];
621 else
622 {
623 /* punt! */
624 puntData.Data = (uint8 *)"X509 Certificate";
625 puntData.Length = 16;
626 printName = &puntData;
627 }
628 printEncoding = kCFStringEncodingUTF8;
629 }
630
631 /* If we couldn't find an email address just use the printName which might be the url or something else useful. */
632 if (emailAddresses.empty())
633 emailAddresses.push_back(CssmData::overlay(*printName));
634
635 /* What do we do with the inferred label - return it or add it mDbAttributes? */
636 if (addLabel)
637 {
638 mDbAttributes->add(Schema::kX509CertificatePrintName, *printName);
639 CssmDbAttributeData &attrData = mDbAttributes->add(Schema::kX509CertificateAlias);
640
641 /* Add the email addresses to attrData and normalize them. */
642 uint32 ix = 0;
643 for (std::vector<CssmData>::const_iterator it = emailAddresses.begin(); it != emailAddresses.end(); ++it, ++ix)
644 {
645 /* Add the email address using the allocator from mDbAttributes. */
646 attrData.add(*it, *mDbAttributes);
647 /* Normalize the emailAddresses in place since attrData already copied it. */
648 normalizeEmailAddress(attrData.Value[ix]);
649 }
650 }
651
652 if (rtnString)
653 {
654 CFStringBuiltInEncodings testEncoding = printEncoding;
655 if(testEncoding == kCFStringEncodingISOLatin1) {
656 // try UTF-8 first
657 testEncoding = kCFStringEncodingUTF8;
658 }
659 *rtnString = CFStringCreateWithBytes(NULL, printName->Data,
660 (CFIndex)printName->Length, testEncoding, true);
661 if(*rtnString == NULL && printEncoding == kCFStringEncodingISOLatin1) {
662 // string cannot be represented in UTF-8, fall back to ISO Latin 1
663 *rtnString = CFStringCreateWithBytes(NULL, printName->Data,
664 (CFIndex)printName->Length, printEncoding, true);
665 }
666 }
667
668 // Clean up
669 if (snValue)
670 releaseFieldValue(snOid, snValue);
671 if (sanValues)
672 releaseFieldValues(sanOid, sanValues);
673 }
674
675 void
676 Certificate::populateAttributes()
677 {
678 StLock<Mutex>_(mMutex);
679 if (mPopulated)
680 return;
681
682 addParsedAttribute(Schema::attributeInfo(kSecSubjectItemAttr), CSSMOID_X509V1SubjectName);
683 addParsedAttribute(Schema::attributeInfo(kSecIssuerItemAttr), CSSMOID_X509V1IssuerName);
684 addParsedAttribute(Schema::attributeInfo(kSecSerialNumberItemAttr), CSSMOID_X509V1SerialNumber);
685
686 addSubjectKeyIdentifier();
687
688 if(!mHaveTypeAndEncoding)
689 MacOSError::throwMe(errSecDataNotAvailable); // @@@ Or some other error.
690
691 // Adjust mType based on the actual version of the cert.
692 CSSM_DATA_PTR versionPtr = copyFirstFieldValue(CSSMOID_X509V1Version);
693 if (versionPtr && versionPtr->Data && versionPtr->Length == sizeof(uint32))
694 {
695 mType = CSSM_CERT_X_509v1 + (*reinterpret_cast<uint32 *>(versionPtr->Data));
696 }
697 else
698 mType = CSSM_CERT_X_509v1;
699
700 releaseFieldValue(CSSMOID_X509V1Version, versionPtr);
701
702 mDbAttributes->add(Schema::attributeInfo(kSecCertTypeItemAttr), mType);
703 mDbAttributes->add(Schema::attributeInfo(kSecCertEncodingItemAttr), mEncoding);
704 mDbAttributes->add(Schema::attributeInfo(kSecPublicKeyHashItemAttr), publicKeyHash());
705 inferLabel(true);
706
707 mPopulated = true;
708 }
709
710 const CssmData &
711 Certificate::data()
712 {
713 StLock<Mutex>_(mMutex);
714 CssmDataContainer *data = mData.get();
715 if (!data && mKeychain)
716 {
717 // Make sure mUniqueId is set.
718 dbUniqueRecord();
719 CssmDataContainer _data;
720 mData = NULL;
721 /* new data allocated by CSPDL, implicitly freed by CssmDataContainer */
722 mUniqueId->get(NULL, &_data);
723 /* this saves a copy to be freed at destruction and to be passed to caller */
724 setData((UInt32)_data.length(), _data.data());
725 return *mData.get();
726 }
727
728 // If the data hasn't been set we can't return it.
729 if (!data)
730 MacOSError::throwMe(errSecDataNotAvailable);
731
732 return *data;
733 }
734
735 CFHashCode Certificate::hash()
736 {
737 (void)data(); // ensure that mData is set up
738 return ItemImpl::hash();
739 }
740
741 CSSM_CERT_TYPE
742 Certificate::type()
743 {
744 StLock<Mutex>_(mMutex);
745 if (!mHaveTypeAndEncoding)
746 {
747 SecKeychainAttribute attr;
748 attr.tag = kSecCertTypeItemAttr;
749 attr.data = &mType;
750 attr.length = sizeof(mType);
751 getAttribute(attr, NULL);
752 }
753
754 return mType;
755 }
756
757 CSSM_CERT_ENCODING
758 Certificate::encoding()
759 {
760 StLock<Mutex>_(mMutex);
761 if (!mHaveTypeAndEncoding)
762 {
763 SecKeychainAttribute attr;
764 attr.tag = kSecCertEncodingItemAttr;
765 attr.data = &mEncoding;
766 attr.length = sizeof(mEncoding);
767 getAttribute(attr, NULL);
768 }
769
770 return mEncoding;
771 }
772
773 const CSSM_X509_ALGORITHM_IDENTIFIER_PTR
774 Certificate::algorithmID()
775 {
776 StLock<Mutex>_(mMutex);
777 if (!mV1SubjectPublicKeyCStructValue)
778 mV1SubjectPublicKeyCStructValue = copyFirstFieldValue(CSSMOID_X509V1SubjectPublicKeyCStruct);
779
780 CSSM_X509_SUBJECT_PUBLIC_KEY_INFO *info = (CSSM_X509_SUBJECT_PUBLIC_KEY_INFO *)mV1SubjectPublicKeyCStructValue->Data;
781 CSSM_X509_ALGORITHM_IDENTIFIER *algid = &info->algorithm;
782 return algid;
783 }
784
785 CFDataRef
786 Certificate::sha1Hash()
787 {
788 StLock<Mutex>_(mMutex);
789 if (!mSha1Hash) {
790 SecCertificateRef certRef = handle(false);
791 CFAllocatorRef allocRef = (certRef) ? CFGetAllocator(certRef) : NULL;
792 CSSM_DATA certData = data();
793 if (certData.Length == 0 || !certData.Data) {
794 MacOSError::throwMe(errSecDataNotAvailable);
795 }
796 const UInt8 *dataPtr = (const UInt8 *)certData.Data;
797 CFIndex dataLen = (CFIndex)certData.Length;
798 CFMutableDataRef digest = CFDataCreateMutable(allocRef, CC_SHA1_DIGEST_LENGTH);
799 CFDataSetLength(digest, CC_SHA1_DIGEST_LENGTH);
800 CCDigest(kCCDigestSHA1, dataPtr, dataLen, CFDataGetMutableBytePtr(digest));
801 mSha1Hash = digest;
802 }
803 return mSha1Hash; /* object is owned by our instance; caller should NOT release it */
804 }
805
806 CFStringRef
807 Certificate::commonName()
808 {
809 StLock<Mutex>_(mMutex);
810 return distinguishedName(&CSSMOID_X509V1SubjectNameCStruct, &CSSMOID_CommonName);
811 }
812
813 CFStringRef
814 Certificate::distinguishedName(const CSSM_OID *sourceOid, const CSSM_OID *componentOid)
815 {
816 StLock<Mutex>_(mMutex);
817 CFStringRef rtnString = NULL;
818 CSSM_DATA_PTR fieldValue = copyFirstFieldValue(*sourceOid);
819 CSSM_X509_NAME_PTR x509Name = (CSSM_X509_NAME_PTR)fieldValue->Data;
820 const CSSM_DATA *printValue = NULL;
821 CFStringBuiltInEncodings encoding;
822
823 if (fieldValue && fieldValue->Data)
824 printValue = findPrintableField(*x509Name, componentOid, true, &encoding);
825
826 if (printValue)
827 rtnString = CFStringCreateWithBytes(NULL, printValue->Data,
828 CFIndex(printValue->Length), encoding, true);
829
830 releaseFieldValue(*sourceOid, fieldValue);
831
832 return rtnString;
833 }
834
835
836 /*
837 * Return a CFString containing the first email addresses for this certificate, based on the
838 * X509 SubjectAltName and SubjectName.
839 */
840 CFStringRef
841 Certificate::copyFirstEmailAddress()
842 {
843 StLock<Mutex>_(mMutex);
844 CFStringRef rtnString;
845
846 const CSSM_OID &sanOid = CSSMOID_SubjectAltName;
847 CSSM_DATA_PTR *sanValues = copyFieldValues(sanOid);
848 const CSSM_OID &snOid = CSSMOID_X509V1SubjectNameCStruct;
849 CSSM_DATA_PTR snValue = copyFirstFieldValue(snOid);
850 std::vector<CssmData> emailAddresses;
851
852 getEmailAddresses(sanValues, snValue, emailAddresses);
853 if (emailAddresses.empty())
854 rtnString = NULL;
855 else
856 {
857 /* Encoding is kCFStringEncodingUTF8 since the string is either
858 PRINTABLE_STRING, IA5_STRING, T61_STRING or PKIX_UTF8_STRING. */
859 rtnString = CFStringCreateWithBytes(NULL, emailAddresses[0].Data,
860 (CFIndex)emailAddresses[0].Length, kCFStringEncodingUTF8, true);
861 }
862
863 // Clean up
864 if (snValue)
865 releaseFieldValue(snOid, snValue);
866 if (sanValues)
867 releaseFieldValues(sanOid, sanValues);
868
869 return rtnString;
870 }
871
872 /*
873 * Return a CFArray containing the email addresses for this certificate, based on the
874 * X509 SubjectAltName and SubjectName.
875 */
876 CFArrayRef
877 Certificate::copyEmailAddresses()
878 {
879 StLock<Mutex>_(mMutex);
880 CFMutableArrayRef array = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
881 std::vector<CssmData> emailAddresses;
882
883 // Find the SubjectAltName fields, if any, and extract all the GNT_RFC822Name entries from all of them
884 const CSSM_OID &sanOid = CSSMOID_SubjectAltName;
885 CSSM_DATA_PTR *sanValues = copyFieldValues(sanOid);
886
887 const CSSM_OID &snOid = CSSMOID_X509V1SubjectNameCStruct;
888 CSSM_DATA_PTR snValue = copyFirstFieldValue(snOid);
889
890 getEmailAddresses(sanValues, snValue, emailAddresses);
891
892 for (std::vector<CssmData>::const_iterator it = emailAddresses.begin(); it != emailAddresses.end(); ++it)
893 {
894 /* Encoding is kCFStringEncodingUTF8 since the string is either
895 PRINTABLE_STRING, IA5_STRING, T61_STRING or PKIX_UTF8_STRING. */
896 CFStringRef string = CFStringCreateWithBytes(NULL, it->Data, static_cast<CFIndex>(it->Length), kCFStringEncodingUTF8, true);
897 CFArrayAppendValue(array, string);
898 CFRelease(string);
899 }
900
901 // Clean up
902 if (snValue)
903 releaseFieldValue(snOid, snValue);
904 if (sanValues)
905 releaseFieldValues(sanOid, sanValues);
906
907 return array;
908 }
909
910 const CSSM_X509_NAME_PTR
911 Certificate::subjectName()
912 {
913 StLock<Mutex>_(mMutex);
914 if (!mV1SubjectNameCStructValue)
915 if ((mV1SubjectNameCStructValue = copyFirstFieldValue(CSSMOID_X509V1SubjectNameCStruct)) == NULL)
916 return NULL;
917
918 return (const CSSM_X509_NAME_PTR)mV1SubjectNameCStructValue->Data;
919 }
920
921 const CSSM_X509_NAME_PTR
922 Certificate::issuerName()
923 {
924 StLock<Mutex>_(mMutex);
925 if (!mV1IssuerNameCStructValue)
926 if ((mV1IssuerNameCStructValue = copyFirstFieldValue(CSSMOID_X509V1IssuerNameCStruct)) == NULL)
927 return NULL;
928
929 return (const CSSM_X509_NAME_PTR)mV1IssuerNameCStructValue->Data;
930 }
931
932 CSSM_CL_HANDLE
933 Certificate::clHandle()
934 {
935 StLock<Mutex>_(mMutex);
936 if (!mCL)
937 mCL = clForType(type());
938
939 return mCL->handle();
940 }
941
942 bool
943 Certificate::operator < (Certificate &other)
944 {
945 // Certificates in different keychains are considered equal if data is equal
946 // Note that the Identity '<' operator relies on this assumption.
947 return data() < other.data();
948 }
949
950 bool
951 Certificate::operator == (Certificate &other)
952 {
953 // Certificates in different keychains are considered equal if data is equal
954 // Note that the Identity '==' operator relies on this assumption.
955 return data() == other.data();
956 }
957
958 void
959 Certificate::update()
960 {
961 ItemImpl::update();
962 }
963
964 Item
965 Certificate::copyTo(const Keychain &keychain, Access *newAccess)
966 {
967 StLock<Mutex>_(mMutex);
968 /* Certs can't have access controls. */
969 if (newAccess)
970 MacOSError::throwMe(errSecNoAccessForItem);
971
972 Item item(new Certificate(data(), type(), encoding()));
973 keychain->add(item);
974 return item;
975 }
976
977 void
978 Certificate::didModify()
979 {
980 }
981
982 PrimaryKey
983 Certificate::add(Keychain &keychain)
984 {
985 StLock<Mutex>_(mMutex);
986 // If we already have a Keychain we can't be added.
987 if (mKeychain)
988 MacOSError::throwMe(errSecDuplicateItem);
989
990 populateAttributes();
991
992 CSSM_DB_RECORDTYPE recordType = mDbAttributes->recordType();
993
994 Db db(keychain->database());
995 // add the item to the (regular) db
996 try
997 {
998 mUniqueId = db->insert(recordType, mDbAttributes.get(), mData.get());
999 }
1000 catch (const CssmError &e)
1001 {
1002 if (e.osStatus() != CSSMERR_DL_INVALID_RECORDTYPE)
1003 throw;
1004
1005 // Create the cert relation and try again.
1006 db->createRelation(CSSM_DL_DB_RECORD_X509_CERTIFICATE,
1007 "CSSM_DL_DB_RECORD_X509_CERTIFICATE",
1008 Schema::X509CertificateSchemaAttributeCount,
1009 Schema::X509CertificateSchemaAttributeList,
1010 Schema::X509CertificateSchemaIndexCount,
1011 Schema::X509CertificateSchemaIndexList);
1012 keychain->keychainSchema()->didCreateRelation(
1013 CSSM_DL_DB_RECORD_X509_CERTIFICATE,
1014 "CSSM_DL_DB_RECORD_X509_CERTIFICATE",
1015 Schema::X509CertificateSchemaAttributeCount,
1016 Schema::X509CertificateSchemaAttributeList,
1017 Schema::X509CertificateSchemaIndexCount,
1018 Schema::X509CertificateSchemaIndexList);
1019
1020 mUniqueId = db->insert(recordType, mDbAttributes.get(), mData.get());
1021 }
1022
1023 mPrimaryKey = keychain->makePrimaryKey(recordType, mUniqueId);
1024 mKeychain = keychain;
1025
1026 return mPrimaryKey;
1027 }
1028
1029 SecPointer<KeyItem>
1030 Certificate::publicKey()
1031 {
1032 StLock<Mutex>_(mMutex);
1033 SecPointer<KeyItem> keyItem;
1034 // Return a CSSM_DATA_PTR with the value of the first field specified by field.
1035 // Caller must call releaseFieldValue to free the storage allocated by this call.
1036 // call OSStatus SecKeyGetCSSMKey(SecKeyRef key, const CSSM_KEY **cssmKey); to retrieve
1037
1038 CSSM_DATA_PTR keyPtr = copyFirstFieldValue(CSSMOID_CSSMKeyStruct);
1039 if (keyPtr && keyPtr->Data)
1040 {
1041 CssmClient::CSP csp(gGuidAppleCSP);
1042 CssmKey *cssmKey = reinterpret_cast<CssmKey *>(keyPtr->Data);
1043 CssmClient::Key key(csp, *cssmKey);
1044 keyItem = new KeyItem(key);
1045 // Clear out KeyData since KeyItem() takes over ownership of the key, and we don't want it getting released.
1046 cssmKey->KeyData.Data = NULL;
1047 cssmKey->KeyData.Length = 0;
1048 }
1049
1050 releaseFieldValue(CSSMOID_CSSMKeyStruct, keyPtr);
1051
1052 return keyItem;
1053 }
1054
1055 // This function "borrowed" from the X509 CL, which is (currently) linked into
1056 // the Security.framework as a built-in plugin.
1057 extern "C" bool getField_normRDN_NSS (
1058 const CSSM_DATA &derName,
1059 uint32 &numFields, // RETURNED (if successful, 0 or 1)
1060 CssmOwnedData &fieldValue); // RETURNED
1061
1062 KCCursor
1063 Certificate::cursorForIssuerAndSN(const StorageManager::KeychainList &keychains, const CssmData &issuer, const CssmData &serialNumber)
1064 {
1065 CssmAutoData fieldValue(Allocator::standard(Allocator::normal));
1066 uint32 numFields;
1067
1068 // We need to decode issuer, normalize it, then re-encode it
1069 if (!getField_normRDN_NSS(issuer, numFields, fieldValue))
1070 MacOSError::throwMe(errSecDataNotAvailable);
1071
1072 // Code basically copied from SecKeychainSearchCreateFromAttributes and SecKeychainSearchCopyNext:
1073 KCCursor cursor(keychains, kSecCertificateItemClass, NULL);
1074 cursor->conjunctive(CSSM_DB_AND);
1075 cursor->add(CSSM_DB_EQUAL, Schema::kX509CertificateIssuer, fieldValue.get());
1076 cursor->add(CSSM_DB_EQUAL, Schema::kX509CertificateSerialNumber, serialNumber);
1077
1078 return cursor;
1079 }
1080
1081 KCCursor
1082 Certificate::cursorForIssuerAndSN_CF(const StorageManager::KeychainList &keychains, CFDataRef issuer, CFDataRef serialNumber)
1083 {
1084 // This assumes a normalized issuer
1085 CSSM_DATA issuerCSSM, serialNumberCSSM;
1086
1087 issuerCSSM.Length = CFDataGetLength(issuer);
1088 issuerCSSM.Data = const_cast<uint8 *>(CFDataGetBytePtr(issuer));
1089
1090 serialNumberCSSM.Length = CFDataGetLength(serialNumber);
1091 serialNumberCSSM.Data = const_cast<uint8 *>(CFDataGetBytePtr(serialNumber));
1092
1093 // Code basically copied from SecKeychainSearchCreateFromAttributes and SecKeychainSearchCopyNext:
1094 KCCursor cursor(keychains, kSecCertificateItemClass, NULL);
1095 cursor->conjunctive(CSSM_DB_AND);
1096 cursor->add(CSSM_DB_EQUAL, Schema::kX509CertificateIssuer, issuerCSSM);
1097 cursor->add(CSSM_DB_EQUAL, Schema::kX509CertificateSerialNumber, serialNumberCSSM);
1098
1099 return cursor;
1100 }
1101
1102 KCCursor
1103 Certificate::cursorForSubjectKeyID(const StorageManager::KeychainList &keychains, const CssmData &subjectKeyID)
1104 {
1105 KCCursor cursor(keychains, kSecCertificateItemClass, NULL);
1106 cursor->conjunctive(CSSM_DB_AND);
1107 cursor->add(CSSM_DB_EQUAL, Schema::kX509CertificateSubjectKeyIdentifier, subjectKeyID);
1108
1109 return cursor;
1110 }
1111
1112 KCCursor
1113 Certificate::cursorForEmail(const StorageManager::KeychainList &keychains, const char *emailAddress)
1114 {
1115 KCCursor cursor(keychains, kSecCertificateItemClass, NULL);
1116 if (emailAddress)
1117 {
1118 cursor->conjunctive(CSSM_DB_AND);
1119 CssmSelectionPredicate &pred = cursor->add(CSSM_DB_EQUAL, Schema::kX509CertificateAlias, emailAddress);
1120 /* Normalize the emailAddresses in place since cursor already copied it. */
1121 normalizeEmailAddress(pred.Attribute.Value[0]);
1122 }
1123
1124 return cursor;
1125 }
1126
1127 SecPointer<Certificate>
1128 Certificate::findInKeychain(const StorageManager::KeychainList &keychains)
1129 {
1130 StLock<Mutex>_(mMutex);
1131 const CSSM_OID &issuerOid = CSSMOID_X509V1IssuerName;
1132 CSSM_DATA_PTR issuerPtr = copyFirstFieldValue(issuerOid);
1133 CssmData issuer(issuerPtr->Data, issuerPtr->Length);
1134
1135 const CSSM_OID &serialOid = CSSMOID_X509V1SerialNumber;
1136 CSSM_DATA_PTR serialPtr = copyFirstFieldValue(serialOid);
1137 CssmData serial(serialPtr->Data, serialPtr->Length);
1138
1139 SecPointer<Certificate> foundCert = NULL;
1140 try {
1141 foundCert = findByIssuerAndSN(keychains, issuer, serial);
1142 } catch (...) {
1143 foundCert = NULL;
1144 }
1145
1146 releaseFieldValue(issuerOid, issuerPtr);
1147 releaseFieldValue(serialOid, serialPtr);
1148
1149 return foundCert;
1150 }
1151
1152 SecPointer<Certificate>
1153 Certificate::findByIssuerAndSN(const StorageManager::KeychainList &keychains, const CssmData &issuer, const CssmData &serialNumber)
1154 {
1155 Item item;
1156 if (!cursorForIssuerAndSN(keychains, issuer, serialNumber)->next(item))
1157 CssmError::throwMe(errSecItemNotFound);
1158
1159 return static_cast<Certificate *>(&*item);
1160 }
1161
1162 SecPointer<Certificate>
1163 Certificate::findBySubjectKeyID(const StorageManager::KeychainList &keychains, const CssmData &subjectKeyID)
1164 {
1165 Item item;
1166 if (!cursorForSubjectKeyID(keychains, subjectKeyID)->next(item))
1167 CssmError::throwMe(errSecItemNotFound);
1168
1169 return static_cast<Certificate *>(&*item);
1170 }
1171
1172 SecPointer<Certificate>
1173 Certificate::findByEmail(const StorageManager::KeychainList &keychains, const char *emailAddress)
1174 {
1175 Item item;
1176 if (!cursorForEmail(keychains, emailAddress)->next(item))
1177 CssmError::throwMe(errSecItemNotFound);
1178
1179 return static_cast<Certificate *>(&*item);
1180 }
1181
1182 /* Normalize emailAddresses in place. */
1183 void
1184 Certificate::normalizeEmailAddress(CSSM_DATA &emailAddress)
1185 {
1186 /* Do a check to see if a '\0' was at the end of emailAddress and strip it. */
1187 if (emailAddress.Length && emailAddress.Data[emailAddress.Length - 1] == '\0')
1188 emailAddress.Length--;
1189 bool foundAt = false;
1190 for (uint32 ix = 0; ix < emailAddress.Length; ++ix)
1191 {
1192 uint8 ch = emailAddress.Data[ix];
1193 if (foundAt)
1194 {
1195 if ('A' <= ch && ch <= 'Z')
1196 emailAddress.Data[ix] = ch + 'a' - 'A';
1197 }
1198 else if (ch == '@')
1199 foundAt = true;
1200 }
1201 }
1202
1203 void
1204 Certificate::getEmailAddresses(CSSM_DATA_PTR *sanValues, CSSM_DATA_PTR snValue, std::vector<CssmData> &emailAddresses)
1205 {
1206 // Get the email addresses for this certificate, based on the
1207 // X509 SubjectAltName and SubjectName.
1208
1209 // Find the SubjectAltName fields, if any, and extract all the GNT_RFC822Name entries from all of them
1210 if (sanValues)
1211 {
1212 for (CSSM_DATA_PTR *sanIx = sanValues; *sanIx; ++sanIx)
1213 {
1214 CSSM_DATA_PTR sanValue = *sanIx;
1215 if (sanValue && sanValue->Data)
1216 {
1217 CSSM_X509_EXTENSION *cssmExt = (CSSM_X509_EXTENSION *)sanValue->Data;
1218 CE_GeneralNames *parsedValue = (CE_GeneralNames *)cssmExt->value.parsedValue;
1219
1220 /* Grab all the values that are of type GNT_RFC822Name. */
1221 for (uint32 i = 0; i < parsedValue->numNames; ++i)
1222 {
1223 if (parsedValue->generalName[i].nameType == GNT_RFC822Name)
1224 {
1225 if (parsedValue->generalName[i].berEncoded) // can't handle this
1226 continue;
1227
1228 emailAddresses.push_back(CssmData::overlay(parsedValue->generalName[i].name));
1229 }
1230 }
1231 }
1232 }
1233 }
1234
1235 if (emailAddresses.empty() && snValue && snValue->Data)
1236 {
1237 const CSSM_X509_NAME &x509Name = *(const CSSM_X509_NAME *)snValue->Data;
1238 for (uint32 rdnDex = 0; rdnDex < x509Name.numberOfRDNs; rdnDex++)
1239 {
1240 const CSSM_X509_RDN *rdnPtr =
1241 &x509Name.RelativeDistinguishedName[rdnDex];
1242 for (uint32 tvpDex = 0; tvpDex < rdnPtr->numberOfPairs; tvpDex++)
1243 {
1244 const CSSM_X509_TYPE_VALUE_PAIR *tvpPtr =
1245 &rdnPtr->AttributeTypeAndValue[tvpDex];
1246
1247 /* type/value pair: match caller's specified type? */
1248 if (((tvpPtr->type.Length != CSSMOID_EmailAddress.Length) ||
1249 memcmp(tvpPtr->type.Data, CSSMOID_EmailAddress.Data, CSSMOID_EmailAddress.Length))) {
1250 continue;
1251 }
1252
1253 /* printable? */
1254 switch (tvpPtr->valueType)
1255 {
1256 case BER_TAG_PRINTABLE_STRING:
1257 case BER_TAG_IA5_STRING:
1258 case BER_TAG_T61_STRING:
1259 case BER_TAG_PKIX_UTF8_STRING:
1260 /* success */
1261 emailAddresses.push_back(CssmData::overlay(tvpPtr->value));
1262 break;
1263 default:
1264 break;
1265 }
1266 } /* for each pair */
1267 } /* for each RDN */
1268 }
1269 }
1270
1271 void Certificate::willRead()
1272 {
1273 populateAttributes();
1274 }
1275
1276 Boolean Certificate::isSelfSigned()
1277 {
1278 StLock<Mutex>_(mMutex);
1279 CSSM_DATA_PTR issuer = NULL;
1280 CSSM_DATA_PTR subject = NULL;
1281 OSStatus ortn = errSecSuccess;
1282 Boolean brtn = false;
1283
1284 issuer = copyFirstFieldValue(CSSMOID_X509V1IssuerNameStd);
1285 subject = copyFirstFieldValue(CSSMOID_X509V1SubjectNameStd);
1286 if((issuer == NULL) || (subject == NULL)) {
1287 ortn = errSecParam;
1288 }
1289 else if((issuer->Length == subject->Length) &&
1290 !memcmp(issuer->Data, subject->Data, issuer->Length)) {
1291 brtn = true;
1292 }
1293 if(brtn) {
1294 /* names match: verify signature */
1295 CSSM_RETURN crtn;
1296 CSSM_DATA certData = data();
1297 crtn = CSSM_CL_CertVerify(clHandle(), 0,
1298 &certData, &certData, NULL, 0);
1299 if(crtn) {
1300 brtn = false;
1301 }
1302 }
1303 if(issuer) {
1304 releaseFieldValue(CSSMOID_X509V1IssuerNameStd, issuer);
1305 }
1306 if(subject) {
1307 releaseFieldValue(CSSMOID_X509V1SubjectNameStd, subject);
1308 }
1309 if(ortn) {
1310 MacOSError::throwMe(ortn);
1311 }
1312 return brtn;
1313 }