2 * Copyright (c) 2003 - 2007 Kungliga Tekniska Högskolan
3 * (Royal Institute of Technology, Stockholm, Sweden).
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the Institute nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 * @page page_cms CMS/PKCS7 message functions.
39 * CMS is defined in RFC 3369 and is an continuation of the RSA Labs
40 * standard PKCS7. The basic messages in CMS is
43 * Data signed with private key (RSA, DSA, ECDSA) or secret
46 * Data encrypted with private key (RSA)
48 * Data encrypted with secret (symmetric) key.
50 * Wrapper structure including type and data.
53 * See the library functions here: @ref hx509_cms
56 #define ALLOC(X, N) (X) = calloc((N), sizeof(*(X)))
57 #define ALLOC_SEQ(X, N) do { (X)->len = (N); ALLOC((X)->val, (N)); } while(0)
60 * Wrap data and oid in a ContentInfo and encode it.
62 * @param oid type of the content.
63 * @param buf data to be wrapped. If a NULL pointer is passed in, the
64 * optional content field in the ContentInfo is not going be filled
66 * @param res the encoded buffer, the result should be freed with
67 * der_free_octet_string().
69 * @return Returns an hx509 error code.
74 HX509_LIB_FUNCTION
int HX509_LIB_CALL
75 hx509_cms_wrap_ContentInfo(const heim_oid
*oid
,
76 const heim_octet_string
*buf
,
77 heim_octet_string
*res
)
83 memset(res
, 0, sizeof(*res
));
84 memset(&ci
, 0, sizeof(ci
));
86 ret
= der_copy_oid(oid
, &ci
.contentType
);
91 if (ci
.content
== NULL
) {
92 free_ContentInfo(&ci
);
95 ci
.content
->data
= malloc(buf
->length
);
96 if (ci
.content
->data
== NULL
) {
97 free_ContentInfo(&ci
);
100 memcpy(ci
.content
->data
, buf
->data
, buf
->length
);
101 ci
.content
->length
= buf
->length
;
104 ASN1_MALLOC_ENCODE(ContentInfo
, res
->data
, res
->length
, &ci
, &size
, ret
);
105 free_ContentInfo(&ci
);
108 if (res
->length
!= size
)
109 _hx509_abort("internal ASN.1 encoder error");
115 * Decode an ContentInfo and unwrap data and oid it.
117 * @param in the encoded buffer.
118 * @param oid type of the content.
119 * @param out data to be wrapped.
120 * @param have_data since the data is optional, this flag shows the
121 * difference between no data and the zero length data.
123 * @return Returns an hx509 error code.
128 HX509_LIB_FUNCTION
int HX509_LIB_CALL
129 hx509_cms_unwrap_ContentInfo(const heim_octet_string
*in
,
131 heim_octet_string
*out
,
138 memset(oid
, 0, sizeof(*oid
));
139 memset(out
, 0, sizeof(*out
));
141 ret
= decode_ContentInfo(in
->data
, in
->length
, &ci
, &size
);
145 ret
= der_copy_oid(&ci
.contentType
, oid
);
147 free_ContentInfo(&ci
);
151 ret
= der_copy_octet_string(ci
.content
, out
);
154 free_ContentInfo(&ci
);
158 memset(out
, 0, sizeof(*out
));
161 *have_data
= (ci
.content
!= NULL
) ? 1 : 0;
163 free_ContentInfo(&ci
);
169 #define CMS_ID_NAME 1
172 fill_CMSIdentifier(const hx509_cert cert
,
180 id
->element
= choice_CMSIdentifier_subjectKeyIdentifier
;
181 ret
= _hx509_find_extension_subject_key_id(_hx509_get_cert(cert
),
182 &id
->u
.subjectKeyIdentifier
);
189 id
->element
= choice_CMSIdentifier_issuerAndSerialNumber
;
190 ret
= hx509_cert_get_issuer(cert
, &name
);
193 ret
= hx509_name_to_Name(name
, &id
->u
.issuerAndSerialNumber
.issuer
);
194 hx509_name_free(&name
);
198 ret
= hx509_cert_get_serialnumber(cert
, &id
->u
.issuerAndSerialNumber
.serialNumber
);
202 _hx509_abort("CMS fill identifier with unknown type");
208 unparse_CMSIdentifier(hx509_context context
,
215 switch (id
->element
) {
216 case choice_CMSIdentifier_issuerAndSerialNumber
: {
217 IssuerAndSerialNumber
*iasn
;
220 iasn
= &id
->u
.issuerAndSerialNumber
;
222 ret
= _hx509_Name_to_string(&iasn
->issuer
, &name
);
225 ret
= der_print_hex_heim_integer(&iasn
->serialNumber
, &serial
);
230 ret
= asprintf(str
, "certificate issued by %s with serial number %s",
236 case choice_CMSIdentifier_subjectKeyIdentifier
: {
237 KeyIdentifier
*ki
= &id
->u
.subjectKeyIdentifier
;
241 len
= hex_encode(ki
->data
, ki
->length
, &keyid
);
246 ret
= asprintf(str
, "certificate with id %s", keyid
);
248 ret
= asprintf(str
, "certificate");
253 ret
= asprintf(str
, "certificate has unknown CMSidentifier type");
257 * In the following if, we check ret and *str which should be returned/set
258 * by asprintf(3) in every branch of the switch statement.
260 if (ret
== -1 || *str
== NULL
)
266 find_CMSIdentifier(hx509_context context
,
267 CMSIdentifier
*client
,
270 hx509_cert
*signer_cert
,
278 memset(&c
, 0, sizeof(c
));
279 _hx509_query_clear(&q
);
283 switch (client
->element
) {
284 case choice_CMSIdentifier_issuerAndSerialNumber
:
285 q
.serial
= &client
->u
.issuerAndSerialNumber
.serialNumber
;
286 q
.issuer_name
= &client
->u
.issuerAndSerialNumber
.issuer
;
287 q
.match
= HX509_QUERY_MATCH_SERIALNUMBER
|HX509_QUERY_MATCH_ISSUER_NAME
;
289 case choice_CMSIdentifier_subjectKeyIdentifier
:
290 q
.subject_id
= &client
->u
.subjectKeyIdentifier
;
291 q
.match
= HX509_QUERY_MATCH_SUBJECT_KEY_ID
;
294 hx509_set_error_string(context
, 0, HX509_CMS_NO_RECIPIENT_CERTIFICATE
,
295 "unknown CMS identifier element");
296 return HX509_CMS_NO_RECIPIENT_CERTIFICATE
;
301 q
.match
|= HX509_QUERY_MATCH_TIME
;
303 q
.timenow
= time_now
;
305 q
.timenow
= time(NULL
);
307 ret
= hx509_certs_find(context
, certs
, &q
, &cert
);
308 if (ret
== HX509_CERT_NOT_FOUND
) {
311 ret
= unparse_CMSIdentifier(context
, client
, &str
);
313 hx509_set_error_string(context
, 0,
314 HX509_CMS_NO_RECIPIENT_CERTIFICATE
,
315 "Failed to find %s", str
);
317 hx509_clear_error_string(context
);
318 return HX509_CMS_NO_RECIPIENT_CERTIFICATE
;
320 hx509_set_error_string(context
, HX509_ERROR_APPEND
,
321 HX509_CMS_NO_RECIPIENT_CERTIFICATE
,
322 "Failed to find CMS id in cert store");
323 return HX509_CMS_NO_RECIPIENT_CERTIFICATE
;
332 * Decode and unencrypt EnvelopedData.
334 * Extract data and parameters from the EnvelopedData. Also
335 * supports using detached EnvelopedData.
337 * @param context A hx509 context.
338 * @param certs Certificate that can decrypt the EnvelopedData
340 * @param flags HX509_CMS_UE flags to control the behavior.
341 * @param data pointer the structure the contains the DER/BER encoded
342 * EnvelopedData stucture.
343 * @param length length of the data that data point to.
344 * @param encryptedContent in case of detached signature, this
345 * contains the actual encrypted data, otherwise it should be NULL.
346 * @param time_now set the current time, if zero the library uses now as the date.
347 * @param contentType output type oid, should be freed with der_free_oid().
348 * @param content the data, free with der_free_octet_string().
350 * @return an hx509 error code.
355 HX509_LIB_FUNCTION
int HX509_LIB_CALL
356 hx509_cms_unenvelope(hx509_context context
,
361 const heim_octet_string
*encryptedContent
,
363 heim_oid
*contentType
,
364 heim_octet_string
*content
)
366 heim_octet_string key
;
369 AlgorithmIdentifier
*ai
;
370 const heim_octet_string
*enccontent
;
371 heim_octet_string
*params
, params_data
;
372 heim_octet_string ivec
;
374 int ret
, matched
= 0, findflags
= 0;
378 memset(&key
, 0, sizeof(key
));
379 memset(&ed
, 0, sizeof(ed
));
380 memset(&ivec
, 0, sizeof(ivec
));
381 memset(content
, 0, sizeof(*content
));
382 memset(contentType
, 0, sizeof(*contentType
));
384 if ((flags
& HX509_CMS_UE_DONT_REQUIRE_KU_ENCIPHERMENT
) == 0)
385 findflags
|= HX509_QUERY_KU_ENCIPHERMENT
;
387 ret
= decode_EnvelopedData(data
, length
, &ed
, &size
);
389 hx509_set_error_string(context
, 0, ret
,
390 "Failed to decode EnvelopedData");
394 if (ed
.recipientInfos
.len
== 0) {
395 ret
= HX509_CMS_NO_RECIPIENT_CERTIFICATE
;
396 hx509_set_error_string(context
, 0, ret
,
397 "No recipient info in enveloped data");
401 enccontent
= ed
.encryptedContentInfo
.encryptedContent
;
402 if (enccontent
== NULL
) {
403 if (encryptedContent
== NULL
) {
404 ret
= HX509_CMS_NO_DATA_AVAILABLE
;
405 hx509_set_error_string(context
, 0, ret
,
406 "Content missing from encrypted data");
409 enccontent
= encryptedContent
;
410 } else if (encryptedContent
!= NULL
) {
411 ret
= HX509_CMS_NO_DATA_AVAILABLE
;
412 hx509_set_error_string(context
, 0, ret
,
413 "Both internal and external encrypted data");
418 for (i
= 0; i
< ed
.recipientInfos
.len
; i
++) {
419 KeyTransRecipientInfo
*ri
;
423 ri
= &ed
.recipientInfos
.val
[i
];
425 ret
= find_CMSIdentifier(context
, &ri
->rid
, certs
,
427 HX509_QUERY_PRIVATE_KEY
|findflags
);
431 matched
= 1; /* found a matching certificate, let decrypt */
433 ret
= _hx509_cert_private_decrypt(context
,
435 &ri
->keyEncryptionAlgorithm
.algorithm
,
438 hx509_cert_free(cert
);
440 break; /* successfully decrypted cert */
442 ret2
= unparse_CMSIdentifier(context
, &ri
->rid
, &str
);
444 hx509_set_error_string(context
, HX509_ERROR_APPEND
, ret
,
445 "Failed to decrypt with %s", str
);
451 ret
= HX509_CMS_NO_RECIPIENT_CERTIFICATE
;
452 hx509_set_error_string(context
, 0, ret
,
453 "No private key matched any certificate");
458 ret
= HX509_CMS_NO_RECIPIENT_CERTIFICATE
;
459 hx509_set_error_string(context
, HX509_ERROR_APPEND
, ret
,
460 "No private key decrypted the transfer key");
464 ret
= der_copy_oid(&ed
.encryptedContentInfo
.contentType
, contentType
);
466 hx509_set_error_string(context
, 0, ret
,
467 "Failed to copy EnvelopedData content oid");
471 ai
= &ed
.encryptedContentInfo
.contentEncryptionAlgorithm
;
472 if (ai
->parameters
) {
473 params_data
.data
= ai
->parameters
->data
;
474 params_data
.length
= ai
->parameters
->length
;
475 params
= ¶ms_data
;
482 ret
= hx509_crypto_init(context
, NULL
, &ai
->algorithm
, &crypto
);
486 if (flags
& HX509_CMS_UE_ALLOW_WEAK
)
487 hx509_crypto_allow_weak(crypto
);
490 ret
= hx509_crypto_set_params(context
, crypto
, params
, &ivec
);
492 hx509_crypto_destroy(crypto
);
497 ret
= hx509_crypto_set_key_data(crypto
, key
.data
, key
.length
);
499 hx509_crypto_destroy(crypto
);
500 hx509_set_error_string(context
, 0, ret
,
501 "Failed to set key for decryption "
506 ret
= hx509_crypto_decrypt(crypto
,
509 ivec
.length
? &ivec
: NULL
,
511 hx509_crypto_destroy(crypto
);
513 hx509_set_error_string(context
, 0, ret
,
514 "Failed to decrypt EnvelopedData");
521 free_EnvelopedData(&ed
);
522 der_free_octet_string(&key
);
524 der_free_octet_string(&ivec
);
526 der_free_oid(contentType
);
527 der_free_octet_string(content
);
534 * Encrypt and encode EnvelopedData.
536 * Encrypt and encode EnvelopedData. The data is encrypted with a
537 * random key and the the random key is encrypted with the
538 * certificate's private key. This limits what private key type can be
541 * @param context A hx509 context.
542 * @param flags flags to control the behavior.
543 * - HX509_CMS_EV_NO_KU_CHECK - Don't check KU on certificate
544 * - HX509_CMS_EV_ALLOW_WEAK - Allow weak crypto
545 * - HX509_CMS_EV_ID_NAME - prefer issuer name and serial number
546 * @param cert Certificate to encrypt the EnvelopedData encryption key
548 * @param data pointer the data to encrypt.
549 * @param length length of the data that data point to.
550 * @param encryption_type Encryption cipher to use for the bulk data,
551 * use NULL to get default.
552 * @param contentType type of the data that is encrypted
553 * @param content the output of the function,
554 * free with der_free_octet_string().
556 * @return an hx509 error code.
561 HX509_LIB_FUNCTION
int HX509_LIB_CALL
562 hx509_cms_envelope_1(hx509_context context
,
567 const heim_oid
*encryption_type
,
568 const heim_oid
*contentType
,
569 heim_octet_string
*content
)
571 KeyTransRecipientInfo
*ri
;
572 heim_octet_string ivec
;
573 heim_octet_string key
;
574 hx509_crypto crypto
= NULL
;
579 memset(&ivec
, 0, sizeof(ivec
));
580 memset(&key
, 0, sizeof(key
));
581 memset(&ed
, 0, sizeof(ed
));
582 memset(content
, 0, sizeof(*content
));
584 if (encryption_type
== NULL
)
585 encryption_type
= &asn1_oid_id_aes_256_cbc
;
587 if ((flags
& HX509_CMS_EV_NO_KU_CHECK
) == 0) {
588 ret
= _hx509_check_key_usage(context
, cert
, 1 << 2, TRUE
);
593 ret
= hx509_crypto_init(context
, NULL
, encryption_type
, &crypto
);
597 if (flags
& HX509_CMS_EV_ALLOW_WEAK
)
598 hx509_crypto_allow_weak(crypto
);
600 ret
= hx509_crypto_set_random_key(crypto
, &key
);
602 hx509_set_error_string(context
, 0, ret
,
603 "Create random key for EnvelopedData content");
607 ret
= hx509_crypto_random_iv(crypto
, &ivec
);
609 hx509_set_error_string(context
, 0, ret
,
610 "Failed to create a random iv");
614 ret
= hx509_crypto_encrypt(crypto
,
618 &ed
.encryptedContentInfo
.encryptedContent
);
620 hx509_set_error_string(context
, 0, ret
,
621 "Failed to encrypt EnvelopedData content");
626 AlgorithmIdentifier
*enc_alg
;
627 enc_alg
= &ed
.encryptedContentInfo
.contentEncryptionAlgorithm
;
628 ret
= der_copy_oid(encryption_type
, &enc_alg
->algorithm
);
630 hx509_set_error_string(context
, 0, ret
,
631 "Failed to set crypto oid "
632 "for EnvelopedData");
635 ALLOC(enc_alg
->parameters
, 1);
636 if (enc_alg
->parameters
== NULL
) {
638 hx509_set_error_string(context
, 0, ret
,
639 "Failed to allocate crypto parameters "
640 "for EnvelopedData");
644 ret
= hx509_crypto_get_params(context
,
647 enc_alg
->parameters
);
653 ALLOC_SEQ(&ed
.recipientInfos
, 1);
654 if (ed
.recipientInfos
.val
== NULL
) {
656 hx509_set_error_string(context
, 0, ret
,
657 "Failed to allocate recipients info "
658 "for EnvelopedData");
662 ri
= &ed
.recipientInfos
.val
[0];
664 if (flags
& HX509_CMS_EV_ID_NAME
) {
666 cmsidflag
= CMS_ID_NAME
;
669 cmsidflag
= CMS_ID_SKI
;
672 ret
= fill_CMSIdentifier(cert
, cmsidflag
, &ri
->rid
);
674 hx509_set_error_string(context
, 0, ret
,
675 "Failed to set CMS identifier info "
676 "for EnvelopedData");
680 ret
= hx509_cert_public_encrypt(context
,
682 &ri
->keyEncryptionAlgorithm
.algorithm
,
685 hx509_set_error_string(context
, HX509_ERROR_APPEND
, ret
,
686 "Failed to encrypt transport key for "
696 ed
.originatorInfo
= NULL
;
698 ret
= der_copy_oid(contentType
, &ed
.encryptedContentInfo
.contentType
);
700 hx509_set_error_string(context
, 0, ret
,
701 "Failed to copy content oid for "
706 ed
.unprotectedAttrs
= NULL
;
708 ASN1_MALLOC_ENCODE(EnvelopedData
, content
->data
, content
->length
,
711 hx509_set_error_string(context
, 0, ret
,
712 "Failed to encode EnvelopedData");
715 if (size
!= content
->length
)
716 _hx509_abort("internal ASN.1 encoder error");
720 hx509_crypto_destroy(crypto
);
722 der_free_octet_string(content
);
723 der_free_octet_string(&key
);
724 der_free_octet_string(&ivec
);
725 free_EnvelopedData(&ed
);
731 any_to_certs(hx509_context context
, const SignedData
*sd
, hx509_certs certs
)
736 if (sd
->certificates
== NULL
)
739 for (i
= 0; i
< sd
->certificates
->len
; i
++) {
743 c
= hx509_cert_init_data(context
,
744 sd
->certificates
->val
[i
].data
,
745 sd
->certificates
->val
[i
].length
,
748 ret
= heim_error_get_code(error
);
752 ret
= hx509_certs_add(context
, certs
, c
);
761 static const Attribute
*
762 find_attribute(const CMSAttributes
*attr
, const heim_oid
*oid
)
765 for (i
= 0; i
< attr
->len
; i
++)
766 if (der_heim_oid_cmp(&attr
->val
[i
].type
, oid
) == 0)
767 return &attr
->val
[i
];
772 * Decode SignedData and verify that the signature is correct.
774 * @param context A hx509 context.
775 * @param ctx a hx509 verify context.
776 * @param flags to control the behavior of the function.
777 * - HX509_CMS_VS_NO_KU_CHECK - Don't check KeyUsage
778 * - HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH - allow oid mismatch
779 * - HX509_CMS_VS_ALLOW_ZERO_SIGNER - no signer, see below.
780 * @param data pointer to CMS SignedData encoded data.
781 * @param length length of the data that data points to.
782 * @param signedContent external data used for signature.
783 * @param pool certificate pool to build certificates paths.
784 * @param contentType free with der_free_oid().
785 * @param content the output of the function, free with
786 * der_free_octet_string().
787 * @param signer_certs list of the cerficates used to sign this
788 * request, free with hx509_certs_free().
790 * @return an hx509 error code.
795 HX509_LIB_FUNCTION
int HX509_LIB_CALL
796 hx509_cms_verify_signed(hx509_context context
,
797 hx509_verify_ctx ctx
,
801 const heim_octet_string
*signedContent
,
803 heim_oid
*contentType
,
804 heim_octet_string
*content
,
805 hx509_certs
*signer_certs
)
807 unsigned int verify_flags
;
809 return hx509_cms_verify_signed_ext(context
,
823 * Decode SignedData and verify that the signature is correct.
825 * @param context A hx509 context.
826 * @param ctx a hx509 verify context.
827 * @param flags to control the behaivor of the function.
828 * - HX509_CMS_VS_NO_KU_CHECK - Don't check KeyUsage
829 * - HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH - allow oid mismatch
830 * - HX509_CMS_VS_ALLOW_ZERO_SIGNER - no signer, see below.
831 * @param data pointer to CMS SignedData encoded data.
832 * @param length length of the data that data points to.
833 * @param signedContent external data used for signature.
834 * @param pool certificate pool to build certificates paths.
835 * @param contentType free with der_free_oid().
836 * @param content the output of the function, free with
837 * der_free_octet_string().
838 * @param signer_certs list of the cerficates used to sign this
839 * request, free with hx509_certs_free().
840 * @param verify_flags flags indicating whether the certificate
841 * was verified or not
843 * @return an hx509 error code.
848 HX509_LIB_FUNCTION
int HX509_LIB_CALL
849 hx509_cms_verify_signed_ext(hx509_context context
,
850 hx509_verify_ctx ctx
,
854 const heim_octet_string
*signedContent
,
856 heim_oid
*contentType
,
857 heim_octet_string
*content
,
858 hx509_certs
*signer_certs
,
859 unsigned int *verify_flags
)
861 SignerInfo
*signer_info
;
862 hx509_cert cert
= NULL
;
863 hx509_certs certs
= NULL
;
866 int ret
, found_valid_sig
;
869 *signer_certs
= NULL
;
872 content
->data
= NULL
;
874 contentType
->length
= 0;
875 contentType
->components
= NULL
;
877 memset(&sd
, 0, sizeof(sd
));
879 ret
= decode_SignedData(data
, length
, &sd
, &size
);
881 hx509_set_error_string(context
, 0, ret
,
882 "Failed to decode SignedData");
886 if (sd
.encapContentInfo
.eContent
== NULL
&& signedContent
== NULL
) {
887 ret
= HX509_CMS_NO_DATA_AVAILABLE
;
888 hx509_set_error_string(context
, 0, ret
,
889 "No content data in SignedData");
892 if (sd
.encapContentInfo
.eContent
&& signedContent
) {
893 ret
= HX509_CMS_NO_DATA_AVAILABLE
;
894 hx509_set_error_string(context
, 0, ret
,
895 "Both external and internal SignedData");
899 if (sd
.encapContentInfo
.eContent
)
900 ret
= der_copy_octet_string(sd
.encapContentInfo
.eContent
, content
);
902 ret
= der_copy_octet_string(signedContent
, content
);
904 hx509_set_error_string(context
, 0, ret
, "malloc: out of memory");
908 ret
= hx509_certs_init(context
, "MEMORY:cms-cert-buffer",
913 ret
= hx509_certs_init(context
, "MEMORY:cms-signer-certs",
914 0, NULL
, signer_certs
);
918 /* XXX Check CMS version */
920 ret
= any_to_certs(context
, &sd
, certs
);
925 ret
= hx509_certs_merge(context
, certs
, pool
);
930 for (found_valid_sig
= 0, i
= 0; i
< sd
.signerInfos
.len
; i
++) {
931 heim_octet_string signed_data
= { 0, NULL
};
932 const heim_oid
*match_oid
;
935 signer_info
= &sd
.signerInfos
.val
[i
];
938 if (signer_info
->signature
.length
== 0) {
939 ret
= HX509_CMS_MISSING_SIGNER_DATA
;
940 hx509_set_error_string(context
, 0, ret
,
941 "SignerInfo %zu in SignedData "
942 "missing signature", i
);
946 ret
= find_CMSIdentifier(context
, &signer_info
->sid
, certs
,
947 _hx509_verify_get_time(ctx
), &cert
,
948 HX509_QUERY_KU_DIGITALSIGNATURE
);
951 * If HX509_CMS_VS_NO_KU_CHECK is set, allow more liberal
952 * search for matching certificates by not considering
953 * KeyUsage bits on the certificates.
955 if ((flags
& HX509_CMS_VS_NO_KU_CHECK
) == 0)
958 ret
= find_CMSIdentifier(context
, &signer_info
->sid
, certs
,
959 _hx509_verify_get_time(ctx
), &cert
,
966 if (signer_info
->signedAttrs
) {
967 const Attribute
*attr
;
970 heim_octet_string os
;
972 sa
.val
= signer_info
->signedAttrs
->val
;
973 sa
.len
= signer_info
->signedAttrs
->len
;
975 /* verify that signature exists */
976 attr
= find_attribute(&sa
, &asn1_oid_id_pkcs9_messageDigest
);
978 ret
= HX509_CRYPTO_SIGNATURE_MISSING
;
979 hx509_set_error_string(context
, 0, ret
,
980 "SignerInfo has signed attributes "
981 "but messageDigest (signature) "
985 if (attr
->value
.len
!= 1) {
986 ret
= HX509_CRYPTO_SIGNATURE_MISSING
;
987 hx509_set_error_string(context
, 0, ret
,
988 "SignerInfo has more than one "
989 "messageDigest (signature)");
993 ret
= decode_MessageDigest(attr
->value
.val
[0].data
,
994 attr
->value
.val
[0].length
,
998 hx509_set_error_string(context
, 0, ret
,
1000 "messageDigest (signature)");
1001 goto next_signature
;
1004 ret
= _hx509_verify_signature(context
,
1006 &signer_info
->digestAlgorithm
,
1009 der_free_octet_string(&os
);
1011 hx509_set_error_string(context
, HX509_ERROR_APPEND
, ret
,
1012 "Failed to verify messageDigest");
1013 goto next_signature
;
1017 * Fetch content oid inside signedAttrs or set it to
1020 attr
= find_attribute(&sa
, &asn1_oid_id_pkcs9_contentType
);
1022 match_oid
= &asn1_oid_id_pkcs7_data
;
1024 if (attr
->value
.len
!= 1) {
1025 ret
= HX509_CMS_DATA_OID_MISMATCH
;
1026 hx509_set_error_string(context
, 0, ret
,
1027 "More than one oid in signedAttrs");
1028 goto next_signature
;
1031 ret
= decode_ContentType(attr
->value
.val
[0].data
,
1032 attr
->value
.val
[0].length
,
1036 hx509_set_error_string(context
, 0, ret
,
1038 "oid in signedAttrs");
1039 goto next_signature
;
1041 match_oid
= &decode_oid
;
1044 ASN1_MALLOC_ENCODE(CMSAttributes
,
1050 if (match_oid
== &decode_oid
)
1051 der_free_oid(&decode_oid
);
1052 hx509_clear_error_string(context
);
1053 goto next_signature
;
1055 if (size
!= signed_data
.length
)
1056 _hx509_abort("internal ASN.1 encoder error");
1059 signed_data
.data
= content
->data
;
1060 signed_data
.length
= content
->length
;
1061 match_oid
= &asn1_oid_id_pkcs7_data
;
1065 * If HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH, allow
1066 * encapContentInfo mismatch with the oid in signedAttributes
1067 * (or if no signedAttributes where use, pkcs7-data oid).
1068 * This is only needed to work with broken CMS implementations
1069 * that doesn't follow CMS signedAttributes rules.
1072 if (der_heim_oid_cmp(match_oid
, &sd
.encapContentInfo
.eContentType
) &&
1073 (flags
& HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH
) == 0) {
1074 ret
= HX509_CMS_DATA_OID_MISMATCH
;
1075 hx509_set_error_string(context
, 0, ret
,
1076 "Oid in message mismatch from the expected");
1078 if (match_oid
== &decode_oid
)
1079 der_free_oid(&decode_oid
);
1082 ret
= hx509_verify_signature(context
,
1084 &signer_info
->signatureAlgorithm
,
1086 &signer_info
->signature
);
1088 hx509_set_error_string(context
, HX509_ERROR_APPEND
, ret
,
1089 "Failed to verify signature in "
1092 if (signed_data
.data
!= NULL
&& content
->data
!= signed_data
.data
) {
1093 free(signed_data
.data
);
1094 signed_data
.data
= NULL
;
1097 goto next_signature
;
1100 * If HX509_CMS_VS_NO_VALIDATE flags is set, return the signer
1101 * certificate unconditionally but do not set HX509_CMS_VSE_VALIDATED.
1103 ret
= hx509_verify_path(context
, ctx
, cert
, certs
);
1104 if (ret
== 0 || (flags
& HX509_CMS_VS_NO_VALIDATE
)) {
1106 *verify_flags
|= HX509_CMS_VSE_VALIDATED
;
1108 ret
= hx509_certs_add(context
, *signer_certs
, cert
);
1115 hx509_cert_free(cert
);
1119 * If HX509_CMS_VS_ALLOW_ZERO_SIGNER is set, allow empty
1120 * SignerInfo (no signatures). If SignedData has no signatures,
1121 * the function will return 0 with signer_certs set to NULL. Zero
1122 * signers is allowed by the standard, but since it's only useful
1123 * in corner cases, it's made into a flag that the caller has to
1126 if (sd
.signerInfos
.len
== 0 && (flags
& HX509_CMS_VS_ALLOW_ZERO_SIGNER
)) {
1128 hx509_certs_free(signer_certs
);
1129 } else if (found_valid_sig
== 0) {
1131 ret
= HX509_CMS_SIGNER_NOT_FOUND
;
1132 hx509_set_error_string(context
, 0, ret
,
1133 "No signers were found");
1138 ret
= der_copy_oid(&sd
.encapContentInfo
.eContentType
, contentType
);
1140 hx509_clear_error_string(context
);
1145 free_SignedData(&sd
);
1147 hx509_certs_free(&certs
);
1150 der_free_octet_string(content
);
1152 hx509_certs_free(signer_certs
);
1153 der_free_oid(contentType
);
1154 der_free_octet_string(content
);
1161 add_one_attribute(Attribute
**attr
,
1163 const heim_oid
*oid
,
1164 heim_octet_string
*data
)
1169 d
= realloc(*attr
, sizeof((*attr
)[0]) * (*len
+ 1));
1174 ret
= der_copy_oid(oid
, &(*attr
)[*len
].type
);
1178 ALLOC_SEQ(&(*attr
)[*len
].value
, 1);
1179 if ((*attr
)[*len
].value
.val
== NULL
) {
1180 der_free_oid(&(*attr
)[*len
].type
);
1184 (*attr
)[*len
].value
.val
[0].data
= data
->data
;
1185 (*attr
)[*len
].value
.val
[0].length
= data
->length
;
1193 * Decode SignedData and verify that the signature is correct.
1195 * @param context A hx509 context.
1197 * @param eContentType the type of the data.
1198 * @param data data to sign
1199 * @param length length of the data that data points to.
1200 * @param digest_alg digest algorithm to use, use NULL to get the
1201 * default or the peer determined algorithm.
1202 * @param cert certificate to use for signing the data.
1203 * @param peer info about the peer the message to send the message to,
1204 * like what digest algorithm to use.
1205 * @param anchors trust anchors that the client will use, used to
1206 * polulate the certificates included in the message
1207 * @param pool certificates to use in try to build the path to the
1209 * @param signed_data the output of the function, free with
1210 * der_free_octet_string().
1212 * @return Returns an hx509 error code.
1214 * @ingroup hx509_cms
1217 HX509_LIB_FUNCTION
int HX509_LIB_CALL
1218 hx509_cms_create_signed_1(hx509_context context
,
1220 const heim_oid
*eContentType
,
1221 const void *data
, size_t length
,
1222 const AlgorithmIdentifier
*digest_alg
,
1224 hx509_peer_info peer
,
1225 hx509_certs anchors
,
1227 heim_octet_string
*signed_data
)
1232 signed_data
->data
= NULL
;
1233 signed_data
->length
= 0;
1235 ret
= hx509_certs_init(context
, "MEMORY:certs", 0, NULL
, &certs
);
1238 ret
= hx509_certs_add(context
, certs
, cert
);
1242 ret
= hx509_cms_create_signed(context
, flags
, eContentType
, data
, length
,
1243 digest_alg
, certs
, peer
, anchors
, pool
,
1247 hx509_certs_free(&certs
);
1253 const AlgorithmIdentifier
*digest_alg
;
1254 const heim_oid
*eContentType
;
1255 heim_octet_string content
;
1256 hx509_peer_info peer
;
1260 hx509_certs anchors
;
1264 static int HX509_LIB_CALL
1265 sig_process(hx509_context context
, void *ctx
, hx509_cert cert
)
1267 struct sigctx
*sigctx
= ctx
;
1268 heim_octet_string buf
, sigdata
= { 0, NULL
};
1269 SignerInfo
*signer_info
= NULL
;
1270 AlgorithmIdentifier digest
;
1274 SignedData
*sd
= &sigctx
->sd
;
1277 memset(&digest
, 0, sizeof(digest
));
1278 memset(&path
, 0, sizeof(path
));
1280 if (_hx509_cert_private_key(cert
) == NULL
) {
1281 hx509_set_error_string(context
, 0, HX509_PRIVATE_KEY_MISSING
,
1282 "Private key missing for signing");
1283 return HX509_PRIVATE_KEY_MISSING
;
1286 if (sigctx
->digest_alg
) {
1287 ret
= copy_AlgorithmIdentifier(sigctx
->digest_alg
, &digest
);
1289 hx509_clear_error_string(context
);
1291 ret
= hx509_crypto_select(context
, HX509_SELECT_DIGEST
,
1292 _hx509_cert_private_key(cert
),
1293 sigctx
->peer
, &digest
);
1299 * Allocate on more signerInfo and do the signature processing
1302 ptr
= realloc(sd
->signerInfos
.val
,
1303 (sd
->signerInfos
.len
+ 1) * sizeof(sd
->signerInfos
.val
[0]));
1308 sd
->signerInfos
.val
= ptr
;
1310 signer_info
= &sd
->signerInfos
.val
[sd
->signerInfos
.len
];
1312 memset(signer_info
, 0, sizeof(*signer_info
));
1314 signer_info
->version
= 1;
1316 ret
= fill_CMSIdentifier(cert
, sigctx
->cmsidflag
, &signer_info
->sid
);
1318 hx509_clear_error_string(context
);
1322 signer_info
->signedAttrs
= NULL
;
1323 signer_info
->unsignedAttrs
= NULL
;
1325 ret
= copy_AlgorithmIdentifier(&digest
, &signer_info
->digestAlgorithm
);
1327 hx509_clear_error_string(context
);
1332 * If it isn't pkcs7-data send signedAttributes
1335 if (der_heim_oid_cmp(sigctx
->eContentType
, &asn1_oid_id_pkcs7_data
) != 0) {
1337 heim_octet_string sig
;
1339 ALLOC(signer_info
->signedAttrs
, 1);
1340 if (signer_info
->signedAttrs
== NULL
) {
1345 ret
= _hx509_create_signature(context
,
1354 ASN1_MALLOC_ENCODE(MessageDigest
,
1360 der_free_octet_string(&sig
);
1362 hx509_clear_error_string(context
);
1365 if (size
!= buf
.length
)
1366 _hx509_abort("internal ASN.1 encoder error");
1368 ret
= add_one_attribute(&signer_info
->signedAttrs
->val
,
1369 &signer_info
->signedAttrs
->len
,
1370 &asn1_oid_id_pkcs9_messageDigest
,
1374 hx509_clear_error_string(context
);
1379 ASN1_MALLOC_ENCODE(ContentType
,
1382 sigctx
->eContentType
,
1387 if (size
!= buf
.length
)
1388 _hx509_abort("internal ASN.1 encoder error");
1390 ret
= add_one_attribute(&signer_info
->signedAttrs
->val
,
1391 &signer_info
->signedAttrs
->len
,
1392 &asn1_oid_id_pkcs9_contentType
,
1396 hx509_clear_error_string(context
);
1400 sa
.val
= signer_info
->signedAttrs
->val
;
1401 sa
.len
= signer_info
->signedAttrs
->len
;
1403 ASN1_MALLOC_ENCODE(CMSAttributes
,
1410 hx509_clear_error_string(context
);
1413 if (size
!= sigdata
.length
)
1414 _hx509_abort("internal ASN.1 encoder error");
1416 sigdata
.data
= sigctx
->content
.data
;
1417 sigdata
.length
= sigctx
->content
.length
;
1421 AlgorithmIdentifier sigalg
;
1423 ret
= hx509_crypto_select(context
, HX509_SELECT_PUBLIC_SIG
,
1424 _hx509_cert_private_key(cert
), sigctx
->peer
,
1429 ret
= _hx509_create_signature(context
,
1430 _hx509_cert_private_key(cert
),
1433 &signer_info
->signatureAlgorithm
,
1434 &signer_info
->signature
);
1435 free_AlgorithmIdentifier(&sigalg
);
1440 sigctx
->sd
.signerInfos
.len
++;
1444 * Provide best effort path
1446 if (sigctx
->certs
) {
1449 if (sigctx
->pool
&& sigctx
->leafonly
== 0) {
1450 _hx509_calculate_path(context
,
1451 HX509_CALCULATE_PATH_NO_ANCHOR
,
1459 _hx509_path_append(context
, &path
, cert
);
1461 for (i
= 0; i
< path
.len
; i
++) {
1462 /* XXX remove dups */
1463 ret
= hx509_certs_add(context
, sigctx
->certs
, path
.val
[i
]);
1465 hx509_clear_error_string(context
);
1473 free_SignerInfo(signer_info
);
1474 if (sigdata
.data
!= sigctx
->content
.data
)
1475 der_free_octet_string(&sigdata
);
1476 _hx509_path_free(&path
);
1477 free_AlgorithmIdentifier(&digest
);
1482 static int HX509_LIB_CALL
1483 cert_process(hx509_context context
, void *ctx
, hx509_cert cert
)
1485 struct sigctx
*sigctx
= ctx
;
1486 const unsigned int i
= sigctx
->sd
.certificates
->len
;
1490 ptr
= realloc(sigctx
->sd
.certificates
->val
,
1491 (i
+ 1) * sizeof(sigctx
->sd
.certificates
->val
[0]));
1494 sigctx
->sd
.certificates
->val
= ptr
;
1496 ret
= hx509_cert_binary(context
, cert
,
1497 &sigctx
->sd
.certificates
->val
[i
]);
1499 sigctx
->sd
.certificates
->len
++;
1505 cmp_AlgorithmIdentifier(const AlgorithmIdentifier
*p
, const AlgorithmIdentifier
*q
)
1507 return der_heim_oid_cmp(&p
->algorithm
, &q
->algorithm
);
1510 HX509_LIB_FUNCTION
int HX509_LIB_CALL
1511 hx509_cms_create_signed(hx509_context context
,
1513 const heim_oid
*eContentType
,
1514 const void *data
, size_t length
,
1515 const AlgorithmIdentifier
*digest_alg
,
1517 hx509_peer_info peer
,
1518 hx509_certs anchors
,
1520 heim_octet_string
*signed_data
)
1525 struct sigctx sigctx
;
1527 memset(&sigctx
, 0, sizeof(sigctx
));
1529 if (eContentType
== NULL
)
1530 eContentType
= &asn1_oid_id_pkcs7_data
;
1532 sigctx
.digest_alg
= digest_alg
;
1533 sigctx
.content
.data
= rk_UNCONST(data
);
1534 sigctx
.content
.length
= length
;
1535 sigctx
.eContentType
= eContentType
;
1538 * Use HX509_CMS_SIGNATURE_ID_NAME to preferred use of issuer name
1539 * and serial number if possible. Otherwise subject key identifier
1542 if (flags
& HX509_CMS_SIGNATURE_ID_NAME
)
1543 sigctx
.cmsidflag
= CMS_ID_NAME
;
1545 sigctx
.cmsidflag
= CMS_ID_SKI
;
1548 * Use HX509_CMS_SIGNATURE_LEAF_ONLY to only request leaf
1549 * certificates to be added to the SignedData.
1551 sigctx
.leafonly
= (flags
& HX509_CMS_SIGNATURE_LEAF_ONLY
) ? 1 : 0;
1554 * Use HX509_CMS_NO_CERTS to make the SignedData contain no
1555 * certificates, overrides HX509_CMS_SIGNATURE_LEAF_ONLY.
1558 if ((flags
& HX509_CMS_SIGNATURE_NO_CERTS
) == 0) {
1559 ret
= hx509_certs_init(context
, "MEMORY:certs", 0, NULL
, &sigctx
.certs
);
1564 sigctx
.anchors
= anchors
;
1567 sigctx
.sd
.version
= cMSVersion_v3
;
1569 ret
= der_copy_oid(eContentType
, &sigctx
.sd
.encapContentInfo
.eContentType
);
1574 * Use HX509_CMS_SIGNATURE_DETACHED to create detached signatures.
1576 if ((flags
& HX509_CMS_SIGNATURE_DETACHED
) == 0) {
1577 ALLOC(sigctx
.sd
.encapContentInfo
.eContent
, 1);
1578 if (sigctx
.sd
.encapContentInfo
.eContent
== NULL
) {
1579 hx509_clear_error_string(context
);
1584 sigctx
.sd
.encapContentInfo
.eContent
->data
= malloc(length
);
1585 if (sigctx
.sd
.encapContentInfo
.eContent
->data
== NULL
) {
1586 hx509_clear_error_string(context
);
1590 memcpy(sigctx
.sd
.encapContentInfo
.eContent
->data
, data
, length
);
1591 sigctx
.sd
.encapContentInfo
.eContent
->length
= length
;
1595 * Use HX509_CMS_SIGNATURE_NO_SIGNER to create no sigInfo (no
1598 if ((flags
& HX509_CMS_SIGNATURE_NO_SIGNER
) == 0) {
1599 ret
= hx509_certs_iter_f(context
, certs
, sig_process
, &sigctx
);
1604 if (sigctx
.sd
.signerInfos
.len
) {
1607 * For each signerInfo, collect all different digest types.
1609 for (i
= 0; i
< sigctx
.sd
.signerInfos
.len
; i
++) {
1610 AlgorithmIdentifier
*di
=
1611 &sigctx
.sd
.signerInfos
.val
[i
].digestAlgorithm
;
1613 for (j
= 0; j
< sigctx
.sd
.digestAlgorithms
.len
; j
++)
1614 if (cmp_AlgorithmIdentifier(di
, &sigctx
.sd
.digestAlgorithms
.val
[j
]) == 0)
1616 if (j
== sigctx
.sd
.digestAlgorithms
.len
) {
1617 ret
= add_DigestAlgorithmIdentifiers(&sigctx
.sd
.digestAlgorithms
, di
);
1619 hx509_clear_error_string(context
);
1627 * Add certs we think are needed, build as part of sig_process
1630 ALLOC(sigctx
.sd
.certificates
, 1);
1631 if (sigctx
.sd
.certificates
== NULL
) {
1632 hx509_clear_error_string(context
);
1637 ret
= hx509_certs_iter_f(context
, sigctx
.certs
, cert_process
, &sigctx
);
1642 ASN1_MALLOC_ENCODE(SignedData
,
1643 signed_data
->data
, signed_data
->length
,
1644 &sigctx
.sd
, &size
, ret
);
1646 hx509_clear_error_string(context
);
1649 if (signed_data
->length
!= size
)
1650 _hx509_abort("internal ASN.1 encoder error");
1653 hx509_certs_free(&sigctx
.certs
);
1654 free_SignedData(&sigctx
.sd
);
1659 HX509_LIB_FUNCTION
int HX509_LIB_CALL
1660 hx509_cms_decrypt_encrypted(hx509_context context
,
1664 heim_oid
*contentType
,
1665 heim_octet_string
*content
)
1667 heim_octet_string cont
;
1668 CMSEncryptedData ed
;
1669 AlgorithmIdentifier
*ai
;
1672 memset(content
, 0, sizeof(*content
));
1673 memset(&cont
, 0, sizeof(cont
));
1675 ret
= decode_CMSEncryptedData(data
, length
, &ed
, NULL
);
1677 hx509_set_error_string(context
, 0, ret
,
1678 "Failed to decode CMSEncryptedData");
1682 if (ed
.encryptedContentInfo
.encryptedContent
== NULL
) {
1683 ret
= HX509_CMS_NO_DATA_AVAILABLE
;
1684 hx509_set_error_string(context
, 0, ret
,
1685 "No content in EncryptedData");
1689 ret
= der_copy_oid(&ed
.encryptedContentInfo
.contentType
, contentType
);
1691 hx509_clear_error_string(context
);
1695 ai
= &ed
.encryptedContentInfo
.contentEncryptionAlgorithm
;
1696 if (ai
->parameters
== NULL
) {
1697 ret
= HX509_ALG_NOT_SUPP
;
1698 hx509_clear_error_string(context
);
1702 ret
= _hx509_pbe_decrypt(context
,
1705 ed
.encryptedContentInfo
.encryptedContent
,
1717 free_CMSEncryptedData(&ed
);