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