]> git.saurik.com Git - apple/security.git/blob - OSX/libsecurity_cms/lib/CMSEncoder.cpp
de3b2c1ef43975381be7a239e46bf42939b1409f
[apple/security.git] / OSX / libsecurity_cms / lib / CMSEncoder.cpp
1 /*
2 * Copyright (c) 2006-2013 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24 /*
25 * CMSEncoder.cpp - encode, sign, and/or encrypt CMS messages.
26 */
27
28 #include "CMSEncoder.h"
29 #include "CMSPrivate.h"
30 #include "CMSUtils.h"
31 #include <Security/SecBase.h>
32 #include <Security/SecCmsEncoder.h>
33 #include <Security/SecCmsEnvelopedData.h>
34 #include <Security/SecCmsMessage.h>
35 #include <Security/SecCmsRecipientInfo.h>
36 #include <Security/SecCmsSignedData.h>
37 #include <Security/SecCmsSignerInfo.h>
38 #include <Security/SecCmsContentInfo.h>
39 #include <Security/SecCertificate.h>
40 #include <Security/SecIdentity.h>
41 #include <Security/SecKeychain.h>
42 #include <Security/SecKeychainItem.h>
43 #include <Security/SecSMIME.h>
44 #include <Security/oidsattr.h>
45 #include <Security/SecAsn1Coder.h>
46 #include <Security/SecAsn1Types.h>
47 #include <Security/SecAsn1Templates.h>
48 #include <CoreFoundation/CFRuntime.h>
49 #include <pthread.h>
50 #include <utilities/SecCFRelease.h>
51
52 #include <security_smime/tsaSupport.h>
53 #include <security_smime/cmspriv.h>
54
55 #pragma mark --- Private types and definitions ---
56
57 /*
58 * Encoder state.
59 */
60 typedef enum {
61 ES_Init, /* between CMSEncoderCreate and earlier of CMSEncoderUpdateContent
62 * and CMSEncodeGetCmsMessage */
63 ES_Msg, /* created cmsMsg in CMSEncodeGetCmsMessage, but no encoder yet */
64 ES_Updating, /* between first CMSEncoderUpdateContent and CMSEncoderCopyEncodedContent */
65 ES_Final /* CMSEncoderCopyEncodedContent has been called */
66 } CMSEncoderState;
67
68 /*
69 * High-level operation: what are we doing?
70 */
71 typedef enum {
72 EO_Sign,
73 EO_Encrypt,
74 EO_SignEncrypt
75 } CMSEncoderOp;
76
77 /*
78 * Caller's CMSEncoderRef points to one of these.
79 */
80 struct _CMSEncoder {
81 CFRuntimeBase base;
82 CMSEncoderState encState;
83 CMSEncoderOp op;
84 Boolean detachedContent;
85 CSSM_OID eContentType;
86 CFMutableArrayRef signers;
87 CFMutableArrayRef recipients;
88 CFMutableArrayRef otherCerts;
89 CMSSignedAttributes signedAttributes;
90 CFAbsoluteTime signingTime;
91 SecCmsMessageRef cmsMsg;
92 SecArenaPoolRef arena; /* the encoder's arena */
93 SecCmsEncoderRef encoder;
94 CSSM_DATA encoderOut; /* output goes here... */
95 bool customCoder; /* unless this is set by
96 * CMSEncoderSetEncoder */
97 SECOidTag digestalgtag;
98
99 CMSCertificateChainMode chainMode;
100 CFDataRef hashAgilityAttrValue;
101 CFDictionaryRef hashAgilityV2AttrValues;
102 CFAbsoluteTime expirationTime;
103 };
104
105 static void cmsEncoderInit(CFTypeRef enc);
106 static void cmsEncoderFinalize(CFTypeRef enc);
107
108 static CFRuntimeClass cmsEncoderRuntimeClass =
109 {
110 0, /* version */
111 "CMSEncoder",
112 cmsEncoderInit,
113 NULL, /* copy */
114 cmsEncoderFinalize,
115 NULL, /* equal - just use pointer equality */
116 NULL, /* hash, ditto */
117 NULL, /* copyFormattingDesc */
118 NULL /* copyDebugDesc */
119 };
120
121 void
122 CmsMessageSetTSACallback(CMSEncoderRef cmsEncoder, SecCmsTSACallback tsaCallback);
123
124 #pragma mark --- Private routines ---
125
126 /*
127 * Decode a CFStringRef representation of an integer
128 */
129 static int cfStringToNumber(
130 CFStringRef inStr)
131 {
132 int max = 32;
133 char buf[max];
134 if (!inStr || !CFStringGetCString(inStr, buf, max-1, kCFStringEncodingASCII))
135 return -1;
136 return atoi(buf);
137 }
138
139 /*
140 * Encode an integer component of an OID, return resulting number of bytes;
141 * actual bytes are mallocd and returned in *encodeArray.
142 */
143 static unsigned encodeNumber(
144 int num,
145 unsigned char **encodeArray) // mallocd and RETURNED
146 {
147 unsigned char *result;
148 unsigned dex;
149 unsigned numDigits = 0;
150 unsigned scratch;
151
152 /* trival case - 0 maps to 0 */
153 if(num == 0) {
154 *encodeArray = (unsigned char *)malloc(1);
155 **encodeArray = 0;
156 return 1;
157 }
158
159 /* first calculate the number of digits in num, base 128 */
160 scratch = (unsigned)num;
161 while(scratch != 0) {
162 numDigits++;
163 scratch >>= 7;
164 }
165
166 result = (unsigned char *)malloc(numDigits);
167 scratch = (unsigned)num;
168 for(dex=0; dex<numDigits; dex++) {
169 result[numDigits - dex - 1] = scratch & 0x7f;
170 scratch >>= 7;
171 }
172
173 /* all digits except the last one have m.s. bit set */
174 for(dex=0; dex<(numDigits - 1); dex++) {
175 result[dex] |= 0x80;
176 }
177
178 *encodeArray = result;
179 return numDigits;
180 }
181
182 /*
183 * Given an OID in dotted-decimal string representation, convert to binary
184 * DER format. Returns a pointer in outOid which the caller must free(),
185 * as well as the length of the data in outLen.
186 * Function returns 0 if successful, non-zero otherwise.
187 */
188 static int encodeOid(
189 const unsigned char *inStr,
190 unsigned char **outOid,
191 unsigned int *outLen)
192 {
193 unsigned char **digits = NULL; /* array of char * from encodeNumber */
194 unsigned *numDigits = NULL; /* array of unsigned from encodeNumber */
195 CFIndex digit;
196 unsigned numDigitBytes; /* total #of output chars */
197 unsigned char firstByte;
198 unsigned char *outP;
199 CFIndex numsToProcess;
200 CFStringRef oidStr = NULL;
201 CFArrayRef argvRef = NULL;
202 int num, result = 1;
203 CFIndex argc;
204
205 /* parse input string into array of substrings */
206 if (!inStr || !outOid || !outLen) goto cleanExit;
207 oidStr = CFStringCreateWithCString(NULL, (const char *)inStr, kCFStringEncodingASCII);
208 if (!oidStr) goto cleanExit;
209 argvRef = CFStringCreateArrayBySeparatingStrings(NULL, oidStr, CFSTR("."));
210 if (!argvRef) goto cleanExit;
211 argc = CFArrayGetCount(argvRef);
212 if (argc < 3) goto cleanExit;
213
214 /* first two numbers in OID munge together */
215 num = cfStringToNumber((CFStringRef)CFArrayGetValueAtIndex(argvRef, 0));
216 if (num < 0) goto cleanExit;
217 firstByte = (40 * num);
218 num = cfStringToNumber((CFStringRef)CFArrayGetValueAtIndex(argvRef, 1));
219 if (num < 0) goto cleanExit;
220 firstByte += num;
221 numDigitBytes = 1;
222
223 numsToProcess = argc - 2;
224 if(numsToProcess > 0) {
225 /* skip this loop in the unlikely event that input is only two numbers */
226 digits = (unsigned char **) malloc(numsToProcess * sizeof(unsigned char *));
227 numDigits = (unsigned *) malloc(numsToProcess * sizeof(unsigned));
228 for(digit=0; digit<numsToProcess; digit++) {
229 num = cfStringToNumber((CFStringRef)CFArrayGetValueAtIndex(argvRef, digit+2));
230 if (num < 0) goto cleanExit;
231 numDigits[digit] = encodeNumber(num, &digits[digit]);
232 numDigitBytes += numDigits[digit];
233 }
234 }
235 *outLen = (2 + numDigitBytes);
236 *outOid = outP = (unsigned char *) malloc(*outLen);
237 *outP++ = 0x06;
238 *outP++ = numDigitBytes;
239 *outP++ = firstByte;
240 for(digit=0; digit<numsToProcess; digit++) {
241 unsigned int byteDex;
242 for(byteDex=0; byteDex<numDigits[digit]; byteDex++) {
243 *outP++ = digits[digit][byteDex];
244 }
245 }
246 if(digits) {
247 for(digit=0; digit<numsToProcess; digit++) {
248 free(digits[digit]);
249 }
250 }
251 result = 0;
252
253 cleanExit:
254 if (digits) free(digits);
255 if (numDigits) free(numDigits);
256 if (oidStr) CFRelease(oidStr);
257 if (argvRef) CFRelease(argvRef);
258
259 return result;
260 }
261
262 /*
263 * Given a CF object reference describing an OID, convert to binary DER format
264 * and fill out the CSSM_OID structure provided by the caller. Caller is
265 * responsible for freeing the data pointer in outOid->Data.
266 *
267 * Function returns 0 if successful, non-zero otherwise.
268 */
269
270 static int convertOid(
271 CFTypeRef inRef,
272 CSSM_OID *outOid)
273 {
274 if (!inRef || !outOid)
275 return errSecParam;
276
277 unsigned char *oidData = NULL;
278 unsigned int oidLen = 0;
279
280 if (CFGetTypeID(inRef) == CFStringGetTypeID()) {
281 // CFStringRef: OID representation is a dotted-decimal string
282 CFStringRef inStr = (CFStringRef)inRef;
283 CFIndex max = CFStringGetLength(inStr) * 3;
284 char *buf = (char *)malloc(max);
285 if (!buf) {
286 return errSecMemoryError;
287 }
288 if (!CFStringGetCString(inStr, buf, max-1, kCFStringEncodingASCII)) {
289 free(buf);
290 return errSecParam;
291 }
292
293 if (encodeOid((unsigned char *)buf, &oidData, &oidLen) != 0) {
294 free(buf);
295 return errSecParam;
296 }
297 free(buf);
298 }
299 else if (CFGetTypeID(inRef) == CFDataGetTypeID()) {
300 // CFDataRef: OID representation is in binary DER format
301 CFDataRef inData = (CFDataRef)inRef;
302 oidLen = (unsigned int) CFDataGetLength(inData);
303 oidData = (unsigned char *) malloc(oidLen);
304 memcpy(oidData, CFDataGetBytePtr(inData), oidLen);
305 }
306 else {
307 // Not in a format we understand
308 return errSecParam;
309 }
310 outOid->Length = oidLen;
311 outOid->Data = (uint8 *)oidData;
312 return 0;
313 }
314
315 static CFTypeID cmsEncoderTypeID = _kCFRuntimeNotATypeID;
316
317 /* one time only class init, called via pthread_once() in CMSEncoderGetTypeID() */
318 static void cmsEncoderClassInitialize(void)
319 {
320 cmsEncoderTypeID =
321 _CFRuntimeRegisterClass((const CFRuntimeClass * const)&cmsEncoderRuntimeClass);
322 }
323
324 /* init called out from _CFRuntimeCreateInstance() */
325 static void cmsEncoderInit(CFTypeRef enc)
326 {
327 char *start = ((char *)enc) + sizeof(CFRuntimeBase);
328 memset(start, 0, sizeof(struct _CMSEncoder) - sizeof(CFRuntimeBase));
329 }
330
331 /*
332 * Dispose of a CMSEncoder. Called out from CFRelease().
333 */
334 static void cmsEncoderFinalize(
335 CFTypeRef enc)
336 {
337 CMSEncoderRef cmsEncoder = (CMSEncoderRef)enc;
338 if(cmsEncoder == NULL) {
339 return;
340 }
341 if(cmsEncoder->eContentType.Data != NULL) {
342 free(cmsEncoder->eContentType.Data);
343 }
344 CFRELEASE(cmsEncoder->signers);
345 CFRELEASE(cmsEncoder->recipients);
346 CFRELEASE(cmsEncoder->otherCerts);
347 if(cmsEncoder->cmsMsg != NULL) {
348 SecCmsMessageDestroy(cmsEncoder->cmsMsg);
349 cmsEncoder->cmsMsg = NULL;
350 }
351 if(cmsEncoder->arena != NULL) {
352 SecArenaPoolFree(cmsEncoder->arena, false);
353 }
354 if(cmsEncoder->encoder != NULL) {
355 /*
356 * Normally this gets freed in SecCmsEncoderFinish - this is
357 * an error case.
358 */
359 SecCmsEncoderDestroy(cmsEncoder->encoder);
360 }
361 }
362
363 static OSStatus cmsSetupEncoder(
364 CMSEncoderRef cmsEncoder)
365 {
366 OSStatus ortn;
367
368 ASSERT(cmsEncoder->arena == NULL);
369 ASSERT(cmsEncoder->encoder == NULL);
370
371 ortn = SecArenaPoolCreate(1024, &cmsEncoder->arena);
372 if(ortn) {
373 return cmsRtnToOSStatus(ortn);
374 }
375 ortn = SecCmsEncoderCreate(cmsEncoder->cmsMsg,
376 NULL, NULL, // no callback
377 &cmsEncoder->encoderOut, // data goes here
378 cmsEncoder->arena,
379 NULL, NULL, // no password callback (right?)
380 NULL, NULL, // decrypt key callback
381 NULL, NULL, // detached digests
382 &cmsEncoder->encoder);
383 if(ortn) {
384 return cmsRtnToOSStatus(ortn);
385 }
386 return errSecSuccess;
387 }
388
389 /*
390 * Set up a SecCmsMessageRef for a SignedData creation.
391 */
392 static OSStatus cmsSetupForSignedData(
393 CMSEncoderRef cmsEncoder)
394 {
395 ASSERT((cmsEncoder->signers != NULL) || (cmsEncoder->otherCerts != NULL));
396
397 SecCmsContentInfoRef contentInfo = NULL;
398 SecCmsSignedDataRef signedData = NULL;
399 OSStatus ortn;
400
401 /* build chain of objects: message->signedData->data */
402 if(cmsEncoder->cmsMsg != NULL) {
403 SecCmsMessageDestroy(cmsEncoder->cmsMsg);
404 }
405 cmsEncoder->cmsMsg = SecCmsMessageCreate(NULL);
406 if(cmsEncoder->cmsMsg == NULL) {
407 return errSecInternalComponent;
408 }
409
410 signedData = SecCmsSignedDataCreate(cmsEncoder->cmsMsg);
411 if(signedData == NULL) {
412 return errSecInternalComponent;
413 }
414 contentInfo = SecCmsMessageGetContentInfo(cmsEncoder->cmsMsg);
415 ortn = SecCmsContentInfoSetContentSignedData(cmsEncoder->cmsMsg, contentInfo,
416 signedData);
417 if(ortn) {
418 return cmsRtnToOSStatus(ortn);
419 }
420 contentInfo = SecCmsSignedDataGetContentInfo(signedData);
421 if(cmsEncoder->eContentType.Data != NULL) {
422 /* Override the default eContentType of id-data */
423 ortn = SecCmsContentInfoSetContentOther(cmsEncoder->cmsMsg,
424 contentInfo,
425 NULL, /* data - provided to encoder, not here */
426 cmsEncoder->detachedContent,
427 &cmsEncoder->eContentType);
428 }
429 else {
430 ortn = SecCmsContentInfoSetContentData(cmsEncoder->cmsMsg,
431 contentInfo,
432 NULL, /* data - provided to encoder, not here */
433 cmsEncoder->detachedContent);
434 }
435 if(ortn) {
436 ortn = cmsRtnToOSStatus(ortn);
437 CSSM_PERROR("SecCmsContentInfoSetContent*", ortn);
438 return ortn;
439 }
440
441 /* optional 'global' (per-SignedData) certs */
442 if(cmsEncoder->otherCerts != NULL) {
443 ortn = SecCmsSignedDataAddCertList(signedData, cmsEncoder->otherCerts);
444 if(ortn) {
445 ortn = cmsRtnToOSStatus(ortn);
446 CSSM_PERROR("SecCmsSignedDataAddCertList", ortn);
447 return ortn;
448 }
449 }
450
451 /* SignerInfos, one per signer */
452 CFIndex numSigners = 0;
453 if(cmsEncoder->signers != NULL) {
454 /* this is optional...in case we're just creating a cert bundle */
455 numSigners = CFArrayGetCount(cmsEncoder->signers);
456 }
457 CFIndex dex;
458 SecCertificateRef ourCert = NULL;
459 SecCmsCertChainMode chainMode = SecCmsCMCertChain;
460
461 switch(cmsEncoder->chainMode) {
462 case kCMSCertificateNone:
463 chainMode = SecCmsCMNone;
464 break;
465 case kCMSCertificateSignerOnly:
466 chainMode = SecCmsCMCertOnly;
467 break;
468 case kCMSCertificateChainWithRoot:
469 chainMode = SecCmsCMCertChainWithRoot;
470 break;
471 default:
472 break;
473 }
474 for(dex=0; dex<numSigners; dex++) {
475 SecCmsSignerInfoRef signerInfo;
476
477 SecIdentityRef ourId =
478 (SecIdentityRef)CFArrayGetValueAtIndex(cmsEncoder->signers, dex);
479 ortn = SecIdentityCopyCertificate(ourId, &ourCert);
480 if(ortn) {
481 CSSM_PERROR("SecIdentityCopyCertificate", ortn);
482 break;
483 }
484 signerInfo = SecCmsSignerInfoCreate(cmsEncoder->cmsMsg, ourId, cmsEncoder->digestalgtag);
485 if (signerInfo == NULL) {
486 ortn = errSecInternalComponent;
487 break;
488 }
489
490 /* we want the cert chain included for this one */
491 /* NOTE the usage parameter is currently unused by the SMIME lib */
492 ortn = SecCmsSignerInfoIncludeCerts(signerInfo, chainMode,
493 certUsageEmailSigner);
494 if(ortn) {
495 ortn = cmsRtnToOSStatus(ortn);
496 CSSM_PERROR("SecCmsSignerInfoIncludeCerts", ortn);
497 break;
498 }
499
500 /* other options */
501 if(cmsEncoder->signedAttributes & kCMSAttrSmimeCapabilities) {
502 ortn = SecCmsSignerInfoAddSMIMECaps(signerInfo);
503 if(ortn) {
504 ortn = cmsRtnToOSStatus(ortn);
505 CSSM_PERROR("SecCmsSignerInfoAddSMIMEEncKeyPrefs", ortn);
506 break;
507 }
508 }
509 if(cmsEncoder->signedAttributes & kCMSAttrSmimeEncryptionKeyPrefs) {
510 ortn = SecCmsSignerInfoAddSMIMEEncKeyPrefs(signerInfo, ourCert, NULL);
511 if(ortn) {
512 ortn = cmsRtnToOSStatus(ortn);
513 CSSM_PERROR("SecCmsSignerInfoAddSMIMEEncKeyPrefs", ortn);
514 break;
515 }
516 }
517 if(cmsEncoder->signedAttributes & kCMSAttrSmimeMSEncryptionKeyPrefs) {
518 ortn = SecCmsSignerInfoAddMSSMIMEEncKeyPrefs(signerInfo, ourCert, NULL);
519 if(ortn) {
520 ortn = cmsRtnToOSStatus(ortn);
521 CSSM_PERROR("SecCmsSignerInfoAddMSSMIMEEncKeyPrefs", ortn);
522 break;
523 }
524 }
525 if(cmsEncoder->signedAttributes & kCMSAttrSigningTime) {
526 if (cmsEncoder->signingTime == 0)
527 cmsEncoder->signingTime = CFAbsoluteTimeGetCurrent();
528 ortn = SecCmsSignerInfoAddSigningTime(signerInfo, cmsEncoder->signingTime);
529 if(ortn) {
530 ortn = cmsRtnToOSStatus(ortn);
531 CSSM_PERROR("SecCmsSignerInfoAddSigningTime", ortn);
532 break;
533 }
534 }
535 if(cmsEncoder->signedAttributes & kCMSAttrAppleCodesigningHashAgility) {
536 ortn = SecCmsSignerInfoAddAppleCodesigningHashAgility(signerInfo, cmsEncoder->hashAgilityAttrValue);
537 /* libsecurity_smime made a copy of the attribute value. We don't need it anymore. */
538 CFReleaseNull(cmsEncoder->hashAgilityAttrValue);
539 if(ortn) {
540 ortn = cmsRtnToOSStatus(ortn);
541 CSSM_PERROR("SecCmsSignerInfoAddAppleCodesigningHashAgility", ortn);
542 break;
543 }
544 }
545 if(cmsEncoder->signedAttributes & kCMSAttrAppleCodesigningHashAgilityV2) {
546 ortn = SecCmsSignerInfoAddAppleCodesigningHashAgilityV2(signerInfo, cmsEncoder->hashAgilityV2AttrValues);
547 /* libsecurity_smime made a copy of the attribute value. We don't need it anymore. */
548 CFReleaseNull(cmsEncoder->hashAgilityV2AttrValues);
549 if(ortn) {
550 ortn = cmsRtnToOSStatus(ortn);
551 CSSM_PERROR("SecCmsSignerInfoAddAppleCodesigningHashAgilityV2", ortn);
552 break;
553 }
554 }
555 if (cmsEncoder->signedAttributes & kCMSAttrAppleExpirationTime) {
556 ortn = SecCmsSignerInfoAddAppleExpirationTime(signerInfo, cmsEncoder->expirationTime);
557 if(ortn) {
558 ortn = cmsRtnToOSStatus(ortn);
559 CSSM_PERROR("SecCmsSignerInfoAddAppleExpirationTime", ortn);
560 break;
561 }
562 }
563
564 ortn = SecCmsSignedDataAddSignerInfo(signedData, signerInfo);
565 if(ortn) {
566 ortn = cmsRtnToOSStatus(ortn);
567 CSSM_PERROR("SecCmsSignedDataAddSignerInfo", ortn);
568 break;
569 }
570
571 CFRELEASE(ourCert);
572 ourCert = NULL;
573 }
574 if(ortn) {
575 CFRELEASE(ourCert);
576 }
577 return ortn;
578 }
579
580 /*
581 * Set up a SecCmsMessageRef for a EnvelopedData creation.
582 */
583 static OSStatus cmsSetupForEnvelopedData(
584 CMSEncoderRef cmsEncoder)
585 {
586 ASSERT(cmsEncoder->op == EO_Encrypt);
587 ASSERT(cmsEncoder->recipients != NULL);
588
589 SecCmsContentInfoRef contentInfo = NULL;
590 SecCmsEnvelopedDataRef envelopedData = NULL;
591 SECOidTag algorithmTag;
592 int keySize;
593 OSStatus ortn;
594
595 /*
596 * Find encryption algorithm...unfortunately we need a NULL-terminated array
597 * of SecCertificateRefs for this.
598 */
599 CFIndex numCerts = CFArrayGetCount(cmsEncoder->recipients);
600 CFIndex dex;
601 SecCertificateRef *certArray = (SecCertificateRef *)malloc(
602 (numCerts+1) * sizeof(SecCertificateRef));
603
604 for(dex=0; dex<numCerts; dex++) {
605 certArray[dex] = (SecCertificateRef)CFArrayGetValueAtIndex(
606 cmsEncoder->recipients, dex);
607 }
608 certArray[numCerts] = NULL;
609 ortn = SecSMIMEFindBulkAlgForRecipients(certArray, &algorithmTag, &keySize);
610 free(certArray);
611 if(ortn) {
612 CSSM_PERROR("SecSMIMEFindBulkAlgForRecipients", ortn);
613 return ortn;
614 }
615
616 /* build chain of objects: message->envelopedData->data */
617 if(cmsEncoder->cmsMsg != NULL) {
618 SecCmsMessageDestroy(cmsEncoder->cmsMsg);
619 }
620 cmsEncoder->cmsMsg = SecCmsMessageCreate(NULL);
621 if(cmsEncoder->cmsMsg == NULL) {
622 return errSecInternalComponent;
623 }
624 envelopedData = SecCmsEnvelopedDataCreate(cmsEncoder->cmsMsg,
625 algorithmTag, keySize);
626 if(envelopedData == NULL) {
627 return errSecInternalComponent;
628 }
629 contentInfo = SecCmsMessageGetContentInfo(cmsEncoder->cmsMsg);
630 ortn = SecCmsContentInfoSetContentEnvelopedData(cmsEncoder->cmsMsg,
631 contentInfo, envelopedData);
632 if(ortn) {
633 ortn = cmsRtnToOSStatus(ortn);
634 CSSM_PERROR("SecCmsContentInfoSetContentEnvelopedData", ortn);
635 return ortn;
636 }
637 contentInfo = SecCmsEnvelopedDataGetContentInfo(envelopedData);
638 if(cmsEncoder->eContentType.Data != NULL) {
639 /* Override the default ContentType of id-data */
640 ortn = SecCmsContentInfoSetContentOther(cmsEncoder->cmsMsg,
641 contentInfo,
642 NULL, /* data - provided to encoder, not here */
643 FALSE, /* detachedContent */
644 &cmsEncoder->eContentType);
645 }
646 else {
647 ortn = SecCmsContentInfoSetContentData(cmsEncoder->cmsMsg,
648 contentInfo,
649 NULL /* data - provided to encoder, not here */,
650 cmsEncoder->detachedContent);
651 }
652 if(ortn) {
653 ortn = cmsRtnToOSStatus(ortn);
654 CSSM_PERROR("SecCmsContentInfoSetContentData*", ortn);
655 return ortn;
656 }
657
658 /*
659 * create & attach recipient information, one for each recipient
660 */
661 for(dex=0; dex<numCerts; dex++) {
662 SecCmsRecipientInfoRef recipientInfo = NULL;
663
664 SecCertificateRef thisRecip = (SecCertificateRef)CFArrayGetValueAtIndex(
665 cmsEncoder->recipients, dex);
666 recipientInfo = SecCmsRecipientInfoCreate(cmsEncoder->cmsMsg, thisRecip);
667 ortn = SecCmsEnvelopedDataAddRecipient(envelopedData, recipientInfo);
668 if(ortn) {
669 ortn = cmsRtnToOSStatus(ortn);
670 CSSM_PERROR("SecCmsEnvelopedDataAddRecipient", ortn);
671 return ortn;
672 }
673 }
674 return errSecSuccess;
675 }
676
677 /*
678 * Set up cmsMsg. Called from either the first call to CMSEncoderUpdateContent, or
679 * from CMSEncodeGetCmsMessage().
680 */
681 static OSStatus cmsSetupCmsMsg(
682 CMSEncoderRef cmsEncoder)
683 {
684 ASSERT(cmsEncoder != NULL);
685 ASSERT(cmsEncoder->encState == ES_Init);
686
687 /* figure out what high-level operation we're doing */
688 if((cmsEncoder->signers != NULL) || (cmsEncoder->otherCerts != NULL)) {
689 if(cmsEncoder->recipients != NULL) {
690 cmsEncoder->op = EO_SignEncrypt;
691 }
692 else {
693 cmsEncoder->op = EO_Sign;
694 }
695 }
696 else if(cmsEncoder->recipients != NULL) {
697 cmsEncoder->op = EO_Encrypt;
698 }
699 else {
700 dprintf("CMSEncoderUpdateContent: nothing to do\n");
701 return errSecParam;
702 }
703
704 OSStatus ortn = errSecSuccess;
705
706 switch(cmsEncoder->op) {
707 case EO_Sign:
708 case EO_SignEncrypt:
709 /* If we're signing & encrypting, do the signing first */
710 ortn = cmsSetupForSignedData(cmsEncoder);
711 break;
712 case EO_Encrypt:
713 ortn = cmsSetupForEnvelopedData(cmsEncoder);
714 break;
715 }
716 cmsEncoder->encState = ES_Msg;
717 return ortn;
718 }
719
720 /*
721 * ASN.1 template for decoding a ContentInfo.
722 */
723 typedef struct {
724 CSSM_OID contentType;
725 CSSM_DATA content;
726 } SimpleContentInfo;
727
728 static const SecAsn1Template cmsSimpleContentInfoTemplate[] = {
729 { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(SimpleContentInfo) },
730 { SEC_ASN1_OBJECT_ID, offsetof(SimpleContentInfo, contentType) },
731 { SEC_ASN1_EXPLICIT | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 0,
732 offsetof(SimpleContentInfo, content),
733 kSecAsn1AnyTemplate },
734 { 0, }
735 };
736
737 /*
738 * Obtain the content of a contentInfo, This basically strips off the contentType OID
739 * and returns its ASN_ANY content, allocated the provided coder's memory space.
740 */
741 static OSStatus cmsContentInfoContent(
742 SecAsn1CoderRef asn1Coder,
743 const CSSM_DATA *contentInfo,
744 CSSM_DATA *content) /* RETURNED */
745 {
746 OSStatus ortn;
747 SimpleContentInfo decodedInfo;
748
749 memset(&decodedInfo, 0, sizeof(decodedInfo));
750 ortn = SecAsn1DecodeData(asn1Coder, contentInfo,
751 cmsSimpleContentInfoTemplate, &decodedInfo);
752 if(ortn) {
753 return ortn;
754 }
755 if(decodedInfo.content.Data == NULL) {
756 dprintf("***Error decoding contentInfo: no content\n");
757 return errSecInternalComponent;
758 }
759 *content = decodedInfo.content;
760 return errSecSuccess;
761 }
762
763 #pragma mark --- Start of Public API ---
764
765 CFTypeID CMSEncoderGetTypeID(void)
766 {
767 static pthread_once_t once = PTHREAD_ONCE_INIT;
768
769 if(cmsEncoderTypeID == _kCFRuntimeNotATypeID) {
770 pthread_once(&once, &cmsEncoderClassInitialize);
771 }
772 return cmsEncoderTypeID;
773 }
774
775 /*
776 * Create a CMSEncoder. Result must eventually be freed via CFRelease().
777 */
778 OSStatus CMSEncoderCreate(
779 CMSEncoderRef *cmsEncoderOut) /* RETURNED */
780 {
781 CMSEncoderRef cmsEncoder = NULL;
782
783 uint32_t extra = sizeof(*cmsEncoder) - sizeof(cmsEncoder->base);
784 cmsEncoder = (CMSEncoderRef)_CFRuntimeCreateInstance(NULL, CMSEncoderGetTypeID(),
785 extra, NULL);
786 if(cmsEncoder == NULL) {
787 return errSecAllocate;
788 }
789 cmsEncoder->encState = ES_Init;
790 cmsEncoder->chainMode = kCMSCertificateChain;
791 cmsEncoder->digestalgtag = SEC_OID_SHA1;
792 *cmsEncoderOut = cmsEncoder;
793 return errSecSuccess;
794 }
795
796 #pragma mark --- Getters & Setters ---
797
798 const CFStringRef __nonnull kCMSEncoderDigestAlgorithmSHA1 = CFSTR("sha1");
799 const CFStringRef __nonnull kCMSEncoderDigestAlgorithmSHA256 = CFSTR("sha256");
800
801
802 OSStatus CMSEncoderSetSignerAlgorithm(
803 CMSEncoderRef cmsEncoder,
804 CFStringRef digestAlgorithm)
805 {
806 if (CFEqual(digestAlgorithm, kCMSEncoderDigestAlgorithmSHA1)) {
807 cmsEncoder->digestalgtag = SEC_OID_SHA1;
808 } else if (CFEqual(digestAlgorithm, kCMSEncoderDigestAlgorithmSHA256)) {
809 cmsEncoder->digestalgtag = SEC_OID_SHA256;
810 } else {
811 return errSecParam;
812 }
813
814 return errSecSuccess;
815 }
816
817 /*
818 * Specify signers of the CMS message; implies that the message will be signed.
819 */
820 OSStatus CMSEncoderAddSigners(
821 CMSEncoderRef cmsEncoder,
822 CFTypeRef signerOrArray)
823 {
824 if(cmsEncoder == NULL) {
825 return errSecParam;
826 }
827 if(cmsEncoder->encState != ES_Init) {
828 return errSecParam;
829 }
830 return cmsAppendToArray(signerOrArray, &cmsEncoder->signers, SecIdentityGetTypeID());
831 }
832
833 /*
834 * Obtain an array of signers as specified in CMSEncoderSetSigners().
835 */
836 OSStatus CMSEncoderCopySigners(
837 CMSEncoderRef cmsEncoder,
838 CFArrayRef *signers)
839 {
840 if((cmsEncoder == NULL) || (signers == NULL)) {
841 return errSecParam;
842 }
843 if(cmsEncoder->signers != NULL) {
844 CFRetain(cmsEncoder->signers);
845 }
846 *signers = cmsEncoder->signers;
847 return errSecSuccess;
848 }
849
850 /*
851 * Specify recipients of the message. Implies that the message will be encrypted.
852 */
853 OSStatus CMSEncoderAddRecipients(
854 CMSEncoderRef cmsEncoder,
855 CFTypeRef recipientOrArray)
856 {
857 if(cmsEncoder == NULL) {
858 return errSecParam;
859 }
860 if(cmsEncoder->encState != ES_Init) {
861 return errSecParam;
862 }
863 return cmsAppendToArray(recipientOrArray, &cmsEncoder->recipients,
864 SecCertificateGetTypeID());
865 }
866
867 /*
868 * Obtain an array of recipients as specified in CMSEncoderSetRecipients().
869 */
870 OSStatus CMSEncoderCopyRecipients(
871 CMSEncoderRef cmsEncoder,
872 CFArrayRef *recipients)
873 {
874 if((cmsEncoder == NULL) || (recipients == NULL)) {
875 return errSecParam;
876 }
877 if(cmsEncoder->recipients != NULL) {
878 CFRetain(cmsEncoder->recipients);
879 }
880 *recipients = cmsEncoder->recipients;
881 return errSecSuccess;
882 }
883
884 /*
885 * Specify additional certs to include in a signed message.
886 */
887 OSStatus CMSEncoderAddSupportingCerts(
888 CMSEncoderRef cmsEncoder,
889 CFTypeRef certOrArray)
890 {
891 if(cmsEncoder == NULL) {
892 return errSecParam;
893 }
894 if(cmsEncoder->encState != ES_Init) {
895 return errSecParam;
896 }
897 return cmsAppendToArray(certOrArray, &cmsEncoder->otherCerts,
898 SecCertificateGetTypeID());
899 }
900
901 /*
902 * Obtain the SecCertificates provided in CMSEncoderAddSupportingCerts().
903 */
904 OSStatus CMSEncoderCopySupportingCerts(
905 CMSEncoderRef cmsEncoder,
906 CFArrayRef *certs) /* RETURNED */
907 {
908 if((cmsEncoder == NULL) || (certs == NULL)) {
909 return errSecParam;
910 }
911 if(cmsEncoder->otherCerts != NULL) {
912 CFRetain(cmsEncoder->otherCerts);
913 }
914 *certs = cmsEncoder->otherCerts;
915 return errSecSuccess;
916 }
917
918 OSStatus CMSEncoderSetHasDetachedContent(
919 CMSEncoderRef cmsEncoder,
920 Boolean detachedContent)
921 {
922 if(cmsEncoder == NULL) {
923 return errSecParam;
924 }
925 if(cmsEncoder->encState != ES_Init) {
926 return errSecParam;
927 }
928 cmsEncoder->detachedContent = detachedContent;
929 return errSecSuccess;
930 }
931
932 OSStatus CMSEncoderGetHasDetachedContent(
933 CMSEncoderRef cmsEncoder,
934 Boolean *detachedContent) /* RETURNED */
935 {
936 if((cmsEncoder == NULL) || (detachedContent == NULL)) {
937 return errSecParam;
938 }
939 *detachedContent = cmsEncoder->detachedContent;
940 return errSecSuccess;
941 }
942
943 /*
944 * Optionally specify an eContentType OID for the inner EncapsulatedData for
945 * a signed message. The default eContentType, used of this function is not
946 * called, is id-data.
947 */
948 OSStatus CMSEncoderSetEncapsulatedContentType(
949 CMSEncoderRef cmsEncoder,
950 const CSSM_OID *eContentType)
951 {
952 if((cmsEncoder == NULL) || (eContentType == NULL)) {
953 return errSecParam;
954 }
955 if(cmsEncoder->encState != ES_Init) {
956 return errSecParam;
957 }
958
959 CSSM_OID *ecOid = &cmsEncoder->eContentType;
960 if(ecOid->Data != NULL) {
961 free(ecOid->Data);
962 }
963 cmsCopyCmsData(eContentType, ecOid);
964 return errSecSuccess;
965 }
966
967 OSStatus CMSEncoderSetEncapsulatedContentTypeOID(
968 CMSEncoderRef cmsEncoder,
969 CFTypeRef eContentTypeOID)
970 {
971 // convert eContentTypeOID to a CSSM_OID
972 CSSM_OID contentType = { 0, NULL };
973 if (!eContentTypeOID || convertOid(eContentTypeOID, &contentType) != 0)
974 return errSecParam;
975 OSStatus result = CMSEncoderSetEncapsulatedContentType(cmsEncoder, &contentType);
976 if (contentType.Data)
977 free(contentType.Data);
978 return result;
979 }
980
981 /*
982 * Obtain the eContentType OID specified in CMSEncoderSetEncapsulatedContentType().
983 */
984 OSStatus CMSEncoderCopyEncapsulatedContentType(
985 CMSEncoderRef cmsEncoder,
986 CFDataRef *eContentType)
987 {
988 if((cmsEncoder == NULL) || (eContentType == NULL)) {
989 return errSecParam;
990 }
991
992 CSSM_OID *ecOid = &cmsEncoder->eContentType;
993 if(ecOid->Data == NULL) {
994 *eContentType = NULL;
995 }
996 else {
997 *eContentType = CFDataCreate(NULL, ecOid->Data, ecOid->Length);
998 }
999 return errSecSuccess;
1000 }
1001
1002 /*
1003 * Optionally specify signed attributes. Only meaningful when creating a
1004 * signed message. If this is called, it must be called before
1005 * CMSEncoderUpdateContent().
1006 */
1007 OSStatus CMSEncoderAddSignedAttributes(
1008 CMSEncoderRef cmsEncoder,
1009 CMSSignedAttributes signedAttributes)
1010 {
1011 if(cmsEncoder == NULL) {
1012 return errSecParam;
1013 }
1014 if(cmsEncoder->encState != ES_Init) {
1015 return errSecParam;
1016 }
1017 cmsEncoder->signedAttributes |= signedAttributes;
1018 return errSecSuccess;
1019 }
1020
1021 /*
1022 * Set the signing time for a CMSEncoder.
1023 * This is only used if the kCMSAttrSigningTime attribute is included.
1024 */
1025 OSStatus CMSEncoderSetSigningTime(
1026 CMSEncoderRef cmsEncoder,
1027 CFAbsoluteTime time)
1028 {
1029 if(cmsEncoder == NULL) {
1030 return errSecParam;
1031 }
1032 if(cmsEncoder->encState != ES_Init) {
1033 return errSecParam;
1034 }
1035 cmsEncoder->signingTime = time;
1036 return errSecSuccess;
1037 }
1038
1039 /*
1040 * Set the hash agility attribute for a CMSEncoder.
1041 * This is only used if the kCMSAttrAppleCodesigningHashAgility attribute
1042 * is included.
1043 */
1044 OSStatus CMSEncoderSetAppleCodesigningHashAgility(
1045 CMSEncoderRef cmsEncoder,
1046 CFDataRef hashAgilityAttrValue)
1047 {
1048 if (cmsEncoder == NULL || cmsEncoder->encState != ES_Init) {
1049 return errSecParam;
1050 }
1051 cmsEncoder->hashAgilityAttrValue = CFRetainSafe(hashAgilityAttrValue);
1052 return errSecSuccess;
1053 }
1054
1055 /*
1056 * Set the hash agility attribute for a CMSEncoder.
1057 * This is only used if the kCMSAttrAppleCodesigningHashAgilityV2 attribute
1058 * is included.
1059 */
1060 OSStatus CMSEncoderSetAppleCodesigningHashAgilityV2(
1061 CMSEncoderRef cmsEncoder,
1062 CFDictionaryRef hashAgilityV2AttrValues)
1063 {
1064 if (cmsEncoder == NULL || cmsEncoder->encState != ES_Init) {
1065 return errSecParam;
1066 }
1067 cmsEncoder->hashAgilityV2AttrValues = CFRetainSafe(hashAgilityV2AttrValues);
1068 return errSecSuccess;
1069 }
1070
1071 /*
1072 * Set the expiration time for a CMSEncoder.
1073 * This is only used if the kCMSAttrAppleExpirationTime attribute is included.
1074 */
1075 OSStatus CMSEncoderSetAppleExpirationTime(
1076 CMSEncoderRef cmsEncoder,
1077 CFAbsoluteTime time)
1078 {
1079 if(cmsEncoder == NULL) {
1080 return errSecParam;
1081 }
1082 if(cmsEncoder->encState != ES_Init) {
1083 return errSecParam;
1084 }
1085 cmsEncoder->expirationTime = time;
1086 return errSecSuccess;
1087 }
1088
1089 OSStatus CMSEncoderSetCertificateChainMode(
1090 CMSEncoderRef cmsEncoder,
1091 CMSCertificateChainMode chainMode)
1092 {
1093 if(cmsEncoder == NULL) {
1094 return errSecParam;
1095 }
1096 if(cmsEncoder->encState != ES_Init) {
1097 return errSecParam;
1098 }
1099 switch(chainMode) {
1100 case kCMSCertificateNone:
1101 case kCMSCertificateSignerOnly:
1102 case kCMSCertificateChain:
1103 case kCMSCertificateChainWithRoot:
1104 break;
1105 default:
1106 return errSecParam;
1107 }
1108 cmsEncoder->chainMode = chainMode;
1109 return errSecSuccess;
1110 }
1111
1112 OSStatus CMSEncoderGetCertificateChainMode(
1113 CMSEncoderRef cmsEncoder,
1114 CMSCertificateChainMode *chainModeOut)
1115 {
1116 if(cmsEncoder == NULL) {
1117 return errSecParam;
1118 }
1119 *chainModeOut = cmsEncoder->chainMode;
1120 return errSecSuccess;
1121 }
1122
1123 void
1124 CmsMessageSetTSACallback(CMSEncoderRef cmsEncoder, SecCmsTSACallback tsaCallback)
1125 {
1126 if (cmsEncoder->cmsMsg)
1127 SecCmsMessageSetTSACallback(cmsEncoder->cmsMsg, tsaCallback);
1128 }
1129
1130 void
1131 CmsMessageSetTSAContext(CMSEncoderRef cmsEncoder, CFTypeRef tsaContext)
1132 {
1133 if (cmsEncoder->cmsMsg)
1134 SecCmsMessageSetTSAContext(cmsEncoder->cmsMsg, tsaContext);
1135 }
1136
1137 #pragma mark --- Action ---
1138
1139 /*
1140 * Feed content bytes into the encoder.
1141 * Can be called multiple times.
1142 * No 'setter' routines can be called after this function has been called.
1143 */
1144 OSStatus CMSEncoderUpdateContent(
1145 CMSEncoderRef cmsEncoder,
1146 const void *content,
1147 size_t contentLen)
1148 {
1149 if(cmsEncoder == NULL) {
1150 return errSecParam;
1151 }
1152
1153 OSStatus ortn = errSecSuccess;
1154 switch(cmsEncoder->encState) {
1155 case ES_Init:
1156 /*
1157 * First time thru: do the CmsMsg setup.
1158 */
1159 ortn = cmsSetupCmsMsg(cmsEncoder);
1160 if(ortn) {
1161 return ortn;
1162 }
1163 /* fall thru to set up the encoder */
1164
1165 case ES_Msg:
1166 /* We have a cmsMsg but no encoder; create one */
1167 ASSERT(cmsEncoder->cmsMsg != NULL);
1168 ASSERT(cmsEncoder->encoder == NULL);
1169 ortn = cmsSetupEncoder(cmsEncoder);
1170 if(ortn) {
1171 return ortn;
1172 }
1173 /* only legal calls now are update and finalize */
1174 cmsEncoder->encState = ES_Updating;
1175 break;
1176
1177 case ES_Updating:
1178 ASSERT(cmsEncoder->encoder != NULL);
1179 break;
1180
1181 case ES_Final:
1182 /* Too late for another update */
1183 return errSecParam;
1184
1185 default:
1186 return errSecInternalComponent;
1187 }
1188
1189 /* FIXME - CFIndex same size as size_t on 64bit? */
1190 ortn = SecCmsEncoderUpdate(cmsEncoder->encoder, content, (CFIndex)contentLen);
1191 if(ortn) {
1192 ortn = cmsRtnToOSStatus(ortn);
1193 CSSM_PERROR("SecCmsEncoderUpdate", ortn);
1194 }
1195 return ortn;
1196 }
1197
1198 /*
1199 * Finish encoding the message and obtain the encoded result.
1200 * Caller must CFRelease the result.
1201 */
1202 OSStatus CMSEncoderCopyEncodedContent(
1203 CMSEncoderRef cmsEncoder,
1204 CFDataRef *encodedContent)
1205 {
1206 if((cmsEncoder == NULL) || (encodedContent == NULL)) {
1207 return errSecParam;
1208 }
1209
1210 OSStatus ortn;
1211
1212 switch(cmsEncoder->encState) {
1213 case ES_Updating:
1214 /* normal termination */
1215 break;
1216 case ES_Final:
1217 /* already been called */
1218 return errSecParam;
1219 case ES_Msg:
1220 case ES_Init:
1221 /*
1222 * The only time these are legal is when we're doing a SignedData
1223 * with certificates only (no signers, no content).
1224 */
1225 if((cmsEncoder->signers != NULL) ||
1226 (cmsEncoder->recipients != NULL) ||
1227 (cmsEncoder->otherCerts == NULL)) {
1228 return errSecParam;
1229 }
1230
1231 /* Set up for certs only */
1232 ortn = cmsSetupForSignedData(cmsEncoder);
1233 if(ortn) {
1234 return ortn;
1235 }
1236 /* and an encoder */
1237 ortn = cmsSetupEncoder(cmsEncoder);
1238 if(ortn) {
1239 return ortn;
1240 }
1241 break;
1242 }
1243
1244
1245 ASSERT(cmsEncoder->encoder != NULL);
1246 ortn = SecCmsEncoderFinish(cmsEncoder->encoder);
1247 /* regardless of the outcome, the encoder itself has been freed */
1248 cmsEncoder->encoder = NULL;
1249 if(ortn) {
1250 return cmsRtnToOSStatus(ortn);
1251 }
1252 cmsEncoder->encState = ES_Final;
1253
1254 if((cmsEncoder->encoderOut.Data == NULL) && !cmsEncoder->customCoder) {
1255 /* not sure how this could happen... */
1256 dprintf("Successful encode, but no data\n");
1257 return errSecInternalComponent;
1258 }
1259 if(cmsEncoder->customCoder) {
1260 /* we're done */
1261 *encodedContent = NULL;
1262 return errSecSuccess;
1263 }
1264
1265 /* in two out of three cases, we're done */
1266 switch(cmsEncoder->op) {
1267 case EO_Sign:
1268 case EO_Encrypt:
1269 *encodedContent = CFDataCreate(NULL, (const UInt8 *)cmsEncoder->encoderOut.Data,
1270 cmsEncoder->encoderOut.Length);
1271 return errSecSuccess;
1272 case EO_SignEncrypt:
1273 /* proceed, more work to do */
1274 break;
1275 }
1276
1277 /*
1278 * Signing & encrypting.
1279 * Due to bugs in the libsecurity_smime encoder, it can't encode nested
1280 * ContentInfos in one shot. So we do another pass, specifying the SignedData
1281 * inside of the ContentInfo we just created as the data to encrypt.
1282 */
1283 SecAsn1CoderRef asn1Coder = NULL;
1284 CSSM_DATA signedData = {0, NULL};
1285
1286 ortn = SecAsn1CoderCreate(&asn1Coder);
1287 if(ortn) {
1288 return ortn;
1289 }
1290 ortn = cmsContentInfoContent(asn1Coder, &cmsEncoder->encoderOut, &signedData);
1291 if(ortn) {
1292 goto errOut;
1293 }
1294
1295 /* now just encrypt that, one-shot */
1296 ortn = CMSEncode(NULL, /* no signers this time */
1297 cmsEncoder->recipients,
1298 &CSSMOID_PKCS7_SignedData, /* fake out encoder so it doesn't try to actually
1299 * encode the signedData - this asserts the
1300 * SEC_OID_OTHER OID tag in the EnvelopedData's
1301 * ContentInfo */
1302 FALSE, /* detachedContent */
1303 kCMSAttrNone, /* signedAttributes - none this time */
1304 signedData.Data, signedData.Length,
1305 encodedContent);
1306
1307 errOut:
1308 if(asn1Coder) {
1309 SecAsn1CoderRelease(asn1Coder);
1310 }
1311 return ortn;
1312 }
1313
1314 #pragma mark --- High-level API ---
1315
1316 /*
1317 * High-level, one-shot encoder function.
1318 */
1319 OSStatus CMSEncode(
1320 CFTypeRef signers,
1321 CFTypeRef recipients,
1322 const CSSM_OID *eContentType,
1323 Boolean detachedContent,
1324 CMSSignedAttributes signedAttributes,
1325 const void *content,
1326 size_t contentLen,
1327 CFDataRef *encodedContent) /* RETURNED */
1328 {
1329 if((signers == NULL) && (recipients == NULL)) {
1330 return errSecParam;
1331 }
1332 if(encodedContent == NULL) {
1333 return errSecParam;
1334 }
1335
1336 CMSEncoderRef cmsEncoder;
1337 OSStatus ortn;
1338
1339 /* set up the encoder */
1340 ortn = CMSEncoderCreate(&cmsEncoder);
1341 if(ortn) {
1342 return ortn;
1343 }
1344
1345 /* subsequent errors to errOut: */
1346 if(signers) {
1347 ortn = CMSEncoderAddSigners(cmsEncoder, signers);
1348 if(ortn) {
1349 goto errOut;
1350 }
1351 }
1352 if(recipients) {
1353 ortn = CMSEncoderAddRecipients(cmsEncoder, recipients);
1354 if(ortn) {
1355 goto errOut;
1356 }
1357 }
1358 if(eContentType) {
1359 ortn = CMSEncoderSetEncapsulatedContentType(cmsEncoder, eContentType);
1360 if(ortn) {
1361 goto errOut;
1362 }
1363 }
1364 if(detachedContent) {
1365 ortn = CMSEncoderSetHasDetachedContent(cmsEncoder, detachedContent);
1366 if(ortn) {
1367 goto errOut;
1368 }
1369 }
1370 if(signedAttributes) {
1371 ortn = CMSEncoderAddSignedAttributes(cmsEncoder, signedAttributes);
1372 if(ortn) {
1373 goto errOut;
1374 }
1375 }
1376 /* GO */
1377 ortn = CMSEncoderUpdateContent(cmsEncoder, content, contentLen);
1378 if(ortn) {
1379 goto errOut;
1380 }
1381 ortn = CMSEncoderCopyEncodedContent(cmsEncoder, encodedContent);
1382
1383 errOut:
1384 CFRelease(cmsEncoder);
1385 return ortn;
1386 }
1387
1388 OSStatus CMSEncodeContent(
1389 CFTypeRef signers,
1390 CFTypeRef recipients,
1391 CFTypeRef eContentTypeOID,
1392 Boolean detachedContent,
1393 CMSSignedAttributes signedAttributes,
1394 const void *content,
1395 size_t contentLen,
1396 CFDataRef *encodedContentOut) /* RETURNED */
1397 {
1398 // convert eContentTypeOID to a CSSM_OID
1399 CSSM_OID contentType = { 0, NULL };
1400 if (eContentTypeOID && convertOid(eContentTypeOID, &contentType) != 0)
1401 return errSecParam;
1402 const CSSM_OID *contentTypePtr = (eContentTypeOID) ? &contentType : NULL;
1403 OSStatus result = CMSEncode(signers, recipients, contentTypePtr,
1404 detachedContent, signedAttributes,
1405 content, contentLen, encodedContentOut);
1406 if (contentType.Data)
1407 free(contentType.Data);
1408 return result;
1409 }
1410
1411 #pragma mark --- SPI routines declared in CMSPrivate.h ---
1412
1413 /*
1414 * Obtain the SecCmsMessageRef associated with a CMSEncoderRef.
1415 * If we don't have a SecCmsMessageRef yet, we create one now.
1416 * This is the only place where we go to state ES_Msg.
1417 */
1418 OSStatus CMSEncoderGetCmsMessage(
1419 CMSEncoderRef cmsEncoder,
1420 SecCmsMessageRef *cmsMessage) /* RETURNED */
1421 {
1422 if((cmsEncoder == NULL) || (cmsMessage == NULL)) {
1423 return errSecParam;
1424 }
1425 if(cmsEncoder->cmsMsg != NULL) {
1426 ASSERT(cmsEncoder->encState != ES_Init);
1427 *cmsMessage = cmsEncoder->cmsMsg;
1428 return errSecSuccess;
1429 }
1430
1431 OSStatus ortn = cmsSetupCmsMsg(cmsEncoder);
1432 if(ortn) {
1433 return ortn;
1434 }
1435 *cmsMessage = cmsEncoder->cmsMsg;
1436
1437 /* Don't set up encoder yet; caller might do that via CMSEncoderSetEncoder */
1438 cmsEncoder->encState = ES_Msg;
1439 return errSecSuccess;
1440 }
1441
1442 /*
1443 * Optionally specify a SecCmsEncoderRef to use with a CMSEncoderRef.
1444 * If this is called, it must be called before the first call to
1445 * CMSEncoderUpdateContent(). The CMSEncoderRef takes ownership of the
1446 * incoming SecCmsEncoderRef.
1447 */
1448 OSStatus CMSEncoderSetEncoder(
1449 CMSEncoderRef cmsEncoder,
1450 SecCmsEncoderRef encoder)
1451 {
1452 if((cmsEncoder == NULL) || (encoder == NULL)) {
1453 return errSecParam;
1454 }
1455
1456 OSStatus ortn;
1457
1458 switch(cmsEncoder->encState) {
1459 case ES_Init:
1460 /* No message, no encoder */
1461 ASSERT(cmsEncoder->cmsMsg == NULL);
1462 ASSERT(cmsEncoder->encoder == NULL);
1463 ortn = cmsSetupCmsMsg(cmsEncoder);
1464 if(ortn) {
1465 return ortn;
1466 }
1467 /* drop thru to set encoder */
1468 case ES_Msg:
1469 /* cmsMsg but no encoder */
1470 ASSERT(cmsEncoder->cmsMsg != NULL);
1471 ASSERT(cmsEncoder->encoder == NULL);
1472 cmsEncoder->encoder = encoder;
1473 cmsEncoder->encState = ES_Updating;
1474 cmsEncoder->customCoder = true; /* we won't see data */
1475 return errSecSuccess;
1476 default:
1477 /* no can do, too late */
1478 return errSecParam;
1479 }
1480 }
1481
1482 /*
1483 * Obtain the SecCmsEncoderRef associated with a CMSEncoderRef.
1484 * Returns a NULL SecCmsEncoderRef if neither CMSEncoderSetEncoder nor
1485 * CMSEncoderUpdateContent() has been called.
1486 * The CMSEncoderRef retains ownership of the SecCmsEncoderRef.
1487 */
1488 OSStatus CMSEncoderGetEncoder(
1489 CMSEncoderRef cmsEncoder,
1490 SecCmsEncoderRef *encoder) /* RETURNED */
1491 {
1492 if((cmsEncoder == NULL) || (encoder == NULL)) {
1493 return errSecParam;
1494 }
1495
1496 /* any state, whether we have an encoder or not is OK */
1497 *encoder = cmsEncoder->encoder;
1498 return errSecSuccess;
1499 }
1500
1501 #include <AssertMacros.h>
1502
1503 /*
1504 * Obtain the timestamp of signer 'signerIndex' of a CMS message, if
1505 * present. This timestamp is an authenticated timestamp provided by
1506 * a timestamping authority.
1507 *
1508 * Returns errSecParam if the CMS message was not signed or if signerIndex
1509 * is greater than the number of signers of the message minus one.
1510 *
1511 * This cannot be called until after CMSEncoderCopyEncodedContent() is called.
1512 */
1513 OSStatus CMSEncoderCopySignerTimestamp(
1514 CMSEncoderRef cmsEncoder,
1515 size_t signerIndex, /* usually 0 */
1516 CFAbsoluteTime *timestamp) /* RETURNED */
1517 {
1518 return CMSEncoderCopySignerTimestampWithPolicy(
1519 cmsEncoder,
1520 NULL,
1521 signerIndex,
1522 timestamp);
1523 }
1524
1525 OSStatus CMSEncoderCopySignerTimestampWithPolicy(
1526 CMSEncoderRef cmsEncoder,
1527 CFTypeRef timeStampPolicy,
1528 size_t signerIndex, /* usually 0 */
1529 CFAbsoluteTime *timestamp) /* RETURNED */
1530 {
1531 OSStatus status = errSecParam;
1532 SecCmsMessageRef cmsg;
1533 SecCmsSignedDataRef signedData = NULL;
1534 int numContentInfos = 0;
1535
1536 require(cmsEncoder && timestamp, xit);
1537 require_noerr(CMSEncoderGetCmsMessage(cmsEncoder, &cmsg), xit);
1538 numContentInfos = SecCmsMessageContentLevelCount(cmsg);
1539 for (int dex = 0; !signedData && dex < numContentInfos; dex++)
1540 {
1541 SecCmsContentInfoRef ci = SecCmsMessageContentLevel(cmsg, dex);
1542 SECOidTag tag = SecCmsContentInfoGetContentTypeTag(ci);
1543 if (tag == SEC_OID_PKCS7_SIGNED_DATA)
1544 if ((signedData = SecCmsSignedDataRef(SecCmsContentInfoGetContent(ci))))
1545 if (SecCmsSignerInfoRef signerInfo = SecCmsSignedDataGetSignerInfo(signedData, (int)signerIndex))
1546 {
1547 status = SecCmsSignerInfoGetTimestampTimeWithPolicy(signerInfo, timeStampPolicy, timestamp);
1548 break;
1549 }
1550 }
1551
1552 xit:
1553 return status;
1554 }