1 /* $NetBSD: cms.c,v 1.1.1.2 2014/04/24 12:45:41 pettai Exp $ */
4 * Copyright (c) 2003 - 2007 Kungliga Tekniska Högskolan
5 * (Royal Institute of Technology, Stockholm, Sweden).
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
19 * 3. Neither the name of the Institute nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39 * @page page_cms CMS/PKCS7 message functions.
41 * CMS is defined in RFC 3369 and is an continuation of the RSA Labs
42 * standard PKCS7. The basic messages in CMS is
45 * Data signed with private key (RSA, DSA, ECDSA) or secret
48 * Data encrypted with private key (RSA)
50 * Data encrypted with secret (symmetric) key.
52 * Wrapper structure including type and data.
55 * See the library functions here: @ref hx509_cms
58 #define ALLOC(X, N) (X) = calloc((N), sizeof(*(X)))
59 #define ALLOC_SEQ(X, N) do { (X)->len = (N); ALLOC((X)->val, (N)); } while(0)
62 * Wrap data and oid in a ContentInfo and encode it.
64 * @param oid type of the content.
65 * @param buf data to be wrapped. If a NULL pointer is passed in, the
66 * optional content field in the ContentInfo is not going be filled
68 * @param res the encoded buffer, the result should be freed with
69 * der_free_octet_string().
71 * @return Returns an hx509 error code.
77 hx509_cms_wrap_ContentInfo(const heim_oid
*oid
,
78 const heim_octet_string
*buf
,
79 heim_octet_string
*res
)
85 memset(res
, 0, sizeof(*res
));
86 memset(&ci
, 0, sizeof(ci
));
88 ret
= der_copy_oid(oid
, &ci
.contentType
);
93 if (ci
.content
== NULL
) {
94 free_ContentInfo(&ci
);
97 ci
.content
->data
= malloc(buf
->length
);
98 if (ci
.content
->data
== NULL
) {
99 free_ContentInfo(&ci
);
102 memcpy(ci
.content
->data
, buf
->data
, buf
->length
);
103 ci
.content
->length
= buf
->length
;
106 ASN1_MALLOC_ENCODE(ContentInfo
, res
->data
, res
->length
, &ci
, &size
, ret
);
107 free_ContentInfo(&ci
);
110 if (res
->length
!= size
)
111 _hx509_abort("internal ASN.1 encoder error");
117 * Decode an ContentInfo and unwrap data and oid it.
119 * @param in the encoded buffer.
120 * @param oid type of the content.
121 * @param out data to be wrapped.
122 * @param have_data since the data is optional, this flags show dthe
123 * diffrence between no data and the zero length data.
125 * @return Returns an hx509 error code.
131 hx509_cms_unwrap_ContentInfo(const heim_octet_string
*in
,
133 heim_octet_string
*out
,
140 memset(oid
, 0, sizeof(*oid
));
141 memset(out
, 0, sizeof(*out
));
143 ret
= decode_ContentInfo(in
->data
, in
->length
, &ci
, &size
);
147 ret
= der_copy_oid(&ci
.contentType
, oid
);
149 free_ContentInfo(&ci
);
153 ret
= der_copy_octet_string(ci
.content
, out
);
156 free_ContentInfo(&ci
);
160 memset(out
, 0, sizeof(*out
));
163 *have_data
= (ci
.content
!= NULL
) ? 1 : 0;
165 free_ContentInfo(&ci
);
171 #define CMS_ID_NAME 1
174 fill_CMSIdentifier(const hx509_cert cert
,
182 id
->element
= choice_CMSIdentifier_subjectKeyIdentifier
;
183 ret
= _hx509_find_extension_subject_key_id(_hx509_get_cert(cert
),
184 &id
->u
.subjectKeyIdentifier
);
191 id
->element
= choice_CMSIdentifier_issuerAndSerialNumber
;
192 ret
= hx509_cert_get_issuer(cert
, &name
);
195 ret
= hx509_name_to_Name(name
, &id
->u
.issuerAndSerialNumber
.issuer
);
196 hx509_name_free(&name
);
200 ret
= hx509_cert_get_serialnumber(cert
, &id
->u
.issuerAndSerialNumber
.serialNumber
);
204 _hx509_abort("CMS fill identifier with unknown type");
210 unparse_CMSIdentifier(hx509_context context
,
217 switch (id
->element
) {
218 case choice_CMSIdentifier_issuerAndSerialNumber
: {
219 IssuerAndSerialNumber
*iasn
;
222 iasn
= &id
->u
.issuerAndSerialNumber
;
224 ret
= _hx509_Name_to_string(&iasn
->issuer
, &name
);
227 ret
= der_print_hex_heim_integer(&iasn
->serialNumber
, &serial
);
232 asprintf(str
, "certificate issued by %s with serial number %s",
238 case choice_CMSIdentifier_subjectKeyIdentifier
: {
239 KeyIdentifier
*ki
= &id
->u
.subjectKeyIdentifier
;
243 len
= hex_encode(ki
->data
, ki
->length
, &keyid
);
247 asprintf(str
, "certificate with id %s", keyid
);
252 asprintf(str
, "certificate have unknown CMSidentifier type");
261 find_CMSIdentifier(hx509_context context
,
262 CMSIdentifier
*client
,
265 hx509_cert
*signer_cert
,
273 memset(&c
, 0, sizeof(c
));
274 _hx509_query_clear(&q
);
278 switch (client
->element
) {
279 case choice_CMSIdentifier_issuerAndSerialNumber
:
280 q
.serial
= &client
->u
.issuerAndSerialNumber
.serialNumber
;
281 q
.issuer_name
= &client
->u
.issuerAndSerialNumber
.issuer
;
282 q
.match
= HX509_QUERY_MATCH_SERIALNUMBER
|HX509_QUERY_MATCH_ISSUER_NAME
;
284 case choice_CMSIdentifier_subjectKeyIdentifier
:
285 q
.subject_id
= &client
->u
.subjectKeyIdentifier
;
286 q
.match
= HX509_QUERY_MATCH_SUBJECT_KEY_ID
;
289 hx509_set_error_string(context
, 0, HX509_CMS_NO_RECIPIENT_CERTIFICATE
,
290 "unknown CMS identifier element");
291 return HX509_CMS_NO_RECIPIENT_CERTIFICATE
;
296 q
.match
|= HX509_QUERY_MATCH_TIME
;
298 q
.timenow
= time_now
;
300 q
.timenow
= time(NULL
);
302 ret
= hx509_certs_find(context
, certs
, &q
, &cert
);
303 if (ret
== HX509_CERT_NOT_FOUND
) {
306 ret
= unparse_CMSIdentifier(context
, client
, &str
);
308 hx509_set_error_string(context
, 0,
309 HX509_CMS_NO_RECIPIENT_CERTIFICATE
,
310 "Failed to find %s", str
);
312 hx509_clear_error_string(context
);
313 return HX509_CMS_NO_RECIPIENT_CERTIFICATE
;
315 hx509_set_error_string(context
, HX509_ERROR_APPEND
,
316 HX509_CMS_NO_RECIPIENT_CERTIFICATE
,
317 "Failed to find CMS id in cert store");
318 return HX509_CMS_NO_RECIPIENT_CERTIFICATE
;
327 * Decode and unencrypt EnvelopedData.
329 * Extract data and parameteres from from the EnvelopedData. Also
330 * supports using detached EnvelopedData.
332 * @param context A hx509 context.
333 * @param certs Certificate that can decrypt the EnvelopedData
335 * @param flags HX509_CMS_UE flags to control the behavior.
336 * @param data pointer the structure the contains the DER/BER encoded
337 * EnvelopedData stucture.
338 * @param length length of the data that data point to.
339 * @param encryptedContent in case of detached signature, this
340 * contains the actual encrypted data, othersize its should be NULL.
341 * @param time_now set the current time, if zero the library uses now as the date.
342 * @param contentType output type oid, should be freed with der_free_oid().
343 * @param content the data, free with der_free_octet_string().
349 hx509_cms_unenvelope(hx509_context context
,
354 const heim_octet_string
*encryptedContent
,
356 heim_oid
*contentType
,
357 heim_octet_string
*content
)
359 heim_octet_string key
;
362 AlgorithmIdentifier
*ai
;
363 const heim_octet_string
*enccontent
;
364 heim_octet_string
*params
, params_data
;
365 heim_octet_string ivec
;
367 int ret
, matched
= 0, findflags
= 0;
371 memset(&key
, 0, sizeof(key
));
372 memset(&ed
, 0, sizeof(ed
));
373 memset(&ivec
, 0, sizeof(ivec
));
374 memset(content
, 0, sizeof(*content
));
375 memset(contentType
, 0, sizeof(*contentType
));
377 if ((flags
& HX509_CMS_UE_DONT_REQUIRE_KU_ENCIPHERMENT
) == 0)
378 findflags
|= HX509_QUERY_KU_ENCIPHERMENT
;
380 ret
= decode_EnvelopedData(data
, length
, &ed
, &size
);
382 hx509_set_error_string(context
, 0, ret
,
383 "Failed to decode EnvelopedData");
387 if (ed
.recipientInfos
.len
== 0) {
388 ret
= HX509_CMS_NO_RECIPIENT_CERTIFICATE
;
389 hx509_set_error_string(context
, 0, ret
,
390 "No recipient info in enveloped data");
394 enccontent
= ed
.encryptedContentInfo
.encryptedContent
;
395 if (enccontent
== NULL
) {
396 if (encryptedContent
== NULL
) {
397 ret
= HX509_CMS_NO_DATA_AVAILABLE
;
398 hx509_set_error_string(context
, 0, ret
,
399 "Content missing from encrypted data");
402 enccontent
= encryptedContent
;
403 } else if (encryptedContent
!= NULL
) {
404 ret
= HX509_CMS_NO_DATA_AVAILABLE
;
405 hx509_set_error_string(context
, 0, ret
,
406 "Both internal and external encrypted data");
411 for (i
= 0; i
< ed
.recipientInfos
.len
; i
++) {
412 KeyTransRecipientInfo
*ri
;
416 ri
= &ed
.recipientInfos
.val
[i
];
418 ret
= find_CMSIdentifier(context
, &ri
->rid
, certs
,
420 HX509_QUERY_PRIVATE_KEY
|findflags
);
424 matched
= 1; /* found a matching certificate, let decrypt */
426 ret
= _hx509_cert_private_decrypt(context
,
428 &ri
->keyEncryptionAlgorithm
.algorithm
,
431 hx509_cert_free(cert
);
433 break; /* succuessfully decrypted cert */
435 ret2
= unparse_CMSIdentifier(context
, &ri
->rid
, &str
);
437 hx509_set_error_string(context
, HX509_ERROR_APPEND
, ret
,
438 "Failed to decrypt with %s", str
);
444 ret
= HX509_CMS_NO_RECIPIENT_CERTIFICATE
;
445 hx509_set_error_string(context
, 0, ret
,
446 "No private key matched any certificate");
451 ret
= HX509_CMS_NO_RECIPIENT_CERTIFICATE
;
452 hx509_set_error_string(context
, HX509_ERROR_APPEND
, ret
,
453 "No private key decrypted the transfer key");
457 ret
= der_copy_oid(&ed
.encryptedContentInfo
.contentType
, contentType
);
459 hx509_set_error_string(context
, 0, ret
,
460 "Failed to copy EnvelopedData content oid");
464 ai
= &ed
.encryptedContentInfo
.contentEncryptionAlgorithm
;
465 if (ai
->parameters
) {
466 params_data
.data
= ai
->parameters
->data
;
467 params_data
.length
= ai
->parameters
->length
;
468 params
= ¶ms_data
;
475 ret
= hx509_crypto_init(context
, NULL
, &ai
->algorithm
, &crypto
);
479 if (flags
& HX509_CMS_UE_ALLOW_WEAK
)
480 hx509_crypto_allow_weak(crypto
);
483 ret
= hx509_crypto_set_params(context
, crypto
, params
, &ivec
);
485 hx509_crypto_destroy(crypto
);
490 ret
= hx509_crypto_set_key_data(crypto
, key
.data
, key
.length
);
492 hx509_crypto_destroy(crypto
);
493 hx509_set_error_string(context
, 0, ret
,
494 "Failed to set key for decryption "
499 ret
= hx509_crypto_decrypt(crypto
,
502 ivec
.length
? &ivec
: NULL
,
504 hx509_crypto_destroy(crypto
);
506 hx509_set_error_string(context
, 0, ret
,
507 "Failed to decrypt EnvelopedData");
514 free_EnvelopedData(&ed
);
515 der_free_octet_string(&key
);
517 der_free_octet_string(&ivec
);
519 der_free_oid(contentType
);
520 der_free_octet_string(content
);
527 * Encrypt end encode EnvelopedData.
529 * Encrypt and encode EnvelopedData. The data is encrypted with a
530 * random key and the the random key is encrypted with the
531 * certificates private key. This limits what private key type can be
534 * @param context A hx509 context.
535 * @param flags flags to control the behavior.
536 * - HX509_CMS_EV_NO_KU_CHECK - Dont check KU on certificate
537 * - HX509_CMS_EV_ALLOW_WEAK - Allow weak crytpo
538 * - HX509_CMS_EV_ID_NAME - prefer issuer name and serial number
539 * @param cert Certificate to encrypt the EnvelopedData encryption key
541 * @param data pointer the data to encrypt.
542 * @param length length of the data that data point to.
543 * @param encryption_type Encryption cipher to use for the bulk data,
544 * use NULL to get default.
545 * @param contentType type of the data that is encrypted
546 * @param content the output of the function,
547 * free with der_free_octet_string().
553 hx509_cms_envelope_1(hx509_context context
,
558 const heim_oid
*encryption_type
,
559 const heim_oid
*contentType
,
560 heim_octet_string
*content
)
562 KeyTransRecipientInfo
*ri
;
563 heim_octet_string ivec
;
564 heim_octet_string key
;
565 hx509_crypto crypto
= NULL
;
570 memset(&ivec
, 0, sizeof(ivec
));
571 memset(&key
, 0, sizeof(key
));
572 memset(&ed
, 0, sizeof(ed
));
573 memset(content
, 0, sizeof(*content
));
575 if (encryption_type
== NULL
)
576 encryption_type
= &asn1_oid_id_aes_256_cbc
;
578 if ((flags
& HX509_CMS_EV_NO_KU_CHECK
) == 0) {
579 ret
= _hx509_check_key_usage(context
, cert
, 1 << 2, TRUE
);
584 ret
= hx509_crypto_init(context
, NULL
, encryption_type
, &crypto
);
588 if (flags
& HX509_CMS_EV_ALLOW_WEAK
)
589 hx509_crypto_allow_weak(crypto
);
591 ret
= hx509_crypto_set_random_key(crypto
, &key
);
593 hx509_set_error_string(context
, 0, ret
,
594 "Create random key for EnvelopedData content");
598 ret
= hx509_crypto_random_iv(crypto
, &ivec
);
600 hx509_set_error_string(context
, 0, ret
,
601 "Failed to create a random iv");
605 ret
= hx509_crypto_encrypt(crypto
,
609 &ed
.encryptedContentInfo
.encryptedContent
);
611 hx509_set_error_string(context
, 0, ret
,
612 "Failed to encrypt EnvelopedData content");
617 AlgorithmIdentifier
*enc_alg
;
618 enc_alg
= &ed
.encryptedContentInfo
.contentEncryptionAlgorithm
;
619 ret
= der_copy_oid(encryption_type
, &enc_alg
->algorithm
);
621 hx509_set_error_string(context
, 0, ret
,
622 "Failed to set crypto oid "
623 "for EnvelopedData");
626 ALLOC(enc_alg
->parameters
, 1);
627 if (enc_alg
->parameters
== NULL
) {
629 hx509_set_error_string(context
, 0, ret
,
630 "Failed to allocate crypto paramaters "
631 "for EnvelopedData");
635 ret
= hx509_crypto_get_params(context
,
638 enc_alg
->parameters
);
644 ALLOC_SEQ(&ed
.recipientInfos
, 1);
645 if (ed
.recipientInfos
.val
== NULL
) {
647 hx509_set_error_string(context
, 0, ret
,
648 "Failed to allocate recipients info "
649 "for EnvelopedData");
653 ri
= &ed
.recipientInfos
.val
[0];
655 if (flags
& HX509_CMS_EV_ID_NAME
) {
657 cmsidflag
= CMS_ID_NAME
;
660 cmsidflag
= CMS_ID_SKI
;
663 ret
= fill_CMSIdentifier(cert
, cmsidflag
, &ri
->rid
);
665 hx509_set_error_string(context
, 0, ret
,
666 "Failed to set CMS identifier info "
667 "for EnvelopedData");
671 ret
= hx509_cert_public_encrypt(context
,
673 &ri
->keyEncryptionAlgorithm
.algorithm
,
676 hx509_set_error_string(context
, HX509_ERROR_APPEND
, ret
,
677 "Failed to encrypt transport key for "
687 ed
.originatorInfo
= NULL
;
689 ret
= der_copy_oid(contentType
, &ed
.encryptedContentInfo
.contentType
);
691 hx509_set_error_string(context
, 0, ret
,
692 "Failed to copy content oid for "
697 ed
.unprotectedAttrs
= NULL
;
699 ASN1_MALLOC_ENCODE(EnvelopedData
, content
->data
, content
->length
,
702 hx509_set_error_string(context
, 0, ret
,
703 "Failed to encode EnvelopedData");
706 if (size
!= content
->length
)
707 _hx509_abort("internal ASN.1 encoder error");
711 hx509_crypto_destroy(crypto
);
713 der_free_octet_string(content
);
714 der_free_octet_string(&key
);
715 der_free_octet_string(&ivec
);
716 free_EnvelopedData(&ed
);
722 any_to_certs(hx509_context context
, const SignedData
*sd
, hx509_certs certs
)
727 if (sd
->certificates
== NULL
)
730 for (i
= 0; i
< sd
->certificates
->len
; i
++) {
733 ret
= hx509_cert_init_data(context
,
734 sd
->certificates
->val
[i
].data
,
735 sd
->certificates
->val
[i
].length
,
739 ret
= hx509_certs_add(context
, certs
, c
);
748 static const Attribute
*
749 find_attribute(const CMSAttributes
*attr
, const heim_oid
*oid
)
752 for (i
= 0; i
< attr
->len
; i
++)
753 if (der_heim_oid_cmp(&attr
->val
[i
].type
, oid
) == 0)
754 return &attr
->val
[i
];
759 * Decode SignedData and verify that the signature is correct.
761 * @param context A hx509 context.
762 * @param ctx a hx509 verify context.
763 * @param flags to control the behaivor of the function.
764 * - HX509_CMS_VS_NO_KU_CHECK - Don't check KeyUsage
765 * - HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH - allow oid mismatch
766 * - HX509_CMS_VS_ALLOW_ZERO_SIGNER - no signer, see below.
767 * @param data pointer to CMS SignedData encoded data.
768 * @param length length of the data that data point to.
769 * @param signedContent external data used for signature.
770 * @param pool certificate pool to build certificates paths.
771 * @param contentType free with der_free_oid().
772 * @param content the output of the function, free with
773 * der_free_octet_string().
774 * @param signer_certs list of the cerficates used to sign this
775 * request, free with hx509_certs_free().
781 hx509_cms_verify_signed(hx509_context context
,
782 hx509_verify_ctx ctx
,
786 const heim_octet_string
*signedContent
,
788 heim_oid
*contentType
,
789 heim_octet_string
*content
,
790 hx509_certs
*signer_certs
)
792 SignerInfo
*signer_info
;
793 hx509_cert cert
= NULL
;
794 hx509_certs certs
= NULL
;
797 int ret
, found_valid_sig
;
800 *signer_certs
= NULL
;
801 content
->data
= NULL
;
803 contentType
->length
= 0;
804 contentType
->components
= NULL
;
806 memset(&sd
, 0, sizeof(sd
));
808 ret
= decode_SignedData(data
, length
, &sd
, &size
);
810 hx509_set_error_string(context
, 0, ret
,
811 "Failed to decode SignedData");
815 if (sd
.encapContentInfo
.eContent
== NULL
&& signedContent
== NULL
) {
816 ret
= HX509_CMS_NO_DATA_AVAILABLE
;
817 hx509_set_error_string(context
, 0, ret
,
818 "No content data in SignedData");
821 if (sd
.encapContentInfo
.eContent
&& signedContent
) {
822 ret
= HX509_CMS_NO_DATA_AVAILABLE
;
823 hx509_set_error_string(context
, 0, ret
,
824 "Both external and internal SignedData");
828 if (sd
.encapContentInfo
.eContent
)
829 ret
= der_copy_octet_string(sd
.encapContentInfo
.eContent
, content
);
831 ret
= der_copy_octet_string(signedContent
, content
);
833 hx509_set_error_string(context
, 0, ret
, "malloc: out of memory");
837 ret
= hx509_certs_init(context
, "MEMORY:cms-cert-buffer",
842 ret
= hx509_certs_init(context
, "MEMORY:cms-signer-certs",
843 0, NULL
, signer_certs
);
847 /* XXX Check CMS version */
849 ret
= any_to_certs(context
, &sd
, certs
);
854 ret
= hx509_certs_merge(context
, certs
, pool
);
859 for (found_valid_sig
= 0, i
= 0; i
< sd
.signerInfos
.len
; i
++) {
860 heim_octet_string signed_data
;
861 const heim_oid
*match_oid
;
864 signer_info
= &sd
.signerInfos
.val
[i
];
867 if (signer_info
->signature
.length
== 0) {
868 ret
= HX509_CMS_MISSING_SIGNER_DATA
;
869 hx509_set_error_string(context
, 0, ret
,
870 "SignerInfo %d in SignedData "
871 "missing sigature", i
);
875 ret
= find_CMSIdentifier(context
, &signer_info
->sid
, certs
,
876 _hx509_verify_get_time(ctx
), &cert
,
877 HX509_QUERY_KU_DIGITALSIGNATURE
);
880 * If HX509_CMS_VS_NO_KU_CHECK is set, allow more liberal
881 * search for matching certificates by not considering
882 * KeyUsage bits on the certificates.
884 if ((flags
& HX509_CMS_VS_NO_KU_CHECK
) == 0)
887 ret
= find_CMSIdentifier(context
, &signer_info
->sid
, certs
,
888 _hx509_verify_get_time(ctx
), &cert
,
895 if (signer_info
->signedAttrs
) {
896 const Attribute
*attr
;
899 heim_octet_string os
;
901 sa
.val
= signer_info
->signedAttrs
->val
;
902 sa
.len
= signer_info
->signedAttrs
->len
;
904 /* verify that sigature exists */
905 attr
= find_attribute(&sa
, &asn1_oid_id_pkcs9_messageDigest
);
907 ret
= HX509_CRYPTO_SIGNATURE_MISSING
;
908 hx509_set_error_string(context
, 0, ret
,
909 "SignerInfo have signed attributes "
910 "but messageDigest (signature) "
914 if (attr
->value
.len
!= 1) {
915 ret
= HX509_CRYPTO_SIGNATURE_MISSING
;
916 hx509_set_error_string(context
, 0, ret
,
917 "SignerInfo have more then one "
918 "messageDigest (signature)");
922 ret
= decode_MessageDigest(attr
->value
.val
[0].data
,
923 attr
->value
.val
[0].length
,
927 hx509_set_error_string(context
, 0, ret
,
929 "messageDigest (signature)");
933 ret
= _hx509_verify_signature(context
,
935 &signer_info
->digestAlgorithm
,
938 der_free_octet_string(&os
);
940 hx509_set_error_string(context
, HX509_ERROR_APPEND
, ret
,
941 "Failed to verify messageDigest");
946 * Fetch content oid inside signedAttrs or set it to
949 attr
= find_attribute(&sa
, &asn1_oid_id_pkcs9_contentType
);
951 match_oid
= &asn1_oid_id_pkcs7_data
;
953 if (attr
->value
.len
!= 1) {
954 ret
= HX509_CMS_DATA_OID_MISMATCH
;
955 hx509_set_error_string(context
, 0, ret
,
956 "More then one oid in signedAttrs");
960 ret
= decode_ContentType(attr
->value
.val
[0].data
,
961 attr
->value
.val
[0].length
,
965 hx509_set_error_string(context
, 0, ret
,
967 "oid in signedAttrs");
970 match_oid
= &decode_oid
;
973 ASN1_MALLOC_ENCODE(CMSAttributes
,
979 if (match_oid
== &decode_oid
)
980 der_free_oid(&decode_oid
);
981 hx509_clear_error_string(context
);
984 if (size
!= signed_data
.length
)
985 _hx509_abort("internal ASN.1 encoder error");
988 signed_data
.data
= content
->data
;
989 signed_data
.length
= content
->length
;
990 match_oid
= &asn1_oid_id_pkcs7_data
;
994 * If HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH, allow
995 * encapContentInfo mismatch with the oid in signedAttributes
996 * (or if no signedAttributes where use, pkcs7-data oid).
997 * This is only needed to work with broken CMS implementations
998 * that doesn't follow CMS signedAttributes rules.
1001 if (der_heim_oid_cmp(match_oid
, &sd
.encapContentInfo
.eContentType
) &&
1002 (flags
& HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH
) == 0) {
1003 ret
= HX509_CMS_DATA_OID_MISMATCH
;
1004 hx509_set_error_string(context
, 0, ret
,
1005 "Oid in message mismatch from the expected");
1007 if (match_oid
== &decode_oid
)
1008 der_free_oid(&decode_oid
);
1011 ret
= hx509_verify_signature(context
,
1013 &signer_info
->signatureAlgorithm
,
1015 &signer_info
->signature
);
1017 hx509_set_error_string(context
, HX509_ERROR_APPEND
, ret
,
1018 "Failed to verify signature in "
1021 if (signer_info
->signedAttrs
)
1022 free(signed_data
.data
);
1027 * If HX509_CMS_VS_NO_VALIDATE flags is set, do not verify the
1028 * signing certificates and leave that up to the caller.
1031 if ((flags
& HX509_CMS_VS_NO_VALIDATE
) == 0) {
1032 ret
= hx509_verify_path(context
, ctx
, cert
, certs
);
1037 ret
= hx509_certs_add(context
, *signer_certs
, cert
);
1045 hx509_cert_free(cert
);
1049 * If HX509_CMS_VS_ALLOW_ZERO_SIGNER is set, allow empty
1050 * SignerInfo (no signatures). If SignedData have no signatures,
1051 * the function will return 0 with signer_certs set to NULL. Zero
1052 * signers is allowed by the standard, but since its only useful
1053 * in corner cases, it make into a flag that the caller have to
1056 if (sd
.signerInfos
.len
== 0 && (flags
& HX509_CMS_VS_ALLOW_ZERO_SIGNER
)) {
1058 hx509_certs_free(signer_certs
);
1059 } else if (found_valid_sig
== 0) {
1061 ret
= HX509_CMS_SIGNER_NOT_FOUND
;
1062 hx509_set_error_string(context
, 0, ret
,
1063 "No signers where found");
1068 ret
= der_copy_oid(&sd
.encapContentInfo
.eContentType
, contentType
);
1070 hx509_clear_error_string(context
);
1075 free_SignedData(&sd
);
1077 hx509_certs_free(&certs
);
1080 der_free_octet_string(content
);
1082 hx509_certs_free(signer_certs
);
1083 der_free_oid(contentType
);
1084 der_free_octet_string(content
);
1091 add_one_attribute(Attribute
**attr
,
1093 const heim_oid
*oid
,
1094 heim_octet_string
*data
)
1099 d
= realloc(*attr
, sizeof((*attr
)[0]) * (*len
+ 1));
1104 ret
= der_copy_oid(oid
, &(*attr
)[*len
].type
);
1108 ALLOC_SEQ(&(*attr
)[*len
].value
, 1);
1109 if ((*attr
)[*len
].value
.val
== NULL
) {
1110 der_free_oid(&(*attr
)[*len
].type
);
1114 (*attr
)[*len
].value
.val
[0].data
= data
->data
;
1115 (*attr
)[*len
].value
.val
[0].length
= data
->length
;
1123 * Decode SignedData and verify that the signature is correct.
1125 * @param context A hx509 context.
1127 * @param eContentType the type of the data.
1128 * @param data data to sign
1129 * @param length length of the data that data point to.
1130 * @param digest_alg digest algorithm to use, use NULL to get the
1131 * default or the peer determined algorithm.
1132 * @param cert certificate to use for sign the data.
1133 * @param peer info about the peer the message to send the message to,
1134 * like what digest algorithm to use.
1135 * @param anchors trust anchors that the client will use, used to
1136 * polulate the certificates included in the message
1137 * @param pool certificates to use in try to build the path to the
1139 * @param signed_data the output of the function, free with
1140 * der_free_octet_string().
1142 * @ingroup hx509_cms
1146 hx509_cms_create_signed_1(hx509_context context
,
1148 const heim_oid
*eContentType
,
1149 const void *data
, size_t length
,
1150 const AlgorithmIdentifier
*digest_alg
,
1152 hx509_peer_info peer
,
1153 hx509_certs anchors
,
1155 heim_octet_string
*signed_data
)
1160 signed_data
->data
= NULL
;
1161 signed_data
->length
= 0;
1163 ret
= hx509_certs_init(context
, "MEMORY:certs", 0, NULL
, &certs
);
1166 ret
= hx509_certs_add(context
, certs
, cert
);
1170 ret
= hx509_cms_create_signed(context
, flags
, eContentType
, data
, length
,
1171 digest_alg
, certs
, peer
, anchors
, pool
,
1175 hx509_certs_free(&certs
);
1181 const AlgorithmIdentifier
*digest_alg
;
1182 const heim_oid
*eContentType
;
1183 heim_octet_string content
;
1184 hx509_peer_info peer
;
1188 hx509_certs anchors
;
1193 sig_process(hx509_context context
, void *ctx
, hx509_cert cert
)
1195 struct sigctx
*sigctx
= ctx
;
1196 heim_octet_string buf
, sigdata
= { 0, NULL
};
1197 SignerInfo
*signer_info
= NULL
;
1198 AlgorithmIdentifier digest
;
1202 SignedData
*sd
= &sigctx
->sd
;
1205 memset(&digest
, 0, sizeof(digest
));
1206 memset(&path
, 0, sizeof(path
));
1208 if (_hx509_cert_private_key(cert
) == NULL
) {
1209 hx509_set_error_string(context
, 0, HX509_PRIVATE_KEY_MISSING
,
1210 "Private key missing for signing");
1211 return HX509_PRIVATE_KEY_MISSING
;
1214 if (sigctx
->digest_alg
) {
1215 ret
= copy_AlgorithmIdentifier(sigctx
->digest_alg
, &digest
);
1217 hx509_clear_error_string(context
);
1219 ret
= hx509_crypto_select(context
, HX509_SELECT_DIGEST
,
1220 _hx509_cert_private_key(cert
),
1221 sigctx
->peer
, &digest
);
1227 * Allocate on more signerInfo and do the signature processing
1230 ptr
= realloc(sd
->signerInfos
.val
,
1231 (sd
->signerInfos
.len
+ 1) * sizeof(sd
->signerInfos
.val
[0]));
1236 sd
->signerInfos
.val
= ptr
;
1238 signer_info
= &sd
->signerInfos
.val
[sd
->signerInfos
.len
];
1240 memset(signer_info
, 0, sizeof(*signer_info
));
1242 signer_info
->version
= 1;
1244 ret
= fill_CMSIdentifier(cert
, sigctx
->cmsidflag
, &signer_info
->sid
);
1246 hx509_clear_error_string(context
);
1250 signer_info
->signedAttrs
= NULL
;
1251 signer_info
->unsignedAttrs
= NULL
;
1253 ret
= copy_AlgorithmIdentifier(&digest
, &signer_info
->digestAlgorithm
);
1255 hx509_clear_error_string(context
);
1260 * If it isn't pkcs7-data send signedAttributes
1263 if (der_heim_oid_cmp(sigctx
->eContentType
, &asn1_oid_id_pkcs7_data
) != 0) {
1265 heim_octet_string sig
;
1267 ALLOC(signer_info
->signedAttrs
, 1);
1268 if (signer_info
->signedAttrs
== NULL
) {
1273 ret
= _hx509_create_signature(context
,
1282 ASN1_MALLOC_ENCODE(MessageDigest
,
1288 der_free_octet_string(&sig
);
1290 hx509_clear_error_string(context
);
1293 if (size
!= buf
.length
)
1294 _hx509_abort("internal ASN.1 encoder error");
1296 ret
= add_one_attribute(&signer_info
->signedAttrs
->val
,
1297 &signer_info
->signedAttrs
->len
,
1298 &asn1_oid_id_pkcs9_messageDigest
,
1302 hx509_clear_error_string(context
);
1307 ASN1_MALLOC_ENCODE(ContentType
,
1310 sigctx
->eContentType
,
1315 if (size
!= buf
.length
)
1316 _hx509_abort("internal ASN.1 encoder error");
1318 ret
= add_one_attribute(&signer_info
->signedAttrs
->val
,
1319 &signer_info
->signedAttrs
->len
,
1320 &asn1_oid_id_pkcs9_contentType
,
1324 hx509_clear_error_string(context
);
1328 sa
.val
= signer_info
->signedAttrs
->val
;
1329 sa
.len
= signer_info
->signedAttrs
->len
;
1331 ASN1_MALLOC_ENCODE(CMSAttributes
,
1338 hx509_clear_error_string(context
);
1341 if (size
!= sigdata
.length
)
1342 _hx509_abort("internal ASN.1 encoder error");
1344 sigdata
.data
= sigctx
->content
.data
;
1345 sigdata
.length
= sigctx
->content
.length
;
1349 AlgorithmIdentifier sigalg
;
1351 ret
= hx509_crypto_select(context
, HX509_SELECT_PUBLIC_SIG
,
1352 _hx509_cert_private_key(cert
), sigctx
->peer
,
1357 ret
= _hx509_create_signature(context
,
1358 _hx509_cert_private_key(cert
),
1361 &signer_info
->signatureAlgorithm
,
1362 &signer_info
->signature
);
1363 free_AlgorithmIdentifier(&sigalg
);
1368 sigctx
->sd
.signerInfos
.len
++;
1372 * Provide best effort path
1374 if (sigctx
->certs
) {
1377 if (sigctx
->pool
&& sigctx
->leafonly
== 0) {
1378 _hx509_calculate_path(context
,
1379 HX509_CALCULATE_PATH_NO_ANCHOR
,
1387 _hx509_path_append(context
, &path
, cert
);
1389 for (i
= 0; i
< path
.len
; i
++) {
1390 /* XXX remove dups */
1391 ret
= hx509_certs_add(context
, sigctx
->certs
, path
.val
[i
]);
1393 hx509_clear_error_string(context
);
1401 free_SignerInfo(signer_info
);
1402 if (sigdata
.data
!= sigctx
->content
.data
)
1403 der_free_octet_string(&sigdata
);
1404 _hx509_path_free(&path
);
1405 free_AlgorithmIdentifier(&digest
);
1411 cert_process(hx509_context context
, void *ctx
, hx509_cert cert
)
1413 struct sigctx
*sigctx
= ctx
;
1414 const unsigned int i
= sigctx
->sd
.certificates
->len
;
1418 ptr
= realloc(sigctx
->sd
.certificates
->val
,
1419 (i
+ 1) * sizeof(sigctx
->sd
.certificates
->val
[0]));
1422 sigctx
->sd
.certificates
->val
= ptr
;
1424 ret
= hx509_cert_binary(context
, cert
,
1425 &sigctx
->sd
.certificates
->val
[i
]);
1427 sigctx
->sd
.certificates
->len
++;
1433 cmp_AlgorithmIdentifier(const AlgorithmIdentifier
*p
, const AlgorithmIdentifier
*q
)
1435 return der_heim_oid_cmp(&p
->algorithm
, &q
->algorithm
);
1439 hx509_cms_create_signed(hx509_context context
,
1441 const heim_oid
*eContentType
,
1442 const void *data
, size_t length
,
1443 const AlgorithmIdentifier
*digest_alg
,
1445 hx509_peer_info peer
,
1446 hx509_certs anchors
,
1448 heim_octet_string
*signed_data
)
1454 struct sigctx sigctx
;
1456 memset(&sigctx
, 0, sizeof(sigctx
));
1457 memset(&name
, 0, sizeof(name
));
1459 if (eContentType
== NULL
)
1460 eContentType
= &asn1_oid_id_pkcs7_data
;
1462 sigctx
.digest_alg
= digest_alg
;
1463 sigctx
.content
.data
= rk_UNCONST(data
);
1464 sigctx
.content
.length
= length
;
1465 sigctx
.eContentType
= eContentType
;
1468 * Use HX509_CMS_SIGNATURE_ID_NAME to preferred use of issuer name
1469 * and serial number if possible. Otherwise subject key identifier
1472 if (flags
& HX509_CMS_SIGNATURE_ID_NAME
)
1473 sigctx
.cmsidflag
= CMS_ID_NAME
;
1475 sigctx
.cmsidflag
= CMS_ID_SKI
;
1478 * Use HX509_CMS_SIGNATURE_LEAF_ONLY to only request leaf
1479 * certificates to be added to the SignedData.
1481 sigctx
.leafonly
= (flags
& HX509_CMS_SIGNATURE_LEAF_ONLY
) ? 1 : 0;
1484 * Use HX509_CMS_NO_CERTS to make the SignedData contain no
1485 * certificates, overrides HX509_CMS_SIGNATURE_LEAF_ONLY.
1488 if ((flags
& HX509_CMS_SIGNATURE_NO_CERTS
) == 0) {
1489 ret
= hx509_certs_init(context
, "MEMORY:certs", 0, NULL
, &sigctx
.certs
);
1494 sigctx
.anchors
= anchors
;
1497 sigctx
.sd
.version
= CMSVersion_v3
;
1499 der_copy_oid(eContentType
, &sigctx
.sd
.encapContentInfo
.eContentType
);
1502 * Use HX509_CMS_SIGNATURE_DETACHED to create detached signatures.
1504 if ((flags
& HX509_CMS_SIGNATURE_DETACHED
) == 0) {
1505 ALLOC(sigctx
.sd
.encapContentInfo
.eContent
, 1);
1506 if (sigctx
.sd
.encapContentInfo
.eContent
== NULL
) {
1507 hx509_clear_error_string(context
);
1512 sigctx
.sd
.encapContentInfo
.eContent
->data
= malloc(length
);
1513 if (sigctx
.sd
.encapContentInfo
.eContent
->data
== NULL
) {
1514 hx509_clear_error_string(context
);
1518 memcpy(sigctx
.sd
.encapContentInfo
.eContent
->data
, data
, length
);
1519 sigctx
.sd
.encapContentInfo
.eContent
->length
= length
;
1523 * Use HX509_CMS_SIGNATURE_NO_SIGNER to create no sigInfo (no
1526 if ((flags
& HX509_CMS_SIGNATURE_NO_SIGNER
) == 0) {
1527 ret
= hx509_certs_iter_f(context
, certs
, sig_process
, &sigctx
);
1532 if (sigctx
.sd
.signerInfos
.len
) {
1535 * For each signerInfo, collect all different digest types.
1537 for (i
= 0; i
< sigctx
.sd
.signerInfos
.len
; i
++) {
1538 AlgorithmIdentifier
*di
=
1539 &sigctx
.sd
.signerInfos
.val
[i
].digestAlgorithm
;
1541 for (j
= 0; j
< sigctx
.sd
.digestAlgorithms
.len
; j
++)
1542 if (cmp_AlgorithmIdentifier(di
, &sigctx
.sd
.digestAlgorithms
.val
[j
]) == 0)
1544 if (j
== sigctx
.sd
.digestAlgorithms
.len
) {
1545 ret
= add_DigestAlgorithmIdentifiers(&sigctx
.sd
.digestAlgorithms
, di
);
1547 hx509_clear_error_string(context
);
1555 * Add certs we think are needed, build as part of sig_process
1558 ALLOC(sigctx
.sd
.certificates
, 1);
1559 if (sigctx
.sd
.certificates
== NULL
) {
1560 hx509_clear_error_string(context
);
1565 ret
= hx509_certs_iter_f(context
, sigctx
.certs
, cert_process
, &sigctx
);
1570 ASN1_MALLOC_ENCODE(SignedData
,
1571 signed_data
->data
, signed_data
->length
,
1572 &sigctx
.sd
, &size
, ret
);
1574 hx509_clear_error_string(context
);
1577 if (signed_data
->length
!= size
)
1578 _hx509_abort("internal ASN.1 encoder error");
1581 hx509_certs_free(&sigctx
.certs
);
1582 free_SignedData(&sigctx
.sd
);
1588 hx509_cms_decrypt_encrypted(hx509_context context
,
1592 heim_oid
*contentType
,
1593 heim_octet_string
*content
)
1595 heim_octet_string cont
;
1596 CMSEncryptedData ed
;
1597 AlgorithmIdentifier
*ai
;
1600 memset(content
, 0, sizeof(*content
));
1601 memset(&cont
, 0, sizeof(cont
));
1603 ret
= decode_CMSEncryptedData(data
, length
, &ed
, NULL
);
1605 hx509_set_error_string(context
, 0, ret
,
1606 "Failed to decode CMSEncryptedData");
1610 if (ed
.encryptedContentInfo
.encryptedContent
== NULL
) {
1611 ret
= HX509_CMS_NO_DATA_AVAILABLE
;
1612 hx509_set_error_string(context
, 0, ret
,
1613 "No content in EncryptedData");
1617 ret
= der_copy_oid(&ed
.encryptedContentInfo
.contentType
, contentType
);
1619 hx509_clear_error_string(context
);
1623 ai
= &ed
.encryptedContentInfo
.contentEncryptionAlgorithm
;
1624 if (ai
->parameters
== NULL
) {
1625 ret
= HX509_ALG_NOT_SUPP
;
1626 hx509_clear_error_string(context
);
1630 ret
= _hx509_pbe_decrypt(context
,
1633 ed
.encryptedContentInfo
.encryptedContent
,
1645 free_CMSEncryptedData(&ed
);