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
);
339 cmsEncoder
->cmsMsg
= NULL
;
341 if(cmsEncoder
->arena
!= NULL
) {
342 SecArenaPoolFree(cmsEncoder
->arena
, false);
344 if(cmsEncoder
->encoder
!= NULL
) {
346 * Normally this gets freed in SecCmsEncoderFinish - this is
349 SecCmsEncoderDestroy(cmsEncoder
->encoder
);
353 static OSStatus
cmsSetupEncoder(
354 CMSEncoderRef cmsEncoder
)
358 ASSERT(cmsEncoder
->arena
== NULL
);
359 ASSERT(cmsEncoder
->encoder
== NULL
);
361 ortn
= SecArenaPoolCreate(1024, &cmsEncoder
->arena
);
363 return cmsRtnToOSStatus(ortn
);
365 ortn
= SecCmsEncoderCreate(cmsEncoder
->cmsMsg
,
366 NULL
, NULL
, // no callback
367 &cmsEncoder
->encoderOut
, // data goes here
369 NULL
, NULL
, // no password callback (right?)
370 NULL
, NULL
, // decrypt key callback
371 NULL
, NULL
, // detached digests
372 &cmsEncoder
->encoder
);
374 return cmsRtnToOSStatus(ortn
);
376 return errSecSuccess
;
380 * Set up a SecCmsMessageRef for a SignedData creation.
382 static OSStatus
cmsSetupForSignedData(
383 CMSEncoderRef cmsEncoder
)
385 ASSERT((cmsEncoder
->signers
!= NULL
) || (cmsEncoder
->otherCerts
!= NULL
));
387 SecCmsContentInfoRef contentInfo
= NULL
;
388 SecCmsSignedDataRef signedData
= NULL
;
391 /* build chain of objects: message->signedData->data */
392 if(cmsEncoder
->cmsMsg
!= NULL
) {
393 SecCmsMessageDestroy(cmsEncoder
->cmsMsg
);
395 cmsEncoder
->cmsMsg
= SecCmsMessageCreate(NULL
);
396 if(cmsEncoder
->cmsMsg
== NULL
) {
397 return errSecInternalComponent
;
400 signedData
= SecCmsSignedDataCreate(cmsEncoder
->cmsMsg
);
401 if(signedData
== NULL
) {
402 return errSecInternalComponent
;
404 contentInfo
= SecCmsMessageGetContentInfo(cmsEncoder
->cmsMsg
);
405 ortn
= SecCmsContentInfoSetContentSignedData(cmsEncoder
->cmsMsg
, contentInfo
,
408 return cmsRtnToOSStatus(ortn
);
410 contentInfo
= SecCmsSignedDataGetContentInfo(signedData
);
411 if(cmsEncoder
->eContentType
.Data
!= NULL
) {
412 /* Override the default eContentType of id-data */
413 ortn
= SecCmsContentInfoSetContentOther(cmsEncoder
->cmsMsg
,
415 NULL
, /* data - provided to encoder, not here */
416 cmsEncoder
->detachedContent
,
417 &cmsEncoder
->eContentType
);
420 ortn
= SecCmsContentInfoSetContentData(cmsEncoder
->cmsMsg
,
422 NULL
, /* data - provided to encoder, not here */
423 cmsEncoder
->detachedContent
);
426 ortn
= cmsRtnToOSStatus(ortn
);
427 CSSM_PERROR("SecCmsContentInfoSetContent*", ortn
);
431 /* optional 'global' (per-SignedData) certs */
432 if(cmsEncoder
->otherCerts
!= NULL
) {
433 ortn
= SecCmsSignedDataAddCertList(signedData
, cmsEncoder
->otherCerts
);
435 ortn
= cmsRtnToOSStatus(ortn
);
436 CSSM_PERROR("SecCmsSignedDataAddCertList", ortn
);
441 /* SignerInfos, one per signer */
442 CFIndex numSigners
= 0;
443 if(cmsEncoder
->signers
!= NULL
) {
444 /* this is optional...in case we're just creating a cert bundle */
445 numSigners
= CFArrayGetCount(cmsEncoder
->signers
);
448 SecCertificateRef ourCert
= NULL
;
449 SecCmsCertChainMode chainMode
= SecCmsCMCertChain
;
451 switch(cmsEncoder
->chainMode
) {
452 case kCMSCertificateNone
:
453 chainMode
= SecCmsCMNone
;
455 case kCMSCertificateSignerOnly
:
456 chainMode
= SecCmsCMCertOnly
;
458 case kCMSCertificateChainWithRoot
:
459 chainMode
= SecCmsCMCertChainWithRoot
;
464 for(dex
=0; dex
<numSigners
; dex
++) {
465 SecCmsSignerInfoRef signerInfo
;
467 SecIdentityRef ourId
=
468 (SecIdentityRef
)CFArrayGetValueAtIndex(cmsEncoder
->signers
, dex
);
469 ortn
= SecIdentityCopyCertificate(ourId
, &ourCert
);
471 CSSM_PERROR("SecIdentityCopyCertificate", ortn
);
474 signerInfo
= SecCmsSignerInfoCreate(cmsEncoder
->cmsMsg
, ourId
, cmsEncoder
->digestalgtag
);
475 if (signerInfo
== NULL
) {
476 ortn
= errSecInternalComponent
;
480 /* we want the cert chain included for this one */
481 /* NOTE the usage parameter is currently unused by the SMIME lib */
482 ortn
= SecCmsSignerInfoIncludeCerts(signerInfo
, chainMode
,
483 certUsageEmailSigner
);
485 ortn
= cmsRtnToOSStatus(ortn
);
486 CSSM_PERROR("SecCmsSignerInfoIncludeCerts", ortn
);
491 if(cmsEncoder
->signedAttributes
& kCMSAttrSmimeCapabilities
) {
492 ortn
= SecCmsSignerInfoAddSMIMECaps(signerInfo
);
494 ortn
= cmsRtnToOSStatus(ortn
);
495 CSSM_PERROR("SecCmsSignerInfoAddSMIMEEncKeyPrefs", ortn
);
499 if(cmsEncoder
->signedAttributes
& kCMSAttrSmimeEncryptionKeyPrefs
) {
500 ortn
= SecCmsSignerInfoAddSMIMEEncKeyPrefs(signerInfo
, ourCert
, NULL
);
502 ortn
= cmsRtnToOSStatus(ortn
);
503 CSSM_PERROR("SecCmsSignerInfoAddSMIMEEncKeyPrefs", ortn
);
507 if(cmsEncoder
->signedAttributes
& kCMSAttrSmimeMSEncryptionKeyPrefs
) {
508 ortn
= SecCmsSignerInfoAddMSSMIMEEncKeyPrefs(signerInfo
, ourCert
, NULL
);
510 ortn
= cmsRtnToOSStatus(ortn
);
511 CSSM_PERROR("SecCmsSignerInfoAddMSSMIMEEncKeyPrefs", ortn
);
515 if(cmsEncoder
->signedAttributes
& kCMSAttrSigningTime
) {
516 if (cmsEncoder
->signingTime
== 0)
517 cmsEncoder
->signingTime
= CFAbsoluteTimeGetCurrent();
518 ortn
= SecCmsSignerInfoAddSigningTime(signerInfo
, cmsEncoder
->signingTime
);
520 ortn
= cmsRtnToOSStatus(ortn
);
521 CSSM_PERROR("SecCmsSignerInfoAddSigningTime", ortn
);
525 if(cmsEncoder
->signedAttributes
& kCMSAttrAppleCodesigningHashAgility
) {
526 ortn
= SecCmsSignerInfoAddAppleCodesigningHashAgility(signerInfo
, cmsEncoder
->hashAgilityAttrValue
);
527 /* libsecurity_smime made a copy of the attribute value. We don't need it anymore. */
528 CFReleaseNull(cmsEncoder
->hashAgilityAttrValue
);
530 ortn
= cmsRtnToOSStatus(ortn
);
531 CSSM_PERROR("SecCmsSignerInfoAddAppleCodesigningHashAgility", ortn
);
536 ortn
= SecCmsSignedDataAddSignerInfo(signedData
, signerInfo
);
538 ortn
= cmsRtnToOSStatus(ortn
);
539 CSSM_PERROR("SecCmsSignedDataAddSignerInfo", ortn
);
553 * Set up a SecCmsMessageRef for a EnvelopedData creation.
555 static OSStatus
cmsSetupForEnvelopedData(
556 CMSEncoderRef cmsEncoder
)
558 ASSERT(cmsEncoder
->op
== EO_Encrypt
);
559 ASSERT(cmsEncoder
->recipients
!= NULL
);
561 SecCmsContentInfoRef contentInfo
= NULL
;
562 SecCmsEnvelopedDataRef envelopedData
= NULL
;
563 SECOidTag algorithmTag
;
568 * Find encryption algorithm...unfortunately we need a NULL-terminated array
569 * of SecCertificateRefs for this.
571 CFIndex numCerts
= CFArrayGetCount(cmsEncoder
->recipients
);
573 SecCertificateRef
*certArray
= (SecCertificateRef
*)malloc(
574 (numCerts
+1) * sizeof(SecCertificateRef
));
576 for(dex
=0; dex
<numCerts
; dex
++) {
577 certArray
[dex
] = (SecCertificateRef
)CFArrayGetValueAtIndex(
578 cmsEncoder
->recipients
, dex
);
580 certArray
[numCerts
] = NULL
;
581 ortn
= SecSMIMEFindBulkAlgForRecipients(certArray
, &algorithmTag
, &keySize
);
584 CSSM_PERROR("SecSMIMEFindBulkAlgForRecipients", ortn
);
588 /* build chain of objects: message->envelopedData->data */
589 if(cmsEncoder
->cmsMsg
!= NULL
) {
590 SecCmsMessageDestroy(cmsEncoder
->cmsMsg
);
592 cmsEncoder
->cmsMsg
= SecCmsMessageCreate(NULL
);
593 if(cmsEncoder
->cmsMsg
== NULL
) {
594 return errSecInternalComponent
;
596 envelopedData
= SecCmsEnvelopedDataCreate(cmsEncoder
->cmsMsg
,
597 algorithmTag
, keySize
);
598 if(envelopedData
== NULL
) {
599 return errSecInternalComponent
;
601 contentInfo
= SecCmsMessageGetContentInfo(cmsEncoder
->cmsMsg
);
602 ortn
= SecCmsContentInfoSetContentEnvelopedData(cmsEncoder
->cmsMsg
,
603 contentInfo
, envelopedData
);
605 ortn
= cmsRtnToOSStatus(ortn
);
606 CSSM_PERROR("SecCmsContentInfoSetContentEnvelopedData", ortn
);
609 contentInfo
= SecCmsEnvelopedDataGetContentInfo(envelopedData
);
610 if(cmsEncoder
->eContentType
.Data
!= NULL
) {
611 /* Override the default ContentType of id-data */
612 ortn
= SecCmsContentInfoSetContentOther(cmsEncoder
->cmsMsg
,
614 NULL
, /* data - provided to encoder, not here */
615 FALSE
, /* detachedContent */
616 &cmsEncoder
->eContentType
);
619 ortn
= SecCmsContentInfoSetContentData(cmsEncoder
->cmsMsg
,
621 NULL
/* data - provided to encoder, not here */,
622 cmsEncoder
->detachedContent
);
625 ortn
= cmsRtnToOSStatus(ortn
);
626 CSSM_PERROR("SecCmsContentInfoSetContentData*", ortn
);
631 * create & attach recipient information, one for each recipient
633 for(dex
=0; dex
<numCerts
; dex
++) {
634 SecCmsRecipientInfoRef recipientInfo
= NULL
;
636 SecCertificateRef thisRecip
= (SecCertificateRef
)CFArrayGetValueAtIndex(
637 cmsEncoder
->recipients
, dex
);
638 recipientInfo
= SecCmsRecipientInfoCreate(cmsEncoder
->cmsMsg
, thisRecip
);
639 ortn
= SecCmsEnvelopedDataAddRecipient(envelopedData
, recipientInfo
);
641 ortn
= cmsRtnToOSStatus(ortn
);
642 CSSM_PERROR("SecCmsEnvelopedDataAddRecipient", ortn
);
646 return errSecSuccess
;
650 * Set up cmsMsg. Called from either the first call to CMSEncoderUpdateContent, or
651 * from CMSEncodeGetCmsMessage().
653 static OSStatus
cmsSetupCmsMsg(
654 CMSEncoderRef cmsEncoder
)
656 ASSERT(cmsEncoder
!= NULL
);
657 ASSERT(cmsEncoder
->encState
== ES_Init
);
659 /* figure out what high-level operation we're doing */
660 if((cmsEncoder
->signers
!= NULL
) || (cmsEncoder
->otherCerts
!= NULL
)) {
661 if(cmsEncoder
->recipients
!= NULL
) {
662 cmsEncoder
->op
= EO_SignEncrypt
;
665 cmsEncoder
->op
= EO_Sign
;
668 else if(cmsEncoder
->recipients
!= NULL
) {
669 cmsEncoder
->op
= EO_Encrypt
;
672 dprintf("CMSEncoderUpdateContent: nothing to do\n");
676 OSStatus ortn
= errSecSuccess
;
678 switch(cmsEncoder
->op
) {
681 /* If we're signing & encrypting, do the signing first */
682 ortn
= cmsSetupForSignedData(cmsEncoder
);
685 ortn
= cmsSetupForEnvelopedData(cmsEncoder
);
688 cmsEncoder
->encState
= ES_Msg
;
693 * ASN.1 template for decoding a ContentInfo.
696 CSSM_OID contentType
;
700 static const SecAsn1Template cmsSimpleContentInfoTemplate
[] = {
701 { SEC_ASN1_SEQUENCE
, 0, NULL
, sizeof(SimpleContentInfo
) },
702 { SEC_ASN1_OBJECT_ID
, offsetof(SimpleContentInfo
, contentType
) },
703 { SEC_ASN1_EXPLICIT
| SEC_ASN1_CONSTRUCTED
| SEC_ASN1_CONTEXT_SPECIFIC
| 0,
704 offsetof(SimpleContentInfo
, content
),
705 kSecAsn1AnyTemplate
},
710 * Obtain the content of a contentInfo, This basically strips off the contentType OID
711 * and returns its ASN_ANY content, allocated the provided coder's memory space.
713 static OSStatus
cmsContentInfoContent(
714 SecAsn1CoderRef asn1Coder
,
715 const CSSM_DATA
*contentInfo
,
716 CSSM_DATA
*content
) /* RETURNED */
719 SimpleContentInfo decodedInfo
;
721 memset(&decodedInfo
, 0, sizeof(decodedInfo
));
722 ortn
= SecAsn1DecodeData(asn1Coder
, contentInfo
,
723 cmsSimpleContentInfoTemplate
, &decodedInfo
);
727 if(decodedInfo
.content
.Data
== NULL
) {
728 dprintf("***Error decoding contentInfo: no content\n");
729 return errSecInternalComponent
;
731 *content
= decodedInfo
.content
;
732 return errSecSuccess
;
735 #pragma mark --- Start of Public API ---
737 CFTypeID
CMSEncoderGetTypeID(void)
739 static pthread_once_t once
= PTHREAD_ONCE_INIT
;
741 if(cmsEncoderTypeID
== _kCFRuntimeNotATypeID
) {
742 pthread_once(&once
, &cmsEncoderClassInitialize
);
744 return cmsEncoderTypeID
;
748 * Create a CMSEncoder. Result must eventually be freed via CFRelease().
750 OSStatus
CMSEncoderCreate(
751 CMSEncoderRef
*cmsEncoderOut
) /* RETURNED */
753 CMSEncoderRef cmsEncoder
= NULL
;
755 uint32_t extra
= sizeof(*cmsEncoder
) - sizeof(cmsEncoder
->base
);
756 cmsEncoder
= (CMSEncoderRef
)_CFRuntimeCreateInstance(NULL
, CMSEncoderGetTypeID(),
758 if(cmsEncoder
== NULL
) {
759 return errSecAllocate
;
761 cmsEncoder
->encState
= ES_Init
;
762 cmsEncoder
->chainMode
= kCMSCertificateChain
;
763 cmsEncoder
->digestalgtag
= SEC_OID_SHA1
;
764 *cmsEncoderOut
= cmsEncoder
;
765 return errSecSuccess
;
768 #pragma mark --- Getters & Setters ---
770 const CFStringRef __nonnull kCMSEncoderDigestAlgorithmSHA1
= CFSTR("sha1");
771 const CFStringRef __nonnull kCMSEncoderDigestAlgorithmSHA256
= CFSTR("sha256");
774 OSStatus
CMSEncoderSetSignerAlgorithm(
775 CMSEncoderRef cmsEncoder
,
776 CFStringRef digestAlgorithm
)
778 if (CFEqual(digestAlgorithm
, kCMSEncoderDigestAlgorithmSHA1
)) {
779 cmsEncoder
->digestalgtag
= SEC_OID_SHA1
;
780 } else if (CFEqual(digestAlgorithm
, kCMSEncoderDigestAlgorithmSHA256
)) {
781 cmsEncoder
->digestalgtag
= SEC_OID_SHA256
;
786 return errSecSuccess
;
790 * Specify signers of the CMS message; implies that the message will be signed.
792 OSStatus
CMSEncoderAddSigners(
793 CMSEncoderRef cmsEncoder
,
794 CFTypeRef signerOrArray
)
796 if(cmsEncoder
== NULL
) {
799 if(cmsEncoder
->encState
!= ES_Init
) {
802 return cmsAppendToArray(signerOrArray
, &cmsEncoder
->signers
, SecIdentityGetTypeID());
806 * Obtain an array of signers as specified in CMSEncoderSetSigners().
808 OSStatus
CMSEncoderCopySigners(
809 CMSEncoderRef cmsEncoder
,
812 if((cmsEncoder
== NULL
) || (signers
== NULL
)) {
815 if(cmsEncoder
->signers
!= NULL
) {
816 CFRetain(cmsEncoder
->signers
);
818 *signers
= cmsEncoder
->signers
;
819 return errSecSuccess
;
823 * Specify recipients of the message. Implies that the message will be encrypted.
825 OSStatus
CMSEncoderAddRecipients(
826 CMSEncoderRef cmsEncoder
,
827 CFTypeRef recipientOrArray
)
829 if(cmsEncoder
== NULL
) {
832 if(cmsEncoder
->encState
!= ES_Init
) {
835 return cmsAppendToArray(recipientOrArray
, &cmsEncoder
->recipients
,
836 SecCertificateGetTypeID());
840 * Obtain an array of recipients as specified in CMSEncoderSetRecipients().
842 OSStatus
CMSEncoderCopyRecipients(
843 CMSEncoderRef cmsEncoder
,
844 CFArrayRef
*recipients
)
846 if((cmsEncoder
== NULL
) || (recipients
== NULL
)) {
849 if(cmsEncoder
->recipients
!= NULL
) {
850 CFRetain(cmsEncoder
->recipients
);
852 *recipients
= cmsEncoder
->recipients
;
853 return errSecSuccess
;
857 * Specify additional certs to include in a signed message.
859 OSStatus
CMSEncoderAddSupportingCerts(
860 CMSEncoderRef cmsEncoder
,
861 CFTypeRef certOrArray
)
863 if(cmsEncoder
== NULL
) {
866 if(cmsEncoder
->encState
!= ES_Init
) {
869 return cmsAppendToArray(certOrArray
, &cmsEncoder
->otherCerts
,
870 SecCertificateGetTypeID());
874 * Obtain the SecCertificates provided in CMSEncoderAddSupportingCerts().
876 OSStatus
CMSEncoderCopySupportingCerts(
877 CMSEncoderRef cmsEncoder
,
878 CFArrayRef
*certs
) /* RETURNED */
880 if((cmsEncoder
== NULL
) || (certs
== NULL
)) {
883 if(cmsEncoder
->otherCerts
!= NULL
) {
884 CFRetain(cmsEncoder
->otherCerts
);
886 *certs
= cmsEncoder
->otherCerts
;
887 return errSecSuccess
;
890 OSStatus
CMSEncoderSetHasDetachedContent(
891 CMSEncoderRef cmsEncoder
,
892 Boolean detachedContent
)
894 if(cmsEncoder
== NULL
) {
897 if(cmsEncoder
->encState
!= ES_Init
) {
900 cmsEncoder
->detachedContent
= detachedContent
;
901 return errSecSuccess
;
904 OSStatus
CMSEncoderGetHasDetachedContent(
905 CMSEncoderRef cmsEncoder
,
906 Boolean
*detachedContent
) /* RETURNED */
908 if((cmsEncoder
== NULL
) || (detachedContent
== NULL
)) {
911 *detachedContent
= cmsEncoder
->detachedContent
;
912 return errSecSuccess
;
916 * Optionally specify an eContentType OID for the inner EncapsulatedData for
917 * a signed message. The default eContentType, used of this function is not
918 * called, is id-data.
920 OSStatus
CMSEncoderSetEncapsulatedContentType(
921 CMSEncoderRef cmsEncoder
,
922 const CSSM_OID
*eContentType
)
924 if((cmsEncoder
== NULL
) || (eContentType
== NULL
)) {
927 if(cmsEncoder
->encState
!= ES_Init
) {
931 CSSM_OID
*ecOid
= &cmsEncoder
->eContentType
;
932 if(ecOid
->Data
!= NULL
) {
935 cmsCopyCmsData(eContentType
, ecOid
);
936 return errSecSuccess
;
939 OSStatus
CMSEncoderSetEncapsulatedContentTypeOID(
940 CMSEncoderRef cmsEncoder
,
941 CFTypeRef eContentTypeOID
)
943 // convert eContentTypeOID to a CSSM_OID
944 CSSM_OID contentType
= { 0, NULL
};
945 if (!eContentTypeOID
|| convertOid(eContentTypeOID
, &contentType
) != 0)
947 OSStatus result
= CMSEncoderSetEncapsulatedContentType(cmsEncoder
, &contentType
);
948 if (contentType
.Data
)
949 free(contentType
.Data
);
954 * Obtain the eContentType OID specified in CMSEncoderSetEncapsulatedContentType().
956 OSStatus
CMSEncoderCopyEncapsulatedContentType(
957 CMSEncoderRef cmsEncoder
,
958 CFDataRef
*eContentType
)
960 if((cmsEncoder
== NULL
) || (eContentType
== NULL
)) {
964 CSSM_OID
*ecOid
= &cmsEncoder
->eContentType
;
965 if(ecOid
->Data
== NULL
) {
966 *eContentType
= NULL
;
969 *eContentType
= CFDataCreate(NULL
, ecOid
->Data
, ecOid
->Length
);
971 return errSecSuccess
;
975 * Optionally specify signed attributes. Only meaningful when creating a
976 * signed message. If this is called, it must be called before
977 * CMSEncoderUpdateContent().
979 OSStatus
CMSEncoderAddSignedAttributes(
980 CMSEncoderRef cmsEncoder
,
981 CMSSignedAttributes signedAttributes
)
983 if(cmsEncoder
== NULL
) {
986 if(cmsEncoder
->encState
!= ES_Init
) {
989 cmsEncoder
->signedAttributes
|= signedAttributes
;
990 return errSecSuccess
;
994 * Set the signing time for a CMSEncoder.
995 * This is only used if the kCMSAttrSigningTime attribute is included.
997 OSStatus
CMSEncoderSetSigningTime(
998 CMSEncoderRef cmsEncoder
,
1001 if(cmsEncoder
== NULL
) {
1004 if(cmsEncoder
->encState
!= ES_Init
) {
1007 cmsEncoder
->signingTime
= time
;
1008 return errSecSuccess
;
1012 * Set the hash agility attribute for a CMSEncoder.
1013 * This is only used if the kCMSAttrAppleCodesigningHashAgility attribute
1016 OSStatus
CMSEncoderSetAppleCodesigningHashAgility(
1017 CMSEncoderRef cmsEncoder
,
1018 CFDataRef hashAgilityAttrValue
)
1020 if (cmsEncoder
== NULL
|| cmsEncoder
->encState
!= ES_Init
) {
1023 cmsEncoder
->hashAgilityAttrValue
= CFRetainSafe(hashAgilityAttrValue
);
1024 return errSecSuccess
;
1027 OSStatus
CMSEncoderSetCertificateChainMode(
1028 CMSEncoderRef cmsEncoder
,
1029 CMSCertificateChainMode chainMode
)
1031 if(cmsEncoder
== NULL
) {
1034 if(cmsEncoder
->encState
!= ES_Init
) {
1038 case kCMSCertificateNone
:
1039 case kCMSCertificateSignerOnly
:
1040 case kCMSCertificateChain
:
1041 case kCMSCertificateChainWithRoot
:
1046 cmsEncoder
->chainMode
= chainMode
;
1047 return errSecSuccess
;
1050 OSStatus
CMSEncoderGetCertificateChainMode(
1051 CMSEncoderRef cmsEncoder
,
1052 CMSCertificateChainMode
*chainModeOut
)
1054 if(cmsEncoder
== NULL
) {
1057 *chainModeOut
= cmsEncoder
->chainMode
;
1058 return errSecSuccess
;
1062 CmsMessageSetTSACallback(CMSEncoderRef cmsEncoder
, SecCmsTSACallback tsaCallback
)
1064 if (cmsEncoder
->cmsMsg
)
1065 SecCmsMessageSetTSACallback(cmsEncoder
->cmsMsg
, tsaCallback
);
1069 CmsMessageSetTSAContext(CMSEncoderRef cmsEncoder
, CFTypeRef tsaContext
)
1071 if (cmsEncoder
->cmsMsg
)
1072 SecCmsMessageSetTSAContext(cmsEncoder
->cmsMsg
, tsaContext
);
1075 #pragma mark --- Action ---
1078 * Feed content bytes into the encoder.
1079 * Can be called multiple times.
1080 * No 'setter' routines can be called after this function has been called.
1082 OSStatus
CMSEncoderUpdateContent(
1083 CMSEncoderRef cmsEncoder
,
1084 const void *content
,
1087 if(cmsEncoder
== NULL
) {
1091 OSStatus ortn
= errSecSuccess
;
1092 switch(cmsEncoder
->encState
) {
1095 * First time thru: do the CmsMsg setup.
1097 ortn
= cmsSetupCmsMsg(cmsEncoder
);
1101 /* fall thru to set up the encoder */
1104 /* We have a cmsMsg but no encoder; create one */
1105 ASSERT(cmsEncoder
->cmsMsg
!= NULL
);
1106 ASSERT(cmsEncoder
->encoder
== NULL
);
1107 ortn
= cmsSetupEncoder(cmsEncoder
);
1111 /* only legal calls now are update and finalize */
1112 cmsEncoder
->encState
= ES_Updating
;
1116 ASSERT(cmsEncoder
->encoder
!= NULL
);
1120 /* Too late for another update */
1124 return errSecInternalComponent
;
1127 /* FIXME - CFIndex same size as size_t on 64bit? */
1128 ortn
= SecCmsEncoderUpdate(cmsEncoder
->encoder
, content
, (CFIndex
)contentLen
);
1130 ortn
= cmsRtnToOSStatus(ortn
);
1131 CSSM_PERROR("SecCmsEncoderUpdate", ortn
);
1137 * Finish encoding the message and obtain the encoded result.
1138 * Caller must CFRelease the result.
1140 OSStatus
CMSEncoderCopyEncodedContent(
1141 CMSEncoderRef cmsEncoder
,
1142 CFDataRef
*encodedContent
)
1144 if((cmsEncoder
== NULL
) || (encodedContent
== NULL
)) {
1150 switch(cmsEncoder
->encState
) {
1152 /* normal termination */
1155 /* already been called */
1160 * The only time these are legal is when we're doing a SignedData
1161 * with certificates only (no signers, no content).
1163 if((cmsEncoder
->signers
!= NULL
) ||
1164 (cmsEncoder
->recipients
!= NULL
) ||
1165 (cmsEncoder
->otherCerts
== NULL
)) {
1169 /* Set up for certs only */
1170 ortn
= cmsSetupForSignedData(cmsEncoder
);
1174 /* and an encoder */
1175 ortn
= cmsSetupEncoder(cmsEncoder
);
1183 ASSERT(cmsEncoder
->encoder
!= NULL
);
1184 ortn
= SecCmsEncoderFinish(cmsEncoder
->encoder
);
1185 /* regardless of the outcome, the encoder itself has been freed */
1186 cmsEncoder
->encoder
= NULL
;
1188 return cmsRtnToOSStatus(ortn
);
1190 cmsEncoder
->encState
= ES_Final
;
1192 if((cmsEncoder
->encoderOut
.Data
== NULL
) && !cmsEncoder
->customCoder
) {
1193 /* not sure how this could happen... */
1194 dprintf("Successful encode, but no data\n");
1195 return errSecInternalComponent
;
1197 if(cmsEncoder
->customCoder
) {
1199 *encodedContent
= NULL
;
1200 return errSecSuccess
;
1203 /* in two out of three cases, we're done */
1204 switch(cmsEncoder
->op
) {
1207 *encodedContent
= CFDataCreate(NULL
, (const UInt8
*)cmsEncoder
->encoderOut
.Data
,
1208 cmsEncoder
->encoderOut
.Length
);
1209 return errSecSuccess
;
1210 case EO_SignEncrypt
:
1211 /* proceed, more work to do */
1216 * Signing & encrypting.
1217 * Due to bugs in the libsecurity_smime encoder, it can't encode nested
1218 * ContentInfos in one shot. So we do another pass, specifying the SignedData
1219 * inside of the ContentInfo we just created as the data to encrypt.
1221 SecAsn1CoderRef asn1Coder
= NULL
;
1222 CSSM_DATA signedData
= {0, NULL
};
1224 ortn
= SecAsn1CoderCreate(&asn1Coder
);
1228 ortn
= cmsContentInfoContent(asn1Coder
, &cmsEncoder
->encoderOut
, &signedData
);
1233 /* now just encrypt that, one-shot */
1234 ortn
= CMSEncode(NULL
, /* no signers this time */
1235 cmsEncoder
->recipients
,
1236 &CSSMOID_PKCS7_SignedData
, /* fake out encoder so it doesn't try to actually
1237 * encode the signedData - this asserts the
1238 * SEC_OID_OTHER OID tag in the EnvelopedData's
1240 FALSE
, /* detachedContent */
1241 kCMSAttrNone
, /* signedAttributes - none this time */
1242 signedData
.Data
, signedData
.Length
,
1247 SecAsn1CoderRelease(asn1Coder
);
1252 #pragma mark --- High-level API ---
1255 * High-level, one-shot encoder function.
1259 CFTypeRef recipients
,
1260 const CSSM_OID
*eContentType
,
1261 Boolean detachedContent
,
1262 CMSSignedAttributes signedAttributes
,
1263 const void *content
,
1265 CFDataRef
*encodedContent
) /* RETURNED */
1267 if((signers
== NULL
) && (recipients
== NULL
)) {
1270 if(encodedContent
== NULL
) {
1274 CMSEncoderRef cmsEncoder
;
1277 /* set up the encoder */
1278 ortn
= CMSEncoderCreate(&cmsEncoder
);
1283 /* subsequent errors to errOut: */
1285 ortn
= CMSEncoderAddSigners(cmsEncoder
, signers
);
1291 ortn
= CMSEncoderAddRecipients(cmsEncoder
, recipients
);
1297 ortn
= CMSEncoderSetEncapsulatedContentType(cmsEncoder
, eContentType
);
1302 if(detachedContent
) {
1303 ortn
= CMSEncoderSetHasDetachedContent(cmsEncoder
, detachedContent
);
1308 if(signedAttributes
) {
1309 ortn
= CMSEncoderAddSignedAttributes(cmsEncoder
, signedAttributes
);
1315 ortn
= CMSEncoderUpdateContent(cmsEncoder
, content
, contentLen
);
1319 ortn
= CMSEncoderCopyEncodedContent(cmsEncoder
, encodedContent
);
1322 CFRelease(cmsEncoder
);
1326 OSStatus
CMSEncodeContent(
1328 CFTypeRef recipients
,
1329 CFTypeRef eContentTypeOID
,
1330 Boolean detachedContent
,
1331 CMSSignedAttributes signedAttributes
,
1332 const void *content
,
1334 CFDataRef
*encodedContentOut
) /* RETURNED */
1336 // convert eContentTypeOID to a CSSM_OID
1337 CSSM_OID contentType
= { 0, NULL
};
1338 if (eContentTypeOID
&& convertOid(eContentTypeOID
, &contentType
) != 0)
1340 const CSSM_OID
*contentTypePtr
= (eContentTypeOID
) ? &contentType
: NULL
;
1341 OSStatus result
= CMSEncode(signers
, recipients
, contentTypePtr
,
1342 detachedContent
, signedAttributes
,
1343 content
, contentLen
, encodedContentOut
);
1344 if (contentType
.Data
)
1345 free(contentType
.Data
);
1349 #pragma mark --- SPI routines declared in CMSPrivate.h ---
1352 * Obtain the SecCmsMessageRef associated with a CMSEncoderRef.
1353 * If we don't have a SecCmsMessageRef yet, we create one now.
1354 * This is the only place where we go to state ES_Msg.
1356 OSStatus
CMSEncoderGetCmsMessage(
1357 CMSEncoderRef cmsEncoder
,
1358 SecCmsMessageRef
*cmsMessage
) /* RETURNED */
1360 if((cmsEncoder
== NULL
) || (cmsMessage
== NULL
)) {
1363 if(cmsEncoder
->cmsMsg
!= NULL
) {
1364 ASSERT(cmsEncoder
->encState
!= ES_Init
);
1365 *cmsMessage
= cmsEncoder
->cmsMsg
;
1366 return errSecSuccess
;
1369 OSStatus ortn
= cmsSetupCmsMsg(cmsEncoder
);
1373 *cmsMessage
= cmsEncoder
->cmsMsg
;
1375 /* Don't set up encoder yet; caller might do that via CMSEncoderSetEncoder */
1376 cmsEncoder
->encState
= ES_Msg
;
1377 return errSecSuccess
;
1381 * Optionally specify a SecCmsEncoderRef to use with a CMSEncoderRef.
1382 * If this is called, it must be called before the first call to
1383 * CMSEncoderUpdateContent(). The CMSEncoderRef takes ownership of the
1384 * incoming SecCmsEncoderRef.
1386 OSStatus
CMSEncoderSetEncoder(
1387 CMSEncoderRef cmsEncoder
,
1388 SecCmsEncoderRef encoder
)
1390 if((cmsEncoder
== NULL
) || (encoder
== NULL
)) {
1396 switch(cmsEncoder
->encState
) {
1398 /* No message, no encoder */
1399 ASSERT(cmsEncoder
->cmsMsg
== NULL
);
1400 ASSERT(cmsEncoder
->encoder
== NULL
);
1401 ortn
= cmsSetupCmsMsg(cmsEncoder
);
1405 /* drop thru to set encoder */
1407 /* cmsMsg but no encoder */
1408 ASSERT(cmsEncoder
->cmsMsg
!= NULL
);
1409 ASSERT(cmsEncoder
->encoder
== NULL
);
1410 cmsEncoder
->encoder
= encoder
;
1411 cmsEncoder
->encState
= ES_Updating
;
1412 cmsEncoder
->customCoder
= true; /* we won't see data */
1413 return errSecSuccess
;
1415 /* no can do, too late */
1421 * Obtain the SecCmsEncoderRef associated with a CMSEncoderRef.
1422 * Returns a NULL SecCmsEncoderRef if neither CMSEncoderSetEncoder nor
1423 * CMSEncoderUpdateContent() has been called.
1424 * The CMSEncoderRef retains ownership of the SecCmsEncoderRef.
1426 OSStatus
CMSEncoderGetEncoder(
1427 CMSEncoderRef cmsEncoder
,
1428 SecCmsEncoderRef
*encoder
) /* RETURNED */
1430 if((cmsEncoder
== NULL
) || (encoder
== NULL
)) {
1434 /* any state, whether we have an encoder or not is OK */
1435 *encoder
= cmsEncoder
->encoder
;
1436 return errSecSuccess
;
1439 #include <AssertMacros.h>
1442 * Obtain the timestamp of signer 'signerIndex' of a CMS message, if
1443 * present. This timestamp is an authenticated timestamp provided by
1444 * a timestamping authority.
1446 * Returns errSecParam if the CMS message was not signed or if signerIndex
1447 * is greater than the number of signers of the message minus one.
1449 * This cannot be called until after CMSEncoderCopyEncodedContent() is called.
1451 OSStatus
CMSEncoderCopySignerTimestamp(
1452 CMSEncoderRef cmsEncoder
,
1453 size_t signerIndex
, /* usually 0 */
1454 CFAbsoluteTime
*timestamp
) /* RETURNED */
1456 return CMSEncoderCopySignerTimestampWithPolicy(
1463 OSStatus
CMSEncoderCopySignerTimestampWithPolicy(
1464 CMSEncoderRef cmsEncoder
,
1465 CFTypeRef timeStampPolicy
,
1466 size_t signerIndex
, /* usually 0 */
1467 CFAbsoluteTime
*timestamp
) /* RETURNED */
1469 OSStatus status
= errSecParam
;
1470 SecCmsMessageRef cmsg
;
1471 SecCmsSignedDataRef signedData
= NULL
;
1472 int numContentInfos
= 0;
1474 require(cmsEncoder
&& timestamp
, xit
);
1475 require_noerr(CMSEncoderGetCmsMessage(cmsEncoder
, &cmsg
), xit
);
1476 numContentInfos
= SecCmsMessageContentLevelCount(cmsg
);
1477 for (int dex
= 0; !signedData
&& dex
< numContentInfos
; dex
++)
1479 SecCmsContentInfoRef ci
= SecCmsMessageContentLevel(cmsg
, dex
);
1480 SECOidTag tag
= SecCmsContentInfoGetContentTypeTag(ci
);
1481 if (tag
== SEC_OID_PKCS7_SIGNED_DATA
)
1482 if ((signedData
= SecCmsSignedDataRef(SecCmsContentInfoGetContent(ci
))))
1483 if (SecCmsSignerInfoRef signerInfo
= SecCmsSignedDataGetSignerInfo(signedData
, (int)signerIndex
))
1485 status
= SecCmsSignerInfoGetTimestampTimeWithPolicy(signerInfo
, timeStampPolicy
, timestamp
);