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 flags show dthe
121 * diffrence 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
);
190 id
->element
= choice_CMSIdentifier_issuerAndSerialNumber
;
191 ret
= hx509_cert_get_issuer(cert
, &name
);
194 ret
= hx509_name_to_Name(name
, &id
->u
.issuerAndSerialNumber
.issuer
);
195 hx509_name_free(&name
);
199 ret
= hx509_cert_get_serialnumber(cert
, &id
->u
.issuerAndSerialNumber
.serialNumber
);
203 _hx509_abort("CMS fill identifier with unknown type");
209 unparse_CMSIdentifier(hx509_context context
,
216 switch (id
->element
) {
217 case choice_CMSIdentifier_issuerAndSerialNumber
: {
218 IssuerAndSerialNumber
*iasn
;
221 iasn
= &id
->u
.issuerAndSerialNumber
;
223 ret
= _hx509_Name_to_string(&iasn
->issuer
, &name
);
226 ret
= der_print_hex_heim_integer(&iasn
->serialNumber
, &serial
);
231 ret
= asprintf(str
, "certificate issued by %s with serial number %s",
237 case choice_CMSIdentifier_subjectKeyIdentifier
: {
238 KeyIdentifier
*ki
= &id
->u
.subjectKeyIdentifier
;
242 len
= hex_encode(ki
->data
, ki
->length
, &keyid
);
246 ret
= asprintf(str
, "certificate with id %s", keyid
);
251 ret
= asprintf(str
, "certificate have unknown CMSidentifier type");
255 * In the following if, we check ret and *str which should be returned/set
256 * by asprintf(3) in every branch of the switch statement.
258 if (ret
== -1 || *str
== NULL
)
264 find_CMSIdentifier(hx509_context context
,
265 CMSIdentifier
*client
,
268 hx509_cert
*signer_cert
,
276 memset(&c
, 0, sizeof(c
));
277 _hx509_query_clear(&q
);
281 switch (client
->element
) {
282 case choice_CMSIdentifier_issuerAndSerialNumber
:
283 q
.serial
= &client
->u
.issuerAndSerialNumber
.serialNumber
;
284 q
.issuer_name
= &client
->u
.issuerAndSerialNumber
.issuer
;
285 q
.match
= HX509_QUERY_MATCH_SERIALNUMBER
|HX509_QUERY_MATCH_ISSUER_NAME
;
287 case choice_CMSIdentifier_subjectKeyIdentifier
:
288 q
.subject_id
= &client
->u
.subjectKeyIdentifier
;
289 q
.match
= HX509_QUERY_MATCH_SUBJECT_KEY_ID
;
292 hx509_set_error_string(context
, 0, HX509_CMS_NO_RECIPIENT_CERTIFICATE
,
293 "unknown CMS identifier element");
294 return HX509_CMS_NO_RECIPIENT_CERTIFICATE
;
299 q
.match
|= HX509_QUERY_MATCH_TIME
;
301 q
.timenow
= time_now
;
303 q
.timenow
= time(NULL
);
305 ret
= hx509_certs_find(context
, certs
, &q
, &cert
);
306 if (ret
== HX509_CERT_NOT_FOUND
) {
309 ret
= unparse_CMSIdentifier(context
, client
, &str
);
311 hx509_set_error_string(context
, 0,
312 HX509_CMS_NO_RECIPIENT_CERTIFICATE
,
313 "Failed to find %s", str
);
315 hx509_clear_error_string(context
);
316 return HX509_CMS_NO_RECIPIENT_CERTIFICATE
;
318 hx509_set_error_string(context
, HX509_ERROR_APPEND
,
319 HX509_CMS_NO_RECIPIENT_CERTIFICATE
,
320 "Failed to find CMS id in cert store");
321 return HX509_CMS_NO_RECIPIENT_CERTIFICATE
;
330 * Decode and unencrypt EnvelopedData.
332 * Extract data and parameteres from from the EnvelopedData. Also
333 * supports using detached EnvelopedData.
335 * @param context A hx509 context.
336 * @param certs Certificate that can decrypt the EnvelopedData
338 * @param flags HX509_CMS_UE flags to control the behavior.
339 * @param data pointer the structure the contains the DER/BER encoded
340 * EnvelopedData stucture.
341 * @param length length of the data that data point to.
342 * @param encryptedContent in case of detached signature, this
343 * contains the actual encrypted data, othersize its should be NULL.
344 * @param time_now set the current time, if zero the library uses now as the date.
345 * @param contentType output type oid, should be freed with der_free_oid().
346 * @param content the data, free with der_free_octet_string().
348 * @return an hx509 error code.
353 HX509_LIB_FUNCTION
int HX509_LIB_CALL
354 hx509_cms_unenvelope(hx509_context context
,
359 const heim_octet_string
*encryptedContent
,
361 heim_oid
*contentType
,
362 heim_octet_string
*content
)
364 heim_octet_string key
;
367 AlgorithmIdentifier
*ai
;
368 const heim_octet_string
*enccontent
;
369 heim_octet_string
*params
, params_data
;
370 heim_octet_string ivec
;
372 int ret
, matched
= 0, findflags
= 0;
376 memset(&key
, 0, sizeof(key
));
377 memset(&ed
, 0, sizeof(ed
));
378 memset(&ivec
, 0, sizeof(ivec
));
379 memset(content
, 0, sizeof(*content
));
380 memset(contentType
, 0, sizeof(*contentType
));
382 if ((flags
& HX509_CMS_UE_DONT_REQUIRE_KU_ENCIPHERMENT
) == 0)
383 findflags
|= HX509_QUERY_KU_ENCIPHERMENT
;
385 ret
= decode_EnvelopedData(data
, length
, &ed
, &size
);
387 hx509_set_error_string(context
, 0, ret
,
388 "Failed to decode EnvelopedData");
392 if (ed
.recipientInfos
.len
== 0) {
393 ret
= HX509_CMS_NO_RECIPIENT_CERTIFICATE
;
394 hx509_set_error_string(context
, 0, ret
,
395 "No recipient info in enveloped data");
399 enccontent
= ed
.encryptedContentInfo
.encryptedContent
;
400 if (enccontent
== NULL
) {
401 if (encryptedContent
== NULL
) {
402 ret
= HX509_CMS_NO_DATA_AVAILABLE
;
403 hx509_set_error_string(context
, 0, ret
,
404 "Content missing from encrypted data");
407 enccontent
= encryptedContent
;
408 } else if (encryptedContent
!= NULL
) {
409 ret
= HX509_CMS_NO_DATA_AVAILABLE
;
410 hx509_set_error_string(context
, 0, ret
,
411 "Both internal and external encrypted data");
416 for (i
= 0; i
< ed
.recipientInfos
.len
; i
++) {
417 KeyTransRecipientInfo
*ri
;
421 ri
= &ed
.recipientInfos
.val
[i
];
423 ret
= find_CMSIdentifier(context
, &ri
->rid
, certs
,
425 HX509_QUERY_PRIVATE_KEY
|findflags
);
429 matched
= 1; /* found a matching certificate, let decrypt */
431 ret
= _hx509_cert_private_decrypt(context
,
433 &ri
->keyEncryptionAlgorithm
.algorithm
,
436 hx509_cert_free(cert
);
438 break; /* succuessfully decrypted cert */
440 ret2
= unparse_CMSIdentifier(context
, &ri
->rid
, &str
);
442 hx509_set_error_string(context
, HX509_ERROR_APPEND
, ret
,
443 "Failed to decrypt with %s", str
);
449 ret
= HX509_CMS_NO_RECIPIENT_CERTIFICATE
;
450 hx509_set_error_string(context
, 0, ret
,
451 "No private key matched any certificate");
456 ret
= HX509_CMS_NO_RECIPIENT_CERTIFICATE
;
457 hx509_set_error_string(context
, HX509_ERROR_APPEND
, ret
,
458 "No private key decrypted the transfer key");
462 ret
= der_copy_oid(&ed
.encryptedContentInfo
.contentType
, contentType
);
464 hx509_set_error_string(context
, 0, ret
,
465 "Failed to copy EnvelopedData content oid");
469 ai
= &ed
.encryptedContentInfo
.contentEncryptionAlgorithm
;
470 if (ai
->parameters
) {
471 params_data
.data
= ai
->parameters
->data
;
472 params_data
.length
= ai
->parameters
->length
;
473 params
= ¶ms_data
;
480 ret
= hx509_crypto_init(context
, NULL
, &ai
->algorithm
, &crypto
);
484 if (flags
& HX509_CMS_UE_ALLOW_WEAK
)
485 hx509_crypto_allow_weak(crypto
);
488 ret
= hx509_crypto_set_params(context
, crypto
, params
, &ivec
);
490 hx509_crypto_destroy(crypto
);
495 ret
= hx509_crypto_set_key_data(crypto
, key
.data
, key
.length
);
497 hx509_crypto_destroy(crypto
);
498 hx509_set_error_string(context
, 0, ret
,
499 "Failed to set key for decryption "
504 ret
= hx509_crypto_decrypt(crypto
,
507 ivec
.length
? &ivec
: NULL
,
509 hx509_crypto_destroy(crypto
);
511 hx509_set_error_string(context
, 0, ret
,
512 "Failed to decrypt EnvelopedData");
519 free_EnvelopedData(&ed
);
520 der_free_octet_string(&key
);
522 der_free_octet_string(&ivec
);
524 der_free_oid(contentType
);
525 der_free_octet_string(content
);
532 * Encrypt end encode EnvelopedData.
534 * Encrypt and encode EnvelopedData. The data is encrypted with a
535 * random key and the the random key is encrypted with the
536 * certificates private key. This limits what private key type can be
539 * @param context A hx509 context.
540 * @param flags flags to control the behavior.
541 * - HX509_CMS_EV_NO_KU_CHECK - Don't check KU on certificate
542 * - HX509_CMS_EV_ALLOW_WEAK - Allow weak crytpo
543 * - HX509_CMS_EV_ID_NAME - prefer issuer name and serial number
544 * @param cert Certificate to encrypt the EnvelopedData encryption key
546 * @param data pointer the data to encrypt.
547 * @param length length of the data that data point to.
548 * @param encryption_type Encryption cipher to use for the bulk data,
549 * use NULL to get default.
550 * @param contentType type of the data that is encrypted
551 * @param content the output of the function,
552 * free with der_free_octet_string().
554 * @return an hx509 error code.
559 HX509_LIB_FUNCTION
int HX509_LIB_CALL
560 hx509_cms_envelope_1(hx509_context context
,
565 const heim_oid
*encryption_type
,
566 const heim_oid
*contentType
,
567 heim_octet_string
*content
)
569 KeyTransRecipientInfo
*ri
;
570 heim_octet_string ivec
;
571 heim_octet_string key
;
572 hx509_crypto crypto
= NULL
;
577 memset(&ivec
, 0, sizeof(ivec
));
578 memset(&key
, 0, sizeof(key
));
579 memset(&ed
, 0, sizeof(ed
));
580 memset(content
, 0, sizeof(*content
));
582 if (encryption_type
== NULL
)
583 encryption_type
= &asn1_oid_id_aes_256_cbc
;
585 if ((flags
& HX509_CMS_EV_NO_KU_CHECK
) == 0) {
586 ret
= _hx509_check_key_usage(context
, cert
, 1 << 2, TRUE
);
591 ret
= hx509_crypto_init(context
, NULL
, encryption_type
, &crypto
);
595 if (flags
& HX509_CMS_EV_ALLOW_WEAK
)
596 hx509_crypto_allow_weak(crypto
);
598 ret
= hx509_crypto_set_random_key(crypto
, &key
);
600 hx509_set_error_string(context
, 0, ret
,
601 "Create random key for EnvelopedData content");
605 ret
= hx509_crypto_random_iv(crypto
, &ivec
);
607 hx509_set_error_string(context
, 0, ret
,
608 "Failed to create a random iv");
612 ret
= hx509_crypto_encrypt(crypto
,
616 &ed
.encryptedContentInfo
.encryptedContent
);
618 hx509_set_error_string(context
, 0, ret
,
619 "Failed to encrypt EnvelopedData content");
624 AlgorithmIdentifier
*enc_alg
;
625 enc_alg
= &ed
.encryptedContentInfo
.contentEncryptionAlgorithm
;
626 ret
= der_copy_oid(encryption_type
, &enc_alg
->algorithm
);
628 hx509_set_error_string(context
, 0, ret
,
629 "Failed to set crypto oid "
630 "for EnvelopedData");
633 ALLOC(enc_alg
->parameters
, 1);
634 if (enc_alg
->parameters
== NULL
) {
636 hx509_set_error_string(context
, 0, ret
,
637 "Failed to allocate crypto parameters "
638 "for EnvelopedData");
642 ret
= hx509_crypto_get_params(context
,
645 enc_alg
->parameters
);
651 ALLOC_SEQ(&ed
.recipientInfos
, 1);
652 if (ed
.recipientInfos
.val
== NULL
) {
654 hx509_set_error_string(context
, 0, ret
,
655 "Failed to allocate recipients info "
656 "for EnvelopedData");
660 ri
= &ed
.recipientInfos
.val
[0];
662 if (flags
& HX509_CMS_EV_ID_NAME
) {
664 cmsidflag
= CMS_ID_NAME
;
667 cmsidflag
= CMS_ID_SKI
;
670 ret
= fill_CMSIdentifier(cert
, cmsidflag
, &ri
->rid
);
672 hx509_set_error_string(context
, 0, ret
,
673 "Failed to set CMS identifier info "
674 "for EnvelopedData");
678 ret
= hx509_cert_public_encrypt(context
,
680 &ri
->keyEncryptionAlgorithm
.algorithm
,
683 hx509_set_error_string(context
, HX509_ERROR_APPEND
, ret
,
684 "Failed to encrypt transport key for "
694 ed
.originatorInfo
= NULL
;
696 ret
= der_copy_oid(contentType
, &ed
.encryptedContentInfo
.contentType
);
698 hx509_set_error_string(context
, 0, ret
,
699 "Failed to copy content oid for "
704 ed
.unprotectedAttrs
= NULL
;
706 ASN1_MALLOC_ENCODE(EnvelopedData
, content
->data
, content
->length
,
709 hx509_set_error_string(context
, 0, ret
,
710 "Failed to encode EnvelopedData");
713 if (size
!= content
->length
)
714 _hx509_abort("internal ASN.1 encoder error");
718 hx509_crypto_destroy(crypto
);
720 der_free_octet_string(content
);
721 der_free_octet_string(&key
);
722 der_free_octet_string(&ivec
);
723 free_EnvelopedData(&ed
);
729 any_to_certs(hx509_context context
, const SignedData
*sd
, hx509_certs certs
)
734 if (sd
->certificates
== NULL
)
737 for (i
= 0; i
< sd
->certificates
->len
; i
++) {
741 c
= hx509_cert_init_data(context
,
742 sd
->certificates
->val
[i
].data
,
743 sd
->certificates
->val
[i
].length
,
746 ret
= heim_error_get_code(error
);
750 ret
= hx509_certs_add(context
, certs
, c
);
759 static const Attribute
*
760 find_attribute(const CMSAttributes
*attr
, const heim_oid
*oid
)
763 for (i
= 0; i
< attr
->len
; i
++)
764 if (der_heim_oid_cmp(&attr
->val
[i
].type
, oid
) == 0)
765 return &attr
->val
[i
];
770 * Decode SignedData and verify that the signature is correct.
772 * @param context A hx509 context.
773 * @param ctx a hx509 verify context.
774 * @param flags to control the behaivor of the function.
775 * - HX509_CMS_VS_NO_KU_CHECK - Don't check KeyUsage
776 * - HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH - allow oid mismatch
777 * - HX509_CMS_VS_ALLOW_ZERO_SIGNER - no signer, see below.
778 * @param data pointer to CMS SignedData encoded data.
779 * @param length length of the data that data point to.
780 * @param signedContent external data used for signature.
781 * @param pool certificate pool to build certificates paths.
782 * @param contentType free with der_free_oid().
783 * @param content the output of the function, free with
784 * der_free_octet_string().
785 * @param signer_certs list of the cerficates used to sign this
786 * request, free with hx509_certs_free().
788 * @return an hx509 error code.
793 HX509_LIB_FUNCTION
int HX509_LIB_CALL
794 hx509_cms_verify_signed(hx509_context context
,
795 hx509_verify_ctx ctx
,
799 const heim_octet_string
*signedContent
,
801 heim_oid
*contentType
,
802 heim_octet_string
*content
,
803 hx509_certs
*signer_certs
)
805 unsigned int verify_flags
;
807 return hx509_cms_verify_signed_ext(context
,
821 * Decode SignedData and verify that the signature is correct.
823 * @param context A hx509 context.
824 * @param ctx a hx509 verify context.
825 * @param flags to control the behaivor of the function.
826 * - HX509_CMS_VS_NO_KU_CHECK - Don't check KeyUsage
827 * - HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH - allow oid mismatch
828 * - HX509_CMS_VS_ALLOW_ZERO_SIGNER - no signer, see below.
829 * @param data pointer to CMS SignedData encoded data.
830 * @param length length of the data that data point to.
831 * @param signedContent external data used for signature.
832 * @param pool certificate pool to build certificates paths.
833 * @param contentType free with der_free_oid().
834 * @param content the output of the function, free with
835 * der_free_octet_string().
836 * @param signer_certs list of the cerficates used to sign this
837 * request, free with hx509_certs_free().
838 * @param verify_flags flags indicating whether the certificate
839 * was verified or not
841 * @return an hx509 error code.
846 HX509_LIB_FUNCTION
int HX509_LIB_CALL
847 hx509_cms_verify_signed_ext(hx509_context context
,
848 hx509_verify_ctx ctx
,
852 const heim_octet_string
*signedContent
,
854 heim_oid
*contentType
,
855 heim_octet_string
*content
,
856 hx509_certs
*signer_certs
,
857 unsigned int *verify_flags
)
859 SignerInfo
*signer_info
;
860 hx509_cert cert
= NULL
;
861 hx509_certs certs
= NULL
;
864 int ret
, found_valid_sig
;
867 *signer_certs
= NULL
;
870 content
->data
= NULL
;
872 contentType
->length
= 0;
873 contentType
->components
= NULL
;
875 memset(&sd
, 0, sizeof(sd
));
877 ret
= decode_SignedData(data
, length
, &sd
, &size
);
879 hx509_set_error_string(context
, 0, ret
,
880 "Failed to decode SignedData");
884 if (sd
.encapContentInfo
.eContent
== NULL
&& signedContent
== NULL
) {
885 ret
= HX509_CMS_NO_DATA_AVAILABLE
;
886 hx509_set_error_string(context
, 0, ret
,
887 "No content data in SignedData");
890 if (sd
.encapContentInfo
.eContent
&& signedContent
) {
891 ret
= HX509_CMS_NO_DATA_AVAILABLE
;
892 hx509_set_error_string(context
, 0, ret
,
893 "Both external and internal SignedData");
897 if (sd
.encapContentInfo
.eContent
)
898 ret
= der_copy_octet_string(sd
.encapContentInfo
.eContent
, content
);
900 ret
= der_copy_octet_string(signedContent
, content
);
902 hx509_set_error_string(context
, 0, ret
, "malloc: out of memory");
906 ret
= hx509_certs_init(context
, "MEMORY:cms-cert-buffer",
911 ret
= hx509_certs_init(context
, "MEMORY:cms-signer-certs",
912 0, NULL
, signer_certs
);
916 /* XXX Check CMS version */
918 ret
= any_to_certs(context
, &sd
, certs
);
923 ret
= hx509_certs_merge(context
, certs
, pool
);
928 for (found_valid_sig
= 0, i
= 0; i
< sd
.signerInfos
.len
; i
++) {
929 heim_octet_string signed_data
= { 0, 0 };
930 const heim_oid
*match_oid
;
933 signer_info
= &sd
.signerInfos
.val
[i
];
936 if (signer_info
->signature
.length
== 0) {
937 ret
= HX509_CMS_MISSING_SIGNER_DATA
;
938 hx509_set_error_string(context
, 0, ret
,
939 "SignerInfo %d in SignedData "
940 "missing sigature", i
);
944 ret
= find_CMSIdentifier(context
, &signer_info
->sid
, certs
,
945 _hx509_verify_get_time(ctx
), &cert
,
946 HX509_QUERY_KU_DIGITALSIGNATURE
);
949 * If HX509_CMS_VS_NO_KU_CHECK is set, allow more liberal
950 * search for matching certificates by not considering
951 * KeyUsage bits on the certificates.
953 if ((flags
& HX509_CMS_VS_NO_KU_CHECK
) == 0)
956 ret
= find_CMSIdentifier(context
, &signer_info
->sid
, certs
,
957 _hx509_verify_get_time(ctx
), &cert
,
964 if (signer_info
->signedAttrs
) {
965 const Attribute
*attr
;
968 heim_octet_string os
;
970 sa
.val
= signer_info
->signedAttrs
->val
;
971 sa
.len
= signer_info
->signedAttrs
->len
;
973 /* verify that sigature exists */
974 attr
= find_attribute(&sa
, &asn1_oid_id_pkcs9_messageDigest
);
976 ret
= HX509_CRYPTO_SIGNATURE_MISSING
;
977 hx509_set_error_string(context
, 0, ret
,
978 "SignerInfo have signed attributes "
979 "but messageDigest (signature) "
983 if (attr
->value
.len
!= 1) {
984 ret
= HX509_CRYPTO_SIGNATURE_MISSING
;
985 hx509_set_error_string(context
, 0, ret
,
986 "SignerInfo have more then one "
987 "messageDigest (signature)");
991 ret
= decode_MessageDigest(attr
->value
.val
[0].data
,
992 attr
->value
.val
[0].length
,
996 hx509_set_error_string(context
, 0, ret
,
998 "messageDigest (signature)");
1002 ret
= _hx509_verify_signature(context
,
1004 &signer_info
->digestAlgorithm
,
1007 der_free_octet_string(&os
);
1009 hx509_set_error_string(context
, HX509_ERROR_APPEND
, ret
,
1010 "Failed to verify messageDigest");
1015 * Fetch content oid inside signedAttrs or set it to
1018 attr
= find_attribute(&sa
, &asn1_oid_id_pkcs9_contentType
);
1020 match_oid
= &asn1_oid_id_pkcs7_data
;
1022 if (attr
->value
.len
!= 1) {
1023 ret
= HX509_CMS_DATA_OID_MISMATCH
;
1024 hx509_set_error_string(context
, 0, ret
,
1025 "More then one oid in signedAttrs");
1029 ret
= decode_ContentType(attr
->value
.val
[0].data
,
1030 attr
->value
.val
[0].length
,
1034 hx509_set_error_string(context
, 0, ret
,
1036 "oid in signedAttrs");
1039 match_oid
= &decode_oid
;
1042 ASN1_MALLOC_ENCODE(CMSAttributes
,
1048 if (match_oid
== &decode_oid
)
1049 der_free_oid(&decode_oid
);
1050 hx509_clear_error_string(context
);
1053 if (size
!= signed_data
.length
)
1054 _hx509_abort("internal ASN.1 encoder error");
1057 signed_data
.data
= content
->data
;
1058 signed_data
.length
= content
->length
;
1059 match_oid
= &asn1_oid_id_pkcs7_data
;
1063 * If HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH, allow
1064 * encapContentInfo mismatch with the oid in signedAttributes
1065 * (or if no signedAttributes where use, pkcs7-data oid).
1066 * This is only needed to work with broken CMS implementations
1067 * that doesn't follow CMS signedAttributes rules.
1070 if (der_heim_oid_cmp(match_oid
, &sd
.encapContentInfo
.eContentType
) &&
1071 (flags
& HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH
) == 0) {
1072 ret
= HX509_CMS_DATA_OID_MISMATCH
;
1073 hx509_set_error_string(context
, 0, ret
,
1074 "Oid in message mismatch from the expected");
1076 if (match_oid
== &decode_oid
)
1077 der_free_oid(&decode_oid
);
1080 ret
= hx509_verify_signature(context
,
1082 &signer_info
->signatureAlgorithm
,
1084 &signer_info
->signature
);
1086 hx509_set_error_string(context
, HX509_ERROR_APPEND
, ret
,
1087 "Failed to verify signature in "
1090 if (signed_data
.data
!= NULL
&& content
->data
!= signed_data
.data
) {
1091 free(signed_data
.data
);
1092 signed_data
.data
= NULL
;
1098 * If HX509_CMS_VS_NO_VALIDATE flags is set, return the signer
1099 * certificate unconditionally but do not set HX509_CMS_VSE_VALIDATED.
1101 ret
= hx509_verify_path(context
, ctx
, cert
, certs
);
1102 if (ret
== 0 || (flags
& HX509_CMS_VS_NO_VALIDATE
)) {
1104 *verify_flags
|= HX509_CMS_VSE_VALIDATED
;
1106 ret
= hx509_certs_add(context
, *signer_certs
, cert
);
1113 hx509_cert_free(cert
);
1117 * If HX509_CMS_VS_ALLOW_ZERO_SIGNER is set, allow empty
1118 * SignerInfo (no signatures). If SignedData have no signatures,
1119 * the function will return 0 with signer_certs set to NULL. Zero
1120 * signers is allowed by the standard, but since its only useful
1121 * in corner cases, it make into a flag that the caller have to
1124 if (sd
.signerInfos
.len
== 0 && (flags
& HX509_CMS_VS_ALLOW_ZERO_SIGNER
)) {
1126 hx509_certs_free(signer_certs
);
1127 } else if (found_valid_sig
== 0) {
1129 ret
= HX509_CMS_SIGNER_NOT_FOUND
;
1130 hx509_set_error_string(context
, 0, ret
,
1131 "No signers where found");
1136 ret
= der_copy_oid(&sd
.encapContentInfo
.eContentType
, contentType
);
1138 hx509_clear_error_string(context
);
1143 free_SignedData(&sd
);
1145 hx509_certs_free(&certs
);
1148 der_free_octet_string(content
);
1150 hx509_certs_free(signer_certs
);
1151 der_free_oid(contentType
);
1152 der_free_octet_string(content
);
1159 add_one_attribute(Attribute
**attr
,
1161 const heim_oid
*oid
,
1162 heim_octet_string
*data
)
1167 d
= realloc(*attr
, sizeof((*attr
)[0]) * (*len
+ 1));
1172 ret
= der_copy_oid(oid
, &(*attr
)[*len
].type
);
1176 ALLOC_SEQ(&(*attr
)[*len
].value
, 1);
1177 if ((*attr
)[*len
].value
.val
== NULL
) {
1178 der_free_oid(&(*attr
)[*len
].type
);
1182 (*attr
)[*len
].value
.val
[0].data
= data
->data
;
1183 (*attr
)[*len
].value
.val
[0].length
= data
->length
;
1191 * Decode SignedData and verify that the signature is correct.
1193 * @param context A hx509 context.
1195 * @param eContentType the type of the data.
1196 * @param data data to sign
1197 * @param length length of the data that data point to.
1198 * @param digest_alg digest algorithm to use, use NULL to get the
1199 * default or the peer determined algorithm.
1200 * @param cert certificate to use for sign the data.
1201 * @param peer info about the peer the message to send the message to,
1202 * like what digest algorithm to use.
1203 * @param anchors trust anchors that the client will use, used to
1204 * polulate the certificates included in the message
1205 * @param pool certificates to use in try to build the path to the
1207 * @param signed_data the output of the function, free with
1208 * der_free_octet_string().
1210 * @return Returns an hx509 error code.
1212 * @ingroup hx509_cms
1215 HX509_LIB_FUNCTION
int HX509_LIB_CALL
1216 hx509_cms_create_signed_1(hx509_context context
,
1218 const heim_oid
*eContentType
,
1219 const void *data
, size_t length
,
1220 const AlgorithmIdentifier
*digest_alg
,
1222 hx509_peer_info peer
,
1223 hx509_certs anchors
,
1225 heim_octet_string
*signed_data
)
1230 signed_data
->data
= NULL
;
1231 signed_data
->length
= 0;
1233 ret
= hx509_certs_init(context
, "MEMORY:certs", 0, NULL
, &certs
);
1236 ret
= hx509_certs_add(context
, certs
, cert
);
1240 ret
= hx509_cms_create_signed(context
, flags
, eContentType
, data
, length
,
1241 digest_alg
, certs
, peer
, anchors
, pool
,
1245 hx509_certs_free(&certs
);
1251 const AlgorithmIdentifier
*digest_alg
;
1252 const heim_oid
*eContentType
;
1253 heim_octet_string content
;
1254 hx509_peer_info peer
;
1258 hx509_certs anchors
;
1262 static int HX509_LIB_CALL
1263 sig_process(hx509_context context
, void *ctx
, hx509_cert cert
)
1265 struct sigctx
*sigctx
= ctx
;
1266 heim_octet_string buf
, sigdata
= { 0, NULL
};
1267 SignerInfo
*signer_info
= NULL
;
1268 AlgorithmIdentifier digest
;
1272 SignedData
*sd
= &sigctx
->sd
;
1275 memset(&digest
, 0, sizeof(digest
));
1276 memset(&path
, 0, sizeof(path
));
1278 if (_hx509_cert_private_key(cert
) == NULL
) {
1279 hx509_set_error_string(context
, 0, HX509_PRIVATE_KEY_MISSING
,
1280 "Private key missing for signing");
1281 return HX509_PRIVATE_KEY_MISSING
;
1284 if (sigctx
->digest_alg
) {
1285 ret
= copy_AlgorithmIdentifier(sigctx
->digest_alg
, &digest
);
1287 hx509_clear_error_string(context
);
1289 ret
= hx509_crypto_select(context
, HX509_SELECT_DIGEST
,
1290 _hx509_cert_private_key(cert
),
1291 sigctx
->peer
, &digest
);
1297 * Allocate on more signerInfo and do the signature processing
1300 ptr
= realloc(sd
->signerInfos
.val
,
1301 (sd
->signerInfos
.len
+ 1) * sizeof(sd
->signerInfos
.val
[0]));
1306 sd
->signerInfos
.val
= ptr
;
1308 signer_info
= &sd
->signerInfos
.val
[sd
->signerInfos
.len
];
1310 memset(signer_info
, 0, sizeof(*signer_info
));
1312 signer_info
->version
= 1;
1314 ret
= fill_CMSIdentifier(cert
, sigctx
->cmsidflag
, &signer_info
->sid
);
1316 hx509_clear_error_string(context
);
1320 signer_info
->signedAttrs
= NULL
;
1321 signer_info
->unsignedAttrs
= NULL
;
1323 ret
= copy_AlgorithmIdentifier(&digest
, &signer_info
->digestAlgorithm
);
1325 hx509_clear_error_string(context
);
1330 * If it isn't pkcs7-data send signedAttributes
1333 if (der_heim_oid_cmp(sigctx
->eContentType
, &asn1_oid_id_pkcs7_data
) != 0) {
1335 heim_octet_string sig
;
1337 ALLOC(signer_info
->signedAttrs
, 1);
1338 if (signer_info
->signedAttrs
== NULL
) {
1343 ret
= _hx509_create_signature(context
,
1352 ASN1_MALLOC_ENCODE(MessageDigest
,
1358 der_free_octet_string(&sig
);
1360 hx509_clear_error_string(context
);
1363 if (size
!= buf
.length
)
1364 _hx509_abort("internal ASN.1 encoder error");
1366 ret
= add_one_attribute(&signer_info
->signedAttrs
->val
,
1367 &signer_info
->signedAttrs
->len
,
1368 &asn1_oid_id_pkcs9_messageDigest
,
1372 hx509_clear_error_string(context
);
1377 ASN1_MALLOC_ENCODE(ContentType
,
1380 sigctx
->eContentType
,
1385 if (size
!= buf
.length
)
1386 _hx509_abort("internal ASN.1 encoder error");
1388 ret
= add_one_attribute(&signer_info
->signedAttrs
->val
,
1389 &signer_info
->signedAttrs
->len
,
1390 &asn1_oid_id_pkcs9_contentType
,
1394 hx509_clear_error_string(context
);
1398 sa
.val
= signer_info
->signedAttrs
->val
;
1399 sa
.len
= signer_info
->signedAttrs
->len
;
1401 ASN1_MALLOC_ENCODE(CMSAttributes
,
1408 hx509_clear_error_string(context
);
1411 if (size
!= sigdata
.length
)
1412 _hx509_abort("internal ASN.1 encoder error");
1414 sigdata
.data
= sigctx
->content
.data
;
1415 sigdata
.length
= sigctx
->content
.length
;
1419 AlgorithmIdentifier sigalg
;
1421 ret
= hx509_crypto_select(context
, HX509_SELECT_PUBLIC_SIG
,
1422 _hx509_cert_private_key(cert
), sigctx
->peer
,
1427 ret
= _hx509_create_signature(context
,
1428 _hx509_cert_private_key(cert
),
1431 &signer_info
->signatureAlgorithm
,
1432 &signer_info
->signature
);
1433 free_AlgorithmIdentifier(&sigalg
);
1438 sigctx
->sd
.signerInfos
.len
++;
1442 * Provide best effort path
1444 if (sigctx
->certs
) {
1447 if (sigctx
->pool
&& sigctx
->leafonly
== 0) {
1448 _hx509_calculate_path(context
,
1449 HX509_CALCULATE_PATH_NO_ANCHOR
,
1457 _hx509_path_append(context
, &path
, cert
);
1459 for (i
= 0; i
< path
.len
; i
++) {
1460 /* XXX remove dups */
1461 ret
= hx509_certs_add(context
, sigctx
->certs
, path
.val
[i
]);
1463 hx509_clear_error_string(context
);
1471 free_SignerInfo(signer_info
);
1472 if (sigdata
.data
!= sigctx
->content
.data
)
1473 der_free_octet_string(&sigdata
);
1474 _hx509_path_free(&path
);
1475 free_AlgorithmIdentifier(&digest
);
1480 static int HX509_LIB_CALL
1481 cert_process(hx509_context context
, void *ctx
, hx509_cert cert
)
1483 struct sigctx
*sigctx
= ctx
;
1484 const unsigned int i
= sigctx
->sd
.certificates
->len
;
1488 ptr
= realloc(sigctx
->sd
.certificates
->val
,
1489 (i
+ 1) * sizeof(sigctx
->sd
.certificates
->val
[0]));
1492 sigctx
->sd
.certificates
->val
= ptr
;
1494 ret
= hx509_cert_binary(context
, cert
,
1495 &sigctx
->sd
.certificates
->val
[i
]);
1497 sigctx
->sd
.certificates
->len
++;
1503 cmp_AlgorithmIdentifier(const AlgorithmIdentifier
*p
, const AlgorithmIdentifier
*q
)
1505 return der_heim_oid_cmp(&p
->algorithm
, &q
->algorithm
);
1508 HX509_LIB_FUNCTION
int HX509_LIB_CALL
1509 hx509_cms_create_signed(hx509_context context
,
1511 const heim_oid
*eContentType
,
1512 const void *data
, size_t length
,
1513 const AlgorithmIdentifier
*digest_alg
,
1515 hx509_peer_info peer
,
1516 hx509_certs anchors
,
1518 heim_octet_string
*signed_data
)
1524 struct sigctx sigctx
;
1526 memset(&sigctx
, 0, sizeof(sigctx
));
1527 memset(&name
, 0, sizeof(name
));
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 der_copy_oid(eContentType
, &sigctx
.sd
.encapContentInfo
.eContentType
);
1572 * Use HX509_CMS_SIGNATURE_DETACHED to create detached signatures.
1574 if ((flags
& HX509_CMS_SIGNATURE_DETACHED
) == 0) {
1575 ALLOC(sigctx
.sd
.encapContentInfo
.eContent
, 1);
1576 if (sigctx
.sd
.encapContentInfo
.eContent
== NULL
) {
1577 hx509_clear_error_string(context
);
1582 sigctx
.sd
.encapContentInfo
.eContent
->data
= malloc(length
);
1583 if (sigctx
.sd
.encapContentInfo
.eContent
->data
== NULL
) {
1584 hx509_clear_error_string(context
);
1588 memcpy(sigctx
.sd
.encapContentInfo
.eContent
->data
, data
, length
);
1589 sigctx
.sd
.encapContentInfo
.eContent
->length
= length
;
1593 * Use HX509_CMS_SIGNATURE_NO_SIGNER to create no sigInfo (no
1596 if ((flags
& HX509_CMS_SIGNATURE_NO_SIGNER
) == 0) {
1597 ret
= hx509_certs_iter_f(context
, certs
, sig_process
, &sigctx
);
1602 if (sigctx
.sd
.signerInfos
.len
) {
1605 * For each signerInfo, collect all different digest types.
1607 for (i
= 0; i
< sigctx
.sd
.signerInfos
.len
; i
++) {
1608 AlgorithmIdentifier
*di
=
1609 &sigctx
.sd
.signerInfos
.val
[i
].digestAlgorithm
;
1611 for (j
= 0; j
< sigctx
.sd
.digestAlgorithms
.len
; j
++)
1612 if (cmp_AlgorithmIdentifier(di
, &sigctx
.sd
.digestAlgorithms
.val
[j
]) == 0)
1614 if (j
== sigctx
.sd
.digestAlgorithms
.len
) {
1615 ret
= add_DigestAlgorithmIdentifiers(&sigctx
.sd
.digestAlgorithms
, di
);
1617 hx509_clear_error_string(context
);
1625 * Add certs we think are needed, build as part of sig_process
1628 ALLOC(sigctx
.sd
.certificates
, 1);
1629 if (sigctx
.sd
.certificates
== NULL
) {
1630 hx509_clear_error_string(context
);
1635 ret
= hx509_certs_iter_f(context
, sigctx
.certs
, cert_process
, &sigctx
);
1640 ASN1_MALLOC_ENCODE(SignedData
,
1641 signed_data
->data
, signed_data
->length
,
1642 &sigctx
.sd
, &size
, ret
);
1644 hx509_clear_error_string(context
);
1647 if (signed_data
->length
!= size
)
1648 _hx509_abort("internal ASN.1 encoder error");
1651 hx509_certs_free(&sigctx
.certs
);
1652 free_SignedData(&sigctx
.sd
);
1657 HX509_LIB_FUNCTION
int HX509_LIB_CALL
1658 hx509_cms_decrypt_encrypted(hx509_context context
,
1662 heim_oid
*contentType
,
1663 heim_octet_string
*content
)
1665 heim_octet_string cont
;
1666 CMSEncryptedData ed
;
1667 AlgorithmIdentifier
*ai
;
1670 memset(content
, 0, sizeof(*content
));
1671 memset(&cont
, 0, sizeof(cont
));
1673 ret
= decode_CMSEncryptedData(data
, length
, &ed
, NULL
);
1675 hx509_set_error_string(context
, 0, ret
,
1676 "Failed to decode CMSEncryptedData");
1680 if (ed
.encryptedContentInfo
.encryptedContent
== NULL
) {
1681 ret
= HX509_CMS_NO_DATA_AVAILABLE
;
1682 hx509_set_error_string(context
, 0, ret
,
1683 "No content in EncryptedData");
1687 ret
= der_copy_oid(&ed
.encryptedContentInfo
.contentType
, contentType
);
1689 hx509_clear_error_string(context
);
1693 ai
= &ed
.encryptedContentInfo
.contentEncryptionAlgorithm
;
1694 if (ai
->parameters
== NULL
) {
1695 ret
= HX509_ALG_NOT_SUPP
;
1696 hx509_clear_error_string(context
);
1700 ret
= _hx509_pbe_decrypt(context
,
1703 ed
.encryptedContentInfo
.encryptedContent
,
1715 free_CMSEncryptedData(&ed
);