]> git.saurik.com Git - apple/security.git/blob - libsecurity_smime/lib/cmssiginfo.c
Security-55179.11.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 "secitem.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/SecKeychain.h>
51 #include <Security/SecIdentity.h>
52 #include <Security/SecCertificatePriv.h>
53 #include <Security/SecKeyPriv.h>
54 #include <CoreFoundation/CFTimeZone.h>
55 #include <AssertMacros.h>
56 #include <CoreServices/../Frameworks/CarbonCore.framework/Headers/MacErrors.h>
57
58 #include "tsaSupport.h"
59 #include "tsaSupportPriv.h"
60
61 #define HIDIGIT(v) (((v) / 10) + '0')
62 #define LODIGIT(v) (((v) % 10) + '0')
63
64 #define ISDIGIT(dig) (((dig) >= '0') && ((dig) <= '9'))
65 #define CAPTURE(var,p,label) \
66 { \
67 if (!ISDIGIT((p)[0]) || !ISDIGIT((p)[1])) goto label; \
68 (var) = ((p)[0] - '0') * 10 + ((p)[1] - '0'); \
69 }
70
71 #ifndef NDEBUG
72 #define SIGINFO_DEBUG 1
73 #endif
74
75 #if SIGINFO_DEBUG
76 #define dprintf(args...) printf(args)
77 #else
78 #define dprintf(args...)
79 #endif
80
81 #if RELEASECOUNTDEBUG
82 #define dprintfRC(args...) dprintf(args)
83 #else
84 #define dprintfRC(args...)
85 #endif
86
87 static OSStatus
88 DER_UTCTimeToCFDate(const CSSM_DATA_PTR utcTime, CFAbsoluteTime *date)
89 {
90 CFGregorianDate gdate;
91 char *string = (char *)utcTime->Data;
92 long year, month, mday, hour, minute, second, hourOff, minOff;
93 CFTimeZoneRef timeZone;
94
95 /* Verify time is formatted properly and capture information */
96 second = 0;
97 hourOff = 0;
98 minOff = 0;
99 CAPTURE(year,string+0,loser);
100 if (year < 50) {
101 /* ASSUME that year # is in the 2000's, not the 1900's */
102 year += 100;
103 }
104 CAPTURE(month,string+2,loser);
105 if ((month == 0) || (month > 12)) goto loser;
106 CAPTURE(mday,string+4,loser);
107 if ((mday == 0) || (mday > 31)) goto loser;
108 CAPTURE(hour,string+6,loser);
109 if (hour > 23) goto loser;
110 CAPTURE(minute,string+8,loser);
111 if (minute > 59) goto loser;
112 if (ISDIGIT(string[10])) {
113 CAPTURE(second,string+10,loser);
114 if (second > 59) goto loser;
115 string += 2;
116 }
117 if (string[10] == '+') {
118 CAPTURE(hourOff,string+11,loser);
119 if (hourOff > 23) goto loser;
120 CAPTURE(minOff,string+13,loser);
121 if (minOff > 59) goto loser;
122 } else if (string[10] == '-') {
123 CAPTURE(hourOff,string+11,loser);
124 if (hourOff > 23) goto loser;
125 hourOff = -hourOff;
126 CAPTURE(minOff,string+13,loser);
127 if (minOff > 59) goto loser;
128 minOff = -minOff;
129 } else if (string[10] != 'Z') {
130 goto loser;
131 }
132
133 gdate.year = year + 1900;
134 gdate.month = month;
135 gdate.day = mday;
136 gdate.hour = hour;
137 gdate.minute = minute;
138 gdate.second = second;
139
140 if (hourOff == 0 && minOff == 0)
141 timeZone = NULL; /* GMT */
142 else
143 {
144 timeZone = CFTimeZoneCreateWithTimeIntervalFromGMT(NULL, (hourOff * 60 + minOff) * 60);
145 }
146
147 *date = CFGregorianDateGetAbsoluteTime(gdate, timeZone);
148 if (timeZone)
149 CFRelease(timeZone);
150
151 return SECSuccess;
152
153 loser:
154 return SECFailure;
155 }
156
157 static OSStatus
158 DER_CFDateToUTCTime(CFAbsoluteTime date, CSSM_DATA_PTR utcTime)
159 {
160 CFGregorianDate gdate = CFAbsoluteTimeGetGregorianDate(date, NULL /* GMT */);
161 unsigned char *d;
162 SInt8 second;
163
164 utcTime->Length = 13;
165 utcTime->Data = d = PORT_Alloc(13);
166 if (!utcTime->Data)
167 return SECFailure;
168
169 /* UTC time does not handle the years before 1950 */
170 if (gdate.year < 1950)
171 return SECFailure;
172
173 /* remove the century since it's added to the year by the
174 CFAbsoluteTimeGetGregorianDate routine, but is not needed for UTC time */
175 gdate.year %= 100;
176 second = gdate.second + 0.5;
177
178 d[0] = HIDIGIT(gdate.year);
179 d[1] = LODIGIT(gdate.year);
180 d[2] = HIDIGIT(gdate.month);
181 d[3] = LODIGIT(gdate.month);
182 d[4] = HIDIGIT(gdate.day);
183 d[5] = LODIGIT(gdate.day);
184 d[6] = HIDIGIT(gdate.hour);
185 d[7] = LODIGIT(gdate.hour);
186 d[8] = HIDIGIT(gdate.minute);
187 d[9] = LODIGIT(gdate.minute);
188 d[10] = HIDIGIT(second);
189 d[11] = LODIGIT(second);
190 d[12] = 'Z';
191 return SECSuccess;
192 }
193
194 /* =============================================================================
195 * SIGNERINFO
196 */
197 SecCmsSignerInfoRef
198 nss_cmssignerinfo_create(SecCmsMessageRef cmsg, SecCmsSignerIDSelector type, SecCertificateRef cert, CSSM_DATA_PTR subjKeyID, SecPublicKeyRef pubKey, SecPrivateKeyRef signingKey, SECOidTag digestalgtag);
199
200 SecCmsSignerInfoRef
201 SecCmsSignerInfoCreateWithSubjKeyID(SecCmsMessageRef cmsg, CSSM_DATA_PTR subjKeyID, SecPublicKeyRef pubKey, SecPrivateKeyRef signingKey, SECOidTag digestalgtag)
202 {
203 return nss_cmssignerinfo_create(cmsg, SecCmsSignerIDSubjectKeyID, NULL, subjKeyID, pubKey, signingKey, digestalgtag);
204 }
205
206 SecCmsSignerInfoRef
207 SecCmsSignerInfoCreate(SecCmsMessageRef cmsg, SecIdentityRef identity, SECOidTag digestalgtag)
208 {
209 SecCmsSignerInfoRef signerInfo = NULL;
210 SecCertificateRef cert = NULL;
211 SecPrivateKeyRef signingKey = NULL;
212
213 if (SecIdentityCopyCertificate(identity, &cert))
214 goto loser;
215 if (SecIdentityCopyPrivateKey(identity, &signingKey))
216 goto loser;
217
218 signerInfo = nss_cmssignerinfo_create(cmsg, SecCmsSignerIDIssuerSN, cert, NULL, NULL, signingKey, digestalgtag);
219
220 loser:
221 if (cert)
222 CFRelease(cert);
223 if (signingKey)
224 CFRelease(signingKey);
225
226 return signerInfo;
227 }
228
229 SecCmsSignerInfoRef
230 nss_cmssignerinfo_create(SecCmsMessageRef cmsg, SecCmsSignerIDSelector type, SecCertificateRef cert, CSSM_DATA_PTR subjKeyID, SecPublicKeyRef pubKey, SecPrivateKeyRef signingKey, SECOidTag digestalgtag)
231 {
232 void *mark;
233 SecCmsSignerInfoRef signerinfo;
234 int version;
235 PLArenaPool *poolp;
236
237 poolp = cmsg->poolp;
238
239 mark = PORT_ArenaMark(poolp);
240
241 signerinfo = (SecCmsSignerInfoRef)PORT_ArenaZAlloc(poolp, sizeof(SecCmsSignerInfo));
242 if (signerinfo == NULL) {
243 PORT_ArenaRelease(poolp, mark);
244 return NULL;
245 }
246
247
248 signerinfo->cmsg = cmsg;
249
250 switch(type) {
251 case SecCmsSignerIDIssuerSN:
252 signerinfo->signerIdentifier.identifierType = SecCmsSignerIDIssuerSN;
253 if ((signerinfo->cert = CERT_DupCertificate(cert)) == NULL)
254 goto loser;
255 if ((signerinfo->signerIdentifier.id.issuerAndSN = CERT_GetCertIssuerAndSN(poolp, cert)) == NULL)
256 goto loser;
257 dprintfRC("nss_cmssignerinfo_create: SecCmsSignerIDIssuerSN: cert.rc %d\n",
258 (int)CFGetRetainCount(signerinfo->cert));
259 break;
260 case SecCmsSignerIDSubjectKeyID:
261 signerinfo->signerIdentifier.identifierType = SecCmsSignerIDSubjectKeyID;
262 PORT_Assert(subjKeyID);
263 if (!subjKeyID)
264 goto loser;
265 signerinfo->signerIdentifier.id.subjectKeyID = PORT_ArenaNew(poolp, CSSM_DATA);
266 SECITEM_CopyItem(poolp, signerinfo->signerIdentifier.id.subjectKeyID,
267 subjKeyID);
268 signerinfo->pubKey = SECKEY_CopyPublicKey(pubKey);
269 if (!signerinfo->pubKey)
270 goto loser;
271 break;
272 default:
273 goto loser;
274 }
275
276 if (!signingKey)
277 goto loser;
278
279 signerinfo->signingKey = SECKEY_CopyPrivateKey(signingKey);
280 if (!signerinfo->signingKey)
281 goto loser;
282
283 /* set version right now */
284 version = SEC_CMS_SIGNER_INFO_VERSION_ISSUERSN;
285 /* RFC2630 5.3 "version is the syntax version number. If the .... " */
286 if (signerinfo->signerIdentifier.identifierType == SecCmsSignerIDSubjectKeyID)
287 version = SEC_CMS_SIGNER_INFO_VERSION_SUBJKEY;
288 (void)SEC_ASN1EncodeInteger(poolp, &(signerinfo->version), (long)version);
289
290 if (SECOID_SetAlgorithmID(poolp, &signerinfo->digestAlg, digestalgtag, NULL) != SECSuccess)
291 goto loser;
292
293 PORT_ArenaUnmark(poolp, mark);
294 return signerinfo;
295
296 loser:
297 PORT_ArenaRelease(poolp, mark);
298 return NULL;
299 }
300
301 /*
302 * SecCmsSignerInfoDestroy - destroy a SignerInfo data structure
303 */
304 void
305 SecCmsSignerInfoDestroy(SecCmsSignerInfoRef si)
306 {
307 if (si->cert != NULL) {
308 dprintfRC("SecCmsSignerInfoDestroy top: certp %p cert.rc %d\n",
309 si->cert, (int)CFGetRetainCount(si->cert));
310 CERT_DestroyCertificate(si->cert);
311 }
312 if (si->certList != NULL) {
313 dprintfRC("SecCmsSignerInfoDestroy top: certList.rc %d\n",
314 (int)CFGetRetainCount(si->certList));
315 CFRelease(si->certList);
316 }
317 if (si->timestampCertList != NULL) {
318 dprintfRC("SecCmsSignerInfoDestroy top: timestampCertList.rc %d\n",
319 (int)CFGetRetainCount(si->timestampCertList));
320 CFRelease(si->timestampCertList);
321 }
322 /* XXX storage ??? */
323 }
324
325 /*
326 * SecCmsSignerInfoSign - sign something
327 *
328 */
329 OSStatus
330 SecCmsSignerInfoSign(SecCmsSignerInfoRef signerinfo, CSSM_DATA_PTR digest, CSSM_DATA_PTR contentType)
331 {
332 SecCertificateRef cert;
333 SecPrivateKeyRef privkey = NULL;
334 SECOidTag digestalgtag;
335 SECOidTag pubkAlgTag;
336 CSSM_DATA signature = { 0 };
337 OSStatus rv;
338 PLArenaPool *poolp, *tmppoolp;
339 const SECAlgorithmID *algID;
340 SECAlgorithmID freeAlgID;
341 //CERTSubjectPublicKeyInfo *spki;
342
343 PORT_Assert (digest != NULL);
344
345 poolp = signerinfo->cmsg->poolp;
346
347 switch (signerinfo->signerIdentifier.identifierType) {
348 case SecCmsSignerIDIssuerSN:
349 privkey = signerinfo->signingKey;
350 signerinfo->signingKey = NULL;
351 cert = signerinfo->cert;
352 if (SecCertificateGetAlgorithmID(cert,&algID)) {
353 PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
354 goto loser;
355 }
356 break;
357 case SecCmsSignerIDSubjectKeyID:
358 privkey = signerinfo->signingKey;
359 signerinfo->signingKey = NULL;
360 #if 0
361 spki = SECKEY_CreateSubjectPublicKeyInfo(signerinfo->pubKey);
362 SECKEY_DestroyPublicKey(signerinfo->pubKey);
363 signerinfo->pubKey = NULL;
364 SECOID_CopyAlgorithmID(NULL, &freeAlgID, &spki->algorithm);
365 SECKEY_DestroySubjectPublicKeyInfo(spki);
366 algID = &freeAlgID;
367 #else
368 if (SecKeyGetAlgorithmID(signerinfo->pubKey,&algID)) {
369 PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
370 goto loser;
371 }
372 CFRelease(signerinfo->pubKey);
373 signerinfo->pubKey = NULL;
374 #endif
375 break;
376 default:
377 PORT_SetError(SEC_ERROR_UNSUPPORTED_MESSAGE_TYPE);
378 goto loser;
379 }
380 digestalgtag = SecCmsSignerInfoGetDigestAlgTag(signerinfo);
381 /*
382 * XXX I think there should be a cert-level interface for this,
383 * so that I do not have to know about subjectPublicKeyInfo...
384 */
385 pubkAlgTag = SECOID_GetAlgorithmTag(algID);
386 if (signerinfo->signerIdentifier.identifierType == SecCmsSignerIDSubjectKeyID) {
387 SECOID_DestroyAlgorithmID(&freeAlgID, PR_FALSE);
388 }
389
390 #if 0
391 // @@@ Not yet
392 /* Fortezza MISSI have weird signature formats.
393 * Map them to standard DSA formats
394 */
395 pubkAlgTag = PK11_FortezzaMapSig(pubkAlgTag);
396 #endif
397
398 if (signerinfo->authAttr != NULL) {
399 CSSM_DATA encoded_attrs;
400
401 /* find and fill in the message digest attribute. */
402 rv = SecCmsAttributeArraySetAttr(poolp, &(signerinfo->authAttr),
403 SEC_OID_PKCS9_MESSAGE_DIGEST, digest, PR_FALSE);
404 if (rv != SECSuccess)
405 goto loser;
406
407 if (contentType != NULL) {
408 /* if the caller wants us to, find and fill in the content type attribute. */
409 rv = SecCmsAttributeArraySetAttr(poolp, &(signerinfo->authAttr),
410 SEC_OID_PKCS9_CONTENT_TYPE, contentType, PR_FALSE);
411 if (rv != SECSuccess)
412 goto loser;
413 }
414
415 if ((tmppoolp = PORT_NewArena (1024)) == NULL) {
416 PORT_SetError(SEC_ERROR_NO_MEMORY);
417 goto loser;
418 }
419
420 /*
421 * Before encoding, reorder the attributes so that when they
422 * are encoded, they will be conforming DER, which is required
423 * to have a specific order and that is what must be used for
424 * the hash/signature. We do this here, rather than building
425 * it into EncodeAttributes, because we do not want to do
426 * such reordering on incoming messages (which also uses
427 * EncodeAttributes) or our old signatures (and other "broken"
428 * implementations) will not verify. So, we want to guarantee
429 * that we send out good DER encodings of attributes, but not
430 * to expect to receive them.
431 */
432 if (SecCmsAttributeArrayReorder(signerinfo->authAttr) != SECSuccess)
433 goto loser;
434
435 encoded_attrs.Data = NULL;
436 encoded_attrs.Length = 0;
437 if (SecCmsAttributeArrayEncode(tmppoolp, &(signerinfo->authAttr),
438 &encoded_attrs) == NULL)
439 goto loser;
440
441 rv = SEC_SignData(&signature, encoded_attrs.Data, encoded_attrs.Length,
442 privkey, digestalgtag, pubkAlgTag);
443 PORT_FreeArena(tmppoolp, PR_FALSE); /* awkward memory management :-( */
444 } else {
445 rv = SGN_Digest(privkey, digestalgtag, pubkAlgTag, &signature, digest);
446 }
447 SECKEY_DestroyPrivateKey(privkey);
448 privkey = NULL;
449
450 if (rv != SECSuccess)
451 goto loser;
452
453 if (SECITEM_CopyItem(poolp, &(signerinfo->encDigest), &signature)
454 != SECSuccess)
455 goto loser;
456
457 SECITEM_FreeItem(&signature, PR_FALSE);
458
459 if(pubkAlgTag == SEC_OID_EC_PUBLIC_KEY) {
460 /*
461 * RFC 3278 section section 2.1.1 states that the signatureAlgorithm
462 * field contains the full ecdsa-with-SHA1 OID, not plain old ecPublicKey
463 * as would appear in other forms of signed datas. However Microsoft doesn't
464 * do this, it puts ecPublicKey there, and if we put ecdsa-with-SHA1 there,
465 * MS can't verify - presumably because it takes the digest of the digest
466 * before feeding it to ECDSA.
467 * We handle this with a preference; default if it's not there is
468 * "Microsoft compatibility mode".
469 */
470 if(!SecCmsMsEcdsaCompatMode()) {
471 pubkAlgTag = SEC_OID_ECDSA_WithSHA1;
472 }
473 /* else violating the spec for compatibility */
474 }
475
476 if (SECOID_SetAlgorithmID(poolp, &(signerinfo->digestEncAlg), pubkAlgTag,
477 NULL) != SECSuccess)
478 goto loser;
479
480 return SECSuccess;
481
482 loser:
483 if (signature.Length != 0)
484 SECITEM_FreeItem (&signature, PR_FALSE);
485 if (privkey)
486 SECKEY_DestroyPrivateKey(privkey);
487 if((algID != NULL) & (algID != &freeAlgID)) {
488 /* this is dicey - this was actually mallocd by either SecCertificate or
489 * by SecKey...it all boils down to a free() in the end though. */
490 SECOID_DestroyAlgorithmID((SECAlgorithmID *)algID, PR_FALSE);
491 }
492 return SECFailure;
493 }
494
495 OSStatus
496 SecCmsSignerInfoVerifyCertificate(SecCmsSignerInfoRef signerinfo, SecKeychainRef keychainOrArray,
497 CFTypeRef policies, SecTrustRef *trustRef)
498 {
499 SecCertificateRef cert;
500 CFAbsoluteTime stime;
501 OSStatus rv;
502 CSSM_DATA_PTR *otherCerts;
503
504 if ((cert = SecCmsSignerInfoGetSigningCertificate(signerinfo, keychainOrArray)) == NULL) {
505 dprintf("SecCmsSignerInfoVerifyCertificate: no signing cert\n");
506 signerinfo->verificationStatus = SecCmsVSSigningCertNotFound;
507 return SECFailure;
508 }
509
510 /*
511 * Get and convert the signing time; if available, it will be used
512 * both on the cert verification and for importing the sender
513 * email profile.
514 */
515 if (SecCmsSignerInfoGetTimestampTime(signerinfo, &stime) != SECSuccess)
516 if (SecCmsSignerInfoGetSigningTime(signerinfo, &stime) != SECSuccess)
517 stime = CFAbsoluteTimeGetCurrent();
518 rv = SecCmsSignedDataRawCerts(signerinfo->sigd, &otherCerts);
519 if(rv) {
520 return rv;
521 }
522 rv = CERT_VerifyCert(keychainOrArray, cert, otherCerts, policies, stime, trustRef);
523 dprintfRC("SecCmsSignerInfoVerifyCertificate after vfy: certp %p cert.rc %d\n",
524 cert, (int)CFGetRetainCount(cert));
525 if (rv || !trustRef)
526 {
527 if (PORT_GetError() == SEC_ERROR_UNTRUSTED_CERT)
528 {
529 /* Signature or digest level verificationStatus errors should supercede certificate level errors, so only change the verificationStatus if the status was GoodSignature. */
530 if (signerinfo->verificationStatus == SecCmsVSGoodSignature)
531 signerinfo->verificationStatus = SecCmsVSSigningCertNotTrusted;
532 }
533 }
534 /* FIXME isn't this leaking the cert? */
535 dprintf("SecCmsSignerInfoVerifyCertificate: CertVerify rtn %d\n", (int)rv);
536 return rv;
537 }
538
539 static void debugShowSigningCertificate(SecCmsSignerInfoRef signerinfo)
540 {
541 #if SIGINFO_DEBUG
542 CFStringRef cn = SecCmsSignerInfoGetSignerCommonName(signerinfo);
543 if (cn)
544 {
545 char *ccn = cfStringToChar(cn);
546 if (ccn)
547 {
548 dprintf("SecCmsSignerInfoVerify: cn: %s\n", ccn);
549 free(ccn);
550 }
551 }
552 #endif
553 }
554
555 /*
556 * SecCmsSignerInfoVerify - verify the signature of a single SignerInfo
557 *
558 * Just verifies the signature. The assumption is that verification of the certificate
559 * is done already.
560 */
561 OSStatus
562 SecCmsSignerInfoVerify(SecCmsSignerInfoRef signerinfo, CSSM_DATA_PTR digest, CSSM_DATA_PTR contentType)
563 {
564 SecPublicKeyRef publickey = NULL;
565 SecCmsAttribute *attr;
566 CSSM_DATA encoded_attrs;
567 SecCertificateRef cert;
568 SecCmsVerificationStatus vs = SecCmsVSUnverified;
569 PLArenaPool *poolp;
570 SECOidTag digestAlgTag, digestEncAlgTag;
571
572 if (signerinfo == NULL)
573 return SECFailure;
574
575 /* SecCmsSignerInfoGetSigningCertificate will fail if 2nd parm is NULL and */
576 /* cert has not been verified */
577 if ((cert = SecCmsSignerInfoGetSigningCertificate(signerinfo, NULL)) == NULL) {
578 dprintf("SecCmsSignerInfoVerify: no signing cert\n");
579 vs = SecCmsVSSigningCertNotFound;
580 goto loser;
581 }
582
583 dprintfRC("SecCmsSignerInfoVerify top: cert %p cert.rc %d\n", cert, (int)CFGetRetainCount(cert));
584
585 debugShowSigningCertificate(signerinfo);
586
587 if (SecCertificateCopyPublicKey(cert, &publickey)) {
588 vs = SecCmsVSProcessingError;
589 goto loser;
590 }
591
592 digestAlgTag = SECOID_GetAlgorithmTag(&(signerinfo->digestAlg));
593 digestEncAlgTag = SECOID_GetAlgorithmTag(&(signerinfo->digestEncAlg));
594
595 /*
596 * Gross hack necessitated by RFC 3278 section 2.1.1, which states
597 * that the signature algorithm (here, digestEncAlg) contains ecdsa_with-SHA1,
598 * *not* (as in all other algorithms) the raw signature algorithm, e.g.
599 * pkcs1RSAEncryption.
600 */
601 if(digestEncAlgTag == SEC_OID_ECDSA_WithSHA1) {
602 digestEncAlgTag = SEC_OID_EC_PUBLIC_KEY;
603 }
604
605 if (!SecCmsArrayIsEmpty((void **)signerinfo->authAttr)) {
606 if (contentType) {
607 /*
608 * Check content type
609 *
610 * RFC2630 sez that if there are any authenticated attributes,
611 * then there must be one for content type which matches the
612 * content type of the content being signed, and there must
613 * be one for message digest which matches our message digest.
614 * So check these things first.
615 */
616 if ((attr = SecCmsAttributeArrayFindAttrByOidTag(signerinfo->authAttr,
617 SEC_OID_PKCS9_CONTENT_TYPE, PR_TRUE)) == NULL)
618 {
619 vs = SecCmsVSMalformedSignature;
620 goto loser;
621 }
622
623 if (SecCmsAttributeCompareValue(attr, contentType) == PR_FALSE) {
624 vs = SecCmsVSMalformedSignature;
625 goto loser;
626 }
627 }
628
629 /*
630 * Check digest
631 */
632 if ((attr = SecCmsAttributeArrayFindAttrByOidTag(signerinfo->authAttr, SEC_OID_PKCS9_MESSAGE_DIGEST, PR_TRUE)) == NULL)
633 {
634 vs = SecCmsVSMalformedSignature;
635 goto loser;
636 }
637 if (SecCmsAttributeCompareValue(attr, digest) == PR_FALSE) {
638 vs = SecCmsVSDigestMismatch;
639 goto loser;
640 }
641
642 if ((poolp = PORT_NewArena (1024)) == NULL) {
643 vs = SecCmsVSProcessingError;
644 goto loser;
645 }
646
647 /*
648 * Check signature
649 *
650 * The signature is based on a digest of the DER-encoded authenticated
651 * attributes. So, first we encode and then we digest/verify.
652 * we trust the decoder to have the attributes in the right (sorted) order
653 */
654 encoded_attrs.Data = NULL;
655 encoded_attrs.Length = 0;
656
657 if (SecCmsAttributeArrayEncode(poolp, &(signerinfo->authAttr), &encoded_attrs) == NULL ||
658 encoded_attrs.Data == NULL || encoded_attrs.Length == 0)
659 {
660 vs = SecCmsVSProcessingError;
661 goto loser;
662 }
663
664 vs = (VFY_VerifyData (encoded_attrs.Data, encoded_attrs.Length,
665 publickey, &(signerinfo->encDigest),
666 digestAlgTag, digestEncAlgTag,
667 signerinfo->cmsg->pwfn_arg) != SECSuccess) ? SecCmsVSBadSignature : SecCmsVSGoodSignature;
668
669 dprintf("VFY_VerifyData (authenticated attributes): %s\n",
670 (vs == SecCmsVSGoodSignature)?"SecCmsVSGoodSignature":"SecCmsVSBadSignature");
671
672 PORT_FreeArena(poolp, PR_FALSE); /* awkward memory management :-( */
673
674 } else {
675 CSSM_DATA_PTR sig;
676
677 /* No authenticated attributes. The signature is based on the plain message digest. */
678 sig = &(signerinfo->encDigest);
679 if (sig->Length == 0)
680 goto loser;
681
682 vs = (VFY_VerifyDigest(digest, publickey, sig,
683 digestAlgTag, digestEncAlgTag,
684 signerinfo->cmsg->pwfn_arg) != SECSuccess) ? SecCmsVSBadSignature : SecCmsVSGoodSignature;
685
686 dprintf("VFY_VerifyData (plain message digest): %s\n",
687 (vs == SecCmsVSGoodSignature)?"SecCmsVSGoodSignature":"SecCmsVSBadSignature");
688 }
689
690 if (!SecCmsArrayIsEmpty((void **)signerinfo->unAuthAttr))
691 {
692 dprintf("found an unAuthAttr\n");
693 OSStatus rux = SecCmsSignerInfoVerifyUnAuthAttrs(signerinfo);
694 dprintf("SecCmsSignerInfoVerifyUnAuthAttrs Status: %ld\n", (long)rux);
695 if (rux)
696 goto loser;
697 }
698
699 if (vs == SecCmsVSBadSignature) {
700 /*
701 * XXX Change the generic error into our specific one, because
702 * in that case we get a better explanation out of the Security
703 * Advisor. This is really a bug in our error strings (the
704 * "generic" error has a lousy/wrong message associated with it
705 * which assumes the signature verification was done for the
706 * purposes of checking the issuer signature on a certificate)
707 * but this is at least an easy workaround and/or in the
708 * Security Advisor, which specifically checks for the error
709 * SEC_ERROR_PKCS7_BAD_SIGNATURE and gives more explanation
710 * in that case but does not similarly check for
711 * SEC_ERROR_BAD_SIGNATURE. It probably should, but then would
712 * probably say the wrong thing in the case that it *was* the
713 * certificate signature check that failed during the cert
714 * verification done above. Our error handling is really a mess.
715 */
716 if (PORT_GetError() == SEC_ERROR_BAD_SIGNATURE)
717 PORT_SetError(SEC_ERROR_PKCS7_BAD_SIGNATURE);
718 }
719
720 if (publickey != NULL)
721 CFRelease(publickey);
722
723 signerinfo->verificationStatus = vs;
724 dprintfRC("SecCmsSignerInfoVerify end: cerp %p cert.rc %d\n",
725 cert, (int)CFGetRetainCount(cert));
726
727 dprintf("verificationStatus: %d\n", vs);
728
729 return (vs == SecCmsVSGoodSignature) ? SECSuccess : SECFailure;
730
731 loser:
732 if (publickey != NULL)
733 SECKEY_DestroyPublicKey (publickey);
734
735 dprintf("verificationStatus2: %d\n", vs);
736 signerinfo->verificationStatus = vs;
737
738 PORT_SetError (SEC_ERROR_PKCS7_BAD_SIGNATURE);
739 return SECFailure;
740 }
741
742
743 OSStatus
744 SecCmsSignerInfoVerifyUnAuthAttrs(SecCmsSignerInfoRef signerinfo)
745 {
746 /*
747 unAuthAttr is an array of attributes; we expect to
748 see just one: the timestamp blob. If we have an unAuthAttr,
749 but don't see a timestamp, return an error since we have
750 no other cases where this would be present.
751 */
752
753 SecCmsAttribute *attr = NULL;
754 OSStatus status = SECFailure;
755
756 require(signerinfo, xit);
757 attr = SecCmsAttributeArrayFindAttrByOidTag(signerinfo->unAuthAttr,
758 SEC_OID_PKCS9_TIMESTAMP_TOKEN, PR_TRUE);
759 if (attr == NULL)
760 {
761 status = errSecTimestampMissing;
762 goto xit;
763 }
764
765 dprintf("found an id-ct-TSTInfo\n");
766 // Don't check the nonce in this case
767 status = decodeTimeStampToken(signerinfo, (attr->values)[0], &signerinfo->encDigest, 0);
768 xit:
769 return status;
770 }
771
772 CSSM_DATA *
773 SecCmsSignerInfoGetEncDigest(SecCmsSignerInfoRef signerinfo)
774 {
775 return &signerinfo->encDigest;
776 }
777
778 SecCmsVerificationStatus
779 SecCmsSignerInfoGetVerificationStatus(SecCmsSignerInfoRef signerinfo)
780 {
781 return signerinfo->verificationStatus;
782 }
783
784 SECOidData *
785 SecCmsSignerInfoGetDigestAlg(SecCmsSignerInfoRef signerinfo)
786 {
787 return SECOID_FindOID (&(signerinfo->digestAlg.algorithm));
788 }
789
790 SECOidTag
791 SecCmsSignerInfoGetDigestAlgTag(SecCmsSignerInfoRef signerinfo)
792 {
793 SECOidData *algdata;
794
795 algdata = SECOID_FindOID (&(signerinfo->digestAlg.algorithm));
796 if (algdata != NULL)
797 return algdata->offset;
798 else
799 return SEC_OID_UNKNOWN;
800 }
801
802 CFArrayRef
803 SecCmsSignerInfoGetCertList(SecCmsSignerInfoRef signerinfo)
804 {
805 dprintfRC("SecCmsSignerInfoGetCertList: certList.rc %d\n",
806 (int)CFGetRetainCount(signerinfo->certList));
807 return signerinfo->certList;
808 }
809
810 CFArrayRef
811 SecCmsSignerInfoGetTimestampCertList(SecCmsSignerInfoRef signerinfo)
812 {
813 dprintfRC("SecCmsSignerInfoGetCertList: timestampCertList.rc %d\n",
814 (int)CFGetRetainCount(signerinfo->timestampCertList));
815 return signerinfo->timestampCertList;
816 }
817
818
819
820 int
821 SecCmsSignerInfoGetVersion(SecCmsSignerInfoRef signerinfo)
822 {
823 unsigned long version;
824
825 /* always take apart the CSSM_DATA */
826 if (SEC_ASN1DecodeInteger(&(signerinfo->version), &version) != SECSuccess)
827 return 0;
828 else
829 return (int)version;
830 }
831
832 /*
833 * SecCmsSignerInfoGetSigningTime - return the signing time,
834 * in UTCTime format, of a CMS signerInfo.
835 *
836 * sinfo - signerInfo data for this signer
837 *
838 * Returns a pointer to XXXX (what?)
839 * A return value of NULL is an error.
840 */
841 OSStatus
842 SecCmsSignerInfoGetSigningTime(SecCmsSignerInfoRef sinfo, CFAbsoluteTime *stime)
843 {
844 SecCmsAttribute *attr;
845 CSSM_DATA_PTR value;
846
847 if (sinfo == NULL)
848 return paramErr;
849
850 if (sinfo->signingTime != 0) {
851 *stime = sinfo->signingTime; /* cached copy */
852 return SECSuccess;
853 }
854
855 attr = SecCmsAttributeArrayFindAttrByOidTag(sinfo->authAttr, SEC_OID_PKCS9_SIGNING_TIME, PR_TRUE);
856 /* XXXX multi-valued attributes NIH */
857 if (attr == NULL || (value = SecCmsAttributeGetValue(attr)) == NULL)
858 return errSecSigningTimeMissing;
859 if (DER_UTCTimeToCFDate(value, stime) != SECSuccess)
860 return errSecSigningTimeMissing;
861 sinfo->signingTime = *stime; /* make cached copy */
862 return SECSuccess;
863 }
864
865 OSStatus
866 SecCmsSignerInfoGetTimestampTime(SecCmsSignerInfoRef sinfo, CFAbsoluteTime *stime)
867 {
868 OSStatus status = paramErr;
869
870 require(sinfo && stime, xit);
871
872 if (sinfo->timestampTime != 0)
873 {
874 *stime = sinfo->timestampTime; /* cached copy */
875 return noErr;
876 }
877
878 // A bit heavyweight if haven't already called verify
879 status = SecCmsSignerInfoVerifyUnAuthAttrs(sinfo);
880 *stime = sinfo->timestampTime;
881 xit:
882 return status;
883 }
884
885 /*
886 * Return the signing cert of a CMS signerInfo.
887 *
888 * the certs in the enclosing SignedData must have been imported already
889 */
890 SecCertificateRef
891 SecCmsSignerInfoGetSigningCertificate(SecCmsSignerInfoRef signerinfo, SecKeychainRef keychainOrArray)
892 {
893 SecCertificateRef cert;
894 SecCmsSignerIdentifier *sid;
895 OSStatus ortn;
896 CSSM_DATA_PTR *rawCerts;
897
898 if (signerinfo->cert != NULL) {
899 dprintfRC("SecCmsSignerInfoGetSigningCertificate top: cert %p cert.rc %d\n",
900 signerinfo->cert, (int)CFGetRetainCount(signerinfo->cert));
901 return signerinfo->cert;
902 }
903 ortn = SecCmsSignedDataRawCerts(signerinfo->sigd, &rawCerts);
904 if(ortn) {
905 return NULL;
906 }
907 dprintf("SecCmsSignerInfoGetSigningCertificate: numRawCerts %d\n",
908 SecCmsArrayCount((void **)rawCerts));
909
910 /*
911 * This cert will also need to be freed, but since we save it
912 * in signerinfo for later, we do not want to destroy it when
913 * we leave this function -- we let the clean-up of the entire
914 * cinfo structure later do the destroy of this cert.
915 */
916 sid = &signerinfo->signerIdentifier;
917 switch (sid->identifierType) {
918 case SecCmsSignerIDIssuerSN:
919 cert = CERT_FindCertByIssuerAndSN(keychainOrArray, rawCerts, signerinfo->cmsg->poolp,
920 sid->id.issuerAndSN);
921 break;
922 case SecCmsSignerIDSubjectKeyID:
923 cert = CERT_FindCertBySubjectKeyID(keychainOrArray, rawCerts, sid->id.subjectKeyID);
924 break;
925 default:
926 cert = NULL;
927 break;
928 }
929
930 /* cert can be NULL at that point */
931 signerinfo->cert = cert; /* earmark it */
932 dprintfRC("SecCmsSignerInfoGetSigningCertificate end: certp %p cert.rc %d\n",
933 signerinfo->cert, (int)CFGetRetainCount(signerinfo->cert));
934
935 return cert;
936 }
937
938 /*
939 * SecCmsSignerInfoGetSignerCommonName - return the common name of the signer
940 *
941 * sinfo - signerInfo data for this signer
942 *
943 * Returns a CFStringRef containing the common name of the signer.
944 * A return value of NULL is an error.
945 */
946 CFStringRef
947 SecCmsSignerInfoGetSignerCommonName(SecCmsSignerInfoRef sinfo)
948 {
949 SecCertificateRef signercert;
950 CFStringRef commonName = NULL;
951
952 /* will fail if cert is not verified */
953 if ((signercert = SecCmsSignerInfoGetSigningCertificate(sinfo, NULL)) == NULL)
954 return NULL;
955
956 SecCertificateGetCommonName(signercert, &commonName);
957
958 return commonName;
959 }
960
961 /*
962 * SecCmsSignerInfoGetSignerEmailAddress - return the email address of the signer
963 *
964 * sinfo - signerInfo data for this signer
965 *
966 * Returns a CFStringRef containing the name of the signer.
967 * A return value of NULL is an error.
968 */
969 CFStringRef
970 SecCmsSignerInfoGetSignerEmailAddress(SecCmsSignerInfoRef sinfo)
971 {
972 SecCertificateRef signercert;
973 CFStringRef emailAddress = NULL;
974
975 if ((signercert = SecCmsSignerInfoGetSigningCertificate(sinfo, NULL)) == NULL)
976 return NULL;
977
978 SecCertificateGetEmailAddress(signercert, &emailAddress);
979
980 return emailAddress;
981 }
982
983
984 /*
985 * SecCmsSignerInfoAddAuthAttr - add an attribute to the
986 * authenticated (i.e. signed) attributes of "signerinfo".
987 */
988 OSStatus
989 SecCmsSignerInfoAddAuthAttr(SecCmsSignerInfoRef signerinfo, SecCmsAttribute *attr)
990 {
991 return SecCmsAttributeArrayAddAttr(signerinfo->cmsg->poolp, &(signerinfo->authAttr), attr);
992 }
993
994 /*
995 * SecCmsSignerInfoAddUnauthAttr - add an attribute to the
996 * unauthenticated attributes of "signerinfo".
997 */
998 OSStatus
999 SecCmsSignerInfoAddUnauthAttr(SecCmsSignerInfoRef signerinfo, SecCmsAttribute *attr)
1000 {
1001 return SecCmsAttributeArrayAddAttr(signerinfo->cmsg->poolp, &(signerinfo->unAuthAttr), attr);
1002 }
1003
1004 /*
1005 * SecCmsSignerInfoAddSigningTime - add the signing time to the
1006 * authenticated (i.e. signed) attributes of "signerinfo".
1007 *
1008 * This is expected to be included in outgoing signed
1009 * messages for email (S/MIME) but is likely useful in other situations.
1010 *
1011 * This should only be added once; a second call will do nothing.
1012 *
1013 * XXX This will probably just shove the current time into "signerinfo"
1014 * but it will not actually get signed until the entire item is
1015 * processed for encoding. Is this (expected to be small) delay okay?
1016 */
1017 OSStatus
1018 SecCmsSignerInfoAddSigningTime(SecCmsSignerInfoRef signerinfo, CFAbsoluteTime t)
1019 {
1020 SecCmsAttribute *attr;
1021 CSSM_DATA stime;
1022 void *mark;
1023 PLArenaPool *poolp;
1024
1025 poolp = signerinfo->cmsg->poolp;
1026
1027 mark = PORT_ArenaMark(poolp);
1028
1029 /* create new signing time attribute */
1030 if (DER_CFDateToUTCTime(t, &stime) != SECSuccess)
1031 goto loser;
1032
1033 if ((attr = SecCmsAttributeCreate(poolp, SEC_OID_PKCS9_SIGNING_TIME, &stime, PR_FALSE)) == NULL) {
1034 SECITEM_FreeItem (&stime, PR_FALSE);
1035 goto loser;
1036 }
1037
1038 SECITEM_FreeItem (&stime, PR_FALSE);
1039
1040 if (SecCmsSignerInfoAddAuthAttr(signerinfo, attr) != SECSuccess)
1041 goto loser;
1042
1043 PORT_ArenaUnmark (poolp, mark);
1044
1045 return SECSuccess;
1046
1047 loser:
1048 PORT_ArenaRelease (poolp, mark);
1049 return SECFailure;
1050 }
1051
1052 /*
1053 * SecCmsSignerInfoAddSMIMECaps - add a SMIMECapabilities attribute to the
1054 * authenticated (i.e. signed) attributes of "signerinfo".
1055 *
1056 * This is expected to be included in outgoing signed
1057 * messages for email (S/MIME).
1058 */
1059 OSStatus
1060 SecCmsSignerInfoAddSMIMECaps(SecCmsSignerInfoRef signerinfo)
1061 {
1062 SecCmsAttribute *attr;
1063 CSSM_DATA_PTR smimecaps = NULL;
1064 void *mark;
1065 PLArenaPool *poolp;
1066
1067 poolp = signerinfo->cmsg->poolp;
1068
1069 mark = PORT_ArenaMark(poolp);
1070
1071 smimecaps = SECITEM_AllocItem(poolp, NULL, 0);
1072 if (smimecaps == NULL)
1073 goto loser;
1074
1075 /* create new signing time attribute */
1076 #if 1
1077 // @@@ We don't do Fortezza yet.
1078 if (SecSMIMECreateSMIMECapabilities((SecArenaPoolRef)poolp, smimecaps, PR_FALSE) != SECSuccess)
1079 #else
1080 if (SecSMIMECreateSMIMECapabilities(poolp, smimecaps,
1081 PK11_FortezzaHasKEA(signerinfo->cert)) != SECSuccess)
1082 #endif
1083 goto loser;
1084
1085 if ((attr = SecCmsAttributeCreate(poolp, SEC_OID_PKCS9_SMIME_CAPABILITIES, smimecaps, PR_TRUE)) == NULL)
1086 goto loser;
1087
1088 if (SecCmsSignerInfoAddAuthAttr(signerinfo, attr) != SECSuccess)
1089 goto loser;
1090
1091 PORT_ArenaUnmark (poolp, mark);
1092 return SECSuccess;
1093
1094 loser:
1095 PORT_ArenaRelease (poolp, mark);
1096 return SECFailure;
1097 }
1098
1099 /*
1100 * SecCmsSignerInfoAddSMIMEEncKeyPrefs - add a SMIMEEncryptionKeyPreferences attribute to the
1101 * authenticated (i.e. signed) attributes of "signerinfo".
1102 *
1103 * This is expected to be included in outgoing signed messages for email (S/MIME).
1104 */
1105 OSStatus
1106 SecCmsSignerInfoAddSMIMEEncKeyPrefs(SecCmsSignerInfoRef signerinfo, SecCertificateRef cert, SecKeychainRef keychainOrArray)
1107 {
1108 SecCmsAttribute *attr;
1109 CSSM_DATA_PTR smimeekp = NULL;
1110 void *mark;
1111 PLArenaPool *poolp;
1112
1113 #if 0
1114 CFTypeRef policy;
1115
1116 /* verify this cert for encryption */
1117 policy = CERT_PolicyForCertUsage(certUsageEmailRecipient);
1118 if (CERT_VerifyCert(keychainOrArray, cert, policy, CFAbsoluteTimeGetCurrent(), NULL) != SECSuccess) {
1119 CFRelease(policy);
1120 return SECFailure;
1121 }
1122 CFRelease(policy);
1123 #endif
1124
1125 poolp = signerinfo->cmsg->poolp;
1126 mark = PORT_ArenaMark(poolp);
1127
1128 smimeekp = SECITEM_AllocItem(poolp, NULL, 0);
1129 if (smimeekp == NULL)
1130 goto loser;
1131
1132 /* create new signing time attribute */
1133 if (SecSMIMECreateSMIMEEncKeyPrefs((SecArenaPoolRef)poolp, smimeekp, cert) != SECSuccess)
1134 goto loser;
1135
1136 if ((attr = SecCmsAttributeCreate(poolp, SEC_OID_SMIME_ENCRYPTION_KEY_PREFERENCE, smimeekp, PR_TRUE)) == NULL)
1137 goto loser;
1138
1139 if (SecCmsSignerInfoAddAuthAttr(signerinfo, attr) != SECSuccess)
1140 goto loser;
1141
1142 PORT_ArenaUnmark (poolp, mark);
1143 return SECSuccess;
1144
1145 loser:
1146 PORT_ArenaRelease (poolp, mark);
1147 return SECFailure;
1148 }
1149
1150 /*
1151 * SecCmsSignerInfoAddMSSMIMEEncKeyPrefs - add a SMIMEEncryptionKeyPreferences attribute to the
1152 * authenticated (i.e. signed) attributes of "signerinfo", using the OID prefered by Microsoft.
1153 *
1154 * This is expected to be included in outgoing signed messages for email (S/MIME),
1155 * if compatibility with Microsoft mail clients is wanted.
1156 */
1157 OSStatus
1158 SecCmsSignerInfoAddMSSMIMEEncKeyPrefs(SecCmsSignerInfoRef signerinfo, SecCertificateRef cert, SecKeychainRef keychainOrArray)
1159 {
1160 SecCmsAttribute *attr;
1161 CSSM_DATA_PTR smimeekp = NULL;
1162 void *mark;
1163 PLArenaPool *poolp;
1164
1165 #if 0
1166 CFTypeRef policy;
1167
1168 /* verify this cert for encryption */
1169 policy = CERT_PolicyForCertUsage(certUsageEmailRecipient);
1170 if (CERT_VerifyCert(keychainOrArray, cert, policy, CFAbsoluteTimeGetCurrent(), NULL) != SECSuccess) {
1171 CFRelease(policy);
1172 return SECFailure;
1173 }
1174 CFRelease(policy);
1175 #endif
1176
1177 poolp = signerinfo->cmsg->poolp;
1178 mark = PORT_ArenaMark(poolp);
1179
1180 smimeekp = SECITEM_AllocItem(poolp, NULL, 0);
1181 if (smimeekp == NULL)
1182 goto loser;
1183
1184 /* create new signing time attribute */
1185 if (SecSMIMECreateMSSMIMEEncKeyPrefs((SecArenaPoolRef)poolp, smimeekp, cert) != SECSuccess)
1186 goto loser;
1187
1188 if ((attr = SecCmsAttributeCreate(poolp, SEC_OID_MS_SMIME_ENCRYPTION_KEY_PREFERENCE, smimeekp, PR_TRUE)) == NULL)
1189 goto loser;
1190
1191 if (SecCmsSignerInfoAddAuthAttr(signerinfo, attr) != SECSuccess)
1192 goto loser;
1193
1194 PORT_ArenaUnmark (poolp, mark);
1195 return SECSuccess;
1196
1197 loser:
1198 PORT_ArenaRelease (poolp, mark);
1199 return SECFailure;
1200 }
1201
1202 /*
1203 * SecCmsSignerInfoAddTimeStamp - add time stamp to the
1204 * unauthenticated (i.e. unsigned) attributes of "signerinfo".
1205 *
1206 * This will initially be used for time stamping signed applications
1207 * by using a Time Stamping Authority. It may also be included in outgoing signed
1208 * messages for email (S/MIME), and may be useful in other situations.
1209 *
1210 * This should only be added once; a second call will do nothing.
1211 *
1212 */
1213
1214 /*
1215 Countersignature attribute values have ASN.1 type Countersignature:
1216 Countersignature ::= SignerInfo
1217 Countersignature values have the same meaning as SignerInfo values
1218 for ordinary signatures, except that:
1219 1. The signedAttributes field MUST NOT contain a content-type
1220 attribute; there is no content type for countersignatures.
1221 2. The signedAttributes field MUST contain a message-digest
1222 attribute if it contains any other attributes.
1223 3. The input to the message-digesting process is the contents octets
1224 of the DER encoding of the signatureValue field of the SignerInfo
1225 value with which the attribute is associated.
1226 */
1227
1228 /*!
1229 @function
1230 @abstract Create a timestamp unsigned attribute with a TimeStampToken.
1231 */
1232
1233 OSStatus
1234 SecCmsSignerInfoAddTimeStamp(SecCmsSignerInfoRef signerinfo, CSSM_DATA *tstoken)
1235 {
1236 SecCmsAttribute *attr;
1237 PLArenaPool *poolp = signerinfo->cmsg->poolp;
1238 void *mark = PORT_ArenaMark(poolp);
1239
1240 // We have already encoded this ourselves, so last param is PR_TRUE
1241 if ((attr = SecCmsAttributeCreate(poolp, SEC_OID_PKCS9_TIMESTAMP_TOKEN, tstoken, PR_TRUE)) == NULL)
1242 goto loser;
1243
1244 if (SecCmsSignerInfoAddUnauthAttr(signerinfo, attr) != SECSuccess)
1245 goto loser;
1246
1247 PORT_ArenaUnmark (poolp, mark);
1248
1249 return SECSuccess;
1250
1251 loser:
1252 PORT_ArenaRelease (poolp, mark);
1253 return SECFailure;
1254 }
1255
1256 /*
1257 * SecCmsSignerInfoAddCounterSignature - countersign a signerinfo
1258 *
1259 * 1. digest the DER-encoded signature value of the original signerinfo
1260 * 2. create new signerinfo with correct version, sid, digestAlg
1261 * 3. add message-digest authAttr, but NO content-type
1262 * 4. sign the authAttrs
1263 * 5. DER-encode the new signerInfo
1264 * 6. add the whole thing to original signerInfo's unAuthAttrs
1265 * as a SEC_OID_PKCS9_COUNTER_SIGNATURE attribute
1266 *
1267 * XXXX give back the new signerinfo?
1268 */
1269 OSStatus
1270 SecCmsSignerInfoAddCounterSignature(SecCmsSignerInfoRef signerinfo,
1271 SECOidTag digestalg, SecIdentityRef identity)
1272 {
1273 /* XXXX TBD XXXX */
1274 return SECFailure;
1275 }
1276
1277 /*
1278 * XXXX the following needs to be done in the S/MIME layer code
1279 * after signature of a signerinfo is verified
1280 */
1281 OSStatus
1282 SecCmsSignerInfoSaveSMIMEProfile(SecCmsSignerInfoRef signerinfo)
1283 {
1284 SecCertificateRef cert = NULL;
1285 CSSM_DATA_PTR profile = NULL;
1286 SecCmsAttribute *attr;
1287 CSSM_DATA_PTR utc_stime = NULL;
1288 CSSM_DATA_PTR ekp;
1289 int save_error;
1290 OSStatus rv;
1291 Boolean must_free_cert = PR_FALSE;
1292 OSStatus status;
1293 SecKeychainRef keychainOrArray;
1294
1295 status = SecKeychainCopyDefault(&keychainOrArray);
1296
1297 /* sanity check - see if verification status is ok (unverified does not count...) */
1298 if (signerinfo->verificationStatus != SecCmsVSGoodSignature)
1299 return SECFailure;
1300
1301 /* find preferred encryption cert */
1302 if (!SecCmsArrayIsEmpty((void **)signerinfo->authAttr) &&
1303 (attr = SecCmsAttributeArrayFindAttrByOidTag(signerinfo->authAttr,
1304 SEC_OID_SMIME_ENCRYPTION_KEY_PREFERENCE, PR_TRUE)) != NULL)
1305 { /* we have a SMIME_ENCRYPTION_KEY_PREFERENCE attribute! */
1306 ekp = SecCmsAttributeGetValue(attr);
1307 if (ekp == NULL)
1308 return SECFailure;
1309
1310 /* we assume that all certs coming with the message have been imported to the */
1311 /* temporary database */
1312 cert = SecSMIMEGetCertFromEncryptionKeyPreference(keychainOrArray, ekp);
1313 if (cert == NULL)
1314 return SECFailure;
1315 must_free_cert = PR_TRUE;
1316 }
1317
1318 if (cert == NULL) {
1319 /* no preferred cert found?
1320 * find the cert the signerinfo is signed with instead */
1321 CFStringRef emailAddress=NULL;
1322
1323 cert = SecCmsSignerInfoGetSigningCertificate(signerinfo, keychainOrArray);
1324 if (cert == NULL)
1325 return SECFailure;
1326 if (SecCertificateGetEmailAddress(cert,&emailAddress))
1327 return SECFailure;
1328 }
1329
1330 /* 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.
1331 * that's OK, we can still save the S/MIME profile. The encryption cert
1332 * should have already been saved */
1333 #ifdef notdef
1334 if (CERT_VerifyCert(keychainOrArray, cert, certUsageEmailRecipient, CFAbsoluteTimeGetCurrent(), NULL) != SECSuccess) {
1335 if (must_free_cert)
1336 CERT_DestroyCertificate(cert);
1337 return SECFailure;
1338 }
1339 #endif
1340
1341 /* XXX store encryption cert permanently? */
1342
1343 /*
1344 * Remember the current error set because we do not care about
1345 * anything set by the functions we are about to call.
1346 */
1347 save_error = PORT_GetError();
1348
1349 if (!SecCmsArrayIsEmpty((void **)signerinfo->authAttr)) {
1350 attr = SecCmsAttributeArrayFindAttrByOidTag(signerinfo->authAttr,
1351 SEC_OID_PKCS9_SMIME_CAPABILITIES,
1352 PR_TRUE);
1353 profile = SecCmsAttributeGetValue(attr);
1354 attr = SecCmsAttributeArrayFindAttrByOidTag(signerinfo->authAttr,
1355 SEC_OID_PKCS9_SIGNING_TIME,
1356 PR_TRUE);
1357 utc_stime = SecCmsAttributeGetValue(attr);
1358 }
1359
1360 rv = CERT_SaveSMimeProfile (cert, profile, utc_stime);
1361 if (must_free_cert)
1362 CERT_DestroyCertificate(cert);
1363
1364 /*
1365 * Restore the saved error in case the calls above set a new
1366 * one that we do not actually care about.
1367 */
1368 PORT_SetError (save_error);
1369
1370 return rv;
1371 }
1372
1373 /*
1374 * SecCmsSignerInfoIncludeCerts - set cert chain inclusion mode for this signer
1375 */
1376 OSStatus
1377 SecCmsSignerInfoIncludeCerts(SecCmsSignerInfoRef signerinfo, SecCmsCertChainMode cm, SECCertUsage usage)
1378 {
1379 if (signerinfo->cert == NULL)
1380 return SECFailure;
1381
1382 /* don't leak if we get called twice */
1383 if (signerinfo->certList != NULL) {
1384 CFRelease(signerinfo->certList);
1385 signerinfo->certList = NULL;
1386 }
1387
1388 switch (cm) {
1389 case SecCmsCMNone:
1390 signerinfo->certList = NULL;
1391 break;
1392 case SecCmsCMCertOnly:
1393 signerinfo->certList = CERT_CertListFromCert(signerinfo->cert);
1394 break;
1395 case SecCmsCMCertChain:
1396 signerinfo->certList = CERT_CertChainFromCert(signerinfo->cert, usage, PR_FALSE);
1397 break;
1398 case SecCmsCMCertChainWithRoot:
1399 signerinfo->certList = CERT_CertChainFromCert(signerinfo->cert, usage, PR_TRUE);
1400 break;
1401 }
1402
1403 if (cm != SecCmsCMNone && signerinfo->certList == NULL)
1404 return SECFailure;
1405
1406 return SECSuccess;
1407 }