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/
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.
12 * The Original Code is the Netscape security libraries.
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
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
35 * CMS signerInfo methods.
38 #include <Security/SecCmsSignerInfo.h>
39 #include "SecSMIMEPriv.h"
48 #include <security_asn1/secasn1.h>
49 #include <security_asn1/secerr.h>
50 #include <Security/SecKeychain.h>
51 #include <Security/SecIdentity.h>
52 #include <Security/SecCertificatePriv.h>
53 #include <Security/SecKeyPriv.h>
54 #include <CoreFoundation/CFTimeZone.h>
55 #include <utilities/SecCFWrappers.h>
56 #include <AssertMacros.h>
57 #include <CoreServices/../Frameworks/CarbonCore.framework/Headers/MacErrors.h>
58 #include <Security/SecPolicyPriv.h>
59 #include <Security/SecItem.h>
61 #include "tsaSupport.h"
62 #include "tsaSupportPriv.h"
66 #define HIDIGIT(v) (((v) / 10) + '0')
67 #define LODIGIT(v) (((v) % 10) + '0')
69 #define ISDIGIT(dig) (((dig) >= '0') && ((dig) <= '9'))
70 #define CAPTURE(var,p,label) \
72 if (!ISDIGIT((p)[0]) || !ISDIGIT((p)[1])) goto label; \
73 (var) = ((p)[0] - '0') * 10 + ((p)[1] - '0'); \
77 #define SIGINFO_DEBUG 1
81 #define dprintf(args...) fprintf(stderr, args)
83 #define dprintf(args...)
87 #define dprintfRC(args...) dprintf(args)
89 #define dprintfRC(args...)
93 DER_UTCTimeToCFDate(const CSSM_DATA_PTR utcTime
, CFAbsoluteTime
*date
)
95 CFGregorianDate gdate
;
96 char *string
= (char *)utcTime
->Data
;
97 long year
, month
, mday
, hour
, minute
, second
, hourOff
, minOff
;
98 CFTimeZoneRef timeZone
;
100 /* Verify time is formatted properly and capture information */
104 CAPTURE(year
,string
+0,loser
);
106 /* ASSUME that year # is in the 2000's, not the 1900's */
109 CAPTURE(month
,string
+2,loser
);
110 if ((month
== 0) || (month
> 12)) goto loser
;
111 CAPTURE(mday
,string
+4,loser
);
112 if ((mday
== 0) || (mday
> 31)) goto loser
;
113 CAPTURE(hour
,string
+6,loser
);
114 if (hour
> 23) goto loser
;
115 CAPTURE(minute
,string
+8,loser
);
116 if (minute
> 59) goto loser
;
117 if (ISDIGIT(string
[10])) {
118 CAPTURE(second
,string
+10,loser
);
119 if (second
> 59) goto loser
;
122 if (string
[10] == '+') {
123 CAPTURE(hourOff
,string
+11,loser
);
124 if (hourOff
> 23) goto loser
;
125 CAPTURE(minOff
,string
+13,loser
);
126 if (minOff
> 59) goto loser
;
127 } else if (string
[10] == '-') {
128 CAPTURE(hourOff
,string
+11,loser
);
129 if (hourOff
> 23) goto loser
;
131 CAPTURE(minOff
,string
+13,loser
);
132 if (minOff
> 59) goto loser
;
134 } else if (string
[10] != 'Z') {
138 gdate
.year
= (SInt32
)(year
+ 1900);
142 gdate
.minute
= minute
;
143 gdate
.second
= second
;
145 if (hourOff
== 0 && minOff
== 0)
146 timeZone
= NULL
; /* GMT */
149 timeZone
= CFTimeZoneCreateWithTimeIntervalFromGMT(NULL
, (hourOff
* 60 + minOff
) * 60);
152 *date
= CFGregorianDateGetAbsoluteTime(gdate
, timeZone
);
163 DER_CFDateToUTCTime(CFAbsoluteTime date
, CSSM_DATA_PTR utcTime
)
165 CFGregorianDate gdate
= CFAbsoluteTimeGetGregorianDate(date
, NULL
/* GMT */);
169 utcTime
->Length
= 13;
170 utcTime
->Data
= d
= PORT_Alloc(13);
174 /* UTC time does not handle the years before 1950 */
175 if (gdate
.year
< 1950)
178 /* remove the century since it's added to the year by the
179 CFAbsoluteTimeGetGregorianDate routine, but is not needed for UTC time */
181 second
= gdate
.second
+ 0.5;
183 d
[0] = HIDIGIT(gdate
.year
);
184 d
[1] = LODIGIT(gdate
.year
);
185 d
[2] = HIDIGIT(gdate
.month
);
186 d
[3] = LODIGIT(gdate
.month
);
187 d
[4] = HIDIGIT(gdate
.day
);
188 d
[5] = LODIGIT(gdate
.day
);
189 d
[6] = HIDIGIT(gdate
.hour
);
190 d
[7] = LODIGIT(gdate
.hour
);
191 d
[8] = HIDIGIT(gdate
.minute
);
192 d
[9] = LODIGIT(gdate
.minute
);
193 d
[10] = HIDIGIT(second
);
194 d
[11] = LODIGIT(second
);
199 /* =============================================================================
203 nss_cmssignerinfo_create(SecCmsMessageRef cmsg
, SecCmsSignerIDSelector type
, SecCertificateRef cert
, CSSM_DATA_PTR subjKeyID
, SecPublicKeyRef pubKey
, SecPrivateKeyRef signingKey
, SECOidTag digestalgtag
);
206 SecCmsSignerInfoCreateWithSubjKeyID(SecCmsMessageRef cmsg
, CSSM_DATA_PTR subjKeyID
, SecPublicKeyRef pubKey
, SecPrivateKeyRef signingKey
, SECOidTag digestalgtag
)
208 return nss_cmssignerinfo_create(cmsg
, SecCmsSignerIDSubjectKeyID
, NULL
, subjKeyID
, pubKey
, signingKey
, digestalgtag
);
212 SecCmsSignerInfoCreate(SecCmsMessageRef cmsg
, SecIdentityRef identity
, SECOidTag digestalgtag
)
214 SecCmsSignerInfoRef signerInfo
= NULL
;
215 SecCertificateRef cert
= NULL
;
216 SecPrivateKeyRef signingKey
= NULL
;
217 CFDictionaryRef keyAttrs
= NULL
;
219 if (SecIdentityCopyCertificate(identity
, &cert
))
221 if (SecIdentityCopyPrivateKey(identity
, &signingKey
))
224 /* In some situations, the "Private Key" in the identity is actually a public key. */
225 keyAttrs
= SecKeyCopyAttributes(signingKey
);
228 CFTypeRef
class = CFDictionaryGetValue(keyAttrs
, kSecAttrKeyClass
);
229 if (!class || (CFGetTypeID(class) != CFStringGetTypeID()) || !CFEqual(class, kSecAttrKeyClassPrivate
))
233 signerInfo
= nss_cmssignerinfo_create(cmsg
, SecCmsSignerIDIssuerSN
, cert
, NULL
, NULL
, signingKey
, digestalgtag
);
239 CFRelease(signingKey
);
247 nss_cmssignerinfo_create(SecCmsMessageRef cmsg
, SecCmsSignerIDSelector type
, SecCertificateRef cert
, CSSM_DATA_PTR subjKeyID
, SecPublicKeyRef pubKey
, SecPrivateKeyRef signingKey
, SECOidTag digestalgtag
)
250 SecCmsSignerInfoRef signerinfo
;
256 mark
= PORT_ArenaMark(poolp
);
258 signerinfo
= (SecCmsSignerInfoRef
)PORT_ArenaZAlloc(poolp
, sizeof(SecCmsSignerInfo
));
259 if (signerinfo
== NULL
) {
260 PORT_ArenaRelease(poolp
, mark
);
265 signerinfo
->cmsg
= cmsg
;
268 case SecCmsSignerIDIssuerSN
:
269 signerinfo
->signerIdentifier
.identifierType
= SecCmsSignerIDIssuerSN
;
270 if ((signerinfo
->cert
= CERT_DupCertificate(cert
)) == NULL
)
272 if ((signerinfo
->signerIdentifier
.id
.issuerAndSN
= CERT_GetCertIssuerAndSN(poolp
, cert
)) == NULL
)
274 dprintfRC("nss_cmssignerinfo_create: SecCmsSignerIDIssuerSN: cert.rc %d\n",
275 (int)CFGetRetainCount(signerinfo
->cert
));
277 case SecCmsSignerIDSubjectKeyID
:
278 signerinfo
->signerIdentifier
.identifierType
= SecCmsSignerIDSubjectKeyID
;
279 PORT_Assert(subjKeyID
);
282 signerinfo
->signerIdentifier
.id
.subjectKeyID
= PORT_ArenaNew(poolp
, CSSM_DATA
);
283 if (SECITEM_CopyItem(poolp
, signerinfo
->signerIdentifier
.id
.subjectKeyID
,
287 signerinfo
->pubKey
= SECKEY_CopyPublicKey(pubKey
);
288 if (!signerinfo
->pubKey
)
298 signerinfo
->signingKey
= SECKEY_CopyPrivateKey(signingKey
);
299 if (!signerinfo
->signingKey
)
302 /* set version right now */
303 version
= SEC_CMS_SIGNER_INFO_VERSION_ISSUERSN
;
304 /* RFC2630 5.3 "version is the syntax version number. If the .... " */
305 if (signerinfo
->signerIdentifier
.identifierType
== SecCmsSignerIDSubjectKeyID
)
306 version
= SEC_CMS_SIGNER_INFO_VERSION_SUBJKEY
;
307 (void)SEC_ASN1EncodeInteger(poolp
, &(signerinfo
->version
), (long)version
);
309 if (SECOID_SetAlgorithmID(poolp
, &signerinfo
->digestAlg
, digestalgtag
, NULL
) != SECSuccess
)
312 PORT_ArenaUnmark(poolp
, mark
);
316 PORT_ArenaRelease(poolp
, mark
);
321 * SecCmsSignerInfoDestroy - destroy a SignerInfo data structure
324 SecCmsSignerInfoDestroy(SecCmsSignerInfoRef si
)
326 if (si
->cert
!= NULL
) {
327 dprintfRC("SecCmsSignerInfoDestroy top: certp %p cert.rc %d\n",
328 si
->cert
, (int)CFGetRetainCount(si
->cert
));
329 CERT_DestroyCertificate(si
->cert
);
331 if (si
->certList
!= NULL
) {
332 dprintfRC("SecCmsSignerInfoDestroy top: certList.rc %d\n",
333 (int)CFGetRetainCount(si
->certList
));
334 CFRelease(si
->certList
);
336 if (si
->timestampCertList
!= NULL
) {
337 dprintfRC("SecCmsSignerInfoDestroy top: timestampCertList.rc %d\n",
338 (int)CFGetRetainCount(si
->timestampCertList
));
339 CFRelease(si
->timestampCertList
);
341 if (si
->timestampCert
!= NULL
) {
342 dprintfRC("SecCmsSignerInfoDestroy top: timestampCert.rc %d\n",
343 (int)CFGetRetainCount(si
->timestampCert
));
344 CFRelease(si
->timestampCert
);
346 if (si
->hashAgilityAttrValue
!= NULL
) {
347 dprintfRC("SecCmsSignerInfoDestroy top: hashAgilityAttrValue.rc %d\n",
348 (int)CFGetRetainCount(si
->hashAgilityAttrValue
));
349 CFRelease(si
->hashAgilityAttrValue
);
351 if (si
->hashAgilityV2AttrValues
!= NULL
) {
352 dprintfRC("SecCmsSignerInfoDestroy top: hashAgilityV2AttrValues.rc %d\n",
353 (int)CFGetRetainCount(si
->hashAgilityV2AttrValues
));
354 CFRelease(si
->hashAgilityV2AttrValues
);
356 /* XXX storage ??? */
360 * SecCmsSignerInfoSign - sign something
364 SecCmsSignerInfoSign(SecCmsSignerInfoRef signerinfo
, CSSM_DATA_PTR digest
, CSSM_DATA_PTR contentType
)
366 SecCertificateRef cert
;
367 SecPrivateKeyRef privkey
= NULL
;
368 SECOidTag digestalgtag
;
369 SECOidTag pubkAlgTag
;
370 CSSM_DATA signature
= { 0 };
372 PLArenaPool
*poolp
, *tmppoolp
= NULL
;
373 const SECAlgorithmID
*algID
;
374 SECAlgorithmID freeAlgID
;
375 //CERTSubjectPublicKeyInfo *spki;
377 PORT_Assert (digest
!= NULL
);
379 poolp
= signerinfo
->cmsg
->poolp
;
381 switch (signerinfo
->signerIdentifier
.identifierType
) {
382 case SecCmsSignerIDIssuerSN
:
383 privkey
= signerinfo
->signingKey
;
384 signerinfo
->signingKey
= NULL
;
385 cert
= signerinfo
->cert
;
386 if (SecCertificateGetAlgorithmID(cert
,&algID
)) {
387 PORT_SetError(SEC_ERROR_INVALID_ALGORITHM
);
391 case SecCmsSignerIDSubjectKeyID
:
392 privkey
= signerinfo
->signingKey
;
393 signerinfo
->signingKey
= NULL
;
395 spki
= SECKEY_CreateSubjectPublicKeyInfo(signerinfo
->pubKey
);
396 SECKEY_DestroyPublicKey(signerinfo
->pubKey
);
397 signerinfo
->pubKey
= NULL
;
398 SECOID_CopyAlgorithmID(NULL
, &freeAlgID
, &spki
->algorithm
);
399 SECKEY_DestroySubjectPublicKeyInfo(spki
);
403 #if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR))
404 if (SecKeyGetAlgorithmID(signerinfo
->pubKey
,&algID
)) {
406 /* TBD: Unify this code. Currently, iOS has an incompatible
407 * SecKeyGetAlgorithmID implementation. */
410 PORT_SetError(SEC_ERROR_INVALID_ALGORITHM
);
413 CFRelease(signerinfo
->pubKey
);
414 signerinfo
->pubKey
= NULL
;
418 PORT_SetError(SEC_ERROR_UNSUPPORTED_MESSAGE_TYPE
);
421 digestalgtag
= SecCmsSignerInfoGetDigestAlgTag(signerinfo
);
423 * XXX I think there should be a cert-level interface for this,
424 * so that I do not have to know about subjectPublicKeyInfo...
426 pubkAlgTag
= SECOID_GetAlgorithmTag(algID
);
427 if (signerinfo
->signerIdentifier
.identifierType
== SecCmsSignerIDSubjectKeyID
) {
428 SECOID_DestroyAlgorithmID(&freeAlgID
, PR_FALSE
);
433 /* Fortezza MISSI have weird signature formats.
434 * Map them to standard DSA formats
436 pubkAlgTag
= PK11_FortezzaMapSig(pubkAlgTag
);
439 if (signerinfo
->authAttr
!= NULL
) {
440 CSSM_DATA encoded_attrs
;
442 /* find and fill in the message digest attribute. */
443 rv
= SecCmsAttributeArraySetAttr(poolp
, &(signerinfo
->authAttr
),
444 SEC_OID_PKCS9_MESSAGE_DIGEST
, digest
, PR_FALSE
);
445 if (rv
!= SECSuccess
)
448 if (contentType
!= NULL
) {
449 /* if the caller wants us to, find and fill in the content type attribute. */
450 rv
= SecCmsAttributeArraySetAttr(poolp
, &(signerinfo
->authAttr
),
451 SEC_OID_PKCS9_CONTENT_TYPE
, contentType
, PR_FALSE
);
452 if (rv
!= SECSuccess
)
456 if ((tmppoolp
= PORT_NewArena (1024)) == NULL
) {
457 PORT_SetError(SEC_ERROR_NO_MEMORY
);
462 * Before encoding, reorder the attributes so that when they
463 * are encoded, they will be conforming DER, which is required
464 * to have a specific order and that is what must be used for
465 * the hash/signature. We do this here, rather than building
466 * it into EncodeAttributes, because we do not want to do
467 * such reordering on incoming messages (which also uses
468 * EncodeAttributes) or our old signatures (and other "broken"
469 * implementations) will not verify. So, we want to guarantee
470 * that we send out good DER encodings of attributes, but not
471 * to expect to receive them.
473 if (SecCmsAttributeArrayReorder(signerinfo
->authAttr
) != SECSuccess
)
476 encoded_attrs
.Data
= NULL
;
477 encoded_attrs
.Length
= 0;
478 if (SecCmsAttributeArrayEncode(tmppoolp
, &(signerinfo
->authAttr
),
479 &encoded_attrs
) == NULL
)
482 rv
= SEC_SignData(&signature
, encoded_attrs
.Data
, (int)encoded_attrs
.Length
,
483 privkey
, digestalgtag
, pubkAlgTag
);
484 PORT_FreeArena(tmppoolp
, PR_FALSE
); /* awkward memory management :-( */
487 rv
= SGN_Digest(privkey
, digestalgtag
, pubkAlgTag
, &signature
, digest
);
489 SECKEY_DestroyPrivateKey(privkey
);
492 if (rv
!= SECSuccess
)
495 if (SECITEM_CopyItem(poolp
, &(signerinfo
->encDigest
), &signature
)
499 SECITEM_FreeItem(&signature
, PR_FALSE
);
501 if(pubkAlgTag
== SEC_OID_EC_PUBLIC_KEY
) {
503 * RFC 3278 section section 2.1.1 states that the signatureAlgorithm
504 * field contains the full ecdsa-with-SHA1 OID, not plain old ecPublicKey
505 * as would appear in other forms of signed datas. However Microsoft doesn't
506 * do this, it puts ecPublicKey there, and if we put ecdsa-with-SHA1 there,
507 * MS can't verify - presumably because it takes the digest of the digest
508 * before feeding it to ECDSA.
509 * We handle this with a preference; default if it's not there is
510 * "Microsoft compatibility mode".
512 if(!SecCmsMsEcdsaCompatMode()) {
513 pubkAlgTag
= SEC_OID_ECDSA_WithSHA1
;
515 /* else violating the spec for compatibility */
518 if (SECOID_SetAlgorithmID(poolp
, &(signerinfo
->digestEncAlg
), pubkAlgTag
,
525 if (signature
.Length
!= 0)
526 SECITEM_FreeItem (&signature
, PR_FALSE
);
528 SECKEY_DestroyPrivateKey(privkey
);
530 PORT_FreeArena(tmppoolp
, PR_FALSE
);
535 SecCmsSignerInfoVerifyCertificate(SecCmsSignerInfoRef signerinfo
, SecKeychainRef keychainOrArray
,
536 CFTypeRef policies
, SecTrustRef
*trustRef
)
538 SecCertificateRef cert
;
539 CFAbsoluteTime stime
;
541 CSSM_DATA_PTR
*otherCerts
;
543 if ((cert
= SecCmsSignerInfoGetSigningCertificate(signerinfo
, keychainOrArray
)) == NULL
) {
544 dprintf("SecCmsSignerInfoVerifyCertificate: no signing cert\n");
545 signerinfo
->verificationStatus
= SecCmsVSSigningCertNotFound
;
550 * Get and convert the signing time; if available, it will be used
551 * both on the cert verification and for importing the sender
554 CFTypeRef timeStampPolicies
=SecPolicyCreateAppleTimeStampingAndRevocationPolicies(policies
);
555 if (SecCmsSignerInfoGetTimestampTimeWithPolicy(signerinfo
, timeStampPolicies
, &stime
) != SECSuccess
)
556 if (SecCmsSignerInfoGetSigningTime(signerinfo
, &stime
) != SECSuccess
)
557 stime
= CFAbsoluteTimeGetCurrent();
558 CFReleaseSafe(timeStampPolicies
);
560 rv
= SecCmsSignedDataRawCerts(signerinfo
->sigd
, &otherCerts
);
564 rv
= CERT_VerifyCert(keychainOrArray
, cert
, otherCerts
, policies
, stime
, trustRef
);
565 dprintfRC("SecCmsSignerInfoVerifyCertificate after vfy: certp %p cert.rc %d\n",
566 cert
, (int)CFGetRetainCount(cert
));
569 if (PORT_GetError() == SEC_ERROR_UNTRUSTED_CERT
)
571 /* Signature or digest level verificationStatus errors should supercede certificate level errors, so only change the verificationStatus if the status was GoodSignature. */
572 if (signerinfo
->verificationStatus
== SecCmsVSGoodSignature
)
573 signerinfo
->verificationStatus
= SecCmsVSSigningCertNotTrusted
;
576 /* FIXME isn't this leaking the cert? */
577 dprintf("SecCmsSignerInfoVerifyCertificate: CertVerify rtn %d\n", (int)rv
);
581 static void debugShowSigningCertificate(SecCmsSignerInfoRef signerinfo
)
584 CFStringRef cn
= SecCmsSignerInfoGetSignerCommonName(signerinfo
);
587 char *ccn
= cfStringToChar(cn
);
590 dprintf("SecCmsSignerInfoVerify: cn: %s\n", ccn
);
599 * SecCmsSignerInfoVerify - verify the signature of a single SignerInfo
601 * Just verifies the signature. The assumption is that verification of the certificate
605 SecCmsSignerInfoVerify(SecCmsSignerInfoRef signerinfo
, CSSM_DATA_PTR digest
, CSSM_DATA_PTR contentType
)
607 return SecCmsSignerInfoVerifyWithPolicy(signerinfo
,NULL
, digest
,contentType
);
611 SecCmsSignerInfoVerifyWithPolicy(SecCmsSignerInfoRef signerinfo
,CFTypeRef timeStampPolicy
, CSSM_DATA_PTR digest
, CSSM_DATA_PTR contentType
)
613 SecPublicKeyRef publickey
= NULL
;
614 SecCmsAttribute
*attr
= NULL
;
615 CSSM_DATA encoded_attrs
;
616 SecCertificateRef cert
= NULL
;
617 SecCmsVerificationStatus vs
= SecCmsVSUnverified
;
618 PLArenaPool
*poolp
= NULL
;
619 SECOidTag digestAlgTag
, digestEncAlgTag
;
621 if (signerinfo
== NULL
)
624 /* SecCmsSignerInfoGetSigningCertificate will fail if 2nd parm is NULL and */
625 /* cert has not been verified */
626 if ((cert
= SecCmsSignerInfoGetSigningCertificate(signerinfo
, NULL
)) == NULL
) {
627 dprintf("SecCmsSignerInfoVerify: no signing cert\n");
628 vs
= SecCmsVSSigningCertNotFound
;
632 dprintfRC("SecCmsSignerInfoVerify top: cert %p cert.rc %d\n", cert
, (int)CFGetRetainCount(cert
));
634 debugShowSigningCertificate(signerinfo
);
637 if ((status
= SecCertificateCopyPublicKey(cert
, &publickey
))) {
638 syslog(LOG_ERR
, "SecCmsSignerInfoVerifyWithPolicy: copy public key failed %d", (int)status
);
639 vs
= SecCmsVSProcessingError
;
643 digestAlgTag
= SECOID_GetAlgorithmTag(&(signerinfo
->digestAlg
));
644 digestEncAlgTag
= SECOID_GetAlgorithmTag(&(signerinfo
->digestEncAlg
));
647 * Gross hack necessitated by RFC 3278 section 2.1.1, which states
648 * that the signature algorithm (here, digestEncAlg) contains ecdsa_with-SHA1,
649 * *not* (as in all other algorithms) the raw signature algorithm, e.g.
650 * pkcs1RSAEncryption.
652 if(digestEncAlgTag
== SEC_OID_ECDSA_WithSHA1
) {
653 digestEncAlgTag
= SEC_OID_EC_PUBLIC_KEY
;
656 if (!SecCmsArrayIsEmpty((void **)signerinfo
->authAttr
)) {
661 * RFC2630 sez that if there are any authenticated attributes,
662 * then there must be one for content type which matches the
663 * content type of the content being signed, and there must
664 * be one for message digest which matches our message digest.
665 * So check these things first.
667 if ((attr
= SecCmsAttributeArrayFindAttrByOidTag(signerinfo
->authAttr
,
668 SEC_OID_PKCS9_CONTENT_TYPE
, PR_TRUE
)) == NULL
)
670 vs
= SecCmsVSMalformedSignature
;
674 if (SecCmsAttributeCompareValue(attr
, contentType
) == PR_FALSE
) {
675 vs
= SecCmsVSMalformedSignature
;
683 if ((attr
= SecCmsAttributeArrayFindAttrByOidTag(signerinfo
->authAttr
, SEC_OID_PKCS9_MESSAGE_DIGEST
, PR_TRUE
)) == NULL
)
685 vs
= SecCmsVSMalformedSignature
;
688 if (SecCmsAttributeCompareValue(attr
, digest
) == PR_FALSE
) {
689 vs
= SecCmsVSDigestMismatch
;
693 if ((poolp
= PORT_NewArena (1024)) == NULL
) {
694 vs
= SecCmsVSProcessingError
;
701 * The signature is based on a digest of the DER-encoded authenticated
702 * attributes. So, first we encode and then we digest/verify.
703 * we trust the decoder to have the attributes in the right (sorted) order
705 encoded_attrs
.Data
= NULL
;
706 encoded_attrs
.Length
= 0;
708 if (SecCmsAttributeArrayEncode(poolp
, &(signerinfo
->authAttr
), &encoded_attrs
) == NULL
||
709 encoded_attrs
.Data
== NULL
|| encoded_attrs
.Length
== 0)
711 vs
= SecCmsVSProcessingError
;
715 vs
= (VFY_VerifyData (encoded_attrs
.Data
, (int)encoded_attrs
.Length
,
716 publickey
, &(signerinfo
->encDigest
),
717 digestAlgTag
, digestEncAlgTag
,
718 signerinfo
->cmsg
->pwfn_arg
) != SECSuccess
) ? SecCmsVSBadSignature
: SecCmsVSGoodSignature
;
720 dprintf("VFY_VerifyData (authenticated attributes): %s\n",
721 (vs
== SecCmsVSGoodSignature
)?"SecCmsVSGoodSignature":"SecCmsVSBadSignature");
723 PORT_FreeArena(poolp
, PR_FALSE
); /* awkward memory management :-( */
728 /* No authenticated attributes. The signature is based on the plain message digest. */
729 sig
= &(signerinfo
->encDigest
);
730 if (sig
->Length
== 0)
733 vs
= (VFY_VerifyDigest(digest
, publickey
, sig
,
734 digestAlgTag
, digestEncAlgTag
,
735 signerinfo
->cmsg
->pwfn_arg
) != SECSuccess
) ? SecCmsVSBadSignature
: SecCmsVSGoodSignature
;
737 dprintf("VFY_VerifyData (plain message digest): %s\n",
738 (vs
== SecCmsVSGoodSignature
)?"SecCmsVSGoodSignature":"SecCmsVSBadSignature");
741 if (!SecCmsArrayIsEmpty((void **)signerinfo
->unAuthAttr
))
743 dprintf("found an unAuthAttr\n");
744 OSStatus rux
= SecCmsSignerInfoVerifyUnAuthAttrsWithPolicy(signerinfo
,timeStampPolicy
);
745 dprintf("SecCmsSignerInfoVerifyUnAuthAttrs Status: %ld\n", (long)rux
);
751 if (vs
== SecCmsVSBadSignature
) {
753 * XXX Change the generic error into our specific one, because
754 * in that case we get a better explanation out of the Security
755 * Advisor. This is really a bug in our error strings (the
756 * "generic" error has a lousy/wrong message associated with it
757 * which assumes the signature verification was done for the
758 * purposes of checking the issuer signature on a certificate)
759 * but this is at least an easy workaround and/or in the
760 * Security Advisor, which specifically checks for the error
761 * SEC_ERROR_PKCS7_BAD_SIGNATURE and gives more explanation
762 * in that case but does not similarly check for
763 * SEC_ERROR_BAD_SIGNATURE. It probably should, but then would
764 * probably say the wrong thing in the case that it *was* the
765 * certificate signature check that failed during the cert
766 * verification done above. Our error handling is really a mess.
768 if (PORT_GetError() == SEC_ERROR_BAD_SIGNATURE
)
769 PORT_SetError(SEC_ERROR_PKCS7_BAD_SIGNATURE
);
772 if (publickey
!= NULL
)
773 CFRelease(publickey
);
775 signerinfo
->verificationStatus
= vs
;
776 dprintfRC("SecCmsSignerInfoVerify end: cerp %p cert.rc %d\n",
777 cert
, (int)CFGetRetainCount(cert
));
779 dprintf("verificationStatus: %d\n", vs
);
781 return (vs
== SecCmsVSGoodSignature
) ? SECSuccess
: SECFailure
;
784 if (publickey
!= NULL
)
785 SECKEY_DestroyPublicKey (publickey
);
787 dprintf("verificationStatus2: %d\n", vs
);
788 signerinfo
->verificationStatus
= vs
;
790 PORT_SetError (SEC_ERROR_PKCS7_BAD_SIGNATURE
);
795 SecCmsSignerInfoVerifyUnAuthAttrs(SecCmsSignerInfoRef signerinfo
) {
796 return SecCmsSignerInfoVerifyUnAuthAttrsWithPolicy(signerinfo
, NULL
);
800 SecCmsSignerInfoVerifyUnAuthAttrsWithPolicy(SecCmsSignerInfoRef signerinfo
,CFTypeRef timeStampPolicy
)
803 unAuthAttr is an array of attributes; we expect to
804 see just one: the timestamp blob. If we have an unAuthAttr,
805 but don't see a timestamp, return an error since we have
806 no other cases where this would be present.
809 SecCmsAttribute
*attr
= NULL
;
810 OSStatus status
= SECFailure
;
812 require(signerinfo
, xit
);
813 attr
= SecCmsAttributeArrayFindAttrByOidTag(signerinfo
->unAuthAttr
,
814 SEC_OID_PKCS9_TIMESTAMP_TOKEN
, PR_TRUE
);
817 status
= errSecTimestampMissing
;
821 dprintf("found an id-ct-TSTInfo\n");
822 // Don't check the nonce in this case
823 status
= decodeTimeStampTokenWithPolicy(signerinfo
, timeStampPolicy
, (attr
->values
)[0], &signerinfo
->encDigest
, 0);
829 SecCmsSignerInfoGetEncDigest(SecCmsSignerInfoRef signerinfo
)
831 return &signerinfo
->encDigest
;
834 SecCmsVerificationStatus
835 SecCmsSignerInfoGetVerificationStatus(SecCmsSignerInfoRef signerinfo
)
837 return signerinfo
->verificationStatus
;
841 SecCmsSignerInfoGetDigestAlg(SecCmsSignerInfoRef signerinfo
)
843 return SECOID_FindOID (&(signerinfo
->digestAlg
.algorithm
));
847 SecCmsSignerInfoGetDigestAlgTag(SecCmsSignerInfoRef signerinfo
)
851 algdata
= SECOID_FindOID (&(signerinfo
->digestAlg
.algorithm
));
853 return algdata
->offset
;
855 return SEC_OID_UNKNOWN
;
859 SecCmsSignerInfoGetCertList(SecCmsSignerInfoRef signerinfo
)
861 dprintfRC("SecCmsSignerInfoGetCertList: certList.rc %d\n",
862 (int)CFGetRetainCount(signerinfo
->certList
));
863 return signerinfo
->certList
;
867 SecCmsSignerInfoGetTimestampCertList(SecCmsSignerInfoRef signerinfo
)
869 dprintfRC("SecCmsSignerInfoGetTimestampCertList: timestampCertList.rc %d\n",
870 (int)CFGetRetainCount(signerinfo
->timestampCertList
));
871 return signerinfo
->timestampCertList
;
875 SecCmsSignerInfoGetTimestampSigningCert(SecCmsSignerInfoRef signerinfo
)
877 dprintfRC("SecCmsSignerInfoGetTimestampSigningCert: timestampCert.rc %d\n",
878 (int)CFGetRetainCount(signerinfo
->timestampCert
));
879 return signerinfo
->timestampCert
;
883 SecCmsSignerInfoGetVersion(SecCmsSignerInfoRef signerinfo
)
885 unsigned long version
;
887 /* always take apart the CSSM_DATA */
888 if (SEC_ASN1DecodeInteger(&(signerinfo
->version
), &version
) != SECSuccess
)
895 * SecCmsSignerInfoGetSigningTime - return the signing time,
896 * in UTCTime format, of a CMS signerInfo.
898 * sinfo - signerInfo data for this signer
900 * Returns a pointer to XXXX (what?)
901 * A return value of NULL is an error.
904 SecCmsSignerInfoGetSigningTime(SecCmsSignerInfoRef sinfo
, CFAbsoluteTime
*stime
)
906 SecCmsAttribute
*attr
;
912 if (sinfo
->signingTime
!= 0) {
913 *stime
= sinfo
->signingTime
; /* cached copy */
917 attr
= SecCmsAttributeArrayFindAttrByOidTag(sinfo
->authAttr
, SEC_OID_PKCS9_SIGNING_TIME
, PR_TRUE
);
918 /* XXXX multi-valued attributes NIH */
919 if (attr
== NULL
|| (value
= SecCmsAttributeGetValue(attr
)) == NULL
)
920 return errSecSigningTimeMissing
;
921 if (DER_UTCTimeToCFDate(value
, stime
) != SECSuccess
)
922 return errSecSigningTimeMissing
;
923 sinfo
->signingTime
= *stime
; /* make cached copy */
928 SecCmsSignerInfoGetTimestampTime(SecCmsSignerInfoRef sinfo
, CFAbsoluteTime
*stime
)
930 return SecCmsSignerInfoGetTimestampTimeWithPolicy(sinfo
, NULL
, stime
);
934 SecCmsSignerInfoGetTimestampTimeWithPolicy(SecCmsSignerInfoRef sinfo
, CFTypeRef timeStampPolicy
, CFAbsoluteTime
*stime
)
936 OSStatus status
= paramErr
;
938 require(sinfo
&& stime
, xit
);
940 if (sinfo
->timestampTime
!= 0)
942 *stime
= sinfo
->timestampTime
; /* cached copy */
946 // A bit heavyweight if haven't already called verify
947 status
= SecCmsSignerInfoVerifyUnAuthAttrsWithPolicy(sinfo
,timeStampPolicy
);
948 *stime
= sinfo
->timestampTime
;
955 @abstract Return the data in the signed Codesigning Hash Agility attribute.
956 @param sinfo SignerInfo data for this signer, pointer to a CFDataRef for attribute value
957 @discussion Returns a CFDataRef containing the value of the attribute
958 @result A return value of errSecInternal is an error trying to look up the oid.
959 A status value of success with null result data indicates the attribute was not present.
962 SecCmsSignerInfoGetAppleCodesigningHashAgility(SecCmsSignerInfoRef sinfo
, CFDataRef
*sdata
)
964 SecCmsAttribute
*attr
;
967 if (sinfo
== NULL
|| sdata
== NULL
)
972 if (sinfo
->hashAgilityAttrValue
!= NULL
) {
973 *sdata
= sinfo
->hashAgilityAttrValue
; /* cached copy */
977 attr
= SecCmsAttributeArrayFindAttrByOidTag(sinfo
->authAttr
, SEC_OID_APPLE_HASH_AGILITY
, PR_TRUE
);
979 /* attribute not found */
980 if (attr
== NULL
|| (value
= SecCmsAttributeGetValue(attr
)) == NULL
)
983 sinfo
->hashAgilityAttrValue
= CFDataCreate(NULL
, value
->Data
, value
->Length
); /* make cached copy */
984 if (sinfo
->hashAgilityAttrValue
) {
985 *sdata
= sinfo
->hashAgilityAttrValue
;
988 return errSecAllocate
;
991 /* AgileHash ::= SEQUENCE {
992 hashType OBJECT IDENTIFIER,
993 hashValues OCTET STRING }
996 SecAsn1Item digestOID
;
997 SecAsn1Item digestValue
;
1000 static const SecAsn1Template CMSAppleAgileHashTemplate
[] = {
1001 { SEC_ASN1_SEQUENCE
,
1002 0, NULL
, sizeof(CMSAppleAgileHash
) },
1003 { SEC_ASN1_OBJECT_ID
,
1004 offsetof(CMSAppleAgileHash
, digestOID
), },
1005 { SEC_ASN1_OCTET_STRING
,
1006 offsetof(CMSAppleAgileHash
, digestValue
), },
1010 static OSStatus
CMSAddAgileHashToDictionary(CFMutableDictionaryRef dictionary
, SecAsn1Item
*DERAgileHash
) {
1011 PLArenaPool
*tmppoolp
= NULL
;
1012 OSStatus status
= errSecSuccess
;
1013 CMSAppleAgileHash agileHash
;
1014 CFDataRef digestValue
= NULL
;
1015 CFNumberRef digestTag
= NULL
;
1017 tmppoolp
= PORT_NewArena(1024);
1018 if (tmppoolp
== NULL
) {
1019 return errSecAllocate
;
1022 if ((status
= SEC_ASN1DecodeItem(tmppoolp
, &agileHash
, CMSAppleAgileHashTemplate
, DERAgileHash
)) != errSecSuccess
) {
1026 int64_t tag
= SECOID_FindOIDTag(&agileHash
.digestOID
);
1027 digestTag
= CFNumberCreate(NULL
, kCFNumberSInt64Type
, &tag
);
1028 digestValue
= CFDataCreate(NULL
, agileHash
.digestValue
.Data
, agileHash
.digestValue
.Length
);
1029 CFDictionaryAddValue(dictionary
, digestTag
, digestValue
);
1032 CFReleaseNull(digestValue
);
1033 CFReleaseNull(digestTag
);
1035 PORT_FreeArena(tmppoolp
, PR_FALSE
);
1042 @abstract Return the data in the signed Codesigning Hash Agility V2 attribute.
1043 @param sinfo SignerInfo data for this signer, pointer to a CFDictionaryRef for attribute values
1044 @discussion Returns a CFDictionaryRef containing the values of the attribute
1045 @result A return value of errSecInternal is an error trying to look up the oid.
1046 A status value of success with null result data indicates the attribute was not present.
1049 SecCmsSignerInfoGetAppleCodesigningHashAgilityV2(SecCmsSignerInfoRef sinfo
, CFDictionaryRef
*sdict
)
1051 SecCmsAttribute
*attr
;
1053 if (sinfo
== NULL
|| sdict
== NULL
) {
1059 if (sinfo
->hashAgilityV2AttrValues
!= NULL
) {
1060 *sdict
= sinfo
->hashAgilityV2AttrValues
; /* cached copy */
1064 attr
= SecCmsAttributeArrayFindAttrByOidTag(sinfo
->authAttr
, SEC_OID_APPLE_HASH_AGILITY_V2
, PR_TRUE
);
1066 /* attribute not found */
1071 /* attrValues SET OF AttributeValue
1072 * AttributeValue ::= ANY
1074 CSSM_DATA_PTR
*values
= attr
->values
;
1075 if (values
== NULL
) { /* There must be values */
1076 return errSecDecode
;
1079 CFMutableDictionaryRef agileHashValues
= CFDictionaryCreateMutable(NULL
, SecCmsArrayCount((void **)values
),
1080 &kCFTypeDictionaryKeyCallBacks
,
1081 &kCFTypeDictionaryValueCallBacks
);
1082 while (*values
!= NULL
) {
1083 (void)CMSAddAgileHashToDictionary(agileHashValues
, *values
++);
1085 if (CFDictionaryGetCount(agileHashValues
) != SecCmsArrayCount((void **)attr
->values
)) {
1086 CFReleaseNull(agileHashValues
);
1087 return errSecDecode
;
1090 sinfo
->hashAgilityV2AttrValues
= agileHashValues
; /* make cached copy */
1091 if (sinfo
->hashAgilityV2AttrValues
) {
1092 *sdict
= sinfo
->hashAgilityV2AttrValues
;
1095 return errSecAllocate
;
1099 * Return the signing cert of a CMS signerInfo.
1101 * the certs in the enclosing SignedData must have been imported already
1104 SecCmsSignerInfoGetSigningCertificate(SecCmsSignerInfoRef signerinfo
, SecKeychainRef keychainOrArray
)
1106 SecCertificateRef cert
;
1107 SecCmsSignerIdentifier
*sid
;
1109 CSSM_DATA_PTR
*rawCerts
;
1111 if (signerinfo
->cert
!= NULL
) {
1112 dprintfRC("SecCmsSignerInfoGetSigningCertificate top: cert %p cert.rc %d\n",
1113 signerinfo
->cert
, (int)CFGetRetainCount(signerinfo
->cert
));
1114 return signerinfo
->cert
;
1116 ortn
= SecCmsSignedDataRawCerts(signerinfo
->sigd
, &rawCerts
);
1120 dprintf("SecCmsSignerInfoGetSigningCertificate: numRawCerts %d\n",
1121 SecCmsArrayCount((void **)rawCerts
));
1124 * This cert will also need to be freed, but since we save it
1125 * in signerinfo for later, we do not want to destroy it when
1126 * we leave this function -- we let the clean-up of the entire
1127 * cinfo structure later do the destroy of this cert.
1129 sid
= &signerinfo
->signerIdentifier
;
1130 switch (sid
->identifierType
) {
1131 case SecCmsSignerIDIssuerSN
:
1132 cert
= CERT_FindCertByIssuerAndSN(keychainOrArray
, rawCerts
, signerinfo
->sigd
->certs
, signerinfo
->cmsg
->poolp
,
1133 sid
->id
.issuerAndSN
);
1135 case SecCmsSignerIDSubjectKeyID
:
1136 cert
= CERT_FindCertBySubjectKeyID(keychainOrArray
, rawCerts
, signerinfo
->sigd
->certs
, sid
->id
.subjectKeyID
);
1143 /* cert can be NULL at that point */
1144 signerinfo
->cert
= cert
; /* earmark it */
1145 dprintfRC("SecCmsSignerInfoGetSigningCertificate end: certp %p cert.rc %d\n",
1146 signerinfo
->cert
, (int)CFGetRetainCount(signerinfo
->cert
));
1152 * SecCmsSignerInfoGetSignerCommonName - return the common name of the signer
1154 * sinfo - signerInfo data for this signer
1156 * Returns a CFStringRef containing the common name of the signer.
1157 * A return value of NULL is an error.
1160 SecCmsSignerInfoGetSignerCommonName(SecCmsSignerInfoRef sinfo
)
1162 SecCertificateRef signercert
;
1163 CFStringRef commonName
= NULL
;
1165 /* will fail if cert is not verified */
1166 if ((signercert
= SecCmsSignerInfoGetSigningCertificate(sinfo
, NULL
)) == NULL
)
1169 if (errSecSuccess
!= SecCertificateCopyCommonName(signercert
, &commonName
)) {
1177 * SecCmsSignerInfoGetSignerEmailAddress - return the email address of the signer
1179 * sinfo - signerInfo data for this signer
1181 * Returns a CFStringRef containing the name of the signer.
1182 * A return value of NULL is an error.
1185 SecCmsSignerInfoGetSignerEmailAddress(SecCmsSignerInfoRef sinfo
)
1187 SecCertificateRef signercert
;
1188 CFStringRef emailAddress
= NULL
;
1190 if ((signercert
= SecCmsSignerInfoGetSigningCertificate(sinfo
, NULL
)) == NULL
)
1193 SecCertificateGetEmailAddress(signercert
, &emailAddress
);
1195 return emailAddress
;
1200 * SecCmsSignerInfoAddAuthAttr - add an attribute to the
1201 * authenticated (i.e. signed) attributes of "signerinfo".
1204 SecCmsSignerInfoAddAuthAttr(SecCmsSignerInfoRef signerinfo
, SecCmsAttribute
*attr
)
1206 return SecCmsAttributeArrayAddAttr(signerinfo
->cmsg
->poolp
, &(signerinfo
->authAttr
), attr
);
1210 * SecCmsSignerInfoAddUnauthAttr - add an attribute to the
1211 * unauthenticated attributes of "signerinfo".
1214 SecCmsSignerInfoAddUnauthAttr(SecCmsSignerInfoRef signerinfo
, SecCmsAttribute
*attr
)
1216 return SecCmsAttributeArrayAddAttr(signerinfo
->cmsg
->poolp
, &(signerinfo
->unAuthAttr
), attr
);
1220 * SecCmsSignerInfoAddSigningTime - add the signing time to the
1221 * authenticated (i.e. signed) attributes of "signerinfo".
1223 * This is expected to be included in outgoing signed
1224 * messages for email (S/MIME) but is likely useful in other situations.
1226 * This should only be added once; a second call will do nothing.
1228 * XXX This will probably just shove the current time into "signerinfo"
1229 * but it will not actually get signed until the entire item is
1230 * processed for encoding. Is this (expected to be small) delay okay?
1233 SecCmsSignerInfoAddSigningTime(SecCmsSignerInfoRef signerinfo
, CFAbsoluteTime t
)
1235 SecCmsAttribute
*attr
;
1240 poolp
= signerinfo
->cmsg
->poolp
;
1242 mark
= PORT_ArenaMark(poolp
);
1244 /* create new signing time attribute */
1245 if (DER_CFDateToUTCTime(t
, &stime
) != SECSuccess
)
1248 if ((attr
= SecCmsAttributeCreate(poolp
, SEC_OID_PKCS9_SIGNING_TIME
, &stime
, PR_FALSE
)) == NULL
) {
1249 SECITEM_FreeItem (&stime
, PR_FALSE
);
1253 SECITEM_FreeItem (&stime
, PR_FALSE
);
1255 if (SecCmsSignerInfoAddAuthAttr(signerinfo
, attr
) != SECSuccess
)
1258 PORT_ArenaUnmark (poolp
, mark
);
1263 PORT_ArenaRelease (poolp
, mark
);
1268 * SecCmsSignerInfoAddSMIMECaps - add a SMIMECapabilities attribute to the
1269 * authenticated (i.e. signed) attributes of "signerinfo".
1271 * This is expected to be included in outgoing signed
1272 * messages for email (S/MIME).
1275 SecCmsSignerInfoAddSMIMECaps(SecCmsSignerInfoRef signerinfo
)
1277 SecCmsAttribute
*attr
;
1278 CSSM_DATA_PTR smimecaps
= NULL
;
1282 poolp
= signerinfo
->cmsg
->poolp
;
1284 mark
= PORT_ArenaMark(poolp
);
1286 smimecaps
= SECITEM_AllocItem(poolp
, NULL
, 0);
1287 if (smimecaps
== NULL
)
1290 /* create new signing time attribute */
1292 // @@@ We don't do Fortezza yet.
1293 if (SecSMIMECreateSMIMECapabilities((SecArenaPoolRef
)poolp
, smimecaps
, PR_FALSE
) != SECSuccess
)
1295 if (SecSMIMECreateSMIMECapabilities(poolp
, smimecaps
,
1296 PK11_FortezzaHasKEA(signerinfo
->cert
)) != SECSuccess
)
1300 if ((attr
= SecCmsAttributeCreate(poolp
, SEC_OID_PKCS9_SMIME_CAPABILITIES
, smimecaps
, PR_TRUE
)) == NULL
)
1303 if (SecCmsSignerInfoAddAuthAttr(signerinfo
, attr
) != SECSuccess
)
1306 PORT_ArenaUnmark (poolp
, mark
);
1310 PORT_ArenaRelease (poolp
, mark
);
1315 * SecCmsSignerInfoAddSMIMEEncKeyPrefs - add a SMIMEEncryptionKeyPreferences attribute to the
1316 * authenticated (i.e. signed) attributes of "signerinfo".
1318 * This is expected to be included in outgoing signed messages for email (S/MIME).
1321 SecCmsSignerInfoAddSMIMEEncKeyPrefs(SecCmsSignerInfoRef signerinfo
, SecCertificateRef cert
, SecKeychainRef keychainOrArray
)
1323 SecCmsAttribute
*attr
;
1324 CSSM_DATA_PTR smimeekp
= NULL
;
1331 /* verify this cert for encryption */
1332 policy
= CERT_PolicyForCertUsage(certUsageEmailRecipient
);
1333 if (CERT_VerifyCert(keychainOrArray
, cert
, policy
, CFAbsoluteTimeGetCurrent(), NULL
) != SECSuccess
) {
1340 poolp
= signerinfo
->cmsg
->poolp
;
1341 mark
= PORT_ArenaMark(poolp
);
1343 smimeekp
= SECITEM_AllocItem(poolp
, NULL
, 0);
1344 if (smimeekp
== NULL
)
1347 /* create new signing time attribute */
1348 if (SecSMIMECreateSMIMEEncKeyPrefs((SecArenaPoolRef
)poolp
, smimeekp
, cert
) != SECSuccess
)
1351 if ((attr
= SecCmsAttributeCreate(poolp
, SEC_OID_SMIME_ENCRYPTION_KEY_PREFERENCE
, smimeekp
, PR_TRUE
)) == NULL
)
1354 if (SecCmsSignerInfoAddAuthAttr(signerinfo
, attr
) != SECSuccess
)
1357 PORT_ArenaUnmark (poolp
, mark
);
1361 PORT_ArenaRelease (poolp
, mark
);
1366 * SecCmsSignerInfoAddMSSMIMEEncKeyPrefs - add a SMIMEEncryptionKeyPreferences attribute to the
1367 * authenticated (i.e. signed) attributes of "signerinfo", using the OID preferred by Microsoft.
1369 * This is expected to be included in outgoing signed messages for email (S/MIME),
1370 * if compatibility with Microsoft mail clients is wanted.
1373 SecCmsSignerInfoAddMSSMIMEEncKeyPrefs(SecCmsSignerInfoRef signerinfo
, SecCertificateRef cert
, SecKeychainRef keychainOrArray
)
1375 SecCmsAttribute
*attr
;
1376 CSSM_DATA_PTR smimeekp
= NULL
;
1383 /* verify this cert for encryption */
1384 policy
= CERT_PolicyForCertUsage(certUsageEmailRecipient
);
1385 if (CERT_VerifyCert(keychainOrArray
, cert
, policy
, CFAbsoluteTimeGetCurrent(), NULL
) != SECSuccess
) {
1392 poolp
= signerinfo
->cmsg
->poolp
;
1393 mark
= PORT_ArenaMark(poolp
);
1395 smimeekp
= SECITEM_AllocItem(poolp
, NULL
, 0);
1396 if (smimeekp
== NULL
)
1399 /* create new signing time attribute */
1400 if (SecSMIMECreateMSSMIMEEncKeyPrefs((SecArenaPoolRef
)poolp
, smimeekp
, cert
) != SECSuccess
)
1403 if ((attr
= SecCmsAttributeCreate(poolp
, SEC_OID_MS_SMIME_ENCRYPTION_KEY_PREFERENCE
, smimeekp
, PR_TRUE
)) == NULL
)
1406 if (SecCmsSignerInfoAddAuthAttr(signerinfo
, attr
) != SECSuccess
)
1409 PORT_ArenaUnmark (poolp
, mark
);
1413 PORT_ArenaRelease (poolp
, mark
);
1418 * SecCmsSignerInfoAddTimeStamp - add time stamp to the
1419 * unauthenticated (i.e. unsigned) attributes of "signerinfo".
1421 * This will initially be used for time stamping signed applications
1422 * by using a Time Stamping Authority. It may also be included in outgoing signed
1423 * messages for email (S/MIME), and may be useful in other situations.
1425 * This should only be added once; a second call will do nothing.
1430 Countersignature attribute values have ASN.1 type Countersignature:
1431 Countersignature ::= SignerInfo
1432 Countersignature values have the same meaning as SignerInfo values
1433 for ordinary signatures, except that:
1434 1. The signedAttributes field MUST NOT contain a content-type
1435 attribute; there is no content type for countersignatures.
1436 2. The signedAttributes field MUST contain a message-digest
1437 attribute if it contains any other attributes.
1438 3. The input to the message-digesting process is the contents octets
1439 of the DER encoding of the signatureValue field of the SignerInfo
1440 value with which the attribute is associated.
1445 @abstract Create a timestamp unsigned attribute with a TimeStampToken.
1449 SecCmsSignerInfoAddTimeStamp(SecCmsSignerInfoRef signerinfo
, CSSM_DATA
*tstoken
)
1451 SecCmsAttribute
*attr
;
1452 PLArenaPool
*poolp
= signerinfo
->cmsg
->poolp
;
1453 void *mark
= PORT_ArenaMark(poolp
);
1455 // We have already encoded this ourselves, so last param is PR_TRUE
1456 if ((attr
= SecCmsAttributeCreate(poolp
, SEC_OID_PKCS9_TIMESTAMP_TOKEN
, tstoken
, PR_TRUE
)) == NULL
)
1459 if (SecCmsSignerInfoAddUnauthAttr(signerinfo
, attr
) != SECSuccess
)
1462 PORT_ArenaUnmark (poolp
, mark
);
1467 PORT_ArenaRelease (poolp
, mark
);
1472 * SecCmsSignerInfoAddCounterSignature - countersign a signerinfo
1474 * 1. digest the DER-encoded signature value of the original signerinfo
1475 * 2. create new signerinfo with correct version, sid, digestAlg
1476 * 3. add message-digest authAttr, but NO content-type
1477 * 4. sign the authAttrs
1478 * 5. DER-encode the new signerInfo
1479 * 6. add the whole thing to original signerInfo's unAuthAttrs
1480 * as a SEC_OID_PKCS9_COUNTER_SIGNATURE attribute
1482 * XXXX give back the new signerinfo?
1485 SecCmsSignerInfoAddCounterSignature(SecCmsSignerInfoRef signerinfo
,
1486 SECOidTag digestalg
, SecIdentityRef identity
)
1494 @abstract Add the Apple Codesigning Hash Agility attribute to the authenticated (i.e. signed) attributes of "signerinfo".
1495 @discussion This is expected to be included in outgoing Apple code signatures.
1498 SecCmsSignerInfoAddAppleCodesigningHashAgility(SecCmsSignerInfoRef signerinfo
, CFDataRef attrValue
)
1500 SecCmsAttribute
*attr
;
1501 PLArenaPool
*poolp
= signerinfo
->cmsg
->poolp
;
1502 void *mark
= PORT_ArenaMark(poolp
);
1503 OSStatus status
= SECFailure
;
1505 /* The value is required for this attribute. */
1507 status
= errSecParam
;
1512 * SecCmsAttributeCreate makes a copy of the data in value, so
1513 * we don't need to copy into the CSSM_DATA struct.
1516 value
.Length
= CFDataGetLength(attrValue
);
1517 value
.Data
= (uint8_t *)CFDataGetBytePtr(attrValue
);
1519 if ((attr
= SecCmsAttributeCreate(poolp
,
1520 SEC_OID_APPLE_HASH_AGILITY
,
1522 PR_FALSE
)) == NULL
) {
1523 status
= errSecAllocate
;
1527 if (SecCmsSignerInfoAddAuthAttr(signerinfo
, attr
) != SECSuccess
) {
1528 status
= errSecInternalError
;
1532 PORT_ArenaUnmark(poolp
, mark
);
1536 PORT_ArenaRelease(poolp
, mark
);
1540 static OSStatus
CMSAddAgileHashToAttribute(PLArenaPool
*poolp
, SecCmsAttribute
*attr
, CFNumberRef cftag
, CFDataRef value
) {
1541 PLArenaPool
*tmppoolp
= NULL
;
1543 SECOidData
*digestOid
= NULL
;
1544 CMSAppleAgileHash agileHash
;
1545 SecAsn1Item attrValue
= { .Data
= NULL
, .Length
= 0 };
1546 OSStatus status
= errSecSuccess
;
1548 memset(&agileHash
, 0, sizeof(agileHash
));
1550 if(!CFNumberGetValue(cftag
, kCFNumberSInt64Type
, &tag
)) {
1553 digestOid
= SECOID_FindOIDByTag((SECOidTag
)tag
);
1555 agileHash
.digestValue
.Data
= (uint8_t *)CFDataGetBytePtr(value
);
1556 agileHash
.digestValue
.Length
= CFDataGetLength(value
);
1557 agileHash
.digestOID
.Data
= digestOid
->oid
.Data
;
1558 agileHash
.digestOID
.Length
= digestOid
->oid
.Length
;
1560 tmppoolp
= PORT_NewArena(1024);
1561 if (tmppoolp
== NULL
) {
1562 return errSecAllocate
;
1565 if (SEC_ASN1EncodeItem(tmppoolp
, &attrValue
, &agileHash
, CMSAppleAgileHashTemplate
) == NULL
) {
1566 status
= errSecParam
;
1570 status
= SecCmsAttributeAddValue(poolp
, attr
, &attrValue
);
1574 PORT_FreeArena(tmppoolp
, PR_FALSE
);
1581 @abstract Add the Apple Codesigning Hash Agility attribute to the authenticated (i.e. signed) attributes of "signerinfo".
1582 @discussion This is expected to be included in outgoing Apple code signatures.
1585 SecCmsSignerInfoAddAppleCodesigningHashAgilityV2(SecCmsSignerInfoRef signerinfo
, CFDictionaryRef attrValues
)
1587 __block SecCmsAttribute
*attr
;
1588 __block PLArenaPool
*poolp
= signerinfo
->cmsg
->poolp
;
1589 void *mark
= PORT_ArenaMark(poolp
);
1590 OSStatus status
= SECFailure
;
1592 /* The value is required for this attribute. */
1594 status
= errSecParam
;
1598 if ((attr
= SecCmsAttributeCreate(poolp
, SEC_OID_APPLE_HASH_AGILITY_V2
,
1599 NULL
, PR_TRUE
)) == NULL
) {
1600 status
= errSecAllocate
;
1604 CFDictionaryForEach(attrValues
, ^(const void *key
, const void *value
) {
1605 if (!isNumber(key
) || !isData(value
)) {
1608 (void)CMSAddAgileHashToAttribute(poolp
, attr
, (CFNumberRef
)key
, (CFDataRef
)value
);
1611 if (SecCmsSignerInfoAddAuthAttr(signerinfo
, attr
) != SECSuccess
) {
1612 status
= errSecInternal
;
1616 PORT_ArenaUnmark(poolp
, mark
);
1620 PORT_ArenaRelease(poolp
, mark
);
1625 SecCertificateRef
SecCmsSignerInfoCopyCertFromEncryptionKeyPreference(SecCmsSignerInfoRef signerinfo
) {
1626 SecCertificateRef cert
= NULL
;
1627 SecCmsAttribute
*attr
;
1629 SecKeychainRef keychainOrArray
;
1631 (void)SecKeychainCopyDefault(&keychainOrArray
);
1633 /* sanity check - see if verification status is ok (unverified does not count...) */
1634 if (signerinfo
->verificationStatus
!= SecCmsVSGoodSignature
)
1637 /* Prep the raw certs */
1638 CSSM_DATA_PTR
*rawCerts
= NULL
;
1639 if (signerinfo
->sigd
) {
1640 rawCerts
= signerinfo
->sigd
->rawCerts
;
1643 /* find preferred encryption cert */
1644 if (!SecCmsArrayIsEmpty((void **)signerinfo
->authAttr
) &&
1645 (attr
= SecCmsAttributeArrayFindAttrByOidTag(signerinfo
->authAttr
,
1646 SEC_OID_SMIME_ENCRYPTION_KEY_PREFERENCE
, PR_TRUE
)) != NULL
)
1647 { /* we have a SMIME_ENCRYPTION_KEY_PREFERENCE attribute! Find the cert. */
1648 ekp
= SecCmsAttributeGetValue(attr
);
1651 cert
= SecSMIMEGetCertFromEncryptionKeyPreference(keychainOrArray
, rawCerts
, ekp
);
1653 if(cert
) return cert
;
1655 if (!SecCmsArrayIsEmpty((void **)signerinfo
->authAttr
) &&
1656 (attr
= SecCmsAttributeArrayFindAttrByOidTag(signerinfo
->authAttr
,
1657 SEC_OID_MS_SMIME_ENCRYPTION_KEY_PREFERENCE
, PR_TRUE
)) != NULL
)
1658 { /* we have a MS_SMIME_ENCRYPTION_KEY_PREFERENCE attribute! Find the cert. */
1659 ekp
= SecCmsAttributeGetValue(attr
);
1662 cert
= SecSMIMEGetCertFromEncryptionKeyPreference(keychainOrArray
, rawCerts
, ekp
);
1668 * XXXX the following needs to be done in the S/MIME layer code
1669 * after signature of a signerinfo is verified
1672 SecCmsSignerInfoSaveSMIMEProfile(SecCmsSignerInfoRef signerinfo
)
1674 SecCertificateRef cert
= NULL
;
1675 CSSM_DATA_PTR profile
= NULL
;
1676 SecCmsAttribute
*attr
;
1677 CSSM_DATA_PTR utc_stime
= NULL
;
1681 Boolean must_free_cert
= PR_FALSE
;
1683 SecKeychainRef keychainOrArray
;
1685 status
= SecKeychainCopyDefault(&keychainOrArray
);
1687 /* sanity check - see if verification status is ok (unverified does not count...) */
1688 if (signerinfo
->verificationStatus
!= SecCmsVSGoodSignature
)
1691 /* find preferred encryption cert */
1692 if (!SecCmsArrayIsEmpty((void **)signerinfo
->authAttr
) &&
1693 (attr
= SecCmsAttributeArrayFindAttrByOidTag(signerinfo
->authAttr
,
1694 SEC_OID_SMIME_ENCRYPTION_KEY_PREFERENCE
, PR_TRUE
)) != NULL
)
1695 { /* we have a SMIME_ENCRYPTION_KEY_PREFERENCE attribute! */
1696 ekp
= SecCmsAttributeGetValue(attr
);
1700 /* we assume that all certs coming with the message have been imported to the */
1701 /* temporary database */
1702 cert
= SecSMIMEGetCertFromEncryptionKeyPreference(keychainOrArray
, NULL
, ekp
);
1705 must_free_cert
= PR_TRUE
;
1709 /* no preferred cert found?
1710 * find the cert the signerinfo is signed with instead */
1711 CFStringRef emailAddress
=NULL
;
1713 cert
= SecCmsSignerInfoGetSigningCertificate(signerinfo
, keychainOrArray
);
1716 if (SecCertificateGetEmailAddress(cert
,&emailAddress
))
1720 /* verify this cert for encryption (has been verified for signing so far) */ /* don't verify this cert for encryption. It may just be a signing cert.
1721 * that's OK, we can still save the S/MIME profile. The encryption cert
1722 * should have already been saved */
1724 if (CERT_VerifyCert(keychainOrArray
, cert
, certUsageEmailRecipient
, CFAbsoluteTimeGetCurrent(), NULL
) != SECSuccess
) {
1726 CERT_DestroyCertificate(cert
);
1731 /* XXX store encryption cert permanently? */
1734 * Remember the current error set because we do not care about
1735 * anything set by the functions we are about to call.
1737 save_error
= PORT_GetError();
1739 if (!SecCmsArrayIsEmpty((void **)signerinfo
->authAttr
)) {
1740 attr
= SecCmsAttributeArrayFindAttrByOidTag(signerinfo
->authAttr
,
1741 SEC_OID_PKCS9_SMIME_CAPABILITIES
,
1743 profile
= SecCmsAttributeGetValue(attr
);
1744 attr
= SecCmsAttributeArrayFindAttrByOidTag(signerinfo
->authAttr
,
1745 SEC_OID_PKCS9_SIGNING_TIME
,
1747 utc_stime
= SecCmsAttributeGetValue(attr
);
1750 rv
= CERT_SaveSMimeProfile (cert
, profile
, utc_stime
);
1752 CERT_DestroyCertificate(cert
);
1755 * Restore the saved error in case the calls above set a new
1756 * one that we do not actually care about.
1758 PORT_SetError (save_error
);
1764 * SecCmsSignerInfoIncludeCerts - set cert chain inclusion mode for this signer
1767 SecCmsSignerInfoIncludeCerts(SecCmsSignerInfoRef signerinfo
, SecCmsCertChainMode cm
, SECCertUsage usage
)
1769 if (signerinfo
->cert
== NULL
)
1772 /* don't leak if we get called twice */
1773 if (signerinfo
->certList
!= NULL
) {
1774 CFRelease(signerinfo
->certList
);
1775 signerinfo
->certList
= NULL
;
1780 signerinfo
->certList
= NULL
;
1782 case SecCmsCMCertOnly
:
1783 signerinfo
->certList
= CERT_CertListFromCert(signerinfo
->cert
);
1785 case SecCmsCMCertChain
:
1786 signerinfo
->certList
= CERT_CertChainFromCert(signerinfo
->cert
, usage
, PR_FALSE
);
1788 case SecCmsCMCertChainWithRoot
:
1789 signerinfo
->certList
= CERT_CertChainFromCert(signerinfo
->cert
, usage
, PR_TRUE
);
1793 if (cm
!= SecCmsCMNone
&& signerinfo
->certList
== NULL
)