]> git.saurik.com Git - apple/security.git/blob - libsecurity_smime/lib/cmssiginfo.c
Security-59754.80.3.tar.gz
[apple/security.git] / libsecurity_smime / lib / cmssiginfo.c
1 /*
2 * The contents of this file are subject to the Mozilla Public
3 * License Version 1.1 (the "License"); you may not use this file
4 * except in compliance with the License. You may obtain a copy of
5 * the License at http://www.mozilla.org/MPL/
6 *
7 * Software distributed under the License is distributed on an "AS
8 * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
9 * implied. See the License for the specific language governing
10 * rights and limitations under the License.
11 *
12 * The Original Code is the Netscape security libraries.
13 *
14 * The Initial Developer of the Original Code is Netscape
15 * Communications Corporation. Portions created by Netscape are
16 * Copyright (C) 1994-2000 Netscape Communications Corporation. All
17 * Rights Reserved.
18 *
19 * Contributor(s):
20 *
21 * Alternatively, the contents of this file may be used under the
22 * terms of the GNU General Public License Version 2 or later (the
23 * "GPL"), in which case the provisions of the GPL are applicable
24 * instead of those above. If you wish to allow use of your
25 * version of this file only under the terms of the GPL and not to
26 * allow others to use your version of this file under the MPL,
27 * indicate your decision by deleting the provisions above and
28 * replace them with the notice and other provisions required by
29 * the GPL. If you do not delete the provisions above, a recipient
30 * may use your version of this file under either the MPL or the
31 * GPL.
32 */
33
34 /*
35 * CMS signerInfo methods.
36 */
37
38 #include <Security/SecCmsSignerInfo.h>
39 #include "SecSMIMEPriv.h"
40
41 #include "cmslocal.h"
42
43 #include "cert.h"
44 #include "SecAsn1Item.h"
45 #include "secoid.h"
46 #include "cryptohi.h"
47
48 #include <security_asn1/secasn1.h>
49 #include <security_asn1/secerr.h>
50 #include <security_asn1/secport.h>
51
52 #if USE_CDSA_CRYPTO
53 #include <Security/SecKeychain.h>
54 #endif
55
56 #include <Security/SecIdentity.h>
57 #include <Security/SecCertificateInternal.h>
58 #include <Security/SecInternal.h>
59 #include <Security/SecKeyPriv.h>
60 #include <utilities/SecCFWrappers.h>
61 #include <CoreFoundation/CFTimeZone.h>
62 #include <Security/SecBasePriv.h>
63 #include <Security/SecItem.h>
64
65 #include <libDER/asn1Types.h>
66
67
68 #define HIDIGIT(v) (((v) / 10) + '0')
69 #define LODIGIT(v) (((v) % 10) + '0')
70
71 #define ISDIGIT(dig) (((dig) >= '0') && ((dig) <= '9'))
72 #define CAPTURE(var,p,label) \
73 { \
74 if (!ISDIGIT((p)[0]) || !ISDIGIT((p)[1])) goto label; \
75 (var) = ((p)[0] - '0') * 10 + ((p)[1] - '0'); \
76 }
77
78
79 static OSStatus
80 DER_UTCTimeToCFDate(const SecAsn1Item * utcTime, CFAbsoluteTime *date)
81 {
82 CFErrorRef error = NULL;
83 /* <rdar://problem/55316705> CMS attributes don't correctly encode/decode times (always use UTCTime) */
84 CFAbsoluteTime result = SecAbsoluteTimeFromDateContentWithError(ASN1_UTC_TIME, utcTime->Data, utcTime->Length, &error);
85 if (error) {
86 CFReleaseNull(error);
87 return SECFailure;
88 }
89
90 if (date) {
91 *date = result;
92 }
93 return SECSuccess;
94 }
95
96 static OSStatus
97 DER_CFDateToUTCTime(CFAbsoluteTime date, SecAsn1Item * utcTime)
98 {
99 unsigned char *d;
100
101 utcTime->Length = 13;
102 utcTime->Data = d = PORT_Alloc(13);
103 if (!utcTime->Data) {
104 return SECFailure;
105 }
106
107 __block int year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0;
108 __block bool result;
109 SecCFCalendarDoWithZuluCalendar(^(CFCalendarRef zuluCalendar) {
110 result = CFCalendarDecomposeAbsoluteTime(zuluCalendar, date, "yMdHms", &year, &month, &day, &hour, &minute, &second);
111 });
112 if (!result) {
113 return SECFailure;
114 }
115
116 /* UTC time does not handle the years before 1950 or after 2049 */
117 /* <rdar://problem/55316705> CMS attributes don't correctly encode/decode times (always use UTCTime) */
118 if (year < 1950 || year > 2049) {
119 return SECFailure;
120 }
121
122 /* remove the century since it's added to the year by the
123 CFAbsoluteTimeGetGregorianDate routine, but is not needed for UTC time */
124 year %= 100;
125
126 d[0] = HIDIGIT(year);
127 d[1] = LODIGIT(year);
128 d[2] = HIDIGIT(month);
129 d[3] = LODIGIT(month);
130 d[4] = HIDIGIT(day);
131 d[5] = LODIGIT(day);
132 d[6] = HIDIGIT(hour);
133 d[7] = LODIGIT(hour);
134 d[8] = HIDIGIT(minute);
135 d[9] = LODIGIT(minute);
136 d[10] = HIDIGIT(second);
137 d[11] = LODIGIT(second);
138 d[12] = 'Z';
139 return SECSuccess;
140 }
141
142 /* =============================================================================
143 * SIGNERINFO
144 */
145 SecCmsSignerInfoRef
146 nss_cmssignerinfo_create(SecCmsSignedDataRef sigd, SecCmsSignerIDSelector type, SecCertificateRef cert, const SecAsn1Item *subjKeyID, SecPublicKeyRef pubKey, SecPrivateKeyRef signingKey, SECOidTag digestalgtag);
147
148 SecCmsSignerInfoRef
149 SecCmsSignerInfoCreateWithSubjKeyID(SecCmsSignedDataRef sigd, const SecAsn1Item *subjKeyID, SecPublicKeyRef pubKey, SecPrivateKeyRef signingKey, SECOidTag digestalgtag)
150 {
151 return nss_cmssignerinfo_create(sigd, SecCmsSignerIDSubjectKeyID, NULL, subjKeyID, pubKey, signingKey, digestalgtag);
152 }
153
154 SecCmsSignerInfoRef
155 SecCmsSignerInfoCreate(SecCmsSignedDataRef sigd, SecIdentityRef identity, SECOidTag digestalgtag)
156 {
157 SecCmsSignerInfoRef signerInfo = NULL;
158 SecCertificateRef cert = NULL;
159 SecPrivateKeyRef signingKey = NULL;
160 CFDictionaryRef keyAttrs = NULL;
161
162 if (SecIdentityCopyCertificate(identity, &cert))
163 goto loser;
164 if (SecIdentityCopyPrivateKey(identity, &signingKey))
165 goto loser;
166
167 /* In some situations, the "Private Key" in the identity is actually a public key. Check. */
168 keyAttrs = SecKeyCopyAttributes(signingKey);
169 if (!keyAttrs)
170 goto loser;
171 CFTypeRef class = CFDictionaryGetValue(keyAttrs, kSecAttrKeyClass);
172 if (!class || (CFGetTypeID(class) != CFStringGetTypeID()) || !CFEqual(class, kSecAttrKeyClassPrivate)) {
173 goto loser;
174 }
175
176 signerInfo = nss_cmssignerinfo_create(sigd, SecCmsSignerIDIssuerSN, cert, NULL, NULL, signingKey, digestalgtag);
177
178 loser:
179 if (cert)
180 CFRelease(cert);
181 if (signingKey)
182 CFRelease(signingKey);
183 if (keyAttrs)
184 CFRelease(keyAttrs);
185
186 return signerInfo;
187 }
188
189 SecCmsSignerInfoRef
190 nss_cmssignerinfo_create(SecCmsSignedDataRef sigd, SecCmsSignerIDSelector type, SecCertificateRef cert, const SecAsn1Item *subjKeyID, SecPublicKeyRef pubKey, SecPrivateKeyRef signingKey, SECOidTag digestalgtag)
191 {
192 void *mark;
193 SecCmsSignerInfoRef signerinfo;
194 int version;
195 PLArenaPool *poolp;
196
197 poolp = sigd->contentInfo.cmsg->poolp;
198
199 mark = PORT_ArenaMark(poolp);
200
201 signerinfo = (SecCmsSignerInfoRef)PORT_ArenaZAlloc(poolp, sizeof(SecCmsSignerInfo));
202 if (signerinfo == NULL) {
203 PORT_ArenaRelease(poolp, mark);
204 return NULL;
205 }
206
207
208 signerinfo->signedData = sigd;
209
210 switch(type) {
211 case SecCmsSignerIDIssuerSN:
212 signerinfo->signerIdentifier.identifierType = SecCmsSignerIDIssuerSN;
213 if ((signerinfo->cert = CERT_DupCertificate(cert)) == NULL)
214 goto loser;
215 if ((signerinfo->signerIdentifier.id.issuerAndSN = CERT_GetCertIssuerAndSN(poolp, cert)) == NULL)
216 goto loser;
217 break;
218 case SecCmsSignerIDSubjectKeyID:
219 signerinfo->signerIdentifier.identifierType = SecCmsSignerIDSubjectKeyID;
220 PORT_Assert(subjKeyID);
221 if (!subjKeyID)
222 goto loser;
223 signerinfo->signerIdentifier.id.subjectKeyID = PORT_ArenaNew(poolp, SecAsn1Item);
224 if (SECITEM_CopyItem(poolp, signerinfo->signerIdentifier.id.subjectKeyID,
225 subjKeyID)) {
226 goto loser;
227 }
228 signerinfo->pubKey = SECKEY_CopyPublicKey(pubKey);
229 if (!signerinfo->pubKey)
230 goto loser;
231 break;
232 default:
233 goto loser;
234 }
235
236 if (!signingKey)
237 goto loser;
238
239 signerinfo->signingKey = SECKEY_CopyPrivateKey(signingKey);
240 if (!signerinfo->signingKey)
241 goto loser;
242
243 /* set version right now */
244 version = SEC_CMS_SIGNER_INFO_VERSION_ISSUERSN;
245 /* RFC2630 5.3 "version is the syntax version number. If the .... " */
246 if (signerinfo->signerIdentifier.identifierType == SecCmsSignerIDSubjectKeyID)
247 version = SEC_CMS_SIGNER_INFO_VERSION_SUBJKEY;
248 (void)SEC_ASN1EncodeInteger(poolp, &(signerinfo->version), (long)version);
249
250 if (SECOID_SetAlgorithmID(poolp, &signerinfo->digestAlg, digestalgtag, NULL) != SECSuccess)
251 goto loser;
252
253 if (SecCmsSignedDataAddSignerInfo(sigd, signerinfo))
254 goto loser;
255
256 PORT_ArenaUnmark(poolp, mark);
257 return signerinfo;
258
259 loser:
260 PORT_ArenaRelease(poolp, mark);
261 return NULL;
262 }
263
264 /*
265 * SecCmsSignerInfoDestroy - destroy a SignerInfo data structure
266 */
267 void
268 SecCmsSignerInfoDestroy(SecCmsSignerInfoRef si)
269 {
270 if (si->cert != NULL) {
271 CERT_DestroyCertificate(si->cert);
272 }
273
274 if (si->certList != NULL) {
275 CFRelease(si->certList);
276 }
277
278 if (si->hashAgilityAttrValue != NULL) {
279 CFRelease(si->hashAgilityAttrValue);
280 }
281
282 if (si->hashAgilityV2AttrValues != NULL) {
283 CFRelease(si->hashAgilityV2AttrValues);
284 }
285
286 /* XXX storage ??? */
287 }
288
289 static SecAsn1AlgId SecCertificateGetPublicKeyAlgorithmID(SecCertificateRef cert)
290 {
291 const DERAlgorithmId *length_data_swapped = SecCertificateGetPublicKeyAlgorithm(cert);
292 SecAsn1AlgId temp = {
293 { length_data_swapped->oid.length, length_data_swapped->oid.data },
294 { length_data_swapped->params.length, length_data_swapped->params.data } };
295
296 return temp;
297 }
298
299 /*
300 * SecCmsSignerInfoSign - sign something
301 *
302 */
303 OSStatus
304 SecCmsSignerInfoSign(SecCmsSignerInfoRef signerinfo, SecAsn1Item * digest, SecAsn1Item * contentType)
305 {
306 SecCertificateRef cert;
307 SecPrivateKeyRef privkey = NULL;
308 SECOidTag digestalgtag;
309 SECOidTag pubkAlgTag;
310 SecAsn1Item signature = { 0 };
311 OSStatus rv;
312 PLArenaPool *poolp, *tmppoolp = NULL;
313 const SECAlgorithmID *algID = NULL;
314 //CERTSubjectPublicKeyInfo *spki;
315
316 PORT_Assert (digest != NULL);
317
318 poolp = signerinfo->signedData->contentInfo.cmsg->poolp;
319
320 SecAsn1AlgId _algID;
321
322 switch (signerinfo->signerIdentifier.identifierType) {
323 case SecCmsSignerIDIssuerSN:
324 privkey = signerinfo->signingKey;
325 signerinfo->signingKey = NULL;
326 cert = signerinfo->cert;
327 #if USE_CDSA_CRYPTO
328 if (SecCertificateGetAlgorithmID(cert,&algID)) {
329 PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
330 goto loser;
331 }
332 #else
333 _algID = SecCertificateGetPublicKeyAlgorithmID(cert);
334 algID = &_algID;
335 #endif
336 break;
337 case SecCmsSignerIDSubjectKeyID:
338 privkey = signerinfo->signingKey;
339 signerinfo->signingKey = NULL;
340 #if 0
341 spki = SECKEY_CreateSubjectPublicKeyInfo(signerinfo->pubKey);
342 SECKEY_DestroyPublicKey(signerinfo->pubKey);
343 signerinfo->pubKey = NULL;
344 SECOID_CopyAlgorithmID(NULL, &freeAlgID, &spki->algorithm);
345 SECKEY_DestroySubjectPublicKeyInfo(spki);
346 algID = &freeAlgID;
347 #else
348 #if USE_CDSA_CRYPTO
349 if (SecKeyGetAlgorithmID(signerinfo->pubKey,&algID)) {
350 PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
351 goto loser;
352 }
353 #endif
354 #endif
355 CFRelease(signerinfo->pubKey);
356 signerinfo->pubKey = NULL;
357 break;
358 default:
359 PORT_SetError(SEC_ERROR_UNSUPPORTED_MESSAGE_TYPE);
360 goto loser;
361 }
362 digestalgtag = SecCmsSignerInfoGetDigestAlgTag(signerinfo);
363 pubkAlgTag = SECOID_GetAlgorithmTag(algID);
364
365 /* we no longer support signing with MD5 */
366 if (digestalgtag == SEC_OID_MD5) {
367 PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
368 goto loser;
369 }
370
371 #if USE_CDSA_CRYPTO
372 if (signerinfo->signerIdentifier.identifierType == SecCmsSignerIDSubjectKeyID) {
373 SECOID_DestroyAlgorithmID(&freeAlgID, PR_FALSE);
374 }
375 #endif
376 #if 0
377 // @@@ Not yet
378 /* Fortezza MISSI have weird signature formats.
379 * Map them to standard DSA formats
380 */
381 pubkAlgTag = PK11_FortezzaMapSig(pubkAlgTag);
382 #endif
383
384 if (signerinfo->authAttr != NULL) {
385 SecAsn1Item encoded_attrs;
386
387 /* find and fill in the message digest attribute. */
388 rv = SecCmsAttributeArraySetAttr(poolp, &(signerinfo->authAttr),
389 SEC_OID_PKCS9_MESSAGE_DIGEST, digest, PR_FALSE);
390 if (rv != SECSuccess)
391 goto loser;
392
393 if (contentType != NULL) {
394 /* if the caller wants us to, find and fill in the content type attribute. */
395 rv = SecCmsAttributeArraySetAttr(poolp, &(signerinfo->authAttr),
396 SEC_OID_PKCS9_CONTENT_TYPE, contentType, PR_FALSE);
397 if (rv != SECSuccess)
398 goto loser;
399 }
400
401 if ((tmppoolp = PORT_NewArena (1024)) == NULL) {
402 PORT_SetError(SEC_ERROR_NO_MEMORY);
403 goto loser;
404 }
405
406 /*
407 * Before encoding, reorder the attributes so that when they
408 * are encoded, they will be conforming DER, which is required
409 * to have a specific order and that is what must be used for
410 * the hash/signature. We do this here, rather than building
411 * it into EncodeAttributes, because we do not want to do
412 * such reordering on incoming messages (which also uses
413 * EncodeAttributes) or our old signatures (and other "broken"
414 * implementations) will not verify. So, we want to guarantee
415 * that we send out good DER encodings of attributes, but not
416 * to expect to receive them.
417 */
418 if (SecCmsAttributeArrayReorder(signerinfo->authAttr) != SECSuccess)
419 goto loser;
420
421 encoded_attrs.Data = NULL;
422 encoded_attrs.Length = 0;
423 if (SecCmsAttributeArrayEncode(tmppoolp, &(signerinfo->authAttr),
424 &encoded_attrs) == NULL)
425 goto loser;
426
427 #if USE_CDSA_CRYPTO
428 rv = SEC_SignData(&signature, encoded_attrs.Data, encoded_attrs.Length,
429 privkey, digestalgtag, pubkAlgTag);
430 #else
431 signature.Length = SecKeyGetSize(privkey, kSecKeySignatureSize);
432 signature.Data = PORT_ZAlloc(signature.Length);
433 if (!signature.Data) {
434 signature.Length = 0;
435 goto loser;
436 }
437 rv = SecKeyDigestAndSign(privkey, &signerinfo->digestAlg, encoded_attrs.Data, encoded_attrs.Length, signature.Data, &signature.Length);
438 if (rv) {
439 PORT_ZFree(signature.Data, signature.Length);
440 signature.Length = 0;
441 }
442 #endif
443
444 PORT_FreeArena(tmppoolp, PR_FALSE); /* awkward memory management :-( */
445 tmppoolp = 0;
446 } else {
447 signature.Length = SecKeyGetSize(privkey, kSecKeySignatureSize);
448 signature.Data = PORT_ZAlloc(signature.Length);
449 if (!signature.Data) {
450 signature.Length = 0;
451 goto loser;
452 }
453 rv = SecKeySignDigest(privkey, &signerinfo->digestAlg, digest->Data, digest->Length,
454 signature.Data, &signature.Length);
455 if (rv) {
456 PORT_ZFree(signature.Data, signature.Length);
457 signature.Length = 0;
458 }
459 }
460 SECKEY_DestroyPrivateKey(privkey);
461 privkey = NULL;
462
463 if (rv != SECSuccess)
464 goto loser;
465
466 if (SECITEM_CopyItem(poolp, &(signerinfo->encDigest), &signature)
467 != SECSuccess)
468 goto loser;
469
470 SECITEM_FreeItem(&signature, PR_FALSE);
471
472 SECOidTag sigAlgTag = SecCmsUtilMakeSignatureAlgorithm(digestalgtag, pubkAlgTag);
473 if (SECOID_SetAlgorithmID(poolp, &(signerinfo->digestEncAlg), sigAlgTag,
474 NULL) != SECSuccess)
475 goto loser;
476
477 return SECSuccess;
478
479 loser:
480 if (signature.Length != 0)
481 SECITEM_FreeItem (&signature, PR_FALSE);
482 if (privkey)
483 SECKEY_DestroyPrivateKey(privkey);
484 if (tmppoolp)
485 PORT_FreeArena(tmppoolp, PR_FALSE);
486 return SECFailure;
487 }
488
489 #if !USE_CDSA_CRYPTO
490 static CFArrayRef
491 SecCmsSignerInfoCopySigningCertificates(SecCmsSignerInfoRef signerinfo)
492 {
493 CFMutableArrayRef certs = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
494 SecAsn1Item **cert_datas = signerinfo->signedData->rawCerts;
495 SecAsn1Item *cert_data;
496 if (cert_datas) while ((cert_data = *cert_datas) != NULL) {
497 SecCertificateRef cert = SecCertificateCreateWithBytes(NULL, cert_data->Data, cert_data->Length);
498 if (cert) {
499 switch (signerinfo->signerIdentifier.identifierType) {
500 case SecCmsSignerIDIssuerSN:
501 if (CERT_CheckIssuerAndSerial(cert,
502 &(signerinfo->signerIdentifier.id.issuerAndSN->derIssuer),
503 &(signerinfo->signerIdentifier.id.issuerAndSN->serialNumber)))
504 CFArrayInsertValueAtIndex(certs, 0, cert);
505 else
506 CFArrayAppendValue(certs, cert);
507 break;
508 case SecCmsSignerIDSubjectKeyID:
509 {
510 CFDataRef cert_keyid = SecCertificateGetSubjectKeyID(cert);
511 SecAsn1Item *tbf_keyid = signerinfo->signerIdentifier.id.subjectKeyID;
512 if (tbf_keyid->Length == (size_t)CFDataGetLength(cert_keyid) &&
513 !memcmp(tbf_keyid->Data, CFDataGetBytePtr(cert_keyid), tbf_keyid->Length))
514 CFArrayInsertValueAtIndex(certs, 0, cert);
515 else
516 CFArrayAppendValue(certs, cert);
517 break;
518 }
519 }
520 CFReleaseNull(cert);
521 }
522 cert_datas++;
523 }
524
525 if ((CFArrayGetCount(certs) == 0) &&
526 (signerinfo->signerIdentifier.identifierType == SecCmsSignerIDIssuerSN))
527 {
528 SecCertificateRef cert = CERT_FindCertificateByIssuerAndSN(signerinfo->signedData->certs, signerinfo->signerIdentifier.id.issuerAndSN);
529 if (cert) {
530 CFArrayAppendValue(certs, cert);
531 CFRelease(cert);
532 }
533 }
534
535 if ((CFArrayGetCount(certs) == 0) &&
536 (signerinfo->signerIdentifier.identifierType == SecCmsSignerIDSubjectKeyID))
537 {
538 SecCertificateRef cert = CERT_FindCertificateBySubjectKeyID(signerinfo->signedData->certs,
539 signerinfo->signerIdentifier.id.subjectKeyID);
540 if (cert) {
541 CFArrayAppendValue(certs, cert);
542 CFRelease(cert);
543 }
544 }
545 return certs;
546 }
547 #endif
548
549 OSStatus
550 SecCmsSignerInfoVerifyCertificate(SecCmsSignerInfoRef signerinfo, SecKeychainRef keychainOrArray,
551 CFTypeRef policies, SecTrustRef *trustRef)
552 {
553 CFAbsoluteTime stime;
554 OSStatus rv;
555
556 #if USE_CDSA_CRYPTO
557 SecCertificateRef cert;
558
559 if ((cert = SecCmsSignerInfoGetSigningCertificate(signerinfo, keychainOrArray)) == NULL) {
560 #else
561 CFArrayRef certs;
562
563 if ((certs = SecCmsSignerInfoCopySigningCertificates(signerinfo)) == NULL) {
564 #endif
565 signerinfo->verificationStatus = SecCmsVSSigningCertNotFound;
566 return SECFailure;
567 }
568 /*
569 * Get and convert the signing time; if available, it will be used
570 * both on the cert verification and for importing the sender
571 * email profile.
572 */
573 if (SecCmsSignerInfoGetSigningTime(signerinfo, &stime) != SECSuccess)
574 stime = CFAbsoluteTimeGetCurrent();
575
576
577 #if USE_CDSA_CRYPTO
578 rv = CERT_VerifyCert(keychainOrArray, cert, policies, stime, trustRef);
579 #else
580 rv = CERT_VerifyCert(keychainOrArray, certs, policies, stime, trustRef);
581 CFRelease(certs);
582 #endif
583 if (rv || !trustRef)
584 {
585 if (PORT_GetError() == SEC_ERROR_UNTRUSTED_CERT)
586 {
587 /* Signature or digest level verificationStatus errors should supercede certificate level errors, so only change the verificationStatus if the status was GoodSignature. */
588 #if 0
589 #warning DEBUG - SecCmsSignerInfoVerifyCertificate trusts everything!
590 if (signerinfo->verificationStatus == SecCmsVSGoodSignature) {
591 syslog(LOG_ERR, "SecCmsSignerInfoVerifyCertificate ignoring SEC_ERROR_UNTRUSTED_CERT");
592 rv = SECSuccess;
593 }
594 #else
595 if (signerinfo->verificationStatus == SecCmsVSGoodSignature)
596 signerinfo->verificationStatus = SecCmsVSSigningCertNotTrusted;
597 #endif
598 }
599 }
600
601 return rv;
602 }
603
604 /*
605 * SecCmsSignerInfoVerify - verify the signature of a single SignerInfo
606 *
607 * Just verifies the signature. The assumption is that verification of the certificate
608 * is done already.
609 */
610 OSStatus
611 SecCmsSignerInfoVerify(SecCmsSignerInfoRef signerinfo, SecAsn1Item * digest, SecAsn1Item * contentType)
612 {
613 SecPublicKeyRef publickey = NULL;
614 SecCmsAttribute *attr;
615 SecAsn1Item encoded_attrs;
616 SecCertificateRef cert;
617 SecCmsVerificationStatus vs = SecCmsVSUnverified;
618 PLArenaPool *poolp;
619
620 if (signerinfo == NULL)
621 return SECFailure;
622
623 /* SecCmsSignerInfoGetSigningCertificate will fail if 2nd parm is NULL and */
624 /* cert has not been verified */
625 if ((cert = SecCmsSignerInfoGetSigningCertificate(signerinfo, NULL)) == NULL) {
626 vs = SecCmsVSSigningCertNotFound;
627 goto loser;
628 }
629
630 publickey = SecCertificateCopyKey(cert);
631 if (publickey == NULL)
632 goto loser;
633
634 if (!SecCmsArrayIsEmpty((void **)signerinfo->authAttr)) {
635 if (contentType) {
636 /*
637 * Check content type
638 *
639 * RFC2630 sez that if there are any authenticated attributes,
640 * then there must be one for content type which matches the
641 * content type of the content being signed, and there must
642 * be one for message digest which matches our message digest.
643 * So check these things first.
644 */
645 if ((attr = SecCmsAttributeArrayFindAttrByOidTag(signerinfo->authAttr,
646 SEC_OID_PKCS9_CONTENT_TYPE, PR_TRUE)) == NULL)
647 {
648 vs = SecCmsVSMalformedSignature;
649 goto loser;
650 }
651
652 if (SecCmsAttributeCompareValue(attr, contentType) == PR_FALSE) {
653 vs = SecCmsVSMalformedSignature;
654 goto loser;
655 }
656 }
657
658 /*
659 * Check digest
660 */
661 if ((attr = SecCmsAttributeArrayFindAttrByOidTag(signerinfo->authAttr, SEC_OID_PKCS9_MESSAGE_DIGEST, PR_TRUE)) == NULL)
662 {
663 vs = SecCmsVSMalformedSignature;
664 goto loser;
665 }
666 if (SecCmsAttributeCompareValue(attr, digest) == PR_FALSE) {
667 vs = SecCmsVSDigestMismatch;
668 goto loser;
669 }
670
671 if ((poolp = PORT_NewArena (1024)) == NULL) {
672 vs = SecCmsVSProcessingError;
673 goto loser;
674 }
675
676 /*
677 * Check signature
678 *
679 * The signature is based on a digest of the DER-encoded authenticated
680 * attributes. So, first we encode and then we digest/verify.
681 * we trust the decoder to have the attributes in the right (sorted) order
682 */
683 encoded_attrs.Data = NULL;
684 encoded_attrs.Length = 0;
685
686 if (SecCmsAttributeArrayEncode(poolp, &(signerinfo->authAttr), &encoded_attrs) == NULL ||
687 encoded_attrs.Data == NULL || encoded_attrs.Length == 0)
688 {
689 vs = SecCmsVSProcessingError;
690 goto loser;
691 }
692 if (errSecSuccess == SecKeyDigestAndVerify(publickey, &signerinfo->digestAlg, encoded_attrs.Data, encoded_attrs.Length, signerinfo->encDigest.Data, signerinfo->encDigest.Length))
693 vs = SecCmsVSGoodSignature;
694 else
695 vs = SecCmsVSBadSignature;
696
697 PORT_FreeArena(poolp, PR_FALSE); /* awkward memory management :-( */
698
699 } else {
700 SecAsn1Item * sig;
701
702 /* No authenticated attributes. The signature is based on the plain message digest. */
703 sig = &(signerinfo->encDigest);
704 if (sig->Length == 0)
705 goto loser;
706
707 if (SecKeyVerifyDigest(publickey, &signerinfo->digestAlg, digest->Data, digest->Length, sig->Data, sig->Length))
708 vs = SecCmsVSBadSignature;
709 else
710 vs = SecCmsVSGoodSignature;
711 }
712
713 if (vs == SecCmsVSBadSignature) {
714 /*
715 * XXX Change the generic error into our specific one, because
716 * in that case we get a better explanation out of the Security
717 * Advisor. This is really a bug in our error strings (the
718 * "generic" error has a lousy/wrong message associated with it
719 * which assumes the signature verification was done for the
720 * purposes of checking the issuer signature on a certificate)
721 * but this is at least an easy workaround and/or in the
722 * Security Advisor, which specifically checks for the error
723 * SEC_ERROR_PKCS7_BAD_SIGNATURE and gives more explanation
724 * in that case but does not similarly check for
725 * SEC_ERROR_BAD_SIGNATURE. It probably should, but then would
726 * probably say the wrong thing in the case that it *was* the
727 * certificate signature check that failed during the cert
728 * verification done above. Our error handling is really a mess.
729 */
730 if (PORT_GetError() == SEC_ERROR_BAD_SIGNATURE)
731 PORT_SetError(SEC_ERROR_PKCS7_BAD_SIGNATURE);
732 }
733
734 if (publickey != NULL)
735 CFRelease(publickey);
736
737 signerinfo->verificationStatus = vs;
738
739 return (vs == SecCmsVSGoodSignature) ? SECSuccess : SECFailure;
740
741 loser:
742 if (publickey != NULL)
743 SECKEY_DestroyPublicKey (publickey);
744
745 signerinfo->verificationStatus = vs;
746
747 PORT_SetError (SEC_ERROR_PKCS7_BAD_SIGNATURE);
748 return SECFailure;
749 }
750
751 SecCmsVerificationStatus
752 SecCmsSignerInfoGetVerificationStatus(SecCmsSignerInfoRef signerinfo)
753 {
754 return signerinfo->verificationStatus;
755 }
756
757 SECOidData *
758 SecCmsSignerInfoGetDigestAlg(SecCmsSignerInfoRef signerinfo)
759 {
760 return SECOID_FindOID (&(signerinfo->digestAlg.algorithm));
761 }
762
763 SECOidTag
764 SecCmsSignerInfoGetDigestAlgTag(SecCmsSignerInfoRef signerinfo)
765 {
766 SECOidData *algdata;
767
768 algdata = SECOID_FindOID (&(signerinfo->digestAlg.algorithm));
769 if (algdata != NULL)
770 return algdata->offset;
771 else
772 return SEC_OID_UNKNOWN;
773 }
774
775 CFArrayRef
776 SecCmsSignerInfoGetCertList(SecCmsSignerInfoRef signerinfo)
777 {
778 return signerinfo->certList;
779 }
780
781 int
782 SecCmsSignerInfoGetVersion(SecCmsSignerInfoRef signerinfo)
783 {
784 unsigned long version;
785
786 /* always take apart the SecAsn1Item */
787 if (SEC_ASN1DecodeInteger(&(signerinfo->version), &version) != SECSuccess)
788 return 0;
789 else
790 return (int)version;
791 }
792
793 /*
794 * SecCmsSignerInfoGetSigningTime - return the signing time,
795 * in UTCTime format, of a CMS signerInfo.
796 *
797 * sinfo - signerInfo data for this signer
798 *
799 * Returns a pointer to XXXX (what?)
800 * A return value of NULL is an error.
801 */
802 OSStatus
803 SecCmsSignerInfoGetSigningTime(SecCmsSignerInfoRef sinfo, CFAbsoluteTime *stime)
804 {
805 SecCmsAttribute *attr;
806 SecAsn1Item * value;
807
808 if (sinfo == NULL)
809 return SECFailure;
810
811 if (sinfo->signingTime != 0) {
812 *stime = sinfo->signingTime; /* cached copy */
813 return SECSuccess;
814 }
815
816 attr = SecCmsAttributeArrayFindAttrByOidTag(sinfo->authAttr, SEC_OID_PKCS9_SIGNING_TIME, PR_TRUE);
817 /* XXXX multi-valued attributes NIH */
818 if (attr == NULL || (value = SecCmsAttributeGetValue(attr)) == NULL)
819 return SECFailure;
820 if (DER_UTCTimeToCFDate(value, stime) != SECSuccess)
821 return SECFailure;
822 sinfo->signingTime = *stime; /* make cached copy */
823 return SECSuccess;
824 }
825
826 /*!
827 @function
828 @abstract Return the data in the signed Codesigning Hash Agility attribute.
829 @param sinfo SignerInfo data for this signer, pointer to a CFDataRef for attribute value
830 @discussion Returns a CFDataRef containing the value of the attribute
831 @result A return value of errSecInternal is an error trying to look up the oid.
832 A status value of success with null result data indicates the attribute was not present.
833 */
834 OSStatus
835 SecCmsSignerInfoGetAppleCodesigningHashAgility(SecCmsSignerInfoRef sinfo, CFDataRef *sdata)
836 {
837 SecCmsAttribute *attr;
838 SecAsn1Item *value;
839
840 if (sinfo == NULL || sdata == NULL)
841 return errSecParam;
842
843 *sdata = NULL;
844
845 if (sinfo->hashAgilityAttrValue != NULL) {
846 *sdata = sinfo->hashAgilityAttrValue; /* cached copy */
847 return SECSuccess;
848 }
849
850 attr = SecCmsAttributeArrayFindAttrByOidTag(sinfo->authAttr, SEC_OID_APPLE_HASH_AGILITY, PR_TRUE);
851
852 /* attribute not found */
853 if (attr == NULL || (value = SecCmsAttributeGetValue(attr)) == NULL)
854 return SECSuccess;
855
856 sinfo->hashAgilityAttrValue = CFDataCreate(NULL, value->Data, value->Length); /* make cached copy */
857 if (sinfo->hashAgilityAttrValue) {
858 *sdata = sinfo->hashAgilityAttrValue;
859 return SECSuccess;
860 }
861 return errSecAllocate;
862 }
863
864 /* AgileHash ::= SEQUENCE {
865 hashType OBJECT IDENTIFIER,
866 hashValues OCTET STRING }
867 */
868 typedef struct {
869 SecAsn1Item digestOID;
870 SecAsn1Item digestValue;
871 } CMSAppleAgileHash;
872
873 static const SecAsn1Template CMSAppleAgileHashTemplate[] = {
874 { SEC_ASN1_SEQUENCE,
875 0, NULL, sizeof(CMSAppleAgileHash) },
876 { SEC_ASN1_OBJECT_ID,
877 offsetof(CMSAppleAgileHash, digestOID), },
878 { SEC_ASN1_OCTET_STRING,
879 offsetof(CMSAppleAgileHash, digestValue), },
880 { 0, }
881 };
882
883 static OSStatus CMSAddAgileHashToDictionary(CFMutableDictionaryRef dictionary, SecAsn1Item *DERAgileHash) {
884 PLArenaPool *tmppoolp = NULL;
885 OSStatus status = errSecSuccess;
886 CMSAppleAgileHash agileHash;
887 CFDataRef digestValue = NULL;
888 CFNumberRef digestTag = NULL;
889
890 tmppoolp = PORT_NewArena(1024);
891 if (tmppoolp == NULL) {
892 return errSecAllocate;
893 }
894
895 if ((status = SEC_ASN1DecodeItem(tmppoolp, &agileHash, CMSAppleAgileHashTemplate, DERAgileHash)) != errSecSuccess) {
896 goto loser;
897 }
898
899 int64_t tag = SECOID_FindOIDTag(&agileHash.digestOID);
900 digestTag = CFNumberCreate(NULL, kCFNumberSInt64Type, &tag);
901 digestValue = CFDataCreate(NULL, agileHash.digestValue.Data, agileHash.digestValue.Length);
902 CFDictionaryAddValue(dictionary, digestTag, digestValue);
903
904 loser:
905 CFReleaseNull(digestValue);
906 CFReleaseNull(digestTag);
907 if (tmppoolp) {
908 PORT_FreeArena(tmppoolp, PR_FALSE);
909 }
910 return status;
911 }
912
913 /*!
914 @function
915 @abstract Return the data in the signed Codesigning Hash Agility V2 attribute.
916 @param sinfo SignerInfo data for this signer, pointer to a CFDictionaryRef for attribute values
917 @discussion Returns a CFDictionaryRef containing the values of the attribute
918 @result A return value of errSecInternal is an error trying to look up the oid.
919 A status value of success with null result data indicates the attribute was not present.
920 */
921 OSStatus
922 SecCmsSignerInfoGetAppleCodesigningHashAgilityV2(SecCmsSignerInfoRef sinfo, CFDictionaryRef *sdict)
923 {
924 SecCmsAttribute *attr;
925
926 if (sinfo == NULL || sdict == NULL) {
927 return errSecParam;
928 }
929
930 *sdict = NULL;
931
932 if (sinfo->hashAgilityV2AttrValues != NULL) {
933 *sdict = sinfo->hashAgilityV2AttrValues; /* cached copy */
934 return SECSuccess;
935 }
936
937 attr = SecCmsAttributeArrayFindAttrByOidTag(sinfo->authAttr, SEC_OID_APPLE_HASH_AGILITY_V2, PR_TRUE);
938
939 /* attribute not found */
940 if (attr == NULL) {
941 return SECSuccess;
942 }
943
944 /* attrValues SET OF AttributeValue
945 * AttributeValue ::= ANY
946 */
947 SecAsn1Item **values = attr->values;
948 if (values == NULL) { /* There must be values */
949 return errSecDecode;
950 }
951
952 CFMutableDictionaryRef agileHashValues = CFDictionaryCreateMutable(NULL, SecCmsArrayCount((void **)values),
953 &kCFTypeDictionaryKeyCallBacks,
954 &kCFTypeDictionaryValueCallBacks);
955 while (*values != NULL) {
956 (void)CMSAddAgileHashToDictionary(agileHashValues, *values++);
957 }
958 if (CFDictionaryGetCount(agileHashValues) != SecCmsArrayCount((void **)attr->values)) {
959 CFReleaseNull(agileHashValues);
960 return errSecDecode;
961 }
962
963 sinfo->hashAgilityV2AttrValues = agileHashValues; /* make cached copy */
964 if (sinfo->hashAgilityV2AttrValues) {
965 *sdict = sinfo->hashAgilityV2AttrValues;
966 return SECSuccess;
967 }
968 return errSecAllocate;
969 }
970
971 /*
972 * SecCmsSignerInfoGetAppleExpirationTime - return the expiration time,
973 * in UTCTime format, of a CMS signerInfo.
974 *
975 * sinfo - signerInfo data for this signer
976 *
977 * Returns a pointer to XXXX (what?)
978 * A return value of NULL is an error.
979 */
980 OSStatus
981 SecCmsSignerInfoGetAppleExpirationTime(SecCmsSignerInfoRef sinfo, CFAbsoluteTime *etime)
982 {
983 SecCmsAttribute *attr = NULL;
984 SecAsn1Item * value = NULL;
985
986 if (sinfo == NULL || etime == NULL) {
987 return SECFailure;
988 }
989
990 if (sinfo->expirationTime != 0) {
991 *etime = sinfo->expirationTime; /* cached copy */
992 return SECSuccess;
993 }
994
995 attr = SecCmsAttributeArrayFindAttrByOidTag(sinfo->authAttr, SEC_OID_APPLE_EXPIRATION_TIME, PR_TRUE);
996 if (attr == NULL || (value = SecCmsAttributeGetValue(attr)) == NULL) {
997 return SECFailure;
998 }
999 if (DER_UTCTimeToCFDate(value, etime) != SECSuccess) {
1000 return SECFailure;
1001 }
1002 sinfo->expirationTime = *etime; /* make cached copy */
1003 return SECSuccess;
1004 }
1005
1006 /*
1007 * Return the signing cert of a CMS signerInfo.
1008 *
1009 * the certs in the enclosing SignedData must have been imported already
1010 */
1011 SecCertificateRef
1012 SecCmsSignerInfoGetSigningCertificate(SecCmsSignerInfoRef signerinfo, SecKeychainRef keychainOrArray)
1013 {
1014 SecCertificateRef cert = NULL;
1015
1016 if (signerinfo->cert != NULL)
1017 return signerinfo->cert;
1018
1019 /* @@@ Make sure we search though all the certs in the cms message itself as well, it's silly
1020 to require them to be added to a keychain first. */
1021
1022 #if USE_CDSA_CRYPTO
1023 SecCmsSignerIdentifier *sid;
1024
1025 /*
1026 * This cert will also need to be freed, but since we save it
1027 * in signerinfo for later, we do not want to destroy it when
1028 * we leave this function -- we let the clean-up of the entire
1029 * cinfo structure later do the destroy of this cert.
1030 */
1031 sid = &signerinfo->signerIdentifier;
1032 switch (sid->identifierType) {
1033 case SecCmsSignerIDIssuerSN:
1034 cert = CERT_FindCertByIssuerAndSN(keychainOrArray, sid->id.issuerAndSN);
1035 break;
1036 case SecCmsSignerIDSubjectKeyID:
1037 cert = CERT_FindCertBySubjectKeyID(keychainOrArray, sid->id.subjectKeyID);
1038 break;
1039 default:
1040 cert = NULL;
1041 break;
1042 }
1043
1044 /* cert can be NULL at that point */
1045 signerinfo->cert = cert; /* earmark it */
1046 #else
1047 SecAsn1Item **cert_datas = signerinfo->signedData->rawCerts;
1048 SecAsn1Item *cert_data;
1049 if (cert_datas) while ((cert_data = *cert_datas) != NULL) {
1050 cert = SecCertificateCreateWithBytes(NULL, cert_data->Data, cert_data->Length);
1051 if (cert) {
1052 switch (signerinfo->signerIdentifier.identifierType) {
1053 case SecCmsSignerIDIssuerSN:
1054 if (CERT_CheckIssuerAndSerial(cert,
1055 &(signerinfo->signerIdentifier.id.issuerAndSN->derIssuer),
1056 &(signerinfo->signerIdentifier.id.issuerAndSN->serialNumber)))
1057 signerinfo->cert = cert;
1058 break;
1059 case SecCmsSignerIDSubjectKeyID: {
1060 CFDataRef cert_keyid = SecCertificateGetSubjectKeyID(cert);
1061 SecAsn1Item *tbf_keyid = signerinfo->signerIdentifier.id.subjectKeyID;
1062 if (tbf_keyid->Length == (size_t)CFDataGetLength(cert_keyid) &&
1063 !memcmp(tbf_keyid->Data, CFDataGetBytePtr(cert_keyid), tbf_keyid->Length))
1064 signerinfo->cert = cert;
1065 }
1066 }
1067 if (signerinfo->cert)
1068 break;
1069 CFReleaseNull(cert);
1070 }
1071 cert_datas++;
1072 }
1073
1074 if (!signerinfo->cert && (signerinfo->signerIdentifier.identifierType == SecCmsSignerIDIssuerSN)) {
1075 cert = CERT_FindCertificateByIssuerAndSN(signerinfo->signedData->certs, signerinfo->signerIdentifier.id.issuerAndSN);
1076 signerinfo->cert = cert;
1077 }
1078 if (!signerinfo->cert && (signerinfo->signerIdentifier.identifierType == SecCmsSignerIDSubjectKeyID)) {
1079 cert = CERT_FindCertificateBySubjectKeyID(signerinfo->signedData->certs, signerinfo->signerIdentifier.id.subjectKeyID);
1080 signerinfo->cert = cert;
1081 }
1082 #endif
1083
1084 return cert;
1085 }
1086
1087
1088 /*
1089 * SecCmsSignerInfoGetSignerCommonName - return the common name of the signer
1090 *
1091 * sinfo - signerInfo data for this signer
1092 *
1093 * Returns a CFStringRef containing the common name of the signer.
1094 * A return value of NULL is an error.
1095 */
1096 CFStringRef
1097 SecCmsSignerInfoGetSignerCommonName(SecCmsSignerInfoRef sinfo)
1098 {
1099 SecCertificateRef signercert;
1100 CFStringRef commonName = NULL;
1101
1102 /* will fail if cert is not verified */
1103 if ((signercert = SecCmsSignerInfoGetSigningCertificate(sinfo, NULL)) == NULL)
1104 return NULL;
1105
1106 #if USE_CDSA_CRYPTO
1107 SecCertificateGetCommonName(signercert, &commonName);
1108 #else
1109 CFArrayRef commonNames = SecCertificateCopyCommonNames(signercert);
1110 if (commonNames) {
1111 /* SecCertificateCopyCommonNames doesn't return empty arrays */
1112 commonName = (CFStringRef)CFArrayGetValueAtIndex(commonNames, CFArrayGetCount(commonNames) - 1);
1113 CFRetain(commonName);
1114 CFRelease(commonNames);
1115 }
1116 #endif
1117
1118 return commonName;
1119 }
1120
1121 /*
1122 * SecCmsSignerInfoGetSignerEmailAddress - return the email address of the signer
1123 *
1124 * sinfo - signerInfo data for this signer
1125 *
1126 * Returns a CFStringRef containing the name of the signer.
1127 * A return value of NULL is an error.
1128 */
1129 CFStringRef
1130 SecCmsSignerInfoGetSignerEmailAddress(SecCmsSignerInfoRef sinfo)
1131 {
1132 SecCertificateRef signercert;
1133 CFStringRef emailAddress = NULL;
1134
1135 if ((signercert = SecCmsSignerInfoGetSigningCertificate(sinfo, NULL)) == NULL) {
1136 return NULL;
1137 }
1138
1139 CFArrayRef names = SecCertificateCopyRFC822Names(signercert);
1140 if (names) {
1141 if (CFArrayGetCount(names) > 0) {
1142 emailAddress = (CFStringRef)CFArrayGetValueAtIndex(names, 0);
1143 }
1144 CFRetainSafe(emailAddress);
1145 CFRelease(names);
1146 }
1147 return emailAddress;
1148 }
1149
1150
1151 /*
1152 * SecCmsSignerInfoAddAuthAttr - add an attribute to the
1153 * authenticated (i.e. signed) attributes of "signerinfo".
1154 */
1155 OSStatus
1156 SecCmsSignerInfoAddAuthAttr(SecCmsSignerInfoRef signerinfo, SecCmsAttribute *attr)
1157 {
1158 return SecCmsAttributeArrayAddAttr(signerinfo->signedData->contentInfo.cmsg->poolp, &(signerinfo->authAttr), attr);
1159 }
1160
1161 /*
1162 * SecCmsSignerInfoAddUnauthAttr - add an attribute to the
1163 * unauthenticated attributes of "signerinfo".
1164 */
1165 OSStatus
1166 SecCmsSignerInfoAddUnauthAttr(SecCmsSignerInfoRef signerinfo, SecCmsAttribute *attr)
1167 {
1168 return SecCmsAttributeArrayAddAttr(signerinfo->signedData->contentInfo.cmsg->poolp, &(signerinfo->unAuthAttr), attr);
1169 }
1170
1171 /*
1172 * SecCmsSignerInfoAddSigningTime - add the signing time to the
1173 * authenticated (i.e. signed) attributes of "signerinfo".
1174 *
1175 * This is expected to be included in outgoing signed
1176 * messages for email (S/MIME) but is likely useful in other situations.
1177 *
1178 * This should only be added once; a second call will do nothing.
1179 *
1180 * XXX This will probably just shove the current time into "signerinfo"
1181 * but it will not actually get signed until the entire item is
1182 * processed for encoding. Is this (expected to be small) delay okay?
1183 */
1184 OSStatus
1185 SecCmsSignerInfoAddSigningTime(SecCmsSignerInfoRef signerinfo, CFAbsoluteTime t)
1186 {
1187 SecCmsAttribute *attr;
1188 SecAsn1Item stime;
1189 void *mark;
1190 PLArenaPool *poolp;
1191
1192 poolp = signerinfo->signedData->contentInfo.cmsg->poolp;
1193
1194 mark = PORT_ArenaMark(poolp);
1195
1196 /* create new signing time attribute */
1197 if (DER_CFDateToUTCTime(t, &stime) != SECSuccess)
1198 goto loser;
1199
1200 if ((attr = SecCmsAttributeCreate(poolp, SEC_OID_PKCS9_SIGNING_TIME, &stime, PR_FALSE)) == NULL) {
1201 SECITEM_FreeItem (&stime, PR_FALSE);
1202 goto loser;
1203 }
1204
1205 SECITEM_FreeItem (&stime, PR_FALSE);
1206
1207 if (SecCmsSignerInfoAddAuthAttr(signerinfo, attr) != SECSuccess)
1208 goto loser;
1209
1210 PORT_ArenaUnmark (poolp, mark);
1211
1212 return SECSuccess;
1213
1214 loser:
1215 PORT_ArenaRelease (poolp, mark);
1216 return SECFailure;
1217 }
1218
1219 /*
1220 * SecCmsSignerInfoAddSMIMECaps - add a SMIMECapabilities attribute to the
1221 * authenticated (i.e. signed) attributes of "signerinfo".
1222 *
1223 * This is expected to be included in outgoing signed
1224 * messages for email (S/MIME).
1225 */
1226 OSStatus
1227 SecCmsSignerInfoAddSMIMECaps(SecCmsSignerInfoRef signerinfo)
1228 {
1229 SecCmsAttribute *attr;
1230 SecAsn1Item * smimecaps = NULL;
1231 void *mark;
1232 PLArenaPool *poolp;
1233
1234 poolp = signerinfo->signedData->contentInfo.cmsg->poolp;
1235
1236 mark = PORT_ArenaMark(poolp);
1237
1238 smimecaps = SECITEM_AllocItem(poolp, NULL, 0);
1239 if (smimecaps == NULL)
1240 goto loser;
1241
1242 /* create new signing time attribute */
1243 #if 1
1244 // @@@ We don't do Fortezza yet.
1245 if (SecSMIMECreateSMIMECapabilities(poolp, smimecaps, PR_FALSE) != SECSuccess)
1246 #else
1247 if (SecSMIMECreateSMIMECapabilities(poolp, smimecaps,
1248 PK11_FortezzaHasKEA(signerinfo->cert)) != SECSuccess)
1249 #endif
1250 goto loser;
1251
1252 if ((attr = SecCmsAttributeCreate(poolp, SEC_OID_PKCS9_SMIME_CAPABILITIES, smimecaps, PR_TRUE)) == NULL)
1253 goto loser;
1254
1255 if (SecCmsSignerInfoAddAuthAttr(signerinfo, attr) != SECSuccess)
1256 goto loser;
1257
1258 PORT_ArenaUnmark (poolp, mark);
1259 return SECSuccess;
1260
1261 loser:
1262 PORT_ArenaRelease (poolp, mark);
1263 return SECFailure;
1264 }
1265
1266 /*
1267 * SecCmsSignerInfoAddSMIMEEncKeyPrefs - add a SMIMEEncryptionKeyPreferences attribute to the
1268 * authenticated (i.e. signed) attributes of "signerinfo".
1269 *
1270 * This is expected to be included in outgoing signed messages for email (S/MIME).
1271 */
1272 OSStatus
1273 SecCmsSignerInfoAddSMIMEEncKeyPrefs(SecCmsSignerInfoRef signerinfo, SecCertificateRef cert, SecKeychainRef keychainOrArray)
1274 {
1275 SecCmsAttribute *attr;
1276 SecAsn1Item * smimeekp = NULL;
1277 void *mark;
1278 PLArenaPool *poolp;
1279
1280 #if 0
1281 CFTypeRef policy;
1282
1283 /* verify this cert for encryption */
1284 policy = CERT_PolicyForCertUsage(certUsageEmailRecipient);
1285 if (CERT_VerifyCert(keychainOrArray, cert, policy, CFAbsoluteTimeGetCurrent(), NULL) != SECSuccess) {
1286 CFRelease(policy);
1287 return SECFailure;
1288 }
1289 CFRelease(policy);
1290 #endif
1291
1292 poolp = signerinfo->signedData->contentInfo.cmsg->poolp;
1293 mark = PORT_ArenaMark(poolp);
1294
1295 smimeekp = SECITEM_AllocItem(poolp, NULL, 0);
1296 if (smimeekp == NULL)
1297 goto loser;
1298
1299 /* create new signing time attribute */
1300 if (SecSMIMECreateSMIMEEncKeyPrefs(poolp, smimeekp, cert) != SECSuccess)
1301 goto loser;
1302
1303 if ((attr = SecCmsAttributeCreate(poolp, SEC_OID_SMIME_ENCRYPTION_KEY_PREFERENCE, smimeekp, PR_TRUE)) == NULL)
1304 goto loser;
1305
1306 if (SecCmsSignerInfoAddAuthAttr(signerinfo, attr) != SECSuccess)
1307 goto loser;
1308
1309 PORT_ArenaUnmark (poolp, mark);
1310 return SECSuccess;
1311
1312 loser:
1313 PORT_ArenaRelease (poolp, mark);
1314 return SECFailure;
1315 }
1316
1317 /*
1318 * SecCmsSignerInfoAddMSSMIMEEncKeyPrefs - add a SMIMEEncryptionKeyPreferences attribute to the
1319 * authenticated (i.e. signed) attributes of "signerinfo", using the OID preferred by Microsoft.
1320 *
1321 * This is expected to be included in outgoing signed messages for email (S/MIME),
1322 * if compatibility with Microsoft mail clients is wanted.
1323 */
1324 OSStatus
1325 SecCmsSignerInfoAddMSSMIMEEncKeyPrefs(SecCmsSignerInfoRef signerinfo, SecCertificateRef cert, SecKeychainRef keychainOrArray)
1326 {
1327 SecCmsAttribute *attr;
1328 SecAsn1Item * smimeekp = NULL;
1329 void *mark;
1330 PLArenaPool *poolp;
1331
1332 #if 0
1333 CFTypeRef policy;
1334
1335 /* verify this cert for encryption */
1336 policy = CERT_PolicyForCertUsage(certUsageEmailRecipient);
1337 if (CERT_VerifyCert(keychainOrArray, cert, policy, CFAbsoluteTimeGetCurrent(), NULL) != SECSuccess) {
1338 CFRelease(policy);
1339 return SECFailure;
1340 }
1341 CFRelease(policy);
1342 #endif
1343
1344 poolp = signerinfo->signedData->contentInfo.cmsg->poolp;
1345 mark = PORT_ArenaMark(poolp);
1346
1347 smimeekp = SECITEM_AllocItem(poolp, NULL, 0);
1348 if (smimeekp == NULL)
1349 goto loser;
1350
1351 /* create new signing time attribute */
1352 if (SecSMIMECreateMSSMIMEEncKeyPrefs(poolp, smimeekp, cert) != SECSuccess)
1353 goto loser;
1354
1355 if ((attr = SecCmsAttributeCreate(poolp, SEC_OID_MS_SMIME_ENCRYPTION_KEY_PREFERENCE, smimeekp, PR_TRUE)) == NULL)
1356 goto loser;
1357
1358 if (SecCmsSignerInfoAddAuthAttr(signerinfo, attr) != SECSuccess)
1359 goto loser;
1360
1361 PORT_ArenaUnmark (poolp, mark);
1362 return SECSuccess;
1363
1364 loser:
1365 PORT_ArenaRelease (poolp, mark);
1366 return SECFailure;
1367 }
1368
1369 /*
1370 * SecCmsSignerInfoAddCounterSignature - countersign a signerinfo
1371 *
1372 * 1. digest the DER-encoded signature value of the original signerinfo
1373 * 2. create new signerinfo with correct version, sid, digestAlg
1374 * 3. add message-digest authAttr, but NO content-type
1375 * 4. sign the authAttrs
1376 * 5. DER-encode the new signerInfo
1377 * 6. add the whole thing to original signerInfo's unAuthAttrs
1378 * as a SEC_OID_PKCS9_COUNTER_SIGNATURE attribute
1379 *
1380 * XXXX give back the new signerinfo?
1381 */
1382 OSStatus
1383 SecCmsSignerInfoAddCounterSignature(SecCmsSignerInfoRef signerinfo,
1384 SECOidTag digestalg, SecIdentityRef identity)
1385 {
1386 /* XXXX TBD XXXX */
1387 return SECFailure;
1388 }
1389
1390 /*!
1391 @function
1392 @abstract Add the Apple Codesigning Hash Agility attribute to the authenticated (i.e. signed) attributes of "signerinfo".
1393 @discussion This is expected to be included in outgoing Apple code signatures.
1394 */
1395 OSStatus
1396 SecCmsSignerInfoAddAppleCodesigningHashAgility(SecCmsSignerInfoRef signerinfo, CFDataRef attrValue)
1397 {
1398 SecCmsAttribute *attr;
1399 PLArenaPool *poolp = signerinfo->signedData->contentInfo.cmsg->poolp;
1400 void *mark = PORT_ArenaMark(poolp);
1401 OSStatus status = SECFailure;
1402
1403 /* The value is required for this attribute. */
1404 if (!attrValue) {
1405 status = errSecParam;
1406 goto loser;
1407 }
1408
1409 /*
1410 * SecCmsAttributeCreate makes a copy of the data in value, so
1411 * we don't need to copy into the CSSM_DATA struct.
1412 */
1413 SecAsn1Item value;
1414 value.Length = CFDataGetLength(attrValue);
1415 value.Data = (uint8_t *)CFDataGetBytePtr(attrValue);
1416
1417 if ((attr = SecCmsAttributeCreate(poolp,
1418 SEC_OID_APPLE_HASH_AGILITY,
1419 &value,
1420 PR_FALSE)) == NULL) {
1421 status = errSecAllocate;
1422 goto loser;
1423 }
1424
1425 if (SecCmsSignerInfoAddAuthAttr(signerinfo, attr) != SECSuccess) {
1426 status = errSecInternal;
1427 goto loser;
1428 }
1429
1430 PORT_ArenaUnmark(poolp, mark);
1431 return SECSuccess;
1432
1433 loser:
1434 PORT_ArenaRelease(poolp, mark);
1435 return status;
1436 }
1437
1438 static OSStatus CMSAddAgileHashToAttribute(PLArenaPool *poolp, SecCmsAttribute *attr, CFNumberRef cftag, CFDataRef value) {
1439 PLArenaPool *tmppoolp = NULL;
1440 int64_t tag;
1441 SECOidData *digestOid = NULL;
1442 CMSAppleAgileHash agileHash;
1443 SecAsn1Item attrValue = { .Data = NULL, .Length = 0 };
1444 OSStatus status = errSecSuccess;
1445
1446 memset(&agileHash, 0, sizeof(agileHash));
1447
1448 if(!CFNumberGetValue(cftag, kCFNumberSInt64Type, &tag)) {
1449 return errSecParam;
1450 }
1451 digestOid = SECOID_FindOIDByTag((SECOidTag)tag);
1452
1453 agileHash.digestValue.Data = (uint8_t *)CFDataGetBytePtr(value);
1454 agileHash.digestValue.Length = CFDataGetLength(value);
1455 agileHash.digestOID.Data = digestOid->oid.Data;
1456 agileHash.digestOID.Length = digestOid->oid.Length;
1457
1458 tmppoolp = PORT_NewArena(1024);
1459 if (tmppoolp == NULL) {
1460 return errSecAllocate;
1461 }
1462
1463 if (SEC_ASN1EncodeItem(tmppoolp, &attrValue, &agileHash, CMSAppleAgileHashTemplate) == NULL) {
1464 status = errSecParam;
1465 goto loser;
1466 }
1467
1468 status = SecCmsAttributeAddValue(poolp, attr, &attrValue);
1469
1470 loser:
1471 if (tmppoolp) {
1472 PORT_FreeArena(tmppoolp, PR_FALSE);
1473 }
1474 return status;
1475 }
1476
1477 /*!
1478 @function
1479 @abstract Add the Apple Codesigning Hash Agility attribute to the authenticated (i.e. signed) attributes of "signerinfo".
1480 @discussion This is expected to be included in outgoing Apple code signatures.
1481 */
1482 OSStatus
1483 SecCmsSignerInfoAddAppleCodesigningHashAgilityV2(SecCmsSignerInfoRef signerinfo, CFDictionaryRef attrValues)
1484 {
1485 __block SecCmsAttribute *attr;
1486 __block PLArenaPool *poolp = signerinfo->signedData->contentInfo.cmsg->poolp;
1487 void *mark = PORT_ArenaMark(poolp);
1488 OSStatus status = SECFailure;
1489
1490 /* The value is required for this attribute. */
1491 if (!attrValues) {
1492 status = errSecParam;
1493 goto loser;
1494 }
1495
1496 if ((attr = SecCmsAttributeCreate(poolp, SEC_OID_APPLE_HASH_AGILITY_V2,
1497 NULL, PR_TRUE)) == NULL) {
1498 status = errSecAllocate;
1499 goto loser;
1500 }
1501
1502 CFDictionaryForEach(attrValues, ^(const void *key, const void *value) {
1503 if (!isNumber(key) || !isData(value)) {
1504 return;
1505 }
1506 (void)CMSAddAgileHashToAttribute(poolp, attr, (CFNumberRef)key, (CFDataRef)value);
1507 });
1508
1509 if (SecCmsSignerInfoAddAuthAttr(signerinfo, attr) != SECSuccess) {
1510 status = errSecInternal;
1511 goto loser;
1512 }
1513
1514 PORT_ArenaUnmark(poolp, mark);
1515 return SECSuccess;
1516
1517 loser:
1518 PORT_ArenaRelease(poolp, mark);
1519 return status;
1520 }
1521
1522 /*
1523 * SecCmsSignerInfoAddAppleExpirationTime - add the expiration time to the
1524 * authenticated (i.e. signed) attributes of "signerinfo".
1525 *
1526 * This is expected to be included in outgoing signed
1527 * messages for Asset Receipts but is likely useful in other situations.
1528 *
1529 * This should only be added once; a second call will do nothing.
1530 */
1531 OSStatus
1532 SecCmsSignerInfoAddAppleExpirationTime(SecCmsSignerInfoRef signerinfo, CFAbsoluteTime t)
1533 {
1534 SecCmsAttribute *attr = NULL;
1535 PLArenaPool *poolp = signerinfo->signedData->contentInfo.cmsg->poolp;
1536 void *mark = PORT_ArenaMark(poolp);
1537
1538 /* create new expiration time attribute */
1539 SecAsn1Item etime;
1540 if (DER_CFDateToUTCTime(t, &etime) != SECSuccess) {
1541 goto loser;
1542 }
1543
1544 if ((attr = SecCmsAttributeCreate(poolp, SEC_OID_APPLE_EXPIRATION_TIME, &etime, PR_FALSE)) == NULL) {
1545 SECITEM_FreeItem (&etime, PR_FALSE);
1546 goto loser;
1547 }
1548
1549 SECITEM_FreeItem(&etime, PR_FALSE);
1550
1551 if (SecCmsSignerInfoAddAuthAttr(signerinfo, attr) != SECSuccess) {
1552 goto loser;
1553 }
1554
1555 PORT_ArenaUnmark(poolp, mark);
1556 return SECSuccess;
1557
1558 loser:
1559 PORT_ArenaRelease(poolp, mark);
1560 return SECFailure;
1561 }
1562
1563 SecCertificateRef SecCmsSignerInfoCopyCertFromEncryptionKeyPreference(SecCmsSignerInfoRef signerinfo) {
1564 SecCertificateRef cert = NULL;
1565 SecCmsAttribute *attr;
1566 SecAsn1Item *ekp;
1567
1568 /* sanity check - see if verification status is ok (unverified does not count...) */
1569 if (signerinfo->verificationStatus != SecCmsVSGoodSignature)
1570 return NULL;
1571
1572 /* Prep the rawCerts */
1573 SecAsn1Item **rawCerts = NULL;
1574 if (signerinfo->signedData) {
1575 rawCerts = signerinfo->signedData->rawCerts;
1576 }
1577
1578 /* find preferred encryption cert */
1579 if (!SecCmsArrayIsEmpty((void **)signerinfo->authAttr) &&
1580 (attr = SecCmsAttributeArrayFindAttrByOidTag(signerinfo->authAttr,
1581 SEC_OID_SMIME_ENCRYPTION_KEY_PREFERENCE, PR_TRUE)) != NULL)
1582 { /* we have a SMIME_ENCRYPTION_KEY_PREFERENCE attribute! Find the cert. */
1583 ekp = SecCmsAttributeGetValue(attr);
1584 if (ekp == NULL)
1585 return NULL;
1586 cert = SecSMIMEGetCertFromEncryptionKeyPreference(rawCerts, ekp);
1587 }
1588 if (cert) return cert;
1589
1590 if (!SecCmsArrayIsEmpty((void **)signerinfo->authAttr) &&
1591 (attr = SecCmsAttributeArrayFindAttrByOidTag(signerinfo->authAttr,
1592 SEC_OID_MS_SMIME_ENCRYPTION_KEY_PREFERENCE, PR_TRUE)) != NULL)
1593 { /* we have a MS_SMIME_ENCRYPTION_KEY_PREFERENCE attribute! Find the cert. */
1594 ekp = SecCmsAttributeGetValue(attr);
1595 if (ekp == NULL)
1596 return NULL;
1597 cert = SecSMIMEGetCertFromEncryptionKeyPreference(rawCerts, ekp);
1598 }
1599 return cert;
1600 }
1601
1602 /*
1603 * XXXX the following needs to be done in the S/MIME layer code
1604 * after signature of a signerinfo is verified
1605 */
1606 OSStatus
1607 SecCmsSignerInfoSaveSMIMEProfile(SecCmsSignerInfoRef signerinfo)
1608 {
1609 return -4 /*unImp*/;
1610 }
1611
1612 /*
1613 * SecCmsSignerInfoIncludeCerts - set cert chain inclusion mode for this signer
1614 */
1615 OSStatus
1616 SecCmsSignerInfoIncludeCerts(SecCmsSignerInfoRef signerinfo, SecCmsCertChainMode cm, SECCertUsage usage)
1617 {
1618 if (signerinfo->cert == NULL) {
1619 return SECFailure;
1620 }
1621
1622 /* don't leak if we get called twice */
1623 if (signerinfo->certList != NULL) {
1624 CFRelease(signerinfo->certList);
1625 signerinfo->certList = NULL;
1626 }
1627
1628 switch (cm) {
1629 case SecCmsCMNone:
1630 signerinfo->certList = NULL;
1631 break;
1632 case SecCmsCMCertOnly:
1633 signerinfo->certList = CERT_CertListFromCert(signerinfo->cert);
1634 break;
1635 case SecCmsCMCertChain:
1636 signerinfo->certList = CERT_CertChainFromCert(signerinfo->cert, usage, PR_FALSE, PR_FALSE);
1637 break;
1638 case SecCmsCMCertChainWithRoot:
1639 signerinfo->certList = CERT_CertChainFromCert(signerinfo->cert, usage, PR_TRUE, PR_FALSE);
1640 break;
1641 case SecCmsCMCertChainWithRootOrFail:
1642 signerinfo->certList = CERT_CertChainFromCert(signerinfo->cert, usage, PR_TRUE, PR_TRUE);
1643 break;
1644 }
1645
1646 if (cm != SecCmsCMNone && signerinfo->certList == NULL) {
1647 return SECFailure;
1648 }
1649
1650 return SECSuccess;
1651 }