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
35 RCSID("$Id: cms.c 23268 2008-06-23 03:23:47Z lha $");
38 * @page page_cms CMS/PKCS7 message functions.
40 * CMS is defined in RFC 3369 and is an continuation of the RSA Labs
41 * standard PKCS7. The basic messages in CMS is
44 * Data signed with private key (RSA, DSA, ECDSA) or secret
47 * Data encrypted with private key (RSA)
49 * Data encrypted with secret (symmetric) key.
51 * Wrapper structure including type and data.
54 * See the library functions here: @ref hx509_cms
57 #define ALLOC(X, N) (X) = calloc((N), sizeof(*(X)))
58 #define ALLOC_SEQ(X, N) do { (X)->len = (N); ALLOC((X)->val, (N)); } while(0)
61 * Wrap data and oid in a ContentInfo and encode it.
63 * @param oid type of the content.
64 * @param buf data to be wrapped. If a NULL pointer is passed in, the
65 * optional content field in the ContentInfo is not going be filled
67 * @param res the encoded buffer, the result should be freed with
68 * der_free_octet_string().
70 * @return Returns an hx509 error code.
76 hx509_cms_wrap_ContentInfo(const heim_oid *oid,
77 const heim_octet_string *buf,
78 heim_octet_string *res)
84 memset(res, 0, sizeof(*res));
85 memset(&ci, 0, sizeof(ci));
87 ret = der_copy_oid(oid, &ci.contentType);
92 if (ci.content == NULL) {
93 free_ContentInfo(&ci);
96 ci.content->data = malloc(buf->length);
97 if (ci.content->data == NULL) {
98 free_ContentInfo(&ci);
101 memcpy(ci.content->data, buf->data, buf->length);
102 ci.content->length = buf->length;
105 ASN1_MALLOC_ENCODE(ContentInfo, res->data, res->length, &ci, &size, ret);
106 free_ContentInfo(&ci);
109 if (res->length != size)
110 _hx509_abort("internal ASN.1 encoder error");
116 * Decode an ContentInfo and unwrap data and oid it.
118 * @param in the encoded buffer.
119 * @param oid type of the content.
120 * @param out data to be wrapped.
121 * @param have_data since the data is optional, this flags show dthe
122 * diffrence between no data and the zero length data.
124 * @return Returns an hx509 error code.
130 hx509_cms_unwrap_ContentInfo(const heim_octet_string *in,
132 heim_octet_string *out,
139 memset(oid, 0, sizeof(*oid));
140 memset(out, 0, sizeof(*out));
142 ret = decode_ContentInfo(in->data, in->length, &ci, &size);
146 ret = der_copy_oid(&ci.contentType, oid);
148 free_ContentInfo(&ci);
152 ret = der_copy_octet_string(ci.content, out);
155 free_ContentInfo(&ci);
159 memset(out, 0, sizeof(*out));
162 *have_data = (ci.content != NULL) ? 1 : 0;
164 free_ContentInfo(&ci);
170 #define CMS_ID_NAME 1
173 fill_CMSIdentifier(const hx509_cert cert,
181 id->element = choice_CMSIdentifier_subjectKeyIdentifier;
182 ret = _hx509_find_extension_subject_key_id(_hx509_get_cert(cert),
183 &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 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 asprintf(str, "certificate with id %s", keyid);
251 asprintf(str, "certificate have unknown CMSidentifier type");
260 find_CMSIdentifier(hx509_context context,
261 CMSIdentifier *client,
264 hx509_cert *signer_cert,
272 memset(&c, 0, sizeof(c));
273 _hx509_query_clear(&q);
277 switch (client->element) {
278 case choice_CMSIdentifier_issuerAndSerialNumber:
279 q.serial = &client->u.issuerAndSerialNumber.serialNumber;
280 q.issuer_name = &client->u.issuerAndSerialNumber.issuer;
281 q.match = HX509_QUERY_MATCH_SERIALNUMBER|HX509_QUERY_MATCH_ISSUER_NAME;
283 case choice_CMSIdentifier_subjectKeyIdentifier:
284 q.subject_id = &client->u.subjectKeyIdentifier;
285 q.match = HX509_QUERY_MATCH_SUBJECT_KEY_ID;
288 hx509_set_error_string(context, 0, HX509_CMS_NO_RECIPIENT_CERTIFICATE,
289 "unknown CMS identifier element");
290 return HX509_CMS_NO_RECIPIENT_CERTIFICATE;
295 q.match |= HX509_QUERY_MATCH_TIME;
297 q.timenow = time_now;
299 q.timenow = time(NULL);
301 ret = hx509_certs_find(context, certs, &q, &cert);
302 if (ret == HX509_CERT_NOT_FOUND) {
305 ret = unparse_CMSIdentifier(context, client, &str);
307 hx509_set_error_string(context, 0,
308 HX509_CMS_NO_RECIPIENT_CERTIFICATE,
309 "Failed to find %s", str);
311 hx509_clear_error_string(context);
312 return HX509_CMS_NO_RECIPIENT_CERTIFICATE;
314 hx509_set_error_string(context, HX509_ERROR_APPEND,
315 HX509_CMS_NO_RECIPIENT_CERTIFICATE,
316 "Failed to find CMS id in cert store");
317 return HX509_CMS_NO_RECIPIENT_CERTIFICATE;
326 * Decode and unencrypt EnvelopedData.
328 * Extract data and parameteres from from the EnvelopedData. Also
329 * supports using detached EnvelopedData.
331 * @param context A hx509 context.
332 * @param certs Certificate that can decrypt the EnvelopedData
334 * @param flags HX509_CMS_UE flags to control the behavior.
335 * @param data pointer the structure the contains the DER/BER encoded
336 * EnvelopedData stucture.
337 * @param length length of the data that data point to.
338 * @param encryptedContent in case of detached signature, this
339 * contains the actual encrypted data, othersize its should be NULL.
340 * @param time_now set the current time, if zero the library uses now as the date.
341 * @param contentType output type oid, should be freed with der_free_oid().
342 * @param content the data, free with der_free_octet_string().
348 hx509_cms_unenvelope(hx509_context context,
353 const heim_octet_string *encryptedContent,
355 heim_oid *contentType,
356 heim_octet_string *content)
358 heim_octet_string key;
361 AlgorithmIdentifier *ai;
362 const heim_octet_string *enccontent;
363 heim_octet_string *params, params_data;
364 heim_octet_string ivec;
366 int ret, i, matched = 0, findflags = 0;
369 memset(&key, 0, sizeof(key));
370 memset(&ed, 0, sizeof(ed));
371 memset(&ivec, 0, sizeof(ivec));
372 memset(content, 0, sizeof(*content));
373 memset(contentType, 0, sizeof(*contentType));
375 if ((flags & HX509_CMS_UE_DONT_REQUIRE_KU_ENCIPHERMENT) == 0)
376 findflags |= HX509_QUERY_KU_ENCIPHERMENT;
378 ret = decode_EnvelopedData(data, length, &ed, &size);
380 hx509_set_error_string(context, 0, ret,
381 "Failed to decode EnvelopedData");
385 if (ed.recipientInfos.len == 0) {
386 ret = HX509_CMS_NO_RECIPIENT_CERTIFICATE;
387 hx509_set_error_string(context, 0, ret,
388 "No recipient info in enveloped data");
392 enccontent = ed.encryptedContentInfo.encryptedContent;
393 if (enccontent == NULL) {
394 if (encryptedContent == NULL) {
395 ret = HX509_CMS_NO_DATA_AVAILABLE;
396 hx509_set_error_string(context, 0, ret,
397 "Content missing from encrypted data");
400 enccontent = encryptedContent;
401 } else if (encryptedContent != NULL) {
402 ret = HX509_CMS_NO_DATA_AVAILABLE;
403 hx509_set_error_string(context, 0, ret,
404 "Both internal and external encrypted data");
409 for (i = 0; i < ed.recipientInfos.len; i++) {
410 KeyTransRecipientInfo *ri;
414 ri = &ed.recipientInfos.val[i];
416 ret = find_CMSIdentifier(context, &ri->rid, certs,
418 HX509_QUERY_PRIVATE_KEY|findflags);
422 matched = 1; /* found a matching certificate, let decrypt */
424 ret = _hx509_cert_private_decrypt(context,
426 &ri->keyEncryptionAlgorithm.algorithm,
429 hx509_cert_free(cert);
431 break; /* succuessfully decrypted cert */
433 ret2 = unparse_CMSIdentifier(context, &ri->rid, &str);
435 hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
436 "Failed to decrypt with %s", str);
442 ret = HX509_CMS_NO_RECIPIENT_CERTIFICATE;
443 hx509_set_error_string(context, 0, ret,
444 "No private key matched any certificate");
449 ret = HX509_CMS_NO_RECIPIENT_CERTIFICATE;
450 hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
451 "No private key decrypted the transfer key");
455 ret = der_copy_oid(&ed.encryptedContentInfo.contentType, contentType);
457 hx509_set_error_string(context, 0, ret,
458 "Failed to copy EnvelopedData content oid");
462 ai = &ed.encryptedContentInfo.contentEncryptionAlgorithm;
463 if (ai->parameters) {
464 params_data.data = ai->parameters->data;
465 params_data.length = ai->parameters->length;
466 params = ¶ms_data;
473 ret = hx509_crypto_init(context, NULL, &ai->algorithm, &crypto);
478 ret = hx509_crypto_set_params(context, crypto, params, &ivec);
480 hx509_crypto_destroy(crypto);
485 ret = hx509_crypto_set_key_data(crypto, key.data, key.length);
487 hx509_crypto_destroy(crypto);
488 hx509_set_error_string(context, 0, ret,
489 "Failed to set key for decryption "
494 ret = hx509_crypto_decrypt(crypto,
497 ivec.length ? &ivec : NULL,
499 hx509_crypto_destroy(crypto);
501 hx509_set_error_string(context, 0, ret,
502 "Failed to decrypt EnvelopedData");
509 free_EnvelopedData(&ed);
510 der_free_octet_string(&key);
512 der_free_octet_string(&ivec);
514 der_free_oid(contentType);
515 der_free_octet_string(content);
522 * Encrypt end encode EnvelopedData.
524 * Encrypt and encode EnvelopedData. The data is encrypted with a
525 * random key and the the random key is encrypted with the
526 * certificates private key. This limits what private key type can be
529 * @param context A hx509 context.
530 * @param flags flags to control the behavior, no flags today
531 * @param cert Certificate to encrypt the EnvelopedData encryption key
533 * @param data pointer the data to encrypt.
534 * @param length length of the data that data point to.
535 * @param encryption_type Encryption cipher to use for the bulk data,
536 * use NULL to get default.
537 * @param contentType type of the data that is encrypted
538 * @param content the output of the function,
539 * free with der_free_octet_string().
545 hx509_cms_envelope_1(hx509_context context,
550 const heim_oid *encryption_type,
551 const heim_oid *contentType,
552 heim_octet_string *content)
554 KeyTransRecipientInfo *ri;
555 heim_octet_string ivec;
556 heim_octet_string key;
557 hx509_crypto crypto = NULL;
562 memset(&ivec, 0, sizeof(ivec));
563 memset(&key, 0, sizeof(key));
564 memset(&ed, 0, sizeof(ed));
565 memset(content, 0, sizeof(*content));
567 if (encryption_type == NULL)
568 encryption_type = oid_id_aes_256_cbc();
570 ret = _hx509_check_key_usage(context, cert, 1 << 2, TRUE);
574 ret = hx509_crypto_init(context, NULL, encryption_type, &crypto);
578 ret = hx509_crypto_set_random_key(crypto, &key);
580 hx509_set_error_string(context, 0, ret,
581 "Create random key for EnvelopedData content");
585 ret = hx509_crypto_random_iv(crypto, &ivec);
587 hx509_set_error_string(context, 0, ret,
588 "Failed to create a random iv");
592 ret = hx509_crypto_encrypt(crypto,
596 &ed.encryptedContentInfo.encryptedContent);
598 hx509_set_error_string(context, 0, ret,
599 "Failed to encrypt EnvelopedData content");
604 AlgorithmIdentifier *enc_alg;
605 enc_alg = &ed.encryptedContentInfo.contentEncryptionAlgorithm;
606 ret = der_copy_oid(encryption_type, &enc_alg->algorithm);
608 hx509_set_error_string(context, 0, ret,
609 "Failed to set crypto oid "
610 "for EnvelopedData");
613 ALLOC(enc_alg->parameters, 1);
614 if (enc_alg->parameters == NULL) {
616 hx509_set_error_string(context, 0, ret,
617 "Failed to allocate crypto paramaters "
618 "for EnvelopedData");
622 ret = hx509_crypto_get_params(context,
625 enc_alg->parameters);
631 ALLOC_SEQ(&ed.recipientInfos, 1);
632 if (ed.recipientInfos.val == NULL) {
634 hx509_set_error_string(context, 0, ret,
635 "Failed to allocate recipients info "
636 "for EnvelopedData");
640 ri = &ed.recipientInfos.val[0];
643 ret = fill_CMSIdentifier(cert, CMS_ID_SKI, &ri->rid);
645 hx509_set_error_string(context, 0, ret,
646 "Failed to set CMS identifier info "
647 "for EnvelopedData");
651 ret = _hx509_cert_public_encrypt(context,
653 &ri->keyEncryptionAlgorithm.algorithm,
656 hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
657 "Failed to encrypt transport key for "
667 ed.originatorInfo = NULL;
669 ret = der_copy_oid(contentType, &ed.encryptedContentInfo.contentType);
671 hx509_set_error_string(context, 0, ret,
672 "Failed to copy content oid for "
677 ed.unprotectedAttrs = NULL;
679 ASN1_MALLOC_ENCODE(EnvelopedData, content->data, content->length,
682 hx509_set_error_string(context, 0, ret,
683 "Failed to encode EnvelopedData");
686 if (size != content->length)
687 _hx509_abort("internal ASN.1 encoder error");
691 hx509_crypto_destroy(crypto);
693 der_free_octet_string(content);
694 der_free_octet_string(&key);
695 der_free_octet_string(&ivec);
696 free_EnvelopedData(&ed);
702 any_to_certs(hx509_context context, const SignedData *sd, hx509_certs certs)
706 if (sd->certificates == NULL)
709 for (i = 0; i < sd->certificates->len; i++) {
712 ret = hx509_cert_init_data(context,
713 sd->certificates->val[i].data,
714 sd->certificates->val[i].length,
718 ret = hx509_certs_add(context, certs, c);
727 static const Attribute *
728 find_attribute(const CMSAttributes *attr, const heim_oid *oid)
731 for (i = 0; i < attr->len; i++)
732 if (der_heim_oid_cmp(&attr->val[i].type, oid) == 0)
733 return &attr->val[i];
738 * Decode SignedData and verify that the signature is correct.
740 * @param context A hx509 context.
741 * @param ctx a hx509 version context
743 * @param length length of the data that data point to.
744 * @param signedContent
745 * @param pool certificate pool to build certificates paths.
746 * @param contentType free with der_free_oid()
747 * @param content the output of the function, free with
748 * der_free_octet_string().
749 * @param signer_certs list of the cerficates used to sign this
750 * request, free with hx509_certs_free().
756 hx509_cms_verify_signed(hx509_context context,
757 hx509_verify_ctx ctx,
760 const heim_octet_string *signedContent,
762 heim_oid *contentType,
763 heim_octet_string *content,
764 hx509_certs *signer_certs)
766 SignerInfo *signer_info;
767 hx509_cert cert = NULL;
768 hx509_certs certs = NULL;
771 int ret, i, found_valid_sig;
773 *signer_certs = NULL;
774 content->data = NULL;
776 contentType->length = 0;
777 contentType->components = NULL;
779 memset(&sd, 0, sizeof(sd));
781 ret = decode_SignedData(data, length, &sd, &size);
783 hx509_set_error_string(context, 0, ret,
784 "Failed to decode SignedData");
788 if (sd.encapContentInfo.eContent == NULL && signedContent == NULL) {
789 ret = HX509_CMS_NO_DATA_AVAILABLE;
790 hx509_set_error_string(context, 0, ret,
791 "No content data in SignedData");
794 if (sd.encapContentInfo.eContent && signedContent) {
795 ret = HX509_CMS_NO_DATA_AVAILABLE;
796 hx509_set_error_string(context, 0, ret,
797 "Both external and internal SignedData");
800 if (sd.encapContentInfo.eContent)
801 signedContent = sd.encapContentInfo.eContent;
803 ret = hx509_certs_init(context, "MEMORY:cms-cert-buffer",
808 ret = hx509_certs_init(context, "MEMORY:cms-signer-certs",
809 0, NULL, signer_certs);
813 /* XXX Check CMS version */
815 ret = any_to_certs(context, &sd, certs);
820 ret = hx509_certs_merge(context, certs, pool);
825 for (found_valid_sig = 0, i = 0; i < sd.signerInfos.len; i++) {
826 heim_octet_string *signed_data;
827 const heim_oid *match_oid;
830 signer_info = &sd.signerInfos.val[i];
833 if (signer_info->signature.length == 0) {
834 ret = HX509_CMS_MISSING_SIGNER_DATA;
835 hx509_set_error_string(context, 0, ret,
836 "SignerInfo %d in SignedData "
837 "missing sigature", i);
841 ret = find_CMSIdentifier(context, &signer_info->sid, certs,
842 _hx509_verify_get_time(ctx), &cert,
843 HX509_QUERY_KU_DIGITALSIGNATURE);
847 if (signer_info->signedAttrs) {
848 const Attribute *attr;
851 heim_octet_string os;
853 sa.val = signer_info->signedAttrs->val;
854 sa.len = signer_info->signedAttrs->len;
856 /* verify that sigature exists */
857 attr = find_attribute(&sa, oid_id_pkcs9_messageDigest());
859 ret = HX509_CRYPTO_SIGNATURE_MISSING;
860 hx509_set_error_string(context, 0, ret,
861 "SignerInfo have signed attributes "
862 "but messageDigest (signature) "
866 if (attr->value.len != 1) {
867 ret = HX509_CRYPTO_SIGNATURE_MISSING;
868 hx509_set_error_string(context, 0, ret,
869 "SignerInfo have more then one "
870 "messageDigest (signature)");
874 ret = decode_MessageDigest(attr->value.val[0].data,
875 attr->value.val[0].length,
879 hx509_set_error_string(context, 0, ret,
881 "messageDigest (signature)");
885 ret = _hx509_verify_signature(context,
887 &signer_info->digestAlgorithm,
890 der_free_octet_string(&os);
892 hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
893 "Failed to verify messageDigest");
898 * Fetch content oid inside signedAttrs or set it to
901 attr = find_attribute(&sa, oid_id_pkcs9_contentType());
903 match_oid = oid_id_pkcs7_data();
905 if (attr->value.len != 1) {
906 ret = HX509_CMS_DATA_OID_MISMATCH;
907 hx509_set_error_string(context, 0, ret,
908 "More then one oid in signedAttrs");
912 ret = decode_ContentType(attr->value.val[0].data,
913 attr->value.val[0].length,
917 hx509_set_error_string(context, 0, ret,
919 "oid in signedAttrs");
922 match_oid = &decode_oid;
925 ALLOC(signed_data, 1);
926 if (signed_data == NULL) {
927 if (match_oid == &decode_oid)
928 der_free_oid(&decode_oid);
930 hx509_clear_error_string(context);
934 ASN1_MALLOC_ENCODE(CMSAttributes,
940 if (match_oid == &decode_oid)
941 der_free_oid(&decode_oid);
943 hx509_clear_error_string(context);
946 if (size != signed_data->length)
947 _hx509_abort("internal ASN.1 encoder error");
950 signed_data = rk_UNCONST(signedContent);
951 match_oid = oid_id_pkcs7_data();
954 if (der_heim_oid_cmp(match_oid, &sd.encapContentInfo.eContentType)) {
955 ret = HX509_CMS_DATA_OID_MISMATCH;
956 hx509_set_error_string(context, 0, ret,
957 "Oid in message mismatch from the expected");
959 if (match_oid == &decode_oid)
960 der_free_oid(&decode_oid);
963 ret = hx509_verify_signature(context,
965 &signer_info->signatureAlgorithm,
967 &signer_info->signature);
969 hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
970 "Failed to verify sigature in "
973 if (signed_data != signedContent) {
974 der_free_octet_string(signed_data);
980 ret = hx509_verify_path(context, ctx, cert, certs);
984 ret = hx509_certs_add(context, *signer_certs, cert);
992 hx509_cert_free(cert);
995 if (found_valid_sig == 0) {
997 ret = HX509_CMS_SIGNER_NOT_FOUND;
998 hx509_set_error_string(context, 0, ret,
999 "No signers where found");
1004 ret = der_copy_oid(&sd.encapContentInfo.eContentType, contentType);
1006 hx509_clear_error_string(context);
1010 content->data = malloc(signedContent->length);
1011 if (content->data == NULL) {
1012 hx509_clear_error_string(context);
1016 content->length = signedContent->length;
1017 memcpy(content->data, signedContent->data, content->length);
1020 free_SignedData(&sd);
1022 hx509_certs_free(&certs);
1025 hx509_certs_free(signer_certs);
1026 der_free_oid(contentType);
1027 der_free_octet_string(content);
1034 add_one_attribute(Attribute **attr,
1036 const heim_oid *oid,
1037 heim_octet_string *data)
1042 d = realloc(*attr, sizeof((*attr)[0]) * (*len + 1));
1047 ret = der_copy_oid(oid, &(*attr)[*len].type);
1051 ALLOC_SEQ(&(*attr)[*len].value, 1);
1052 if ((*attr)[*len].value.val == NULL) {
1053 der_free_oid(&(*attr)[*len].type);
1057 (*attr)[*len].value.val[0].data = data->data;
1058 (*attr)[*len].value.val[0].length = data->length;
1066 * Decode SignedData and verify that the signature is correct.
1068 * @param context A hx509 context.
1070 * @param eContentType the type of the data.
1071 * @param data data to sign
1072 * @param length length of the data that data point to.
1073 * @param digest_alg digest algorithm to use, use NULL to get the
1074 * default or the peer determined algorithm.
1075 * @param cert certificate to use for sign the data.
1076 * @param peer info about the peer the message to send the message to,
1077 * like what digest algorithm to use.
1078 * @param anchors trust anchors that the client will use, used to
1079 * polulate the certificates included in the message
1080 * @param pool certificates to use in try to build the path to the
1082 * @param signed_data the output of the function, free with
1083 * der_free_octet_string().
1085 * @ingroup hx509_cms
1089 hx509_cms_create_signed_1(hx509_context context,
1091 const heim_oid *eContentType,
1092 const void *data, size_t length,
1093 const AlgorithmIdentifier *digest_alg,
1095 hx509_peer_info peer,
1096 hx509_certs anchors,
1098 heim_octet_string *signed_data)
1100 AlgorithmIdentifier digest;
1102 SignerInfo *signer_info;
1103 heim_octet_string buf, content, sigdata = { 0, NULL };
1108 int cmsidflag = CMS_ID_SKI;
1110 memset(&sd, 0, sizeof(sd));
1111 memset(&name, 0, sizeof(name));
1112 memset(&path, 0, sizeof(path));
1113 memset(&digest, 0, sizeof(digest));
1115 content.data = rk_UNCONST(data);
1116 content.length = length;
1118 if (flags & HX509_CMS_SIGATURE_ID_NAME)
1119 cmsidflag = CMS_ID_NAME;
1121 if (_hx509_cert_private_key(cert) == NULL) {
1122 hx509_set_error_string(context, 0, HX509_PRIVATE_KEY_MISSING,
1123 "Private key missing for signing");
1124 return HX509_PRIVATE_KEY_MISSING;
1127 if (digest_alg == NULL) {
1128 ret = hx509_crypto_select(context, HX509_SELECT_DIGEST,
1129 _hx509_cert_private_key(cert), peer, &digest);
1131 ret = copy_AlgorithmIdentifier(digest_alg, &digest);
1133 hx509_clear_error_string(context);
1138 sd.version = CMSVersion_v3;
1140 if (eContentType == NULL)
1141 eContentType = oid_id_pkcs7_data();
1143 der_copy_oid(eContentType, &sd.encapContentInfo.eContentType);
1146 if ((flags & HX509_CMS_SIGATURE_DETACHED) == 0) {
1147 ALLOC(sd.encapContentInfo.eContent, 1);
1148 if (sd.encapContentInfo.eContent == NULL) {
1149 hx509_clear_error_string(context);
1154 sd.encapContentInfo.eContent->data = malloc(length);
1155 if (sd.encapContentInfo.eContent->data == NULL) {
1156 hx509_clear_error_string(context);
1160 memcpy(sd.encapContentInfo.eContent->data, data, length);
1161 sd.encapContentInfo.eContent->length = length;
1164 ALLOC_SEQ(&sd.signerInfos, 1);
1165 if (sd.signerInfos.val == NULL) {
1166 hx509_clear_error_string(context);
1171 signer_info = &sd.signerInfos.val[0];
1173 signer_info->version = 1;
1175 ret = fill_CMSIdentifier(cert, cmsidflag, &signer_info->sid);
1177 hx509_clear_error_string(context);
1181 signer_info->signedAttrs = NULL;
1182 signer_info->unsignedAttrs = NULL;
1185 ret = copy_AlgorithmIdentifier(&digest, &signer_info->digestAlgorithm);
1187 hx509_clear_error_string(context);
1192 * If it isn't pkcs7-data send signedAttributes
1195 if (der_heim_oid_cmp(eContentType, oid_id_pkcs7_data()) != 0) {
1197 heim_octet_string sig;
1199 ALLOC(signer_info->signedAttrs, 1);
1200 if (signer_info->signedAttrs == NULL) {
1205 ret = _hx509_create_signature(context,
1214 ASN1_MALLOC_ENCODE(MessageDigest,
1220 der_free_octet_string(&sig);
1222 hx509_clear_error_string(context);
1225 if (size != buf.length)
1226 _hx509_abort("internal ASN.1 encoder error");
1228 ret = add_one_attribute(&signer_info->signedAttrs->val,
1229 &signer_info->signedAttrs->len,
1230 oid_id_pkcs9_messageDigest(),
1233 hx509_clear_error_string(context);
1238 ASN1_MALLOC_ENCODE(ContentType,
1246 if (size != buf.length)
1247 _hx509_abort("internal ASN.1 encoder error");
1249 ret = add_one_attribute(&signer_info->signedAttrs->val,
1250 &signer_info->signedAttrs->len,
1251 oid_id_pkcs9_contentType(),
1254 hx509_clear_error_string(context);
1258 sa.val = signer_info->signedAttrs->val;
1259 sa.len = signer_info->signedAttrs->len;
1261 ASN1_MALLOC_ENCODE(CMSAttributes,
1268 hx509_clear_error_string(context);
1271 if (size != sigdata.length)
1272 _hx509_abort("internal ASN.1 encoder error");
1274 sigdata.data = content.data;
1275 sigdata.length = content.length;
1280 AlgorithmIdentifier sigalg;
1282 ret = hx509_crypto_select(context, HX509_SELECT_PUBLIC_SIG,
1283 _hx509_cert_private_key(cert), peer,
1288 ret = _hx509_create_signature(context,
1289 _hx509_cert_private_key(cert),
1292 &signer_info->signatureAlgorithm,
1293 &signer_info->signature);
1294 free_AlgorithmIdentifier(&sigalg);
1299 ALLOC_SEQ(&sd.digestAlgorithms, 1);
1300 if (sd.digestAlgorithms.val == NULL) {
1302 hx509_clear_error_string(context);
1306 ret = copy_AlgorithmIdentifier(&digest, &sd.digestAlgorithms.val[0]);
1308 hx509_clear_error_string(context);
1313 * Provide best effort path
1316 _hx509_calculate_path(context,
1317 HX509_CALCULATE_PATH_NO_ANCHOR,
1325 _hx509_path_append(context, &path, cert);
1331 ALLOC(sd.certificates, 1);
1332 if (sd.certificates == NULL) {
1333 hx509_clear_error_string(context);
1337 ALLOC_SEQ(sd.certificates, path.len);
1338 if (sd.certificates->val == NULL) {
1339 hx509_clear_error_string(context);
1344 for (i = 0; i < path.len; i++) {
1345 ret = hx509_cert_binary(context, path.val[i],
1346 &sd.certificates->val[i]);
1348 hx509_clear_error_string(context);
1354 ASN1_MALLOC_ENCODE(SignedData,
1355 signed_data->data, signed_data->length,
1358 hx509_clear_error_string(context);
1361 if (signed_data->length != size)
1362 _hx509_abort("internal ASN.1 encoder error");
1365 if (sigdata.data != content.data)
1366 der_free_octet_string(&sigdata);
1367 free_AlgorithmIdentifier(&digest);
1368 _hx509_path_free(&path);
1369 free_SignedData(&sd);
1375 hx509_cms_decrypt_encrypted(hx509_context context,
1379 heim_oid *contentType,
1380 heim_octet_string *content)
1382 heim_octet_string cont;
1383 CMSEncryptedData ed;
1384 AlgorithmIdentifier *ai;
1387 memset(content, 0, sizeof(*content));
1388 memset(&cont, 0, sizeof(cont));
1390 ret = decode_CMSEncryptedData(data, length, &ed, NULL);
1392 hx509_set_error_string(context, 0, ret,
1393 "Failed to decode CMSEncryptedData");
1397 if (ed.encryptedContentInfo.encryptedContent == NULL) {
1398 ret = HX509_CMS_NO_DATA_AVAILABLE;
1399 hx509_set_error_string(context, 0, ret,
1400 "No content in EncryptedData");
1404 ret = der_copy_oid(&ed.encryptedContentInfo.contentType, contentType);
1406 hx509_clear_error_string(context);
1410 ai = &ed.encryptedContentInfo.contentEncryptionAlgorithm;
1411 if (ai->parameters == NULL) {
1412 ret = HX509_ALG_NOT_SUPP;
1413 hx509_clear_error_string(context);
1417 ret = _hx509_pbe_decrypt(context,
1420 ed.encryptedContentInfo.encryptedContent,
1432 free_CMSEncryptedData(&ed);