2 * Copyright (c) 2002-2007 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@
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>
37 #include <CoreServices/../Frameworks/CarbonCore.framework/Headers/MacErrors.h>
38 //#include "CLFieldsCommon.h"
41 using namespace KeychainCore
;
44 Certificate::clForType(CSSM_CERT_TYPE type
)
46 return CL(gGuidAppleX509CL
);
49 Certificate::Certificate(const CSSM_DATA
&data
, CSSM_CERT_TYPE type
, CSSM_CERT_ENCODING encoding
) :
50 ItemImpl(CSSM_DL_DB_RECORD_X509_CERTIFICATE
, reinterpret_cast<SecKeychainAttributeList
*>(NULL
), UInt32(data
.Length
), reinterpret_cast<const void *>(data
.Data
)),
51 mHaveTypeAndEncoding(true),
57 mV1SubjectPublicKeyCStructValue(NULL
),
58 mV1SubjectNameCStructValue(NULL
),
59 mV1IssuerNameCStructValue(NULL
)
61 if (data
.Length
== 0 || data
.Data
== NULL
)
62 MacOSError::throwMe(paramErr
);
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),
72 mV1SubjectPublicKeyCStructValue(NULL
),
73 mV1SubjectNameCStructValue(NULL
),
74 mV1IssuerNameCStructValue(NULL
)
80 Certificate
* Certificate::make(const Keychain
&keychain
, const PrimaryKey
&primaryKey
, const CssmClient::DbUniqueRecord
&uniqueId
)
82 Certificate
* c
= new Certificate(keychain
, primaryKey
, uniqueId
);
83 keychain
->addItem(primaryKey
, c
);
89 Certificate
* Certificate::make(const Keychain
&keychain
, const PrimaryKey
&primaryKey
)
91 Certificate
* c
= new Certificate(keychain
, primaryKey
);
92 keychain
->addItem(primaryKey
, c
);
99 // PrimaryKey item constructor
100 Certificate::Certificate(const Keychain
&keychain
, const PrimaryKey
&primaryKey
) :
101 ItemImpl(keychain
, primaryKey
),
102 mHaveTypeAndEncoding(false),
106 mV1SubjectPublicKeyCStructValue(NULL
),
107 mV1SubjectNameCStructValue(NULL
),
108 mV1IssuerNameCStructValue(NULL
)
110 // @@@ In this case we don't know the type...
113 Certificate::Certificate(Certificate
&certificate
) :
114 ItemImpl(certificate
),
115 mHaveTypeAndEncoding(certificate
.mHaveTypeAndEncoding
),
116 mPopulated(false /* certificate.mPopulated */),
117 mType(certificate
.mType
),
118 mEncoding(certificate
.mEncoding
),
119 mCL(certificate
.mCL
),
121 mV1SubjectPublicKeyCStructValue(NULL
),
122 mV1SubjectNameCStructValue(NULL
),
123 mV1IssuerNameCStructValue(NULL
)
127 Certificate::~Certificate() throw()
129 if (mV1SubjectPublicKeyCStructValue
)
130 releaseFieldValue(CSSMOID_X509V1SubjectPublicKeyCStruct
, mV1SubjectPublicKeyCStructValue
);
132 if (mCertHandle
&& mCL
)
133 CSSM_CL_CertAbortCache(mCL
->handle(), mCertHandle
);
135 if (mV1SubjectNameCStructValue
)
136 releaseFieldValue(CSSMOID_X509V1SubjectNameCStruct
, mV1SubjectNameCStructValue
);
138 if (mV1IssuerNameCStructValue
)
139 releaseFieldValue(CSSMOID_X509V1IssuerNameCStruct
, mV1IssuerNameCStructValue
);
143 Certificate::certHandle()
145 StLock
<Mutex
>_(mMutex
);
146 const CSSM_DATA
*cert
= &data();
149 if (CSSM_RETURN retval
= CSSM_CL_CertCache(clHandle(), cert
, &mCertHandle
))
150 CssmError::throwMe(retval
);
156 /* 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. */
158 Certificate::copyFieldValues(const CSSM_OID
&field
)
160 StLock
<Mutex
>_(mMutex
);
161 CSSM_CL_HANDLE clh
= clHandle();
162 CSSM_DATA_PTR fieldValue
, *fieldValues
;
163 CSSM_HANDLE resultsHandle
= 0;
164 uint32 numberOfFields
= 0;
167 result
= CSSM_CL_CertGetFirstCachedFieldValue(clh
, certHandle(), &field
, &resultsHandle
, &numberOfFields
, &fieldValue
);
170 if (result
== CSSMERR_CL_NO_FIELD_VALUES
)
173 CssmError::throwMe(result
);
176 fieldValues
= new CSSM_DATA_PTR
[numberOfFields
+ 1];
177 fieldValues
[0] = fieldValue
;
178 fieldValues
[numberOfFields
] = NULL
;
180 for (uint32 value
= 1; value
< numberOfFields
; ++value
)
182 CSSM_RETURN cresult
= CSSM_CL_CertGetNextCachedFieldValue(clh
, resultsHandle
, &fieldValues
[value
]);
185 fieldValues
[value
] = NULL
;
187 break; // No point in continuing really.
191 CSSM_CL_CertAbortQuery(clh
, resultsHandle
);
195 releaseFieldValues(field
, fieldValues
);
196 CssmError::throwMe(result
);
203 Certificate::releaseFieldValues(const CSSM_OID
&field
, CSSM_DATA_PTR
*fieldValues
)
205 StLock
<Mutex
>_(mMutex
);
208 CSSM_CL_HANDLE clh
= clHandle();
210 for (int ix
= 0; fieldValues
[ix
]; ++ix
)
211 CSSM_CL_FreeFieldValue(clh
, &field
, fieldValues
[ix
]);
213 delete[] fieldValues
;
218 Certificate::addParsedAttribute(const CSSM_DB_ATTRIBUTE_INFO
&info
, const CSSM_OID
&field
)
220 StLock
<Mutex
>_(mMutex
);
221 CSSM_DATA_PTR
*fieldValues
= copyFieldValues(field
);
224 CssmDbAttributeData
&anAttr
= mDbAttributes
->add(info
);
225 for (int ix
= 0; fieldValues
[ix
]; ++ix
)
226 anAttr
.add(*fieldValues
[ix
], *mDbAttributes
);
228 releaseFieldValues(field
, fieldValues
);
233 Certificate::addSubjectKeyIdentifier()
235 StLock
<Mutex
>_(mMutex
);
236 const CSSM_DB_ATTRIBUTE_INFO
&info
= Schema::attributeInfo(kSecSubjectKeyIdentifierItemAttr
);
237 const CSSM_OID
&field
= CSSMOID_SubjectKeyIdentifier
;
239 CSSM_DATA_PTR
*fieldValues
= copyFieldValues(field
);
242 CssmDbAttributeData
&anAttr
= mDbAttributes
->add(info
);
243 for (int ix
= 0; fieldValues
[ix
]; ++ix
)
245 const CSSM_X509_EXTENSION
*extension
= reinterpret_cast<const CSSM_X509_EXTENSION
*>(fieldValues
[ix
]->Data
);
246 if (extension
== NULL
|| fieldValues
[ix
]->Length
!= sizeof(CSSM_X509_EXTENSION
))
248 assert(extension
!= NULL
&& fieldValues
[ix
]->Length
== sizeof(CSSM_X509_EXTENSION
));
251 const CE_SubjectKeyID
*skid
= reinterpret_cast<CE_SubjectKeyID
*>(extension
->value
.parsedValue
);
254 assert(skid
!= NULL
);
257 anAttr
.add(*skid
, *mDbAttributes
);
260 releaseFieldValues(field
, fieldValues
);
264 /* 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. */
266 Certificate::copyFirstFieldValue(const CSSM_OID
&field
)
268 StLock
<Mutex
>_(mMutex
);
269 CSSM_CL_HANDLE clh
= clHandle();
270 CSSM_DATA_PTR fieldValue
;
271 CSSM_HANDLE resultsHandle
= 0;
272 uint32 numberOfFields
= 0;
275 result
= CSSM_CL_CertGetFirstCachedFieldValue(clh
, certHandle(), &field
, &resultsHandle
, &numberOfFields
, &fieldValue
);
278 if (result
== CSSMERR_CL_NO_FIELD_VALUES
)
281 CssmError::throwMe(result
);
284 result
= CSSM_CL_CertAbortQuery(clh
, resultsHandle
);
288 releaseFieldValue(field
, fieldValue
);
289 CssmError::throwMe(result
);
296 Certificate::releaseFieldValue(const CSSM_OID
&field
, CSSM_DATA_PTR fieldValue
)
298 StLock
<Mutex
>_(mMutex
);
301 CSSM_CL_HANDLE clh
= clHandle();
302 CSSM_CL_FreeFieldValue(clh
, &field
, fieldValue
);
309 This method computes the keyIdentifier for the public key in the cert as
312 The keyIdentifier is composed of the 160-bit SHA-1 hash of the
313 value of the BIT STRING subjectPublicKey (excluding the tag,
314 length, and number of unused bits).
317 Certificate::publicKeyHash()
319 StLock
<Mutex
>_(mMutex
);
320 if (mPublicKeyHash
.Length
)
321 return mPublicKeyHash
;
323 CSSM_DATA_PTR keyPtr
= copyFirstFieldValue(CSSMOID_CSSMKeyStruct
);
324 if (keyPtr
&& keyPtr
->Data
)
326 CssmClient::CSP
csp(gGuidAppleCSP
);
327 CssmClient::PassThrough
passThrough(csp
);
328 CSSM_KEY
*key
= reinterpret_cast<CSSM_KEY
*>(keyPtr
->Data
);
332 /* Given a CSSM_KEY_PTR in any format, obtain the SHA-1 hash of the
333 * associated key blob.
334 * Key is specified in CSSM_CSP_CreatePassThroughContext.
335 * Hash is allocated by the CSP, in the App's memory, and returned
337 passThrough
.key(key
);
338 passThrough(CSSM_APPLECSP_KEYDIGEST
, NULL
, &outData
);
339 cssmData
= reinterpret_cast<CssmData
*>(outData
);
341 assert(cssmData
->Length
<= sizeof(mPublicKeyHashBytes
));
342 mPublicKeyHash
.Data
= mPublicKeyHashBytes
;
343 mPublicKeyHash
.Length
= cssmData
->Length
;
344 memcpy(mPublicKeyHash
.Data
, cssmData
->Data
, cssmData
->Length
);
345 csp
.allocator().free(cssmData
->Data
);
346 csp
.allocator().free(cssmData
);
349 releaseFieldValue(CSSMOID_CSSMKeyStruct
, keyPtr
);
351 return mPublicKeyHash
;
355 Certificate::subjectKeyIdentifier()
357 StLock
<Mutex
>_(mMutex
);
358 if (mSubjectKeyID
.Length
)
359 return mSubjectKeyID
;
361 CSSM_DATA_PTR fieldValue
= copyFirstFieldValue(CSSMOID_SubjectKeyIdentifier
);
362 if (fieldValue
&& fieldValue
->Data
&& fieldValue
->Length
== sizeof(CSSM_X509_EXTENSION
))
364 const CSSM_X509_EXTENSION
*extension
= reinterpret_cast<const CSSM_X509_EXTENSION
*>(fieldValue
->Data
);
365 const CE_SubjectKeyID
*skid
= reinterpret_cast<CE_SubjectKeyID
*>(extension
->value
.parsedValue
); // CSSM_DATA
367 if (skid
->Length
<= sizeof(mSubjectKeyIDBytes
))
369 mSubjectKeyID
.Data
= mSubjectKeyIDBytes
;
370 mSubjectKeyID
.Length
= skid
->Length
;
371 memcpy(mSubjectKeyID
.Data
, skid
->Data
, skid
->Length
);
374 mSubjectKeyID
.Length
= 0;
377 releaseFieldValue(CSSMOID_SubjectKeyIdentifier
, fieldValue
);
379 return mSubjectKeyID
;
384 * Given an CSSM_X509_NAME, Find the first name/value pair with
385 * a printable value which matches the specified OID (e.g., CSSMOID_CommonName).
386 * Returns the CFString-style encoding associated with name component's BER tag.
387 * Returns NULL if none found.
389 static const CSSM_DATA
*
391 const CSSM_X509_NAME
&x509Name
,
392 const CSSM_OID
*tvpType
, // NULL means "any printable field"
393 CFStringBuiltInEncodings
*encoding
) // RETURNED
395 for(uint32 rdnDex
=0; rdnDex
<x509Name
.numberOfRDNs
; rdnDex
++) {
396 const CSSM_X509_RDN
*rdnPtr
=
397 &x509Name
.RelativeDistinguishedName
[rdnDex
];
398 for(uint32 tvpDex
=0; tvpDex
<rdnPtr
->numberOfPairs
; tvpDex
++) {
399 const CSSM_X509_TYPE_VALUE_PAIR
*tvpPtr
=
400 &rdnPtr
->AttributeTypeAndValue
[tvpDex
];
402 /* type/value pair: match caller's specified type? */
403 if(tvpType
!= NULL
&& tvpType
->Data
!= NULL
) {
404 if(tvpPtr
->type
.Length
!= tvpType
->Length
) {
407 if(memcmp(tvpPtr
->type
.Data
, tvpType
->Data
, tvpType
->Length
)) {
408 /* If we don't have a match but the requested OID is CSSMOID_UserID,
409 * look for a matching X.500 UserID OID: (0.9.2342.19200300.100.1.1) */
410 const char cssm_userid_oid
[] = { 0x09,0x49,0x86,0x49,0x1f,0x12,0x8c,0xe4,0x81,0x81 };
411 const char x500_userid_oid
[] = { 0x09,0x92,0x26,0x89,0x93,0xF2,0x2C,0x64,0x01,0x01 };
412 if(!(tvpType
->Length
== sizeof(cssm_userid_oid
) &&
413 !memcmp(tvpPtr
->type
.Data
, x500_userid_oid
, sizeof(x500_userid_oid
)) &&
414 !memcmp(tvpType
->Data
, cssm_userid_oid
, sizeof(cssm_userid_oid
)))) {
421 switch(tvpPtr
->valueType
) {
422 case BER_TAG_PRINTABLE_STRING
:
423 case BER_TAG_IA5_STRING
:
424 *encoding
= kCFStringEncodingASCII
;
425 return &tvpPtr
->value
;
426 case BER_TAG_PKIX_UTF8_STRING
:
427 case BER_TAG_GENERAL_STRING
:
428 case BER_TAG_PKIX_UNIVERSAL_STRING
:
429 *encoding
= kCFStringEncodingUTF8
;
430 return &tvpPtr
->value
;
431 case BER_TAG_T61_STRING
:
432 case BER_TAG_VIDEOTEX_STRING
:
433 case BER_TAG_ISO646_STRING
:
434 *encoding
= kCFStringEncodingISOLatin1
;
435 return &tvpPtr
->value
;
436 case BER_TAG_PKIX_BMP_STRING
:
437 *encoding
= kCFStringEncodingUnicode
;
438 return &tvpPtr
->value
;
443 } /* for each pair */
446 /* no printable component of specified type found */
451 * Infer printable label for a given CSSM_X509_NAME. Returns NULL
452 * if no appropriate printable name found. Returns the CFString-style
453 * encoding associated with name component's BER tag. Also optionally
454 * returns Description component and its encoding if present and the
455 * returned name component was from CommonName.
457 static const CSSM_DATA
*inferLabelFromX509Name(
458 const CSSM_X509_NAME
*x509Name
,
459 CFStringBuiltInEncodings
*encoding
, // RETURNED
460 const CSSM_DATA
**description
, // optionally RETURNED
461 CFStringBuiltInEncodings
*descrEncoding
) // RETURNED if description != NULL
463 const CSSM_DATA
*printValue
;
465 * Search order (take the first one found with a printable
468 * -- Orgnaizational Unit
470 * -- field of any kind
472 printValue
= findPrintableField(*x509Name
, &CSSMOID_CommonName
, encoding
);
473 if(printValue
!= NULL
) {
474 if(description
!= NULL
) {
475 *description
= findPrintableField(*x509Name
, &CSSMOID_Description
, descrEncoding
);
479 printValue
= findPrintableField(*x509Name
, &CSSMOID_OrganizationalUnitName
, encoding
);
480 if(printValue
!= NULL
) {
483 printValue
= findPrintableField(*x509Name
, &CSSMOID_OrganizationName
, encoding
);
484 if(printValue
!= NULL
) {
488 return findPrintableField(*x509Name
, NULL
, encoding
);
492 * Infer printable label for a given an CSSM_X509_NAME. Returns NULL
493 * if no appropriate printable name found.
495 const CSSM_DATA
*SecInferLabelFromX509Name(
496 const CSSM_X509_NAME
*x509Name
)
498 /* callees of this routine don't care about the encoding */
499 CFStringBuiltInEncodings encoding
= kCFStringEncodingASCII
;
500 return inferLabelFromX509Name(x509Name
, &encoding
, NULL
, &encoding
);
505 Certificate::inferLabel(bool addLabel
, CFStringRef
*rtnString
)
507 StLock
<Mutex
>_(mMutex
);
508 // Set PrintName and optionally the Alias attribute for this certificate, based on the
509 // X509 SubjectAltName and SubjectName.
510 const CSSM_DATA
*printName
= NULL
;
511 const CSSM_DATA
*description
= NULL
;
512 std::vector
<CssmData
> emailAddresses
;
514 CssmAutoData
printPlusDescr(Allocator::standard());
515 CssmData printPlusDescData
;
516 CFStringBuiltInEncodings printEncoding
= kCFStringEncodingUTF8
;
517 CFStringBuiltInEncodings descrEncoding
= kCFStringEncodingUTF8
;
519 // Find the SubjectAltName fields, if any, and extract all the GNT_RFC822Name entries from all of them
520 const CSSM_OID
&sanOid
= CSSMOID_SubjectAltName
;
521 CSSM_DATA_PTR
*sanValues
= copyFieldValues(sanOid
);
522 const CSSM_OID
&snOid
= CSSMOID_X509V1SubjectNameCStruct
;
523 CSSM_DATA_PTR snValue
= copyFirstFieldValue(snOid
);
525 getEmailAddresses(sanValues
, snValue
, emailAddresses
);
527 if (snValue
&& snValue
->Data
)
529 const CSSM_X509_NAME
&x509Name
= *(const CSSM_X509_NAME
*)snValue
->Data
;
530 printName
= inferLabelFromX509Name(&x509Name
, &printEncoding
,
531 &description
, &descrEncoding
);
534 /* Don't ever use "Thawte Freemail Member" as the label for a cert. Instead force
535 a fall back on the email address. */
536 const char tfm
[] = "Thawte Freemail Member";
537 if ( (printName
->Length
== sizeof(tfm
) - 1) &&
538 !memcmp(printName
->Data
, tfm
, sizeof(tfm
) - 1)) {
544 /* Do a check to see if a '\0' was at the end of printName and strip it. */
545 CssmData cleanedUpPrintName
;
546 if((printName
!= NULL
) &&
547 (printName
->Length
!= 0) &&
548 (printEncoding
!= kCFStringEncodingISOLatin1
) &&
549 (printEncoding
!= kCFStringEncodingUnicode
) &&
550 (printName
->Data
[printName
->Length
- 1] == '\0')) {
551 cleanedUpPrintName
.Data
= printName
->Data
;
552 cleanedUpPrintName
.Length
= printName
->Length
- 1;
553 printName
= &cleanedUpPrintName
;
556 if((printName
!= NULL
) && (description
!= NULL
) && (description
->Length
!= 0))
559 * Munge Print Name (which in this case is the CommonName) and Description
560 * together with the Description in parentheses. We convert from whatever
561 * format Print Name and Description are in to UTF8 here.
563 CFRef
<CFMutableStringRef
> combo(CFStringCreateMutable(NULL
, 0));
564 CFRef
<CFStringRef
> cfPrint(CFStringCreateWithBytes(NULL
, printName
->Data
,
565 (CFIndex
)printName
->Length
, printEncoding
, true));
566 CssmData
cleanedUpDescr(description
->Data
, description
->Length
);
567 if ((cleanedUpDescr
.Data
[cleanedUpDescr
.Length
- 1] == '\0') &&
568 (descrEncoding
!= kCFStringEncodingISOLatin1
) &&
569 (descrEncoding
!= kCFStringEncodingUnicode
)) {
570 cleanedUpDescr
.Length
--;
572 CFRef
<CFStringRef
> cfDesc(CFStringCreateWithBytes(NULL
, cleanedUpDescr
.Data
,
573 (CFIndex
)cleanedUpDescr
.Length
, descrEncoding
, true));
574 CFStringAppend(combo
, cfPrint
);
575 CFStringAppendCString(combo
, " (", kCFStringEncodingASCII
);
576 CFStringAppend(combo
, cfDesc
);
577 CFStringAppendCString(combo
, ")", kCFStringEncodingASCII
);
578 CFRef
<CFDataRef
> comboData(CFStringCreateExternalRepresentation(NULL
, combo
,
579 kCFStringEncodingUTF8
, 0));
580 printPlusDescr
.copy(CFDataGetBytePtr(comboData
), CFDataGetLength(comboData
));
581 printPlusDescData
= printPlusDescr
;
582 printName
= &printPlusDescData
;
583 printEncoding
= kCFStringEncodingUTF8
;
586 if (printName
== NULL
)
588 /* If the we couldn't find a label use the emailAddress instead. */
589 if (!emailAddresses
.empty())
590 printName
= &emailAddresses
[0];
594 puntData
.Data
= (uint8
*)"X509 Certificate";
595 puntData
.Length
= 16;
596 printName
= &puntData
;
598 printEncoding
= kCFStringEncodingUTF8
;
601 /* If we couldn't find an email address just use the printName which might be the url or something else useful. */
602 if (emailAddresses
.empty())
603 emailAddresses
.push_back(CssmData::overlay(*printName
));
605 /* What do we do with the inferred label - return it or add it mDbAttributes? */
608 mDbAttributes
->add(Schema::kX509CertificatePrintName
, *printName
);
609 CssmDbAttributeData
&attrData
= mDbAttributes
->add(Schema::kX509CertificateAlias
);
611 /* Add the email addresses to attrData and normalize them. */
613 for (std::vector
<CssmData
>::const_iterator it
= emailAddresses
.begin(); it
!= emailAddresses
.end(); ++it
, ++ix
)
615 /* Add the email address using the allocator from mDbAttributes. */
616 attrData
.add(*it
, *mDbAttributes
);
617 /* Normalize the emailAddresses in place since attrData already copied it. */
618 normalizeEmailAddress(attrData
.Value
[ix
]);
624 CFStringBuiltInEncodings testEncoding
= printEncoding
;
625 if(testEncoding
== kCFStringEncodingISOLatin1
) {
627 testEncoding
= kCFStringEncodingUTF8
;
629 *rtnString
= CFStringCreateWithBytes(NULL
, printName
->Data
,
630 (CFIndex
)printName
->Length
, testEncoding
, true);
631 if(*rtnString
== NULL
&& printEncoding
== kCFStringEncodingISOLatin1
) {
632 // string cannot be represented in UTF-8, fall back to ISO Latin 1
633 *rtnString
= CFStringCreateWithBytes(NULL
, printName
->Data
,
634 (CFIndex
)printName
->Length
, printEncoding
, true);
640 releaseFieldValue(snOid
, snValue
);
642 releaseFieldValues(sanOid
, sanValues
);
646 Certificate::populateAttributes()
648 StLock
<Mutex
>_(mMutex
);
652 addParsedAttribute(Schema::attributeInfo(kSecSubjectItemAttr
), CSSMOID_X509V1SubjectName
);
653 addParsedAttribute(Schema::attributeInfo(kSecIssuerItemAttr
), CSSMOID_X509V1IssuerName
);
654 addParsedAttribute(Schema::attributeInfo(kSecSerialNumberItemAttr
), CSSMOID_X509V1SerialNumber
);
656 addSubjectKeyIdentifier();
658 if(!mHaveTypeAndEncoding
)
659 MacOSError::throwMe(errSecDataNotAvailable
); // @@@ Or some other error.
661 // Adjust mType based on the actual version of the cert.
662 CSSM_DATA_PTR versionPtr
= copyFirstFieldValue(CSSMOID_X509V1Version
);
663 if (versionPtr
&& versionPtr
->Data
&& versionPtr
->Length
== sizeof(uint32
))
665 mType
= CSSM_CERT_X_509v1
+ (*reinterpret_cast<uint32
*>(versionPtr
->Data
));
668 mType
= CSSM_CERT_X_509v1
;
670 releaseFieldValue(CSSMOID_X509V1Version
, versionPtr
);
672 mDbAttributes
->add(Schema::attributeInfo(kSecCertTypeItemAttr
), mType
);
673 mDbAttributes
->add(Schema::attributeInfo(kSecCertEncodingItemAttr
), mEncoding
);
674 mDbAttributes
->add(Schema::attributeInfo(kSecPublicKeyHashItemAttr
), publicKeyHash());
683 StLock
<Mutex
>_(mMutex
);
684 CssmDataContainer
*data
= mData
.get();
685 if (!data
&& mKeychain
)
687 // Make sure mUniqueId is set.
689 CssmDataContainer _data
;
691 /* new data allocated by CSPDL, implicitly freed by CssmDataContainer */
692 mUniqueId
->get(NULL
, &_data
);
693 /* this saves a copy to be freed at destruction and to be passed to caller */
694 setData(_data
.length(), _data
.data());
698 // If the data hasn't been set we can't return it.
700 MacOSError::throwMe(errSecDataNotAvailable
);
708 StLock
<Mutex
>_(mMutex
);
709 if (!mHaveTypeAndEncoding
)
711 SecKeychainAttribute attr
;
712 attr
.tag
= kSecCertTypeItemAttr
;
714 attr
.length
= sizeof(mType
);
715 getAttribute(attr
, NULL
);
722 Certificate::encoding()
724 StLock
<Mutex
>_(mMutex
);
725 if (!mHaveTypeAndEncoding
)
727 SecKeychainAttribute attr
;
728 attr
.tag
= kSecCertEncodingItemAttr
;
729 attr
.data
= &mEncoding
;
730 attr
.length
= sizeof(mEncoding
);
731 getAttribute(attr
, NULL
);
737 const CSSM_X509_ALGORITHM_IDENTIFIER_PTR
738 Certificate::algorithmID()
740 StLock
<Mutex
>_(mMutex
);
741 if (!mV1SubjectPublicKeyCStructValue
)
742 mV1SubjectPublicKeyCStructValue
= copyFirstFieldValue(CSSMOID_X509V1SubjectPublicKeyCStruct
);
744 CSSM_X509_SUBJECT_PUBLIC_KEY_INFO
*info
= (CSSM_X509_SUBJECT_PUBLIC_KEY_INFO
*)mV1SubjectPublicKeyCStructValue
->Data
;
745 CSSM_X509_ALGORITHM_IDENTIFIER
*algid
= &info
->algorithm
;
750 Certificate::commonName()
752 StLock
<Mutex
>_(mMutex
);
753 return distinguishedName(&CSSMOID_X509V1SubjectNameCStruct
, &CSSMOID_CommonName
);
757 Certificate::distinguishedName(const CSSM_OID
*sourceOid
, const CSSM_OID
*componentOid
)
759 StLock
<Mutex
>_(mMutex
);
760 CFStringRef rtnString
= NULL
;
761 CSSM_DATA_PTR fieldValue
= copyFirstFieldValue(*sourceOid
);
762 CSSM_X509_NAME_PTR x509Name
= (CSSM_X509_NAME_PTR
)fieldValue
->Data
;
763 const CSSM_DATA
*printValue
= NULL
;
764 CFStringBuiltInEncodings encoding
;
766 if (fieldValue
&& fieldValue
->Data
)
767 printValue
= findPrintableField(*x509Name
, componentOid
, &encoding
);
770 rtnString
= CFStringCreateWithBytes(NULL
, printValue
->Data
,
771 CFIndex(printValue
->Length
), encoding
, true);
773 releaseFieldValue(*sourceOid
, fieldValue
);
780 * Return a CFString containing the first email addresses for this certificate, based on the
781 * X509 SubjectAltName and SubjectName.
784 Certificate::copyFirstEmailAddress()
786 StLock
<Mutex
>_(mMutex
);
787 CFStringRef rtnString
;
789 const CSSM_OID
&sanOid
= CSSMOID_SubjectAltName
;
790 CSSM_DATA_PTR
*sanValues
= copyFieldValues(sanOid
);
791 const CSSM_OID
&snOid
= CSSMOID_X509V1SubjectNameCStruct
;
792 CSSM_DATA_PTR snValue
= copyFirstFieldValue(snOid
);
793 std::vector
<CssmData
> emailAddresses
;
795 getEmailAddresses(sanValues
, snValue
, emailAddresses
);
796 if (emailAddresses
.empty())
800 /* Encoding is kCFStringEncodingUTF8 since the string is either
801 PRINTABLE_STRING, IA5_STRING, T61_STRING or PKIX_UTF8_STRING. */
802 rtnString
= CFStringCreateWithBytes(NULL
, emailAddresses
[0].Data
,
803 (CFIndex
)emailAddresses
[0].Length
, kCFStringEncodingUTF8
, true);
808 releaseFieldValue(snOid
, snValue
);
810 releaseFieldValues(sanOid
, sanValues
);
816 * Return a CFArray containing the email addresses for this certificate, based on the
817 * X509 SubjectAltName and SubjectName.
820 Certificate::copyEmailAddresses()
822 StLock
<Mutex
>_(mMutex
);
823 CFMutableArrayRef array
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
824 std::vector
<CssmData
> emailAddresses
;
826 // Find the SubjectAltName fields, if any, and extract all the GNT_RFC822Name entries from all of them
827 const CSSM_OID
&sanOid
= CSSMOID_SubjectAltName
;
828 CSSM_DATA_PTR
*sanValues
= copyFieldValues(sanOid
);
830 const CSSM_OID
&snOid
= CSSMOID_X509V1SubjectNameCStruct
;
831 CSSM_DATA_PTR snValue
= copyFirstFieldValue(snOid
);
833 getEmailAddresses(sanValues
, snValue
, emailAddresses
);
835 for (std::vector
<CssmData
>::const_iterator it
= emailAddresses
.begin(); it
!= emailAddresses
.end(); ++it
)
837 /* Encoding is kCFStringEncodingUTF8 since the string is either
838 PRINTABLE_STRING, IA5_STRING, T61_STRING or PKIX_UTF8_STRING. */
839 CFStringRef string
= CFStringCreateWithBytes(NULL
, it
->Data
, static_cast<CFIndex
>(it
->Length
), kCFStringEncodingUTF8
, true);
840 CFArrayAppendValue(array
, string
);
846 releaseFieldValue(snOid
, snValue
);
848 releaseFieldValues(sanOid
, sanValues
);
853 const CSSM_X509_NAME_PTR
854 Certificate::subjectName()
856 StLock
<Mutex
>_(mMutex
);
857 if (!mV1SubjectNameCStructValue
)
858 if ((mV1SubjectNameCStructValue
= copyFirstFieldValue(CSSMOID_X509V1SubjectNameCStruct
)) == NULL
)
861 return (const CSSM_X509_NAME_PTR
)mV1SubjectNameCStructValue
->Data
;
864 const CSSM_X509_NAME_PTR
865 Certificate::issuerName()
867 StLock
<Mutex
>_(mMutex
);
868 if (!mV1IssuerNameCStructValue
)
869 if ((mV1IssuerNameCStructValue
= copyFirstFieldValue(CSSMOID_X509V1IssuerNameCStruct
)) == NULL
)
872 return (const CSSM_X509_NAME_PTR
)mV1IssuerNameCStructValue
->Data
;
876 Certificate::clHandle()
878 StLock
<Mutex
>_(mMutex
);
880 mCL
= clForType(type());
882 return mCL
->handle();
886 Certificate::operator < (Certificate
&other
)
888 // Certificates in different keychains are considered equal if data is equal
889 // Note that the Identity '<' operator relies on this assumption.
890 return data() < other
.data();
894 Certificate::operator == (Certificate
&other
)
896 // Certificates in different keychains are considered equal if data is equal
897 // Note that the Identity '==' operator relies on this assumption.
898 return data() == other
.data();
902 Certificate::equal(SecCFObject
&other
)
904 return (*this) == (Certificate
&)other
;
908 Certificate::update()
914 Certificate::copyTo(const Keychain
&keychain
, Access
*newAccess
)
916 StLock
<Mutex
>_(mMutex
);
917 /* Certs can't have access controls. */
919 MacOSError::throwMe(errSecNoAccessForItem
);
921 Item
item(new Certificate(data(), type(), encoding()));
927 Certificate::didModify()
932 Certificate::add(Keychain
&keychain
)
934 StLock
<Mutex
>_(mMutex
);
935 // If we already have a Keychain we can't be added.
937 MacOSError::throwMe(errSecDuplicateItem
);
939 populateAttributes();
941 CSSM_DB_RECORDTYPE recordType
= mDbAttributes
->recordType();
943 Db
db(keychain
->database());
944 // add the item to the (regular) db
947 mUniqueId
= db
->insert(recordType
, mDbAttributes
.get(), mData
.get());
949 catch (const CssmError
&e
)
951 if (e
.osStatus() != CSSMERR_DL_INVALID_RECORDTYPE
)
954 // Create the cert relation and try again.
955 db
->createRelation(CSSM_DL_DB_RECORD_X509_CERTIFICATE
,
956 "CSSM_DL_DB_RECORD_X509_CERTIFICATE",
957 Schema::X509CertificateSchemaAttributeCount
,
958 Schema::X509CertificateSchemaAttributeList
,
959 Schema::X509CertificateSchemaIndexCount
,
960 Schema::X509CertificateSchemaIndexList
);
961 keychain
->keychainSchema()->didCreateRelation(
962 CSSM_DL_DB_RECORD_X509_CERTIFICATE
,
963 "CSSM_DL_DB_RECORD_X509_CERTIFICATE",
964 Schema::X509CertificateSchemaAttributeCount
,
965 Schema::X509CertificateSchemaAttributeList
,
966 Schema::X509CertificateSchemaIndexCount
,
967 Schema::X509CertificateSchemaIndexList
);
969 mUniqueId
= db
->insert(recordType
, mDbAttributes
.get(), mData
.get());
972 mPrimaryKey
= keychain
->makePrimaryKey(recordType
, mUniqueId
);
973 mKeychain
= keychain
;
979 Certificate::publicKey()
981 StLock
<Mutex
>_(mMutex
);
982 SecPointer
<KeyItem
> keyItem
;
983 // Return a CSSM_DATA_PTR with the value of the first field specified by field.
984 // Caller must call releaseFieldValue to free the storage allocated by this call.
985 // call OSStatus SecKeyGetCSSMKey(SecKeyRef key, const CSSM_KEY **cssmKey); to retrieve
987 CSSM_DATA_PTR keyPtr
= copyFirstFieldValue(CSSMOID_CSSMKeyStruct
);
988 if (keyPtr
&& keyPtr
->Data
)
990 CssmClient::CSP
csp(gGuidAppleCSP
);
991 CssmKey
*cssmKey
= reinterpret_cast<CssmKey
*>(keyPtr
->Data
);
992 CssmClient::Key
key(csp
, *cssmKey
);
993 keyItem
= new KeyItem(key
);
994 // Clear out KeyData since KeyItem() takes over ownership of the key, and we don't want it getting released.
995 cssmKey
->KeyData
.Data
= NULL
;
996 cssmKey
->KeyData
.Length
= 0;
999 releaseFieldValue(CSSMOID_CSSMKeyStruct
, keyPtr
);
1004 // This function "borrowed" from the X509 CL, which is (currently) linked into
1005 // the Security.framework as a built-in plugin.
1006 extern "C" bool getField_normRDN_NSS (
1007 const CSSM_DATA
&derName
,
1008 uint32
&numFields
, // RETURNED (if successful, 0 or 1)
1009 CssmOwnedData
&fieldValue
); // RETURNED
1012 Certificate::cursorForIssuerAndSN(const StorageManager::KeychainList
&keychains
, const CssmData
&issuer
, const CssmData
&serialNumber
)
1014 CssmAutoData
fieldValue(Allocator::standard(Allocator::normal
));
1017 // We need to decode issuer, normalize it, then re-encode it
1018 if (!getField_normRDN_NSS(issuer
, numFields
, fieldValue
))
1019 MacOSError::throwMe(errSecDataNotAvailable
);
1021 // Code basically copied from SecKeychainSearchCreateFromAttributes and SecKeychainSearchCopyNext:
1022 KCCursor
cursor(keychains
, kSecCertificateItemClass
, NULL
);
1023 cursor
->conjunctive(CSSM_DB_AND
);
1024 cursor
->add(CSSM_DB_EQUAL
, Schema::kX509CertificateIssuer
, fieldValue
.get());
1025 cursor
->add(CSSM_DB_EQUAL
, Schema::kX509CertificateSerialNumber
, serialNumber
);
1031 Certificate::cursorForIssuerAndSN_CF(const StorageManager::KeychainList
&keychains
, CFDataRef issuer
, CFDataRef serialNumber
)
1033 // This assumes a normalized issuer
1034 CSSM_DATA issuerCSSM
, serialNumberCSSM
;
1036 issuerCSSM
.Length
= CFDataGetLength(issuer
);
1037 issuerCSSM
.Data
= const_cast<uint8
*>(CFDataGetBytePtr(issuer
));
1039 serialNumberCSSM
.Length
= CFDataGetLength(serialNumber
);
1040 serialNumberCSSM
.Data
= const_cast<uint8
*>(CFDataGetBytePtr(serialNumber
));
1042 // Code basically copied from SecKeychainSearchCreateFromAttributes and SecKeychainSearchCopyNext:
1043 KCCursor
cursor(keychains
, kSecCertificateItemClass
, NULL
);
1044 cursor
->conjunctive(CSSM_DB_AND
);
1045 cursor
->add(CSSM_DB_EQUAL
, Schema::kX509CertificateIssuer
, issuerCSSM
);
1046 cursor
->add(CSSM_DB_EQUAL
, Schema::kX509CertificateSerialNumber
, serialNumberCSSM
);
1052 Certificate::cursorForSubjectKeyID(const StorageManager::KeychainList
&keychains
, const CssmData
&subjectKeyID
)
1054 KCCursor
cursor(keychains
, kSecCertificateItemClass
, NULL
);
1055 cursor
->conjunctive(CSSM_DB_AND
);
1056 cursor
->add(CSSM_DB_EQUAL
, Schema::kX509CertificateSubjectKeyIdentifier
, subjectKeyID
);
1062 Certificate::cursorForEmail(const StorageManager::KeychainList
&keychains
, const char *emailAddress
)
1064 KCCursor
cursor(keychains
, kSecCertificateItemClass
, NULL
);
1067 cursor
->conjunctive(CSSM_DB_AND
);
1068 CssmSelectionPredicate
&pred
= cursor
->add(CSSM_DB_EQUAL
, Schema::kX509CertificateAlias
, emailAddress
);
1069 /* Normalize the emailAddresses in place since cursor already copied it. */
1070 normalizeEmailAddress(pred
.Attribute
.Value
[0]);
1076 SecPointer
<Certificate
>
1077 Certificate::findInKeychain(const StorageManager::KeychainList
&keychains
)
1079 StLock
<Mutex
>_(mMutex
);
1080 const CSSM_OID
&issuerOid
= CSSMOID_X509V1IssuerName
;
1081 CSSM_DATA_PTR issuerPtr
= copyFirstFieldValue(issuerOid
);
1082 CssmData
issuer(issuerPtr
->Data
, issuerPtr
->Length
);
1084 const CSSM_OID
&serialOid
= CSSMOID_X509V1SerialNumber
;
1085 CSSM_DATA_PTR serialPtr
= copyFirstFieldValue(serialOid
);
1086 CssmData
serial(serialPtr
->Data
, serialPtr
->Length
);
1088 SecPointer
<Certificate
> foundCert
= NULL
;
1090 foundCert
= findByIssuerAndSN(keychains
, issuer
, serial
);
1095 releaseFieldValue(issuerOid
, issuerPtr
);
1096 releaseFieldValue(serialOid
, serialPtr
);
1101 SecPointer
<Certificate
>
1102 Certificate::findByIssuerAndSN(const StorageManager::KeychainList
&keychains
, const CssmData
&issuer
, const CssmData
&serialNumber
)
1105 if (!cursorForIssuerAndSN(keychains
, issuer
, serialNumber
)->next(item
))
1106 CssmError::throwMe(errSecItemNotFound
);
1108 return static_cast<Certificate
*>(&*item
);
1111 SecPointer
<Certificate
>
1112 Certificate::findBySubjectKeyID(const StorageManager::KeychainList
&keychains
, const CssmData
&subjectKeyID
)
1115 if (!cursorForSubjectKeyID(keychains
, subjectKeyID
)->next(item
))
1116 CssmError::throwMe(errSecItemNotFound
);
1118 return static_cast<Certificate
*>(&*item
);
1121 SecPointer
<Certificate
>
1122 Certificate::findByEmail(const StorageManager::KeychainList
&keychains
, const char *emailAddress
)
1125 if (!cursorForEmail(keychains
, emailAddress
)->next(item
))
1126 CssmError::throwMe(errSecItemNotFound
);
1128 return static_cast<Certificate
*>(&*item
);
1131 /* Normalize emailAddresses in place. */
1133 Certificate::normalizeEmailAddress(CSSM_DATA
&emailAddress
)
1135 /* Do a check to see if a '\0' was at the end of emailAddress and strip it. */
1136 if (emailAddress
.Length
&& emailAddress
.Data
[emailAddress
.Length
- 1] == '\0')
1137 emailAddress
.Length
--;
1138 bool foundAt
= false;
1139 for (uint32 ix
= 0; ix
< emailAddress
.Length
; ++ix
)
1141 uint8 ch
= emailAddress
.Data
[ix
];
1144 if ('A' <= ch
&& ch
<= 'Z')
1145 emailAddress
.Data
[ix
] = ch
+ 'a' - 'A';
1153 Certificate::getEmailAddresses(CSSM_DATA_PTR
*sanValues
, CSSM_DATA_PTR snValue
, std::vector
<CssmData
> &emailAddresses
)
1155 // Get the email addresses for this certificate, based on the
1156 // X509 SubjectAltName and SubjectName.
1158 // Find the SubjectAltName fields, if any, and extract all the GNT_RFC822Name entries from all of them
1161 for (CSSM_DATA_PTR
*sanIx
= sanValues
; *sanIx
; ++sanIx
)
1163 CSSM_DATA_PTR sanValue
= *sanIx
;
1164 if (sanValue
&& sanValue
->Data
)
1166 CSSM_X509_EXTENSION
*cssmExt
= (CSSM_X509_EXTENSION
*)sanValue
->Data
;
1167 CE_GeneralNames
*parsedValue
= (CE_GeneralNames
*)cssmExt
->value
.parsedValue
;
1169 /* Grab all the values that are of type GNT_RFC822Name. */
1170 for (uint32 i
= 0; i
< parsedValue
->numNames
; ++i
)
1172 if (parsedValue
->generalName
[i
].nameType
== GNT_RFC822Name
)
1174 if (parsedValue
->generalName
[i
].berEncoded
) // can't handle this
1177 emailAddresses
.push_back(CssmData::overlay(parsedValue
->generalName
[i
].name
));
1184 if (emailAddresses
.empty() && snValue
&& snValue
->Data
)
1186 const CSSM_X509_NAME
&x509Name
= *(const CSSM_X509_NAME
*)snValue
->Data
;
1187 for (uint32 rdnDex
= 0; rdnDex
< x509Name
.numberOfRDNs
; rdnDex
++)
1189 const CSSM_X509_RDN
*rdnPtr
=
1190 &x509Name
.RelativeDistinguishedName
[rdnDex
];
1191 for (uint32 tvpDex
= 0; tvpDex
< rdnPtr
->numberOfPairs
; tvpDex
++)
1193 const CSSM_X509_TYPE_VALUE_PAIR
*tvpPtr
=
1194 &rdnPtr
->AttributeTypeAndValue
[tvpDex
];
1196 /* type/value pair: match caller's specified type? */
1197 if (((tvpPtr
->type
.Length
!= CSSMOID_EmailAddress
.Length
) ||
1198 memcmp(tvpPtr
->type
.Data
, CSSMOID_EmailAddress
.Data
, CSSMOID_EmailAddress
.Length
))) {
1203 switch (tvpPtr
->valueType
)
1205 case BER_TAG_PRINTABLE_STRING
:
1206 case BER_TAG_IA5_STRING
:
1207 case BER_TAG_T61_STRING
:
1208 case BER_TAG_PKIX_UTF8_STRING
:
1210 emailAddresses
.push_back(CssmData::overlay(tvpPtr
->value
));
1215 } /* for each pair */
1216 } /* for each RDN */
1220 void Certificate::willRead()
1222 populateAttributes();
1225 Boolean
Certificate::isSelfSigned()
1227 StLock
<Mutex
>_(mMutex
);
1228 CSSM_DATA_PTR issuer
= NULL
;
1229 CSSM_DATA_PTR subject
= NULL
;
1230 OSStatus ortn
= noErr
;
1231 Boolean brtn
= false;
1233 issuer
= copyFirstFieldValue(CSSMOID_X509V1IssuerNameStd
);
1234 subject
= copyFirstFieldValue(CSSMOID_X509V1SubjectNameStd
);
1235 if((issuer
== NULL
) || (subject
== NULL
)) {
1238 else if((issuer
->Length
== subject
->Length
) &&
1239 !memcmp(issuer
->Data
, subject
->Data
, issuer
->Length
)) {
1243 /* names match: verify signature */
1245 CSSM_DATA certData
= data();
1246 crtn
= CSSM_CL_CertVerify(clHandle(), 0,
1247 &certData
, &certData
, NULL
, 0);
1253 releaseFieldValue(CSSMOID_X509V1IssuerNameStd
, issuer
);
1256 releaseFieldValue(CSSMOID_X509V1SubjectNameStd
, subject
);
1259 MacOSError::throwMe(ortn
);