2 * Copyright (c) 2006-2013 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
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
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.
21 * @APPLE_LICENSE_HEADER_END@
25 * CMSEncoder.cpp - encode, sign, and/or encrypt CMS messages.
28 #include "CMSEncoder.h"
29 #include "CMSPrivate.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>
50 #include <utilities/SecCFRelease.h>
52 #include <security_smime/tsaSupport.h>
53 #include <security_smime/cmspriv.h>
55 #pragma mark --- Private types and definitions ---
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 */
69 * High-level operation: what are we doing?
78 * Caller's CMSEncoderRef points to one of these.
82 CMSEncoderState encState
;
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
;
99 CMSCertificateChainMode chainMode
;
100 CFDataRef hashAgilityAttrValue
;
103 static void cmsEncoderInit(CFTypeRef enc
);
104 static void cmsEncoderFinalize(CFTypeRef enc
);
106 static CFRuntimeClass cmsEncoderRuntimeClass
=
113 NULL
, /* equal - just use pointer equality */
114 NULL
, /* hash, ditto */
115 NULL
, /* copyFormattingDesc */
116 NULL
/* copyDebugDesc */
120 CmsMessageSetTSACallback(CMSEncoderRef cmsEncoder
, SecCmsTSACallback tsaCallback
);
122 #pragma mark --- Private routines ---
125 * Decode a CFStringRef representation of an integer
127 static int cfStringToNumber(
132 if (!inStr
|| !CFStringGetCString(inStr
, buf
, max
-1, kCFStringEncodingASCII
))
138 * Encode an integer component of an OID, return resulting number of bytes;
139 * actual bytes are mallocd and returned in *encodeArray.
141 static unsigned encodeNumber(
143 unsigned char **encodeArray
) // mallocd and RETURNED
145 unsigned char *result
;
147 unsigned numDigits
= 0;
150 /* trival case - 0 maps to 0 */
152 *encodeArray
= (unsigned char *)malloc(1);
157 /* first calculate the number of digits in num, base 128 */
158 scratch
= (unsigned)num
;
159 while(scratch
!= 0) {
164 result
= (unsigned char *)malloc(numDigits
);
165 scratch
= (unsigned)num
;
166 for(dex
=0; dex
<numDigits
; dex
++) {
167 result
[numDigits
- dex
- 1] = scratch
& 0x7f;
171 /* all digits except the last one have m.s. bit set */
172 for(dex
=0; dex
<(numDigits
- 1); dex
++) {
176 *encodeArray
= result
;
181 * Given an OID in dotted-decimal string representation, convert to binary
182 * DER format. Returns a pointer in outOid which the caller must free(),
183 * as well as the length of the data in outLen.
184 * Function returns 0 if successful, non-zero otherwise.
186 static int encodeOid(
187 const unsigned char *inStr
,
188 unsigned char **outOid
,
189 unsigned int *outLen
)
191 unsigned char **digits
= NULL
; /* array of char * from encodeNumber */
192 unsigned *numDigits
= NULL
; /* array of unsigned from encodeNumber */
194 unsigned numDigitBytes
; /* total #of output chars */
195 unsigned char firstByte
;
197 CFIndex numsToProcess
;
198 CFStringRef oidStr
= NULL
;
199 CFArrayRef argvRef
= NULL
;
203 /* parse input string into array of substrings */
204 if (!inStr
|| !outOid
|| !outLen
) goto cleanExit
;
205 oidStr
= CFStringCreateWithCString(NULL
, (const char *)inStr
, kCFStringEncodingASCII
);
206 if (!oidStr
) goto cleanExit
;
207 argvRef
= CFStringCreateArrayBySeparatingStrings(NULL
, oidStr
, CFSTR("."));
208 if (!argvRef
) goto cleanExit
;
209 argc
= CFArrayGetCount(argvRef
);
210 if (argc
< 3) goto cleanExit
;
212 /* first two numbers in OID munge together */
213 num
= cfStringToNumber((CFStringRef
)CFArrayGetValueAtIndex(argvRef
, 0));
214 if (num
< 0) goto cleanExit
;
215 firstByte
= (40 * num
);
216 num
= cfStringToNumber((CFStringRef
)CFArrayGetValueAtIndex(argvRef
, 1));
217 if (num
< 0) goto cleanExit
;
221 numsToProcess
= argc
- 2;
222 if(numsToProcess
> 0) {
223 /* skip this loop in the unlikely event that input is only two numbers */
224 digits
= (unsigned char **) malloc(numsToProcess
* sizeof(unsigned char *));
225 numDigits
= (unsigned *) malloc(numsToProcess
* sizeof(unsigned));
226 for(digit
=0; digit
<numsToProcess
; digit
++) {
227 num
= cfStringToNumber((CFStringRef
)CFArrayGetValueAtIndex(argvRef
, digit
+2));
228 if (num
< 0) goto cleanExit
;
229 numDigits
[digit
] = encodeNumber(num
, &digits
[digit
]);
230 numDigitBytes
+= numDigits
[digit
];
233 *outLen
= (2 + numDigitBytes
);
234 *outOid
= outP
= (unsigned char *) malloc(*outLen
);
236 *outP
++ = numDigitBytes
;
238 for(digit
=0; digit
<numsToProcess
; digit
++) {
239 unsigned int byteDex
;
240 for(byteDex
=0; byteDex
<numDigits
[digit
]; byteDex
++) {
241 *outP
++ = digits
[digit
][byteDex
];
245 for(digit
=0; digit
<numsToProcess
; digit
++) {
254 if (oidStr
) CFRelease(oidStr
);
255 if (argvRef
) CFRelease(argvRef
);
261 * Given a CF object reference describing an OID, convert to binary DER format
262 * and fill out the CSSM_OID structure provided by the caller. Caller is
263 * responsible for freeing the data pointer in outOid->Data.
265 * Function returns 0 if successful, non-zero otherwise.
268 static int convertOid(
272 if (!inRef
|| !outOid
)
275 unsigned char *oidData
= NULL
;
276 unsigned int oidLen
= 0;
278 if (CFGetTypeID(inRef
) == CFStringGetTypeID()) {
279 // CFStringRef: OID representation is a dotted-decimal string
280 CFStringRef inStr
= (CFStringRef
)inRef
;
281 CFIndex max
= CFStringGetLength(inStr
) * 3;
283 if (!CFStringGetCString(inStr
, buf
, max
-1, kCFStringEncodingASCII
))
286 if(encodeOid((unsigned char *)buf
, &oidData
, &oidLen
) != 0)
289 else if (CFGetTypeID(inRef
) == CFDataGetTypeID()) {
290 // CFDataRef: OID representation is in binary DER format
291 CFDataRef inData
= (CFDataRef
)inRef
;
292 oidLen
= (unsigned int) CFDataGetLength(inData
);
293 oidData
= (unsigned char *) malloc(oidLen
);
294 memcpy(oidData
, CFDataGetBytePtr(inData
), oidLen
);
297 // Not in a format we understand
300 outOid
->Length
= oidLen
;
301 outOid
->Data
= (uint8
*)oidData
;
305 static CFTypeID cmsEncoderTypeID
= _kCFRuntimeNotATypeID
;
307 /* one time only class init, called via pthread_once() in CMSEncoderGetTypeID() */
308 static void cmsEncoderClassInitialize(void)
311 _CFRuntimeRegisterClass((const CFRuntimeClass
* const)&cmsEncoderRuntimeClass
);
314 /* init called out from _CFRuntimeCreateInstance() */
315 static void cmsEncoderInit(CFTypeRef enc
)
317 char *start
= ((char *)enc
) + sizeof(CFRuntimeBase
);
318 memset(start
, 0, sizeof(struct _CMSEncoder
) - sizeof(CFRuntimeBase
));
322 * Dispose of a CMSEncoder. Called out from CFRelease().
324 static void cmsEncoderFinalize(
327 CMSEncoderRef cmsEncoder
= (CMSEncoderRef
)enc
;
328 if(cmsEncoder
== NULL
) {
331 if(cmsEncoder
->eContentType
.Data
!= NULL
) {
332 free(cmsEncoder
->eContentType
.Data
);
334 CFRELEASE(cmsEncoder
->signers
);
335 CFRELEASE(cmsEncoder
->recipients
);
336 CFRELEASE(cmsEncoder
->otherCerts
);
337 if(cmsEncoder
->cmsMsg
!= NULL
) {
338 SecCmsMessageDestroy(cmsEncoder
->cmsMsg
);
340 if(cmsEncoder
->arena
!= NULL
) {
341 SecArenaPoolFree(cmsEncoder
->arena
, false);
343 if(cmsEncoder
->encoder
!= NULL
) {
345 * Normally this gets freed in SecCmsEncoderFinish - this is
348 SecCmsEncoderDestroy(cmsEncoder
->encoder
);
352 static OSStatus
cmsSetupEncoder(
353 CMSEncoderRef cmsEncoder
)
357 ASSERT(cmsEncoder
->arena
== NULL
);
358 ASSERT(cmsEncoder
->encoder
== NULL
);
360 ortn
= SecArenaPoolCreate(1024, &cmsEncoder
->arena
);
362 return cmsRtnToOSStatus(ortn
);
364 ortn
= SecCmsEncoderCreate(cmsEncoder
->cmsMsg
,
365 NULL
, NULL
, // no callback
366 &cmsEncoder
->encoderOut
, // data goes here
368 NULL
, NULL
, // no password callback (right?)
369 NULL
, NULL
, // decrypt key callback
370 NULL
, NULL
, // detached digests
371 &cmsEncoder
->encoder
);
373 return cmsRtnToOSStatus(ortn
);
375 return errSecSuccess
;
379 * Set up a SecCmsMessageRef for a SignedData creation.
381 static OSStatus
cmsSetupForSignedData(
382 CMSEncoderRef cmsEncoder
)
384 ASSERT((cmsEncoder
->signers
!= NULL
) || (cmsEncoder
->otherCerts
!= NULL
));
386 SecCmsContentInfoRef contentInfo
= NULL
;
387 SecCmsSignedDataRef signedData
= NULL
;
390 /* build chain of objects: message->signedData->data */
391 if(cmsEncoder
->cmsMsg
!= NULL
) {
392 SecCmsMessageDestroy(cmsEncoder
->cmsMsg
);
394 cmsEncoder
->cmsMsg
= SecCmsMessageCreate(NULL
);
395 if(cmsEncoder
->cmsMsg
== NULL
) {
396 return errSecInternalComponent
;
399 signedData
= SecCmsSignedDataCreate(cmsEncoder
->cmsMsg
);
400 if(signedData
== NULL
) {
401 return errSecInternalComponent
;
403 contentInfo
= SecCmsMessageGetContentInfo(cmsEncoder
->cmsMsg
);
404 ortn
= SecCmsContentInfoSetContentSignedData(cmsEncoder
->cmsMsg
, contentInfo
,
407 return cmsRtnToOSStatus(ortn
);
409 contentInfo
= SecCmsSignedDataGetContentInfo(signedData
);
410 if(cmsEncoder
->eContentType
.Data
!= NULL
) {
411 /* Override the default eContentType of id-data */
412 ortn
= SecCmsContentInfoSetContentOther(cmsEncoder
->cmsMsg
,
414 NULL
, /* data - provided to encoder, not here */
415 cmsEncoder
->detachedContent
,
416 &cmsEncoder
->eContentType
);
419 ortn
= SecCmsContentInfoSetContentData(cmsEncoder
->cmsMsg
,
421 NULL
, /* data - provided to encoder, not here */
422 cmsEncoder
->detachedContent
);
425 ortn
= cmsRtnToOSStatus(ortn
);
426 CSSM_PERROR("SecCmsContentInfoSetContent*", ortn
);
430 /* optional 'global' (per-SignedData) certs */
431 if(cmsEncoder
->otherCerts
!= NULL
) {
432 ortn
= SecCmsSignedDataAddCertList(signedData
, cmsEncoder
->otherCerts
);
434 ortn
= cmsRtnToOSStatus(ortn
);
435 CSSM_PERROR("SecCmsSignedDataAddCertList", ortn
);
440 /* SignerInfos, one per signer */
441 CFIndex numSigners
= 0;
442 if(cmsEncoder
->signers
!= NULL
) {
443 /* this is optional...in case we're just creating a cert bundle */
444 numSigners
= CFArrayGetCount(cmsEncoder
->signers
);
447 SecCertificateRef ourCert
= NULL
;
448 SecCmsCertChainMode chainMode
= SecCmsCMCertChain
;
450 switch(cmsEncoder
->chainMode
) {
451 case kCMSCertificateNone
:
452 chainMode
= SecCmsCMNone
;
454 case kCMSCertificateSignerOnly
:
455 chainMode
= SecCmsCMCertOnly
;
457 case kCMSCertificateChainWithRoot
:
458 chainMode
= SecCmsCMCertChainWithRoot
;
463 for(dex
=0; dex
<numSigners
; dex
++) {
464 SecCmsSignerInfoRef signerInfo
;
466 SecIdentityRef ourId
=
467 (SecIdentityRef
)CFArrayGetValueAtIndex(cmsEncoder
->signers
, dex
);
468 ortn
= SecIdentityCopyCertificate(ourId
, &ourCert
);
470 CSSM_PERROR("SecIdentityCopyCertificate", ortn
);
473 signerInfo
= SecCmsSignerInfoCreate(cmsEncoder
->cmsMsg
, ourId
, cmsEncoder
->digestalgtag
);
474 if (signerInfo
== NULL
) {
475 ortn
= errSecInternalComponent
;
479 /* we want the cert chain included for this one */
480 /* NOTE the usage parameter is currently unused by the SMIME lib */
481 ortn
= SecCmsSignerInfoIncludeCerts(signerInfo
, chainMode
,
482 certUsageEmailSigner
);
484 ortn
= cmsRtnToOSStatus(ortn
);
485 CSSM_PERROR("SecCmsSignerInfoIncludeCerts", ortn
);
490 if(cmsEncoder
->signedAttributes
& kCMSAttrSmimeCapabilities
) {
491 ortn
= SecCmsSignerInfoAddSMIMECaps(signerInfo
);
493 ortn
= cmsRtnToOSStatus(ortn
);
494 CSSM_PERROR("SecCmsSignerInfoAddSMIMEEncKeyPrefs", ortn
);
498 if(cmsEncoder
->signedAttributes
& kCMSAttrSmimeEncryptionKeyPrefs
) {
499 ortn
= SecCmsSignerInfoAddSMIMEEncKeyPrefs(signerInfo
, ourCert
, NULL
);
501 ortn
= cmsRtnToOSStatus(ortn
);
502 CSSM_PERROR("SecCmsSignerInfoAddSMIMEEncKeyPrefs", ortn
);
506 if(cmsEncoder
->signedAttributes
& kCMSAttrSmimeMSEncryptionKeyPrefs
) {
507 ortn
= SecCmsSignerInfoAddMSSMIMEEncKeyPrefs(signerInfo
, ourCert
, NULL
);
509 ortn
= cmsRtnToOSStatus(ortn
);
510 CSSM_PERROR("SecCmsSignerInfoAddMSSMIMEEncKeyPrefs", ortn
);
514 if(cmsEncoder
->signedAttributes
& kCMSAttrSigningTime
) {
515 if (cmsEncoder
->signingTime
== 0)
516 cmsEncoder
->signingTime
= CFAbsoluteTimeGetCurrent();
517 ortn
= SecCmsSignerInfoAddSigningTime(signerInfo
, cmsEncoder
->signingTime
);
519 ortn
= cmsRtnToOSStatus(ortn
);
520 CSSM_PERROR("SecCmsSignerInfoAddSigningTime", ortn
);
524 if(cmsEncoder
->signedAttributes
& kCMSAttrAppleCodesigningHashAgility
) {
525 ortn
= SecCmsSignerInfoAddAppleCodesigningHashAgility(signerInfo
, cmsEncoder
->hashAgilityAttrValue
);
526 /* libsecurity_smime made a copy of the attribute value. We don't need it anymore. */
527 CFReleaseNull(cmsEncoder
->hashAgilityAttrValue
);
529 ortn
= cmsRtnToOSStatus(ortn
);
530 CSSM_PERROR("SecCmsSignerInfoAddAppleCodesigningHashAgility", ortn
);
535 ortn
= SecCmsSignedDataAddSignerInfo(signedData
, signerInfo
);
537 ortn
= cmsRtnToOSStatus(ortn
);
538 CSSM_PERROR("SecCmsSignedDataAddSignerInfo", ortn
);
552 * Set up a SecCmsMessageRef for a EnvelopedData creation.
554 static OSStatus
cmsSetupForEnvelopedData(
555 CMSEncoderRef cmsEncoder
)
557 ASSERT(cmsEncoder
->op
== EO_Encrypt
);
558 ASSERT(cmsEncoder
->recipients
!= NULL
);
560 SecCmsContentInfoRef contentInfo
= NULL
;
561 SecCmsEnvelopedDataRef envelopedData
= NULL
;
562 SECOidTag algorithmTag
;
567 * Find encryption algorithm...unfortunately we need a NULL-terminated array
568 * of SecCertificateRefs for this.
570 CFIndex numCerts
= CFArrayGetCount(cmsEncoder
->recipients
);
572 SecCertificateRef
*certArray
= (SecCertificateRef
*)malloc(
573 (numCerts
+1) * sizeof(SecCertificateRef
));
575 for(dex
=0; dex
<numCerts
; dex
++) {
576 certArray
[dex
] = (SecCertificateRef
)CFArrayGetValueAtIndex(
577 cmsEncoder
->recipients
, dex
);
579 certArray
[numCerts
] = NULL
;
580 ortn
= SecSMIMEFindBulkAlgForRecipients(certArray
, &algorithmTag
, &keySize
);
583 CSSM_PERROR("SecSMIMEFindBulkAlgForRecipients", ortn
);
587 /* build chain of objects: message->envelopedData->data */
588 if(cmsEncoder
->cmsMsg
!= NULL
) {
589 SecCmsMessageDestroy(cmsEncoder
->cmsMsg
);
591 cmsEncoder
->cmsMsg
= SecCmsMessageCreate(NULL
);
592 if(cmsEncoder
->cmsMsg
== NULL
) {
593 return errSecInternalComponent
;
595 envelopedData
= SecCmsEnvelopedDataCreate(cmsEncoder
->cmsMsg
,
596 algorithmTag
, keySize
);
597 if(envelopedData
== NULL
) {
598 return errSecInternalComponent
;
600 contentInfo
= SecCmsMessageGetContentInfo(cmsEncoder
->cmsMsg
);
601 ortn
= SecCmsContentInfoSetContentEnvelopedData(cmsEncoder
->cmsMsg
,
602 contentInfo
, envelopedData
);
604 ortn
= cmsRtnToOSStatus(ortn
);
605 CSSM_PERROR("SecCmsContentInfoSetContentEnvelopedData", ortn
);
608 contentInfo
= SecCmsEnvelopedDataGetContentInfo(envelopedData
);
609 if(cmsEncoder
->eContentType
.Data
!= NULL
) {
610 /* Override the default ContentType of id-data */
611 ortn
= SecCmsContentInfoSetContentOther(cmsEncoder
->cmsMsg
,
613 NULL
, /* data - provided to encoder, not here */
614 FALSE
, /* detachedContent */
615 &cmsEncoder
->eContentType
);
618 ortn
= SecCmsContentInfoSetContentData(cmsEncoder
->cmsMsg
,
620 NULL
/* data - provided to encoder, not here */,
621 cmsEncoder
->detachedContent
);
624 ortn
= cmsRtnToOSStatus(ortn
);
625 CSSM_PERROR("SecCmsContentInfoSetContentData*", ortn
);
630 * create & attach recipient information, one for each recipient
632 for(dex
=0; dex
<numCerts
; dex
++) {
633 SecCmsRecipientInfoRef recipientInfo
= NULL
;
635 SecCertificateRef thisRecip
= (SecCertificateRef
)CFArrayGetValueAtIndex(
636 cmsEncoder
->recipients
, dex
);
637 recipientInfo
= SecCmsRecipientInfoCreate(cmsEncoder
->cmsMsg
, thisRecip
);
638 ortn
= SecCmsEnvelopedDataAddRecipient(envelopedData
, recipientInfo
);
640 ortn
= cmsRtnToOSStatus(ortn
);
641 CSSM_PERROR("SecCmsEnvelopedDataAddRecipient", ortn
);
645 return errSecSuccess
;
649 * Set up cmsMsg. Called from either the first call to CMSEncoderUpdateContent, or
650 * from CMSEncodeGetCmsMessage().
652 static OSStatus
cmsSetupCmsMsg(
653 CMSEncoderRef cmsEncoder
)
655 ASSERT(cmsEncoder
!= NULL
);
656 ASSERT(cmsEncoder
->encState
== ES_Init
);
658 /* figure out what high-level operation we're doing */
659 if((cmsEncoder
->signers
!= NULL
) || (cmsEncoder
->otherCerts
!= NULL
)) {
660 if(cmsEncoder
->recipients
!= NULL
) {
661 cmsEncoder
->op
= EO_SignEncrypt
;
664 cmsEncoder
->op
= EO_Sign
;
667 else if(cmsEncoder
->recipients
!= NULL
) {
668 cmsEncoder
->op
= EO_Encrypt
;
671 dprintf("CMSEncoderUpdateContent: nothing to do\n");
675 OSStatus ortn
= errSecSuccess
;
677 switch(cmsEncoder
->op
) {
680 /* If we're signing & encrypting, do the signing first */
681 ortn
= cmsSetupForSignedData(cmsEncoder
);
684 ortn
= cmsSetupForEnvelopedData(cmsEncoder
);
687 cmsEncoder
->encState
= ES_Msg
;
692 * ASN.1 template for decoding a ContentInfo.
695 CSSM_OID contentType
;
699 static const SecAsn1Template cmsSimpleContentInfoTemplate
[] = {
700 { SEC_ASN1_SEQUENCE
, 0, NULL
, sizeof(SimpleContentInfo
) },
701 { SEC_ASN1_OBJECT_ID
, offsetof(SimpleContentInfo
, contentType
) },
702 { SEC_ASN1_EXPLICIT
| SEC_ASN1_CONSTRUCTED
| SEC_ASN1_CONTEXT_SPECIFIC
| 0,
703 offsetof(SimpleContentInfo
, content
),
704 kSecAsn1AnyTemplate
},
709 * Obtain the content of a contentInfo, This basically strips off the contentType OID
710 * and returns its ASN_ANY content, allocated the provided coder's memory space.
712 static OSStatus
cmsContentInfoContent(
713 SecAsn1CoderRef asn1Coder
,
714 const CSSM_DATA
*contentInfo
,
715 CSSM_DATA
*content
) /* RETURNED */
718 SimpleContentInfo decodedInfo
;
720 memset(&decodedInfo
, 0, sizeof(decodedInfo
));
721 ortn
= SecAsn1DecodeData(asn1Coder
, contentInfo
,
722 cmsSimpleContentInfoTemplate
, &decodedInfo
);
726 if(decodedInfo
.content
.Data
== NULL
) {
727 dprintf("***Error decoding contentInfo: no content\n");
728 return errSecInternalComponent
;
730 *content
= decodedInfo
.content
;
731 return errSecSuccess
;
734 #pragma mark --- Start of Public API ---
736 CFTypeID
CMSEncoderGetTypeID(void)
738 static pthread_once_t once
= PTHREAD_ONCE_INIT
;
740 if(cmsEncoderTypeID
== _kCFRuntimeNotATypeID
) {
741 pthread_once(&once
, &cmsEncoderClassInitialize
);
743 return cmsEncoderTypeID
;
747 * Create a CMSEncoder. Result must eventually be freed via CFRelease().
749 OSStatus
CMSEncoderCreate(
750 CMSEncoderRef
*cmsEncoderOut
) /* RETURNED */
752 CMSEncoderRef cmsEncoder
= NULL
;
754 uint32_t extra
= sizeof(*cmsEncoder
) - sizeof(cmsEncoder
->base
);
755 cmsEncoder
= (CMSEncoderRef
)_CFRuntimeCreateInstance(NULL
, CMSEncoderGetTypeID(),
757 if(cmsEncoder
== NULL
) {
758 return errSecAllocate
;
760 cmsEncoder
->encState
= ES_Init
;
761 cmsEncoder
->chainMode
= kCMSCertificateChain
;
762 cmsEncoder
->digestalgtag
= SEC_OID_SHA1
;
763 *cmsEncoderOut
= cmsEncoder
;
764 return errSecSuccess
;
767 #pragma mark --- Getters & Setters ---
769 const CFStringRef __nonnull kCMSEncoderDigestAlgorithmSHA1
= CFSTR("sha1");
770 const CFStringRef __nonnull kCMSEncoderDigestAlgorithmSHA256
= CFSTR("sha256");
773 OSStatus
CMSEncoderSetSignerAlgorithm(
774 CMSEncoderRef cmsEncoder
,
775 CFStringRef digestAlgorithm
)
777 if (CFEqual(digestAlgorithm
, kCMSEncoderDigestAlgorithmSHA1
)) {
778 cmsEncoder
->digestalgtag
= SEC_OID_SHA1
;
779 } else if (CFEqual(digestAlgorithm
, kCMSEncoderDigestAlgorithmSHA256
)) {
780 cmsEncoder
->digestalgtag
= SEC_OID_SHA256
;
785 return errSecSuccess
;
789 * Specify signers of the CMS message; implies that the message will be signed.
791 OSStatus
CMSEncoderAddSigners(
792 CMSEncoderRef cmsEncoder
,
793 CFTypeRef signerOrArray
)
795 if(cmsEncoder
== NULL
) {
798 if(cmsEncoder
->encState
!= ES_Init
) {
801 return cmsAppendToArray(signerOrArray
, &cmsEncoder
->signers
, SecIdentityGetTypeID());
805 * Obtain an array of signers as specified in CMSEncoderSetSigners().
807 OSStatus
CMSEncoderCopySigners(
808 CMSEncoderRef cmsEncoder
,
811 if((cmsEncoder
== NULL
) || (signers
== NULL
)) {
814 if(cmsEncoder
->signers
!= NULL
) {
815 CFRetain(cmsEncoder
->signers
);
817 *signers
= cmsEncoder
->signers
;
818 return errSecSuccess
;
822 * Specify recipients of the message. Implies that the message will be encrypted.
824 OSStatus
CMSEncoderAddRecipients(
825 CMSEncoderRef cmsEncoder
,
826 CFTypeRef recipientOrArray
)
828 if(cmsEncoder
== NULL
) {
831 if(cmsEncoder
->encState
!= ES_Init
) {
834 return cmsAppendToArray(recipientOrArray
, &cmsEncoder
->recipients
,
835 SecCertificateGetTypeID());
839 * Obtain an array of recipients as specified in CMSEncoderSetRecipients().
841 OSStatus
CMSEncoderCopyRecipients(
842 CMSEncoderRef cmsEncoder
,
843 CFArrayRef
*recipients
)
845 if((cmsEncoder
== NULL
) || (recipients
== NULL
)) {
848 if(cmsEncoder
->recipients
!= NULL
) {
849 CFRetain(cmsEncoder
->recipients
);
851 *recipients
= cmsEncoder
->recipients
;
852 return errSecSuccess
;
856 * Specify additional certs to include in a signed message.
858 OSStatus
CMSEncoderAddSupportingCerts(
859 CMSEncoderRef cmsEncoder
,
860 CFTypeRef certOrArray
)
862 if(cmsEncoder
== NULL
) {
865 if(cmsEncoder
->encState
!= ES_Init
) {
868 return cmsAppendToArray(certOrArray
, &cmsEncoder
->otherCerts
,
869 SecCertificateGetTypeID());
873 * Obtain the SecCertificates provided in CMSEncoderAddSupportingCerts().
875 OSStatus
CMSEncoderCopySupportingCerts(
876 CMSEncoderRef cmsEncoder
,
877 CFArrayRef
*certs
) /* RETURNED */
879 if((cmsEncoder
== NULL
) || (certs
== NULL
)) {
882 if(cmsEncoder
->otherCerts
!= NULL
) {
883 CFRetain(cmsEncoder
->otherCerts
);
885 *certs
= cmsEncoder
->otherCerts
;
886 return errSecSuccess
;
889 OSStatus
CMSEncoderSetHasDetachedContent(
890 CMSEncoderRef cmsEncoder
,
891 Boolean detachedContent
)
893 if(cmsEncoder
== NULL
) {
896 if(cmsEncoder
->encState
!= ES_Init
) {
899 cmsEncoder
->detachedContent
= detachedContent
;
900 return errSecSuccess
;
903 OSStatus
CMSEncoderGetHasDetachedContent(
904 CMSEncoderRef cmsEncoder
,
905 Boolean
*detachedContent
) /* RETURNED */
907 if((cmsEncoder
== NULL
) || (detachedContent
== NULL
)) {
910 *detachedContent
= cmsEncoder
->detachedContent
;
911 return errSecSuccess
;
915 * Optionally specify an eContentType OID for the inner EncapsulatedData for
916 * a signed message. The default eContentType, used of this function is not
917 * called, is id-data.
919 OSStatus
CMSEncoderSetEncapsulatedContentType(
920 CMSEncoderRef cmsEncoder
,
921 const CSSM_OID
*eContentType
)
923 if((cmsEncoder
== NULL
) || (eContentType
== NULL
)) {
926 if(cmsEncoder
->encState
!= ES_Init
) {
930 CSSM_OID
*ecOid
= &cmsEncoder
->eContentType
;
931 if(ecOid
->Data
!= NULL
) {
934 cmsCopyCmsData(eContentType
, ecOid
);
935 return errSecSuccess
;
938 OSStatus
CMSEncoderSetEncapsulatedContentTypeOID(
939 CMSEncoderRef cmsEncoder
,
940 CFTypeRef eContentTypeOID
)
942 // convert eContentTypeOID to a CSSM_OID
943 CSSM_OID contentType
= { 0, NULL
};
944 if (!eContentTypeOID
|| convertOid(eContentTypeOID
, &contentType
) != 0)
946 OSStatus result
= CMSEncoderSetEncapsulatedContentType(cmsEncoder
, &contentType
);
947 if (contentType
.Data
)
948 free(contentType
.Data
);
953 * Obtain the eContentType OID specified in CMSEncoderSetEncapsulatedContentType().
955 OSStatus
CMSEncoderCopyEncapsulatedContentType(
956 CMSEncoderRef cmsEncoder
,
957 CFDataRef
*eContentType
)
959 if((cmsEncoder
== NULL
) || (eContentType
== NULL
)) {
963 CSSM_OID
*ecOid
= &cmsEncoder
->eContentType
;
964 if(ecOid
->Data
== NULL
) {
965 *eContentType
= NULL
;
968 *eContentType
= CFDataCreate(NULL
, ecOid
->Data
, ecOid
->Length
);
970 return errSecSuccess
;
974 * Optionally specify signed attributes. Only meaningful when creating a
975 * signed message. If this is called, it must be called before
976 * CMSEncoderUpdateContent().
978 OSStatus
CMSEncoderAddSignedAttributes(
979 CMSEncoderRef cmsEncoder
,
980 CMSSignedAttributes signedAttributes
)
982 if(cmsEncoder
== NULL
) {
985 if(cmsEncoder
->encState
!= ES_Init
) {
988 cmsEncoder
->signedAttributes
|= signedAttributes
;
989 return errSecSuccess
;
993 * Set the signing time for a CMSEncoder.
994 * This is only used if the kCMSAttrSigningTime attribute is included.
996 OSStatus
CMSEncoderSetSigningTime(
997 CMSEncoderRef cmsEncoder
,
1000 if(cmsEncoder
== NULL
) {
1003 if(cmsEncoder
->encState
!= ES_Init
) {
1006 cmsEncoder
->signingTime
= time
;
1007 return errSecSuccess
;
1011 * Set the hash agility attribute for a CMSEncoder.
1012 * This is only used if the kCMSAttrAppleCodesigningHashAgility attribute
1015 OSStatus
CMSEncoderSetAppleCodesigningHashAgility(
1016 CMSEncoderRef cmsEncoder
,
1017 CFDataRef hashAgilityAttrValue
)
1019 if (cmsEncoder
== NULL
|| cmsEncoder
->encState
!= ES_Init
) {
1022 cmsEncoder
->hashAgilityAttrValue
= CFRetainSafe(hashAgilityAttrValue
);
1023 return errSecSuccess
;
1026 OSStatus
CMSEncoderSetCertificateChainMode(
1027 CMSEncoderRef cmsEncoder
,
1028 CMSCertificateChainMode chainMode
)
1030 if(cmsEncoder
== NULL
) {
1033 if(cmsEncoder
->encState
!= ES_Init
) {
1037 case kCMSCertificateNone
:
1038 case kCMSCertificateSignerOnly
:
1039 case kCMSCertificateChain
:
1040 case kCMSCertificateChainWithRoot
:
1045 cmsEncoder
->chainMode
= chainMode
;
1046 return errSecSuccess
;
1049 OSStatus
CMSEncoderGetCertificateChainMode(
1050 CMSEncoderRef cmsEncoder
,
1051 CMSCertificateChainMode
*chainModeOut
)
1053 if(cmsEncoder
== NULL
) {
1056 *chainModeOut
= cmsEncoder
->chainMode
;
1057 return errSecSuccess
;
1061 CmsMessageSetTSACallback(CMSEncoderRef cmsEncoder
, SecCmsTSACallback tsaCallback
)
1063 if (cmsEncoder
->cmsMsg
)
1064 SecCmsMessageSetTSACallback(cmsEncoder
->cmsMsg
, tsaCallback
);
1068 CmsMessageSetTSAContext(CMSEncoderRef cmsEncoder
, CFTypeRef tsaContext
)
1070 if (cmsEncoder
->cmsMsg
)
1071 SecCmsMessageSetTSAContext(cmsEncoder
->cmsMsg
, tsaContext
);
1074 #pragma mark --- Action ---
1077 * Feed content bytes into the encoder.
1078 * Can be called multiple times.
1079 * No 'setter' routines can be called after this function has been called.
1081 OSStatus
CMSEncoderUpdateContent(
1082 CMSEncoderRef cmsEncoder
,
1083 const void *content
,
1086 if(cmsEncoder
== NULL
) {
1090 OSStatus ortn
= errSecSuccess
;
1091 switch(cmsEncoder
->encState
) {
1094 * First time thru: do the CmsMsg setup.
1096 ortn
= cmsSetupCmsMsg(cmsEncoder
);
1100 /* fall thru to set up the encoder */
1103 /* We have a cmsMsg but no encoder; create one */
1104 ASSERT(cmsEncoder
->cmsMsg
!= NULL
);
1105 ASSERT(cmsEncoder
->encoder
== NULL
);
1106 ortn
= cmsSetupEncoder(cmsEncoder
);
1110 /* only legal calls now are update and finalize */
1111 cmsEncoder
->encState
= ES_Updating
;
1115 ASSERT(cmsEncoder
->encoder
!= NULL
);
1119 /* Too late for another update */
1123 return errSecInternalComponent
;
1126 /* FIXME - CFIndex same size as size_t on 64bit? */
1127 ortn
= SecCmsEncoderUpdate(cmsEncoder
->encoder
, content
, (CFIndex
)contentLen
);
1129 ortn
= cmsRtnToOSStatus(ortn
);
1130 CSSM_PERROR("SecCmsEncoderUpdate", ortn
);
1136 * Finish encoding the message and obtain the encoded result.
1137 * Caller must CFRelease the result.
1139 OSStatus
CMSEncoderCopyEncodedContent(
1140 CMSEncoderRef cmsEncoder
,
1141 CFDataRef
*encodedContent
)
1143 if((cmsEncoder
== NULL
) || (encodedContent
== NULL
)) {
1149 switch(cmsEncoder
->encState
) {
1151 /* normal termination */
1154 /* already been called */
1159 * The only time these are legal is when we're doing a SignedData
1160 * with certificates only (no signers, no content).
1162 if((cmsEncoder
->signers
!= NULL
) ||
1163 (cmsEncoder
->recipients
!= NULL
) ||
1164 (cmsEncoder
->otherCerts
== NULL
)) {
1168 /* Set up for certs only */
1169 ortn
= cmsSetupForSignedData(cmsEncoder
);
1173 /* and an encoder */
1174 ortn
= cmsSetupEncoder(cmsEncoder
);
1182 ASSERT(cmsEncoder
->encoder
!= NULL
);
1183 ortn
= SecCmsEncoderFinish(cmsEncoder
->encoder
);
1184 /* regardless of the outcome, the encoder itself has been freed */
1185 cmsEncoder
->encoder
= NULL
;
1187 return cmsRtnToOSStatus(ortn
);
1189 cmsEncoder
->encState
= ES_Final
;
1191 if((cmsEncoder
->encoderOut
.Data
== NULL
) && !cmsEncoder
->customCoder
) {
1192 /* not sure how this could happen... */
1193 dprintf("Successful encode, but no data\n");
1194 return errSecInternalComponent
;
1196 if(cmsEncoder
->customCoder
) {
1198 *encodedContent
= NULL
;
1199 return errSecSuccess
;
1202 /* in two out of three cases, we're done */
1203 switch(cmsEncoder
->op
) {
1206 *encodedContent
= CFDataCreate(NULL
, (const UInt8
*)cmsEncoder
->encoderOut
.Data
,
1207 cmsEncoder
->encoderOut
.Length
);
1208 return errSecSuccess
;
1209 case EO_SignEncrypt
:
1210 /* proceed, more work to do */
1215 * Signing & encrypting.
1216 * Due to bugs in the libsecurity_smime encoder, it can't encode nested
1217 * ContentInfos in one shot. So we do another pass, specifying the SignedData
1218 * inside of the ContentInfo we just created as the data to encrypt.
1220 SecAsn1CoderRef asn1Coder
= NULL
;
1221 CSSM_DATA signedData
= {0, NULL
};
1223 ortn
= SecAsn1CoderCreate(&asn1Coder
);
1227 ortn
= cmsContentInfoContent(asn1Coder
, &cmsEncoder
->encoderOut
, &signedData
);
1232 /* now just encrypt that, one-shot */
1233 ortn
= CMSEncode(NULL
, /* no signers this time */
1234 cmsEncoder
->recipients
,
1235 &CSSMOID_PKCS7_SignedData
, /* fake out encoder so it doesn't try to actually
1236 * encode the signedData - this asserts the
1237 * SEC_OID_OTHER OID tag in the EnvelopedData's
1239 FALSE
, /* detachedContent */
1240 kCMSAttrNone
, /* signedAttributes - none this time */
1241 signedData
.Data
, signedData
.Length
,
1246 SecAsn1CoderRelease(asn1Coder
);
1251 #pragma mark --- High-level API ---
1254 * High-level, one-shot encoder function.
1258 CFTypeRef recipients
,
1259 const CSSM_OID
*eContentType
,
1260 Boolean detachedContent
,
1261 CMSSignedAttributes signedAttributes
,
1262 const void *content
,
1264 CFDataRef
*encodedContent
) /* RETURNED */
1266 if((signers
== NULL
) && (recipients
== NULL
)) {
1269 if(encodedContent
== NULL
) {
1273 CMSEncoderRef cmsEncoder
;
1276 /* set up the encoder */
1277 ortn
= CMSEncoderCreate(&cmsEncoder
);
1282 /* subsequent errors to errOut: */
1284 ortn
= CMSEncoderAddSigners(cmsEncoder
, signers
);
1290 ortn
= CMSEncoderAddRecipients(cmsEncoder
, recipients
);
1296 ortn
= CMSEncoderSetEncapsulatedContentType(cmsEncoder
, eContentType
);
1301 if(detachedContent
) {
1302 ortn
= CMSEncoderSetHasDetachedContent(cmsEncoder
, detachedContent
);
1307 if(signedAttributes
) {
1308 ortn
= CMSEncoderAddSignedAttributes(cmsEncoder
, signedAttributes
);
1314 ortn
= CMSEncoderUpdateContent(cmsEncoder
, content
, contentLen
);
1318 ortn
= CMSEncoderCopyEncodedContent(cmsEncoder
, encodedContent
);
1321 CFRelease(cmsEncoder
);
1325 OSStatus
CMSEncodeContent(
1327 CFTypeRef recipients
,
1328 CFTypeRef eContentTypeOID
,
1329 Boolean detachedContent
,
1330 CMSSignedAttributes signedAttributes
,
1331 const void *content
,
1333 CFDataRef
*encodedContentOut
) /* RETURNED */
1335 // convert eContentTypeOID to a CSSM_OID
1336 CSSM_OID contentType
= { 0, NULL
};
1337 if (eContentTypeOID
&& convertOid(eContentTypeOID
, &contentType
) != 0)
1339 const CSSM_OID
*contentTypePtr
= (eContentTypeOID
) ? &contentType
: NULL
;
1340 OSStatus result
= CMSEncode(signers
, recipients
, contentTypePtr
,
1341 detachedContent
, signedAttributes
,
1342 content
, contentLen
, encodedContentOut
);
1343 if (contentType
.Data
)
1344 free(contentType
.Data
);
1348 #pragma mark --- SPI routines declared in CMSPrivate.h ---
1351 * Obtain the SecCmsMessageRef associated with a CMSEncoderRef.
1352 * If we don't have a SecCmsMessageRef yet, we create one now.
1353 * This is the only place where we go to state ES_Msg.
1355 OSStatus
CMSEncoderGetCmsMessage(
1356 CMSEncoderRef cmsEncoder
,
1357 SecCmsMessageRef
*cmsMessage
) /* RETURNED */
1359 if((cmsEncoder
== NULL
) || (cmsMessage
== NULL
)) {
1362 if(cmsEncoder
->cmsMsg
!= NULL
) {
1363 ASSERT(cmsEncoder
->encState
!= ES_Init
);
1364 *cmsMessage
= cmsEncoder
->cmsMsg
;
1365 return errSecSuccess
;
1368 OSStatus ortn
= cmsSetupCmsMsg(cmsEncoder
);
1372 *cmsMessage
= cmsEncoder
->cmsMsg
;
1374 /* Don't set up encoder yet; caller might do that via CMSEncoderSetEncoder */
1375 cmsEncoder
->encState
= ES_Msg
;
1376 return errSecSuccess
;
1380 * Optionally specify a SecCmsEncoderRef to use with a CMSEncoderRef.
1381 * If this is called, it must be called before the first call to
1382 * CMSEncoderUpdateContent(). The CMSEncoderRef takes ownership of the
1383 * incoming SecCmsEncoderRef.
1385 OSStatus
CMSEncoderSetEncoder(
1386 CMSEncoderRef cmsEncoder
,
1387 SecCmsEncoderRef encoder
)
1389 if((cmsEncoder
== NULL
) || (encoder
== NULL
)) {
1395 switch(cmsEncoder
->encState
) {
1397 /* No message, no encoder */
1398 ASSERT(cmsEncoder
->cmsMsg
== NULL
);
1399 ASSERT(cmsEncoder
->encoder
== NULL
);
1400 ortn
= cmsSetupCmsMsg(cmsEncoder
);
1404 /* drop thru to set encoder */
1406 /* cmsMsg but no encoder */
1407 ASSERT(cmsEncoder
->cmsMsg
!= NULL
);
1408 ASSERT(cmsEncoder
->encoder
== NULL
);
1409 cmsEncoder
->encoder
= encoder
;
1410 cmsEncoder
->encState
= ES_Updating
;
1411 cmsEncoder
->customCoder
= true; /* we won't see data */
1412 return errSecSuccess
;
1414 /* no can do, too late */
1420 * Obtain the SecCmsEncoderRef associated with a CMSEncoderRef.
1421 * Returns a NULL SecCmsEncoderRef if neither CMSEncoderSetEncoder nor
1422 * CMSEncoderUpdateContent() has been called.
1423 * The CMSEncoderRef retains ownership of the SecCmsEncoderRef.
1425 OSStatus
CMSEncoderGetEncoder(
1426 CMSEncoderRef cmsEncoder
,
1427 SecCmsEncoderRef
*encoder
) /* RETURNED */
1429 if((cmsEncoder
== NULL
) || (encoder
== NULL
)) {
1433 /* any state, whether we have an encoder or not is OK */
1434 *encoder
= cmsEncoder
->encoder
;
1435 return errSecSuccess
;
1438 #include <AssertMacros.h>
1441 * Obtain the timestamp of signer 'signerIndex' of a CMS message, if
1442 * present. This timestamp is an authenticated timestamp provided by
1443 * a timestamping authority.
1445 * Returns errSecParam if the CMS message was not signed or if signerIndex
1446 * is greater than the number of signers of the message minus one.
1448 * This cannot be called until after CMSEncoderCopyEncodedContent() is called.
1450 OSStatus
CMSEncoderCopySignerTimestamp(
1451 CMSEncoderRef cmsEncoder
,
1452 size_t signerIndex
, /* usually 0 */
1453 CFAbsoluteTime
*timestamp
) /* RETURNED */
1455 return CMSEncoderCopySignerTimestampWithPolicy(
1462 OSStatus
CMSEncoderCopySignerTimestampWithPolicy(
1463 CMSEncoderRef cmsEncoder
,
1464 CFTypeRef timeStampPolicy
,
1465 size_t signerIndex
, /* usually 0 */
1466 CFAbsoluteTime
*timestamp
) /* RETURNED */
1468 OSStatus status
= errSecParam
;
1469 SecCmsMessageRef cmsg
;
1470 SecCmsSignedDataRef signedData
= NULL
;
1471 int numContentInfos
= 0;
1473 require(cmsEncoder
&& timestamp
, xit
);
1474 require_noerr(CMSEncoderGetCmsMessage(cmsEncoder
, &cmsg
), xit
);
1475 numContentInfos
= SecCmsMessageContentLevelCount(cmsg
);
1476 for (int dex
= 0; !signedData
&& dex
< numContentInfos
; dex
++)
1478 SecCmsContentInfoRef ci
= SecCmsMessageContentLevel(cmsg
, dex
);
1479 SECOidTag tag
= SecCmsContentInfoGetContentTypeTag(ci
);
1480 if (tag
== SEC_OID_PKCS7_SIGNED_DATA
)
1481 if ((signedData
= SecCmsSignedDataRef(SecCmsContentInfoGetContent(ci
))))
1482 if (SecCmsSignerInfoRef signerInfo
= SecCmsSignedDataGetSignerInfo(signedData
, (int)signerIndex
))
1484 status
= SecCmsSignerInfoGetTimestampTimeWithPolicy(signerInfo
, timeStampPolicy
, timestamp
);