]> git.saurik.com Git - apple/security.git/blame - OSX/libsecurity_smime/lib/cmssigdata.c
Security-57337.60.2.tar.gz
[apple/security.git] / OSX / libsecurity_smime / lib / cmssigdata.c
CommitLineData
d8f41ccd
A
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 signedData methods.
36 */
37
38#include <Security/SecCmsSignedData.h>
39
40#include <Security/SecCmsContentInfo.h>
41#include <Security/SecCmsDigestContext.h>
42#include <Security/SecCmsSignerInfo.h>
43
44#include "cmslocal.h"
45
46#include "cert.h"
47#include "secitem.h"
48#include "secoid.h"
49#include "tsaTemplates.h"
50
51#include <security_asn1/secasn1.h>
52#include <security_asn1/secerr.h>
53#include <Security/SecBase.h>
54#include <CommonCrypto/CommonRandomSPI.h>
5c19dc3a 55#include <Security/SecPolicy.h>
d8f41ccd
A
56#include <Security/SecPolicyPriv.h>
57#include <utilities/SecCFWrappers.h>
5c19dc3a 58#include <syslog.h>
d8f41ccd
A
59
60#ifndef NDEBUG
61#define SIGDATA_DEBUG 1
62#endif
63
64#if SIGDATA_DEBUG
5c19dc3a 65#define dprintf(args...) fprintf(stderr, args)
d8f41ccd
A
66#else
67#define dprintf(args...)
68#endif
69
70SecCmsSignedDataRef
71SecCmsSignedDataCreate(SecCmsMessageRef cmsg)
72{
73 void *mark;
74 SecCmsSignedDataRef sigd;
75 PLArenaPool *poolp;
76
77 poolp = cmsg->poolp;
78
79 mark = PORT_ArenaMark(poolp);
80
81 sigd = (SecCmsSignedDataRef)PORT_ArenaZAlloc (poolp, sizeof(SecCmsSignedData));
82 if (sigd == NULL)
83 goto loser;
84
85 sigd->cmsg = cmsg;
86
87 /* signerInfos, certs, certlists, crls are all empty */
88 /* version is set in SecCmsSignedDataFinalize() */
89
90 PORT_ArenaUnmark(poolp, mark);
91 return sigd;
92
93loser:
94 PORT_ArenaRelease(poolp, mark);
95 return NULL;
96}
97
98void
99SecCmsSignedDataDestroy(SecCmsSignedDataRef sigd)
100{
101 SecCmsSignerInfoRef *signerinfos, si;
102
103 if (sigd == NULL)
104 return;
105
106 if (sigd->certs != NULL)
107 CFRelease(sigd->certs);
108
109 signerinfos = sigd->signerInfos;
110 if (signerinfos != NULL) {
111 while ((si = *signerinfos++) != NULL)
112 SecCmsSignerInfoDestroy(si);
113 }
114
115 /* everything's in a pool, so don't worry about the storage */
116 SecCmsContentInfoDestroy(&(sigd->contentInfo));
117}
118
119/*
120 * SecCmsSignedDataEncodeBeforeStart - do all the necessary things to a SignedData
121 * before start of encoding.
122 *
123 * In detail:
124 * - find out about the right value to put into sigd->version
125 * - come up with a list of digestAlgorithms (which should be the union of the algorithms
126 * in the signerinfos).
127 * If we happen to have a pre-set list of algorithms (and digest values!), we
128 * check if we have all the signerinfos' algorithms. If not, this is an error.
129 */
130OSStatus
131SecCmsSignedDataEncodeBeforeStart(SecCmsSignedDataRef sigd)
132{
133 SecCmsSignerInfoRef signerinfo;
134 SECOidTag digestalgtag;
135 CSSM_DATA_PTR dummy;
136 int version;
137 OSStatus rv;
138 Boolean haveDigests = PR_FALSE;
139 int n, i;
140 PLArenaPool *poolp;
141
142 poolp = sigd->cmsg->poolp;
143
144 /* we assume that we have precomputed digests if there is a list of algorithms, and */
145 /* a chunk of data for each of those algorithms */
146 if (sigd->digestAlgorithms != NULL && sigd->digests != NULL) {
147 for (i=0; sigd->digestAlgorithms[i] != NULL; i++) {
148 if (sigd->digests[i] == NULL)
149 break;
150 }
151 if (sigd->digestAlgorithms[i] == NULL) /* reached the end of the array? */
152 haveDigests = PR_TRUE; /* yes: we must have all the digests */
153 }
154
155 version = SEC_CMS_SIGNED_DATA_VERSION_BASIC;
156
157 /* RFC2630 5.1 "version is the syntax version number..." */
158 if (SecCmsContentInfoGetContentTypeTag(&(sigd->contentInfo)) != SEC_OID_PKCS7_DATA)
159 version = SEC_CMS_SIGNED_DATA_VERSION_EXT;
160
161 /* prepare all the SignerInfos (there may be none) */
162 for (i=0; i < SecCmsSignedDataSignerInfoCount(sigd); i++) {
163 signerinfo = SecCmsSignedDataGetSignerInfo(sigd, i);
164
165 /* RFC2630 5.1 "version is the syntax version number..." */
166 if (SecCmsSignerInfoGetVersion(signerinfo) != SEC_CMS_SIGNER_INFO_VERSION_ISSUERSN)
167 version = SEC_CMS_SIGNED_DATA_VERSION_EXT;
168
169 /* collect digestAlgorithms from SignerInfos */
170 /* (we need to know which algorithms we have when the content comes in) */
171 /* do not overwrite any existing digestAlgorithms (and digest) */
172 digestalgtag = SecCmsSignerInfoGetDigestAlgTag(signerinfo);
173
174 n = SecCmsAlgArrayGetIndexByAlgTag(sigd->digestAlgorithms, digestalgtag);
175 if (n < 0 && haveDigests) {
176 /* oops, there is a digestalg we do not have a digest for */
177 /* but we were supposed to have all the digests already... */
178 goto loser;
179 } else if (n < 0) {
180 /* add the digestAlgorithm & a NULL digest */
181 rv = SecCmsSignedDataAddDigest((SecArenaPoolRef)poolp, sigd, digestalgtag, NULL);
182 if (rv != SECSuccess)
183 goto loser;
184 } else {
185 /* found it, nothing to do */
186 }
187 }
188
189 dummy = SEC_ASN1EncodeInteger(poolp, &(sigd->version), (long)version);
190 if (dummy == NULL)
191 return SECFailure;
192
193 /* this is a SET OF, so we need to sort them guys */
194 rv = SecCmsArraySortByDER((void **)sigd->digestAlgorithms,
195 SEC_ASN1_GET(SECOID_AlgorithmIDTemplate),
196 (void **)sigd->digests);
197 if (rv != SECSuccess)
198 return SECFailure;
199
200 return SECSuccess;
201
202loser:
203 return SECFailure;
204}
205
206OSStatus
207SecCmsSignedDataEncodeBeforeData(SecCmsSignedDataRef sigd)
208{
209 /* set up the digests */
210 if (sigd->digestAlgorithms != NULL) {
211 sigd->contentInfo.digcx = SecCmsDigestContextStartMultiple(sigd->digestAlgorithms);
212 if (sigd->contentInfo.digcx == NULL)
213 return SECFailure;
214 }
215 return SECSuccess;
216}
217
218#include <AssertMacros.h>
219#include "tsaSupport.h"
220#include "tsaSupportPriv.h"
221#include "tsaTemplates.h"
222#include <security_keychain/tsaDERUtilities.h>
223
224extern const SecAsn1Template kSecAsn1TSATSTInfoTemplate;
225
226OSStatus createTSAMessageImprint(SecCmsSignedDataRef signedData, CSSM_DATA_PTR encDigest,
227 SecAsn1TSAMessageImprint *messageImprint)
228{
229 // Calculate hash of encDigest and put in messageImprint.hashedMessage
230 // We pass in encDigest, since in the verification case, it comes from a different signedData
231
232 OSStatus status = SECFailure;
233
234 require(signedData && messageImprint, xit);
235
236 SECAlgorithmID **digestAlgorithms = SecCmsSignedDataGetDigestAlgs(signedData);
237 require(digestAlgorithms, xit);
238
239 SecCmsDigestContextRef digcx = SecCmsDigestContextStartMultiple(digestAlgorithms);
240 require(digcx, xit);
241 require(encDigest, xit);
242
243 SecCmsSignerInfoRef signerinfo = SecCmsSignedDataGetSignerInfo(signedData, 0); // NB - assume 1 signer only!
244 messageImprint->hashAlgorithm = signerinfo->digestAlg;
245
246 SecCmsDigestContextUpdate(digcx, encDigest->Data, encDigest->Length);
247
248 require_noerr(SecCmsDigestContextFinishSingle(digcx, (SecArenaPoolRef)signedData->cmsg->poolp,
249 &messageImprint->hashedMessage), xit);
250
251 status = SECSuccess;
252xit:
253 return status;
254}
255
256#include <Security/SecAsn1Templates.h>
257
258#ifndef NDEBUG
259static OSStatus decodeDERUTF8String(const CSSM_DATA_PTR content, char *statusstr, size_t strsz)
260{
261 // The statusString should use kSecAsn1SequenceOfUTF8StringTemplate, but doesn't
262 OSStatus status = SECFailure;
263 SecAsn1CoderRef coder = NULL;
264 CSSM_DATA statusString;
265 size_t len = 0;
266
267 require(content && statusstr, xit);
268
269 require_noerr(SecAsn1CoderCreate(&coder), xit);
270 require_noerr(SecAsn1Decode(coder, content->Data, content->Length, kSecAsn1UTF8StringTemplate, &statusString), xit);
271 status = 0;
272 len = (statusString.Length < strsz)?(int)statusString.Length:strsz;
273 if (statusstr && statusString.Data)
274 strncpy(statusstr, (const char *)statusString.Data, len);
275
276xit:
277 if (coder)
278 SecAsn1CoderRelease(coder);
279 return status;
280}
281#endif
282
283static OSStatus validateTSAResponseAndAddTimeStamp(SecCmsSignerInfoRef signerinfo, CSSM_DATA_PTR tsaResponse,
284 uint64_t expectedNonce)
285{
286 OSStatus status = SECFailure;
287 SecAsn1CoderRef coder = NULL;
288 SecAsn1TimeStampRespDER respDER = {{{0}},};
289 SecAsn1TSAPKIStatusInfo *tsastatus = NULL;
290 int respstatus = -1;
291#ifndef NDEBUG
292 int failinfo = -1;
293#endif
294
295 require_action(tsaResponse && tsaResponse->Data && tsaResponse->Length, xit, status = errSecTimestampMissing);
296
297 require_noerr(SecAsn1CoderCreate(&coder), xit);
298 require_noerr(SecTSAResponseCopyDEREncoding(coder, tsaResponse, &respDER), xit);
299
300#ifndef NDEBUG
301 tsaWriteFileX("/tmp/tsa-timeStampToken.der", respDER.timeStampTokenDER.Data, respDER.timeStampTokenDER.Length);
302#endif
303
304 tsastatus = (SecAsn1TSAPKIStatusInfo *)&respDER.status;
305 require_action(tsastatus->status.Data, xit, status = errSecTimestampBadDataFormat);
306 respstatus = (int)tsaDER_ToInt(&tsastatus->status);
307
308#ifndef NDEBUG
309 char buf[80]={0,};
310 if (tsastatus->failInfo.Data) // e.g. FI_BadRequest
311 failinfo = (int)tsaDER_ToInt(&tsastatus->failInfo);
312
313 if (tsastatus->statusString.Data && tsastatus->statusString.Length)
314 {
315 OSStatus strrx = decodeDERUTF8String(&tsastatus->statusString, buf, sizeof(buf));
316 dprintf("decodeDERUTF8String status: %d\n", (int)strrx);
317 }
318
319 dprintf("validateTSAResponse: status: %d, failinfo: %d, %s\n", respstatus, failinfo, buf);
320#endif
321
322 switch (respstatus)
323 {
324 case PKIS_Granted:
325 case PKIS_GrantedWithMods: // Success
326 status = noErr;
327 break;
328 case PKIS_Rejection:
329 status = errSecTimestampRejection;
330 break;
331 case PKIS_Waiting:
332 status = errSecTimestampWaiting;
333 break;
334 case PKIS_RevocationWarning:
335 status = errSecTimestampRevocationWarning;
336 break;
337 case PKIS_RevocationNotification:
338 status = errSecTimestampRevocationNotification;
339 break;
340 default:
341 status = errSecTimestampSystemFailure;
342 break;
343 }
344 require_noerr(status, xit);
345
346 // If we succeeded, then we must have a TimeStampToken
347
348 require_action(respDER.timeStampTokenDER.Data && respDER.timeStampTokenDER.Length, xit, status = errSecTimestampBadDataFormat);
349
350 dprintf("timestamp full expected nonce: %lld\n", expectedNonce);
351
352 /*
353 The bytes in respDER are a full CMS message, which we need to check now for validity.
354 The code for this is essentially the same code taht is done during a timestamp
355 verify, except that we also need to check the nonce.
356 */
357 require_noerr(status = decodeTimeStampToken(signerinfo, &respDER.timeStampTokenDER, NULL, expectedNonce), xit);
358
359 status = SecCmsSignerInfoAddTimeStamp(signerinfo, &respDER.timeStampTokenDER);
360
361xit:
362 if (coder)
363 SecAsn1CoderRelease(coder);
364 return status;
365}
366
367static OSStatus getRandomNonce(uint64_t *nonce)
368{
369 return nonce ? CCRandomCopyBytes(kCCRandomDevRandom, (void *)nonce, sizeof(*nonce)) : SECFailure;
370}
371
372static OSStatus remapTimestampError(OSStatus inStatus)
373{
374 /*
375 Since communicating with the timestamp server is perhaps an unexpected
376 dependency on the network, map unknown errors into something to indicate
377 that signing without a timestamp may be a workaround. In particular, the
378 private CFURL errors (see CFNetworkErrorsPriv.i)
379
380 kCFURLErrorTimedOut = -1001,
381 kCFURLErrorNotConnectedToInternet = -1009,
382
383 are remapped to errSecTimestampServiceNotAvailable.
384 */
385
386 switch (inStatus)
387 {
388 case errSecTimestampMissing:
389 case errSecTimestampInvalid:
390 case errSecTimestampNotTrusted:
391 case errSecTimestampServiceNotAvailable:
392 case errSecTimestampBadAlg:
393 case errSecTimestampBadRequest:
394 case errSecTimestampBadDataFormat:
395 case errSecTimestampTimeNotAvailable:
396 case errSecTimestampUnacceptedPolicy:
397 case errSecTimestampUnacceptedExtension:
398 case errSecTimestampAddInfoNotAvailable:
399 case errSecTimestampSystemFailure:
400 case errSecSigningTimeMissing:
401 case errSecTimestampRejection:
402 case errSecTimestampWaiting:
403 case errSecTimestampRevocationWarning:
404 case errSecTimestampRevocationNotification:
405 return inStatus;
406 default:
407 return errSecTimestampServiceNotAvailable;
408 }
409 return errSecTimestampServiceNotAvailable;
410}
411
412/*
413 * SecCmsSignedDataEncodeAfterData - do all the necessary things to a SignedData
414 * after all the encapsulated data was passed through the encoder.
415 *
416 * In detail:
417 * - create the signatures in all the SignerInfos
418 *
419 * Please note that nothing is done to the Certificates and CRLs in the message - this
420 * is entirely the responsibility of our callers.
421 */
422OSStatus
423SecCmsSignedDataEncodeAfterData(SecCmsSignedDataRef sigd)
424{
425 SecCmsSignerInfoRef *signerinfos, signerinfo;
426 SecCmsContentInfoRef cinfo;
427 SECOidTag digestalgtag;
428 OSStatus ret = SECFailure;
429 OSStatus rv;
430 CSSM_DATA_PTR contentType;
431 int certcount;
432 int i, ci, n, rci, si;
433 PLArenaPool *poolp;
434 CFArrayRef certlist;
435 extern const SecAsn1Template SecCmsSignerInfoTemplate[];
436
437 poolp = sigd->cmsg->poolp;
438 cinfo = &(sigd->contentInfo);
439
440 /* did we have digest calculation going on? */
441 if (cinfo->digcx) {
442 rv = SecCmsDigestContextFinishMultiple(cinfo->digcx, (SecArenaPoolRef)poolp, &(sigd->digests));
443 if (rv != SECSuccess)
444 goto loser; /* error has been set by SecCmsDigestContextFinishMultiple */
445 cinfo->digcx = NULL;
446 }
447
448 signerinfos = sigd->signerInfos;
449 certcount = 0;
450
451 /* prepare all the SignerInfos (there may be none) */
452 for (i=0; i < SecCmsSignedDataSignerInfoCount(sigd); i++) {
453 signerinfo = SecCmsSignedDataGetSignerInfo(sigd, i);
454
455 /* find correct digest for this signerinfo */
456 digestalgtag = SecCmsSignerInfoGetDigestAlgTag(signerinfo);
457 n = SecCmsAlgArrayGetIndexByAlgTag(sigd->digestAlgorithms, digestalgtag);
458 if (n < 0 || sigd->digests == NULL || sigd->digests[n] == NULL) {
459 /* oops - digest not found */
460 PORT_SetError(SEC_ERROR_DIGEST_NOT_FOUND);
461 goto loser;
462 }
463
464 /* XXX if our content is anything else but data, we need to force the
465 * presence of signed attributes (RFC2630 5.3 "signedAttributes is a
466 * collection...") */
467
468 /* pass contentType here as we want a contentType attribute */
469 if ((contentType = SecCmsContentInfoGetContentTypeOID(cinfo)) == NULL)
470 goto loser;
471
472 /* sign the thing */
473 rv = SecCmsSignerInfoSign(signerinfo, sigd->digests[n], contentType);
474 if (rv != SECSuccess)
475 goto loser;
476
477 /* while we're at it, count number of certs in certLists */
478 certlist = SecCmsSignerInfoGetCertList(signerinfo);
479 if (certlist)
480 certcount += CFArrayGetCount(certlist);
481 }
482
483 /* Now we can get a timestamp, since we have all the digests */
484
485 // We force the setting of a callback, since this is the most usual case
486 if (!sigd->cmsg->tsaCallback)
487 SecCmsMessageSetTSACallback(sigd->cmsg, (SecCmsTSACallback)SecCmsTSADefaultCallback);
488
489 if (sigd->cmsg->tsaCallback && sigd->cmsg->tsaContext)
490 {
491 CSSM_DATA tsaResponse = {0,};
492 SecAsn1TSAMessageImprint messageImprint = {{{0},},{0,}};
493 // <rdar://problem/11073466> Add nonce support for timestamping client
494
495 uint64_t nonce = 0;
496
497 require_noerr(getRandomNonce(&nonce), tsxit);
498 dprintf("SecCmsSignedDataSignerInfoCount: %d\n", SecCmsSignedDataSignerInfoCount(sigd));
499
500 // Calculate hash of encDigest and put in messageImprint.hashedMessage
501 SecCmsSignerInfoRef signerinfo = SecCmsSignedDataGetSignerInfo(sigd, 0); // NB - assume 1 signer only!
502 CSSM_DATA *encDigest = SecCmsSignerInfoGetEncDigest(signerinfo);
503 require_noerr(createTSAMessageImprint(sigd, encDigest, &messageImprint), tsxit);
504
505 // Callback to fire up XPC service to talk to TimeStamping server, etc.
506 require_noerr(rv =(*sigd->cmsg->tsaCallback)(sigd->cmsg->tsaContext, &messageImprint,
507 nonce, &tsaResponse), tsxit);
508
509 require_noerr(rv = validateTSAResponseAndAddTimeStamp(signerinfo, &tsaResponse, nonce), tsxit);
510
511 /*
512 It is likely that every occurrence of "goto loser" in this file should
513 also do a PORT_SetError. Since it is not clear what might depend on this
514 behavior, we just do this in the timestamping case.
515 */
516tsxit:
517 if (rv)
518 {
519 dprintf("Original timestamp error: %d\n", (int)rv);
520 rv = remapTimestampError(rv);
521 PORT_SetError(rv);
522 goto loser;
523 }
524 }
525
526 /* this is a SET OF, so we need to sort them guys */
527 rv = SecCmsArraySortByDER((void **)signerinfos, SecCmsSignerInfoTemplate, NULL);
528 if (rv != SECSuccess)
529 goto loser;
530
531 /*
532 * now prepare certs & crls
533 */
534
535 /* count the rest of the certs */
536 if (sigd->certs != NULL)
537 certcount += CFArrayGetCount(sigd->certs);
538
539 if (certcount == 0) {
540 sigd->rawCerts = NULL;
541 } else {
542 /*
543 * Combine all of the certs and cert chains into rawcerts.
544 * Note: certcount is an upper bound; we may not need that many slots
545 * but we will allocate anyway to avoid having to do another pass.
546 * (The temporary space saving is not worth it.)
547 *
548 * XXX ARGH - this NEEDS to be fixed. need to come up with a decent
549 * SetOfDERcertficates implementation
550 */
551 sigd->rawCerts = (CSSM_DATA_PTR *)PORT_ArenaAlloc(poolp, (certcount + 1) * sizeof(CSSM_DATA_PTR));
552 if (sigd->rawCerts == NULL)
553 return SECFailure;
554
555 /*
556 * XXX Want to check for duplicates and not add *any* cert that is
557 * already in the set. This will be more important when we start
558 * dealing with larger sets of certs, dual-key certs (signing and
559 * encryption), etc. For the time being we can slide by...
560 *
561 * XXX ARGH - this NEEDS to be fixed. need to come up with a decent
562 * SetOfDERcertficates implementation
563 */
564 rci = 0;
565 if (signerinfos != NULL) {
566 for (si = 0; signerinfos[si] != NULL; si++) {
567 signerinfo = signerinfos[si];
568 for (ci = 0; ci < CFArrayGetCount(signerinfo->certList); ci++) {
569 sigd->rawCerts[rci] = PORT_ArenaZAlloc(poolp, sizeof(CSSM_DATA));
570 SecCertificateRef cert = (SecCertificateRef)CFArrayGetValueAtIndex(signerinfo->certList, ci);
571 SecCertificateGetData(cert, sigd->rawCerts[rci++]);
572 }
573 }
574 }
575
576 if (sigd->certs != NULL) {
577 for (ci = 0; ci < CFArrayGetCount(sigd->certs); ci++) {
578 sigd->rawCerts[rci] = PORT_ArenaZAlloc(poolp, sizeof(CSSM_DATA));
579 SecCertificateRef cert = (SecCertificateRef)CFArrayGetValueAtIndex(sigd->certs, ci);
580 SecCertificateGetData(cert, sigd->rawCerts[rci++]);
581 }
582 }
583
584 sigd->rawCerts[rci] = NULL;
585
586 /* this is a SET OF, so we need to sort them guys - we have the DER already, though */
587 SecCmsArraySort((void **)sigd->rawCerts, SecCmsUtilDERCompare, NULL, NULL);
588 }
589
590 ret = SECSuccess;
591
592loser:
593
594 dprintf("SecCmsSignedDataEncodeAfterData: ret: %ld, rv: %ld\n", (long)ret, (long)rv);
595 return ret;
596}
597
598OSStatus
599SecCmsSignedDataDecodeBeforeData(SecCmsSignedDataRef sigd)
600{
601 /* set up the digests */
602 if (sigd->digestAlgorithms != NULL && sigd->digests == NULL) {
603 /* if digests are already there, do nothing */
604 sigd->contentInfo.digcx = SecCmsDigestContextStartMultiple(sigd->digestAlgorithms);
605 if (sigd->contentInfo.digcx == NULL)
606 return SECFailure;
607 }
608 return SECSuccess;
609}
610
611/*
612 * SecCmsSignedDataDecodeAfterData - do all the necessary things to a SignedData
613 * after all the encapsulated data was passed through the decoder.
614 */
615OSStatus
616SecCmsSignedDataDecodeAfterData(SecCmsSignedDataRef sigd)
617{
618 /* did we have digest calculation going on? */
619 if (sigd->contentInfo.digcx) {
620 if (SecCmsDigestContextFinishMultiple(sigd->contentInfo.digcx, (SecArenaPoolRef)sigd->cmsg->poolp, &(sigd->digests)) != SECSuccess)
621 return SECFailure; /* error has been set by SecCmsDigestContextFinishMultiple */
622 sigd->contentInfo.digcx = NULL;
623 }
624 return SECSuccess;
625}
626
627/*
628 * SecCmsSignedDataDecodeAfterEnd - do all the necessary things to a SignedData
629 * after all decoding is finished.
630 */
631OSStatus
632SecCmsSignedDataDecodeAfterEnd(SecCmsSignedDataRef sigd)
633{
634 SecCmsSignerInfoRef *signerinfos;
635 int i;
636
637 signerinfos = sigd->signerInfos;
638
639 /* set cmsg and sigd backpointers for all the signerinfos */
640 if (signerinfos) {
641 for (i = 0; signerinfos[i] != NULL; i++) {
642 signerinfos[i]->cmsg = sigd->cmsg;
643 signerinfos[i]->sigd = sigd;
644 }
645 }
646
647 return SECSuccess;
648}
649
650/*
651 * SecCmsSignedDataGetSignerInfos - retrieve the SignedData's signer list
652 */
653SecCmsSignerInfoRef *
654SecCmsSignedDataGetSignerInfos(SecCmsSignedDataRef sigd)
655{
656 return sigd->signerInfos;
657}
658
659int
660SecCmsSignedDataSignerInfoCount(SecCmsSignedDataRef sigd)
661{
662 return SecCmsArrayCount((void **)sigd->signerInfos);
663}
664
665SecCmsSignerInfoRef
666SecCmsSignedDataGetSignerInfo(SecCmsSignedDataRef sigd, int i)
667{
668 return sigd->signerInfos[i];
669}
670
671/*
672 * SecCmsSignedDataGetDigestAlgs - retrieve the SignedData's digest algorithm list
673 */
674SECAlgorithmID **
675SecCmsSignedDataGetDigestAlgs(SecCmsSignedDataRef sigd)
676{
677 return sigd->digestAlgorithms;
678}
679
680/*
681 * SecCmsSignedDataGetContentInfo - return pointer to this signedData's contentinfo
682 */
683SecCmsContentInfoRef
684SecCmsSignedDataGetContentInfo(SecCmsSignedDataRef sigd)
685{
686 return &(sigd->contentInfo);
687}
688
689/*
690 * SecCmsSignedDataGetCertificateList - retrieve the SignedData's certificate list
691 */
692CSSM_DATA_PTR *
693SecCmsSignedDataGetCertificateList(SecCmsSignedDataRef sigd)
694{
695 return sigd->rawCerts;
696}
697
698OSStatus
699SecCmsSignedDataImportCerts(SecCmsSignedDataRef sigd, SecKeychainRef keychain,
700 SECCertUsage certusage, Boolean keepcerts)
701{
702 int certcount;
703 OSStatus rv;
704 int i;
705
706 certcount = SecCmsArrayCount((void **)sigd->rawCerts);
707
708 rv = CERT_ImportCerts(keychain, certusage, certcount, sigd->rawCerts, NULL,
709 keepcerts, PR_FALSE, NULL);
710
711 /* XXX CRL handling */
712
713 if (sigd->signerInfos != NULL) {
714 /* fill in all signerinfo's certs */
715 for (i = 0; sigd->signerInfos[i] != NULL; i++)
716 (void)SecCmsSignerInfoGetSigningCertificate(sigd->signerInfos[i], keychain);
717 }
718
719 return rv;
720}
721
722/*
723 * XXX the digests need to be passed in BETWEEN the decoding and the verification in case
724 * of external signatures!
725 */
726
727/*
728 * SecCmsSignedDataVerifySignerInfo - check the signatures.
729 *
730 * The digests were either calculated during decoding (and are stored in the
731 * signedData itself) or set after decoding using SecCmsSignedDataSetDigests.
732 *
733 * The verification checks if the signing cert is valid and has a trusted chain
734 * for the purpose specified by "policies".
735 *
736 * If trustRef is NULL the cert chain is verified and the VerificationStatus is set accordingly.
737 * Otherwise a SecTrust object is returned for the caller to evaluate using SecTrustEvaluate().
738 */
739OSStatus
740SecCmsSignedDataVerifySignerInfo(SecCmsSignedDataRef sigd, int i,
741 SecKeychainRef keychainOrArray, CFTypeRef policies, SecTrustRef *trustRef)
742{
743 SecCmsSignerInfoRef signerinfo;
744 SecCmsContentInfoRef cinfo;
745 SECOidData *algiddata;
746 CSSM_DATA_PTR contentType, digest;
747 OSStatus status, status2;
748
749 cinfo = &(sigd->contentInfo);
750
751 signerinfo = sigd->signerInfos[i];
752
753 /* Signature or digest level verificationStatus errors should supercede
754 certificate level errors, so check the digest and signature first. */
755
756 /* Find digest and contentType for signerinfo */
757 algiddata = SecCmsSignerInfoGetDigestAlg(signerinfo);
758 if (algiddata == NULL) {
759 return errSecInternalError; // shouldn't have happened, this is likely due to corrupted data
760 }
761
762 digest = SecCmsSignedDataGetDigestByAlgTag(sigd, algiddata->offset);
763 if(digest == NULL) {
764 /*
765 * No digests; this probably had detached content the caller has to
766 * deal with.
767 * FIXME: need some error return for this (as well as many
768 * other places in this library).
769 */
770 return errSecDataNotAvailable;
771 }
772 contentType = SecCmsContentInfoGetContentTypeOID(cinfo);
773
774 /* verify signature */
5c19dc3a
A
775#if SECTRUST_OSX
776#warning STU: <rdar://21328501>
777 // timestamp policy is currently unsupported; use codesign policy only
778 #if !NDEBUG
779 syslog(LOG_ERR, "SecCmsSignedDataVerifySignerInfo: using codesign policy without timestamp verification");
780 #endif
781 CFTypeRef timeStampPolicies=SecPolicyCreateWithProperties(kSecPolicyAppleCodeSigning, NULL);
782#else
d8f41ccd 783 CFTypeRef timeStampPolicies=SecPolicyCreateAppleTimeStampingAndRevocationPolicies(policies);
5c19dc3a 784#endif
d8f41ccd
A
785 status = SecCmsSignerInfoVerifyWithPolicy(signerinfo, timeStampPolicies, digest, contentType);
786 CFReleaseSafe(timeStampPolicies);
787
788 /* Now verify the certificate. We do this even if the signature failed to verify so we can
789 return a trustRef to the caller for display purposes. */
790 status2 = SecCmsSignerInfoVerifyCertificate(signerinfo, keychainOrArray,
791 policies, trustRef);
792 dprintf("SecCmsSignedDataVerifySignerInfo: status %d status2 %d\n", (int) status, (int)status2);
822b670c
A
793 if(status || status2) {
794 syslog(LOG_ERR,"SecCmsSignedDataVerifySignerInfo: status %d status2 %d.", (int) status, (int)status2);
795 syslog(LOG_ERR,"SecCmsSignedDataVerifySignerInfo: verify status %d", signerinfo->verificationStatus);
796 }
d8f41ccd
A
797 /* The error from SecCmsSignerInfoVerify() supercedes error from SecCmsSignerInfoVerifyCertificate(). */
798 if (status)
799 return status;
800
801 return status2;
802}
803
804/*
805 * SecCmsSignedDataVerifyCertsOnly - verify the certs in a certs-only message
806 */
807OSStatus
808SecCmsSignedDataVerifyCertsOnly(SecCmsSignedDataRef sigd,
809 SecKeychainRef keychainOrArray,
810 CFTypeRef policies)
811{
812 SecCertificateRef cert;
813 OSStatus rv = SECSuccess;
814 int i;
815 int count;
816
817 if (!sigd || !keychainOrArray || !sigd->rawCerts) {
818 PORT_SetError(SEC_ERROR_INVALID_ARGS);
819 return SECFailure;
820 }
821
822 count = SecCmsArrayCount((void**)sigd->rawCerts);
823 for (i=0; i < count; i++) {
824 if (sigd->certs && CFArrayGetCount(sigd->certs) > i) {
825 cert = (SecCertificateRef)CFArrayGetValueAtIndex(sigd->certs, i);
826 CFRetain(cert);
827 } else {
828 cert = CERT_FindCertByDERCert(keychainOrArray, sigd->rawCerts[i]);
829 if (!cert) {
830 rv = SECFailure;
831 break;
832 }
833 }
834 rv |= CERT_VerifyCert(keychainOrArray, cert, sigd->rawCerts,
835 policies, CFAbsoluteTimeGetCurrent(), NULL);
836 CFRelease(cert);
837 }
838
839 return rv;
840}
841
842/*
843 * SecCmsSignedDataHasDigests - see if we have digests in place
844 */
845Boolean
846SecCmsSignedDataHasDigests(SecCmsSignedDataRef sigd)
847{
848 return (sigd->digests != NULL);
849}
850
851OSStatus
852SecCmsSignedDataAddCertList(SecCmsSignedDataRef sigd, CFArrayRef certlist)
853{
854 PORT_Assert(certlist != NULL);
855
856 if (certlist == NULL)
857 return SECFailure;
858
859 if (!sigd->certs)
860 sigd->certs = CFArrayCreateMutableCopy(NULL, 0, certlist);
861 else
862 {
863 CFRange certlistRange = { 0, CFArrayGetCount(certlist) };
864 CFArrayAppendArray(sigd->certs, certlist, certlistRange);
865 }
866
867 return SECSuccess;
868}
869
870/*
871 * SecCmsSignedDataAddCertChain - add cert and its entire chain to the set of certs
872 */
873OSStatus
874SecCmsSignedDataAddCertChain(SecCmsSignedDataRef sigd, SecCertificateRef cert)
875{
876 CFArrayRef certlist;
877 SECCertUsage usage;
878 OSStatus rv;
879
880 usage = certUsageEmailSigner;
881
882 /* do not include root */
883 certlist = CERT_CertChainFromCert(cert, usage, PR_FALSE);
884 if (certlist == NULL)
885 return SECFailure;
886
887 rv = SecCmsSignedDataAddCertList(sigd, certlist);
888 CFRelease(certlist);
889
890 return rv;
891}
892
893OSStatus
894SecCmsSignedDataAddCertificate(SecCmsSignedDataRef sigd, SecCertificateRef cert)
895{
896 PORT_Assert(cert != NULL);
897
898 if (cert == NULL)
899 return SECFailure;
900
901 if (!sigd->certs)
902 sigd->certs = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
903
904 CFArrayAppendValue(sigd->certs, cert);
905
906 return SECSuccess;
907}
908
909Boolean
910SecCmsSignedDataContainsCertsOrCrls(SecCmsSignedDataRef sigd)
911{
912 if (sigd->rawCerts != NULL && sigd->rawCerts[0] != NULL)
913 return PR_TRUE;
914 else if (sigd->rawCrls != NULL && sigd->rawCrls[0] != NULL)
915 return PR_TRUE;
916 else
917 return PR_FALSE;
918}
919
920OSStatus
921SecCmsSignedDataAddSignerInfo(SecCmsSignedDataRef sigd,
922 SecCmsSignerInfoRef signerinfo)
923{
924 void *mark;
925 OSStatus rv;
926 SECOidTag digestalgtag;
927 PLArenaPool *poolp;
928
929 poolp = sigd->cmsg->poolp;
930
931 mark = PORT_ArenaMark(poolp);
932
933 /* add signerinfo */
934 rv = SecCmsArrayAdd(poolp, (void ***)&(sigd->signerInfos), (void *)signerinfo);
935 if (rv != SECSuccess)
936 goto loser;
937
938 signerinfo->sigd = sigd;
939
940 /*
941 * add empty digest
942 * Empty because we don't have it yet. Either it gets created during encoding
943 * (if the data is present) or has to be set externally.
944 * XXX maybe pass it in optionally?
945 */
946 digestalgtag = SecCmsSignerInfoGetDigestAlgTag(signerinfo);
947 rv = SecCmsSignedDataSetDigestValue(sigd, digestalgtag, NULL);
948 if (rv != SECSuccess)
949 goto loser;
950
951 /*
952 * The last thing to get consistency would be adding the digest.
953 */
954
955 PORT_ArenaUnmark(poolp, mark);
956 return SECSuccess;
957
958loser:
959 PORT_ArenaRelease (poolp, mark);
960 return SECFailure;
961}
962
963CSSM_DATA_PTR
964SecCmsSignedDataGetDigestByAlgTag(SecCmsSignedDataRef sigd, SECOidTag algtag)
965{
966 int idx;
967
968 if(sigd->digests == NULL) {
969 return NULL;
970 }
971 idx = SecCmsAlgArrayGetIndexByAlgTag(sigd->digestAlgorithms, algtag);
972 return sigd->digests[idx];
973}
974
975/*
976 * SecCmsSignedDataSetDigests - set a signedData's digests member
977 *
978 * "digestalgs" - array of digest algorithm IDs
979 * "digests" - array of digests corresponding to the digest algorithms
980 */
981OSStatus
982SecCmsSignedDataSetDigests(SecCmsSignedDataRef sigd,
983 SECAlgorithmID **digestalgs,
984 CSSM_DATA_PTR *digests)
985{
986 int cnt, i, idx;
987
988 if (sigd->digestAlgorithms == NULL) {
989 PORT_SetError(SEC_ERROR_INVALID_ARGS);
990 return SECFailure;
991 }
992
993 /* we assume that the digests array is just not there yet */
994 PORT_Assert(sigd->digests == NULL);
995 if (sigd->digests != NULL) {
996 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
997 return SECFailure;
998 }
999
1000 /* now allocate one (same size as digestAlgorithms) */
1001 cnt = SecCmsArrayCount((void **)sigd->digestAlgorithms);
1002 sigd->digests = PORT_ArenaZAlloc(sigd->cmsg->poolp, (cnt + 1) * sizeof(CSSM_DATA_PTR));
1003 if (sigd->digests == NULL) {
1004 PORT_SetError(SEC_ERROR_NO_MEMORY);
1005 return SECFailure;
1006 }
1007
1008 for (i = 0; sigd->digestAlgorithms[i] != NULL; i++) {
1009 /* try to find the sigd's i'th digest algorithm in the array we passed in */
1010 idx = SecCmsAlgArrayGetIndexByAlgID(digestalgs, sigd->digestAlgorithms[i]);
1011 if (idx < 0) {
1012 PORT_SetError(SEC_ERROR_DIGEST_NOT_FOUND);
1013 return SECFailure;
1014 }
1015
1016 /* found it - now set it */
1017 if ((sigd->digests[i] = SECITEM_AllocItem(sigd->cmsg->poolp, NULL, 0)) == NULL ||
1018 SECITEM_CopyItem(sigd->cmsg->poolp, sigd->digests[i], digests[idx]) != SECSuccess)
1019 {
1020 PORT_SetError(SEC_ERROR_NO_MEMORY);
1021 return SECFailure;
1022 }
1023 }
1024 return SECSuccess;
1025}
1026
1027OSStatus
1028SecCmsSignedDataSetDigestValue(SecCmsSignedDataRef sigd,
1029 SECOidTag digestalgtag,
1030 CSSM_DATA_PTR digestdata)
1031{
1032 CSSM_DATA_PTR digest = NULL;
1033 PLArenaPool *poolp;
1034 void *mark;
1035 int n, cnt;
1036
1037 poolp = sigd->cmsg->poolp;
1038
1039 mark = PORT_ArenaMark(poolp);
1040
1041
1042 if (digestdata) {
1043 digest = (CSSM_DATA_PTR) PORT_ArenaZAlloc(poolp,sizeof(CSSM_DATA));
1044
1045 /* copy digestdata item to arena (in case we have it and are not only making room) */
1046 if (SECITEM_CopyItem(poolp, digest, digestdata) != SECSuccess)
1047 goto loser;
1048 }
1049
1050 /* now allocate one (same size as digestAlgorithms) */
1051 if (sigd->digests == NULL) {
1052 cnt = SecCmsArrayCount((void **)sigd->digestAlgorithms);
1053 sigd->digests = PORT_ArenaZAlloc(sigd->cmsg->poolp, (cnt + 1) * sizeof(CSSM_DATA_PTR));
1054 if (sigd->digests == NULL) {
1055 PORT_SetError(SEC_ERROR_NO_MEMORY);
1056 return SECFailure;
1057 }
1058 }
1059
1060 n = -1;
1061 if (sigd->digestAlgorithms != NULL)
1062 n = SecCmsAlgArrayGetIndexByAlgTag(sigd->digestAlgorithms, digestalgtag);
1063
1064 /* if not found, add a digest */
1065 if (n < 0) {
1066 if (SecCmsSignedDataAddDigest((SecArenaPoolRef)poolp, sigd, digestalgtag, digest) != SECSuccess)
1067 goto loser;
1068 } else {
1069 /* replace NULL pointer with digest item (and leak previous value) */
1070 sigd->digests[n] = digest;
1071 }
1072
1073 PORT_ArenaUnmark(poolp, mark);
1074 return SECSuccess;
1075
1076loser:
1077 PORT_ArenaRelease(poolp, mark);
1078 return SECFailure;
1079}
1080
1081OSStatus
1082SecCmsSignedDataAddDigest(SecArenaPoolRef pool,
1083 SecCmsSignedDataRef sigd,
1084 SECOidTag digestalgtag,
1085 CSSM_DATA_PTR digest)
1086{
1087 PRArenaPool *poolp = (PRArenaPool *)pool;
1088 SECAlgorithmID *digestalg;
1089 void *mark;
1090
1091 mark = PORT_ArenaMark(poolp);
1092
1093 digestalg = PORT_ArenaZAlloc(poolp, sizeof(SECAlgorithmID));
1094 if (digestalg == NULL)
1095 goto loser;
1096
1097 if (SECOID_SetAlgorithmID (poolp, digestalg, digestalgtag, NULL) != SECSuccess) /* no params */
1098 goto loser;
1099
1100 if (SecCmsArrayAdd(poolp, (void ***)&(sigd->digestAlgorithms), (void *)digestalg) != SECSuccess ||
1101 /* even if digest is NULL, add dummy to have same-size array */
1102 SecCmsArrayAdd(poolp, (void ***)&(sigd->digests), (void *)digest) != SECSuccess)
1103 {
1104 goto loser;
1105 }
1106
1107 PORT_ArenaUnmark(poolp, mark);
1108 return SECSuccess;
1109
1110loser:
1111 PORT_ArenaRelease(poolp, mark);
1112 return SECFailure;
1113}
1114
1115CSSM_DATA_PTR
1116SecCmsSignedDataGetDigestValue(SecCmsSignedDataRef sigd, SECOidTag digestalgtag)
1117{
1118 int n;
1119
1120 if (sigd->digestAlgorithms == NULL)
1121 return NULL;
1122
1123 n = SecCmsAlgArrayGetIndexByAlgTag(sigd->digestAlgorithms, digestalgtag);
1124
1125 return (n < 0) ? NULL : sigd->digests[n];
1126}
1127
1128/* =============================================================================
1129 * Misc. utility functions
1130 */
1131
1132/*
1133 * SecCmsSignedDataCreateCertsOnly - create a certs-only SignedData.
1134 *
1135 * cert - base certificates that will be included
1136 * include_chain - if true, include the complete cert chain for cert
1137 *
1138 * More certs and chains can be added via AddCertificate and AddCertChain.
1139 *
1140 * An error results in a return value of NULL and an error set.
1141 *
1142 * XXXX CRLs
1143 */
1144SecCmsSignedDataRef
1145SecCmsSignedDataCreateCertsOnly(SecCmsMessageRef cmsg, SecCertificateRef cert, Boolean include_chain)
1146{
1147 SecCmsSignedDataRef sigd;
1148 void *mark;
1149 PLArenaPool *poolp;
1150 OSStatus rv;
1151
1152 poolp = cmsg->poolp;
1153 mark = PORT_ArenaMark(poolp);
1154
1155 sigd = SecCmsSignedDataCreate(cmsg);
1156 if (sigd == NULL)
1157 goto loser;
1158
1159 /* no signerinfos, thus no digestAlgorithms */
1160
1161 /* but certs */
1162 if (include_chain) {
1163 rv = SecCmsSignedDataAddCertChain(sigd, cert);
1164 } else {
1165 rv = SecCmsSignedDataAddCertificate(sigd, cert);
1166 }
1167 if (rv != SECSuccess)
1168 goto loser;
1169
1170 /* RFC2630 5.2 sez:
1171 * In the degenerate case where there are no signers, the
1172 * EncapsulatedContentInfo value being "signed" is irrelevant. In this
1173 * case, the content type within the EncapsulatedContentInfo value being
1174 * "signed" should be id-data (as defined in section 4), and the content
1175 * field of the EncapsulatedContentInfo value should be omitted.
1176 */
1177 rv = SecCmsContentInfoSetContentData(cmsg, &(sigd->contentInfo), NULL, PR_TRUE);
1178 if (rv != SECSuccess)
1179 goto loser;
1180
1181 PORT_ArenaUnmark(poolp, mark);
1182 return sigd;
1183
1184loser:
1185 if (sigd)
1186 SecCmsSignedDataDestroy(sigd);
1187 PORT_ArenaRelease(poolp, mark);
1188 return NULL;
1189}
1190
1191/*
1192 * Get SecCmsSignedDataRawCerts - obtain raw certs as a NULL_terminated array
1193 * of pointers.
1194 */
1195extern OSStatus SecCmsSignedDataRawCerts(SecCmsSignedDataRef sigd,
1196 CSSM_DATA_PTR **rawCerts)
1197{
1198 *rawCerts = sigd->rawCerts;
1199 return noErr;
1200}
1201
1202/* TODO:
1203 * SecCmsSignerInfoGetReceiptRequest()
1204 * SecCmsSignedDataHasReceiptRequest()
1205 * easy way to iterate over signers
1206 */
1207