hx509: Remove unused variable
[heimdal.git] / lib / hx509 / cms.c
blob97b23b53e57ea0b8ffc729b3489a2995459be598
1 /*
2 * Copyright (c) 2003 - 2007 Kungliga Tekniska Högskolan
3 * (Royal Institute of Technology, Stockholm, Sweden).
4 * All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
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
31 * SUCH DAMAGE.
34 #include "hx_locl.h"
36 /**
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
42 * - SignedData
43 * Data signed with private key (RSA, DSA, ECDSA) or secret
44 * (symmetric) key
45 * - EnvelopedData
46 * Data encrypted with private key (RSA)
47 * - EncryptedData
48 * Data encrypted with secret (symmetric) key.
49 * - ContentInfo
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)
59 /**
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
65 * in.
66 * @param res the encoded buffer, the result should be freed with
67 * der_free_octet_string().
69 * @return Returns an hx509 error code.
71 * @ingroup hx509_cms
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)
79 ContentInfo ci;
80 size_t size;
81 int ret;
83 memset(res, 0, sizeof(*res));
84 memset(&ci, 0, sizeof(ci));
86 ret = der_copy_oid(oid, &ci.contentType);
87 if (ret)
88 return ret;
89 if (buf) {
90 ALLOC(ci.content, 1);
91 if (ci.content == NULL) {
92 free_ContentInfo(&ci);
93 return ENOMEM;
95 ci.content->data = malloc(buf->length);
96 if (ci.content->data == NULL) {
97 free_ContentInfo(&ci);
98 return ENOMEM;
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);
106 if (ret)
107 return ret;
108 if (res->length != size)
109 _hx509_abort("internal ASN.1 encoder error");
111 return 0;
115 * Decode an ContentInfo and unwrap data and oid it.
117 * @param in the encoded buffer.
118 * @param oid type of the content.
119 * @param out data to be wrapped.
120 * @param have_data since the data is optional, this flag shows the
121 * difference between no data and the zero length data.
123 * @return Returns an hx509 error code.
125 * @ingroup hx509_cms
128 HX509_LIB_FUNCTION int HX509_LIB_CALL
129 hx509_cms_unwrap_ContentInfo(const heim_octet_string *in,
130 heim_oid *oid,
131 heim_octet_string *out,
132 int *have_data)
134 ContentInfo ci;
135 size_t size;
136 int ret;
138 memset(oid, 0, sizeof(*oid));
139 memset(out, 0, sizeof(*out));
141 ret = decode_ContentInfo(in->data, in->length, &ci, &size);
142 if (ret)
143 return ret;
145 ret = der_copy_oid(&ci.contentType, oid);
146 if (ret) {
147 free_ContentInfo(&ci);
148 return ret;
150 if (ci.content) {
151 ret = der_copy_octet_string(ci.content, out);
152 if (ret) {
153 der_free_oid(oid);
154 free_ContentInfo(&ci);
155 return ret;
157 } else
158 memset(out, 0, sizeof(*out));
160 if (have_data)
161 *have_data = (ci.content != NULL) ? 1 : 0;
163 free_ContentInfo(&ci);
165 return 0;
168 #define CMS_ID_SKI 0
169 #define CMS_ID_NAME 1
171 static int
172 fill_CMSIdentifier(const hx509_cert cert,
173 int type,
174 CMSIdentifier *id)
176 int ret;
178 switch (type) {
179 case CMS_ID_SKI:
180 id->element = choice_CMSIdentifier_subjectKeyIdentifier;
181 ret = _hx509_find_extension_subject_key_id(_hx509_get_cert(cert),
182 &id->u.subjectKeyIdentifier);
183 if (ret == 0)
184 break;
185 HEIM_FALLTHROUGH;
186 case CMS_ID_NAME: {
187 hx509_name name;
189 id->element = choice_CMSIdentifier_issuerAndSerialNumber;
190 ret = hx509_cert_get_issuer(cert, &name);
191 if (ret)
192 return ret;
193 ret = hx509_name_to_Name(name, &id->u.issuerAndSerialNumber.issuer);
194 hx509_name_free(&name);
195 if (ret)
196 return ret;
198 ret = hx509_cert_get_serialnumber(cert, &id->u.issuerAndSerialNumber.serialNumber);
199 break;
201 default:
202 _hx509_abort("CMS fill identifier with unknown type");
204 return ret;
207 static int
208 unparse_CMSIdentifier(hx509_context context,
209 CMSIdentifier *id,
210 char **str)
212 int ret = -1;
214 *str = NULL;
215 switch (id->element) {
216 case choice_CMSIdentifier_issuerAndSerialNumber: {
217 IssuerAndSerialNumber *iasn;
218 char *serial, *name;
220 iasn = &id->u.issuerAndSerialNumber;
222 ret = _hx509_Name_to_string(&iasn->issuer, &name);
223 if(ret)
224 return ret;
225 ret = der_print_hex_heim_integer(&iasn->serialNumber, &serial);
226 if (ret) {
227 free(name);
228 return ret;
230 ret = asprintf(str, "certificate issued by %s with serial number %s",
231 name, serial);
232 free(name);
233 free(serial);
234 break;
236 case choice_CMSIdentifier_subjectKeyIdentifier: {
237 KeyIdentifier *ki = &id->u.subjectKeyIdentifier;
238 char *keyid;
239 ssize_t len;
241 len = hex_encode(ki->data, ki->length, &keyid);
242 if (len < 0)
243 return ENOMEM;
245 if (len)
246 ret = asprintf(str, "certificate with id %s", keyid);
247 else
248 ret = asprintf(str, "certificate");
249 free(keyid);
250 break;
252 default:
253 ret = asprintf(str, "certificate has unknown CMSidentifier type");
254 break;
257 * In the following if, we check ret and *str which should be returned/set
258 * by asprintf(3) in every branch of the switch statement.
260 if (ret == -1 || *str == NULL)
261 return ENOMEM;
262 return 0;
265 static int
266 find_CMSIdentifier(hx509_context context,
267 CMSIdentifier *client,
268 hx509_certs certs,
269 time_t time_now,
270 hx509_cert *signer_cert,
271 int match)
273 hx509_query q;
274 hx509_cert cert;
275 Certificate c;
276 int ret;
278 memset(&c, 0, sizeof(c));
279 _hx509_query_clear(&q);
281 *signer_cert = NULL;
283 switch (client->element) {
284 case choice_CMSIdentifier_issuerAndSerialNumber:
285 q.serial = &client->u.issuerAndSerialNumber.serialNumber;
286 q.issuer_name = &client->u.issuerAndSerialNumber.issuer;
287 q.match = HX509_QUERY_MATCH_SERIALNUMBER|HX509_QUERY_MATCH_ISSUER_NAME;
288 break;
289 case choice_CMSIdentifier_subjectKeyIdentifier:
290 q.subject_id = &client->u.subjectKeyIdentifier;
291 q.match = HX509_QUERY_MATCH_SUBJECT_KEY_ID;
292 break;
293 default:
294 hx509_set_error_string(context, 0, HX509_CMS_NO_RECIPIENT_CERTIFICATE,
295 "unknown CMS identifier element");
296 return HX509_CMS_NO_RECIPIENT_CERTIFICATE;
299 q.match |= match;
301 q.match |= HX509_QUERY_MATCH_TIME;
302 if (time_now)
303 q.timenow = time_now;
304 else
305 q.timenow = time(NULL);
307 ret = hx509_certs_find(context, certs, &q, &cert);
308 if (ret == HX509_CERT_NOT_FOUND) {
309 char *str;
311 ret = unparse_CMSIdentifier(context, client, &str);
312 if (ret == 0) {
313 hx509_set_error_string(context, 0,
314 HX509_CMS_NO_RECIPIENT_CERTIFICATE,
315 "Failed to find %s", str);
316 } else
317 hx509_clear_error_string(context);
318 return HX509_CMS_NO_RECIPIENT_CERTIFICATE;
319 } else if (ret) {
320 hx509_set_error_string(context, HX509_ERROR_APPEND,
321 HX509_CMS_NO_RECIPIENT_CERTIFICATE,
322 "Failed to find CMS id in cert store");
323 return HX509_CMS_NO_RECIPIENT_CERTIFICATE;
326 *signer_cert = cert;
328 return 0;
332 * Decode and unencrypt EnvelopedData.
334 * Extract data and parameters from the EnvelopedData. Also
335 * supports using detached EnvelopedData.
337 * @param context A hx509 context.
338 * @param certs Certificate that can decrypt the EnvelopedData
339 * encryption key.
340 * @param flags HX509_CMS_UE flags to control the behavior.
341 * @param data pointer the structure the contains the DER/BER encoded
342 * EnvelopedData stucture.
343 * @param length length of the data that data point to.
344 * @param encryptedContent in case of detached signature, this
345 * contains the actual encrypted data, otherwise it should be NULL.
346 * @param time_now set the current time, if zero the library uses now as the date.
347 * @param contentType output type oid, should be freed with der_free_oid().
348 * @param content the data, free with der_free_octet_string().
350 * @return an hx509 error code.
352 * @ingroup hx509_cms
355 HX509_LIB_FUNCTION int HX509_LIB_CALL
356 hx509_cms_unenvelope(hx509_context context,
357 hx509_certs certs,
358 int flags,
359 const void *data,
360 size_t length,
361 const heim_octet_string *encryptedContent,
362 time_t time_now,
363 heim_oid *contentType,
364 heim_octet_string *content)
366 heim_octet_string key;
367 EnvelopedData ed;
368 hx509_cert cert;
369 AlgorithmIdentifier *ai;
370 const heim_octet_string *enccontent;
371 heim_octet_string *params, params_data;
372 heim_octet_string ivec;
373 size_t size;
374 int ret, matched = 0, findflags = 0;
375 size_t i;
378 memset(&key, 0, sizeof(key));
379 memset(&ed, 0, sizeof(ed));
380 memset(&ivec, 0, sizeof(ivec));
381 memset(content, 0, sizeof(*content));
382 memset(contentType, 0, sizeof(*contentType));
384 if ((flags & HX509_CMS_UE_DONT_REQUIRE_KU_ENCIPHERMENT) == 0)
385 findflags |= HX509_QUERY_KU_ENCIPHERMENT;
387 ret = decode_EnvelopedData(data, length, &ed, &size);
388 if (ret) {
389 hx509_set_error_string(context, 0, ret,
390 "Failed to decode EnvelopedData");
391 return ret;
394 if (ed.recipientInfos.len == 0) {
395 ret = HX509_CMS_NO_RECIPIENT_CERTIFICATE;
396 hx509_set_error_string(context, 0, ret,
397 "No recipient info in enveloped data");
398 goto out;
401 enccontent = ed.encryptedContentInfo.encryptedContent;
402 if (enccontent == NULL) {
403 if (encryptedContent == NULL) {
404 ret = HX509_CMS_NO_DATA_AVAILABLE;
405 hx509_set_error_string(context, 0, ret,
406 "Content missing from encrypted data");
407 goto out;
409 enccontent = encryptedContent;
410 } else if (encryptedContent != NULL) {
411 ret = HX509_CMS_NO_DATA_AVAILABLE;
412 hx509_set_error_string(context, 0, ret,
413 "Both internal and external encrypted data");
414 goto out;
417 cert = NULL;
418 for (i = 0; i < ed.recipientInfos.len; i++) {
419 KeyTransRecipientInfo *ri;
420 char *str;
421 int ret2;
423 ri = &ed.recipientInfos.val[i];
425 ret = find_CMSIdentifier(context, &ri->rid, certs,
426 time_now, &cert,
427 HX509_QUERY_PRIVATE_KEY|findflags);
428 if (ret)
429 continue;
431 matched = 1; /* found a matching certificate, let decrypt */
433 ret = _hx509_cert_private_decrypt(context,
434 &ri->encryptedKey,
435 &ri->keyEncryptionAlgorithm.algorithm,
436 cert, &key);
438 hx509_cert_free(cert);
439 if (ret == 0)
440 break; /* successfully decrypted cert */
441 cert = NULL;
442 ret2 = unparse_CMSIdentifier(context, &ri->rid, &str);
443 if (ret2 == 0) {
444 hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
445 "Failed to decrypt with %s", str);
446 free(str);
450 if (!matched) {
451 ret = HX509_CMS_NO_RECIPIENT_CERTIFICATE;
452 hx509_set_error_string(context, 0, ret,
453 "No private key matched any certificate");
454 goto out;
457 if (cert == NULL) {
458 ret = HX509_CMS_NO_RECIPIENT_CERTIFICATE;
459 hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
460 "No private key decrypted the transfer key");
461 goto out;
464 ret = der_copy_oid(&ed.encryptedContentInfo.contentType, contentType);
465 if (ret) {
466 hx509_set_error_string(context, 0, ret,
467 "Failed to copy EnvelopedData content oid");
468 goto out;
471 ai = &ed.encryptedContentInfo.contentEncryptionAlgorithm;
472 if (ai->parameters) {
473 params_data.data = ai->parameters->data;
474 params_data.length = ai->parameters->length;
475 params = &params_data;
476 } else
477 params = NULL;
480 hx509_crypto crypto;
482 ret = hx509_crypto_init(context, NULL, &ai->algorithm, &crypto);
483 if (ret)
484 goto out;
486 if (flags & HX509_CMS_UE_ALLOW_WEAK)
487 hx509_crypto_allow_weak(crypto);
489 if (params) {
490 ret = hx509_crypto_set_params(context, crypto, params, &ivec);
491 if (ret) {
492 hx509_crypto_destroy(crypto);
493 goto out;
497 ret = hx509_crypto_set_key_data(crypto, key.data, key.length);
498 if (ret) {
499 hx509_crypto_destroy(crypto);
500 hx509_set_error_string(context, 0, ret,
501 "Failed to set key for decryption "
502 "of EnvelopedData");
503 goto out;
506 ret = hx509_crypto_decrypt(crypto,
507 enccontent->data,
508 enccontent->length,
509 ivec.length ? &ivec : NULL,
510 content);
511 hx509_crypto_destroy(crypto);
512 if (ret) {
513 hx509_set_error_string(context, 0, ret,
514 "Failed to decrypt EnvelopedData");
515 goto out;
519 out:
521 free_EnvelopedData(&ed);
522 der_free_octet_string(&key);
523 if (ivec.length)
524 der_free_octet_string(&ivec);
525 if (ret) {
526 der_free_oid(contentType);
527 der_free_octet_string(content);
530 return ret;
534 * Encrypt and encode EnvelopedData.
536 * Encrypt and encode EnvelopedData. The data is encrypted with a
537 * random key and the the random key is encrypted with the
538 * certificate's private key. This limits what private key type can be
539 * used to RSA.
541 * @param context A hx509 context.
542 * @param flags flags to control the behavior.
543 * - HX509_CMS_EV_NO_KU_CHECK - Don't check KU on certificate
544 * - HX509_CMS_EV_ALLOW_WEAK - Allow weak crypto
545 * - HX509_CMS_EV_ID_NAME - prefer issuer name and serial number
546 * @param cert Certificate to encrypt the EnvelopedData encryption key
547 * with.
548 * @param data pointer the data to encrypt.
549 * @param length length of the data that data point to.
550 * @param encryption_type Encryption cipher to use for the bulk data,
551 * use NULL to get default.
552 * @param contentType type of the data that is encrypted
553 * @param content the output of the function,
554 * free with der_free_octet_string().
556 * @return an hx509 error code.
558 * @ingroup hx509_cms
561 HX509_LIB_FUNCTION int HX509_LIB_CALL
562 hx509_cms_envelope_1(hx509_context context,
563 int flags,
564 hx509_cert cert,
565 const void *data,
566 size_t length,
567 const heim_oid *encryption_type,
568 const heim_oid *contentType,
569 heim_octet_string *content)
571 KeyTransRecipientInfo *ri;
572 heim_octet_string ivec;
573 heim_octet_string key;
574 hx509_crypto crypto = NULL;
575 int ret, cmsidflag;
576 EnvelopedData ed;
577 size_t size;
579 memset(&ivec, 0, sizeof(ivec));
580 memset(&key, 0, sizeof(key));
581 memset(&ed, 0, sizeof(ed));
582 memset(content, 0, sizeof(*content));
584 if (encryption_type == NULL)
585 encryption_type = &asn1_oid_id_aes_256_cbc;
587 if ((flags & HX509_CMS_EV_NO_KU_CHECK) == 0) {
588 ret = _hx509_check_key_usage(context, cert, 1 << 2, TRUE);
589 if (ret)
590 goto out;
593 ret = hx509_crypto_init(context, NULL, encryption_type, &crypto);
594 if (ret)
595 goto out;
597 if (flags & HX509_CMS_EV_ALLOW_WEAK)
598 hx509_crypto_allow_weak(crypto);
600 ret = hx509_crypto_set_random_key(crypto, &key);
601 if (ret) {
602 hx509_set_error_string(context, 0, ret,
603 "Create random key for EnvelopedData content");
604 goto out;
607 ret = hx509_crypto_random_iv(crypto, &ivec);
608 if (ret) {
609 hx509_set_error_string(context, 0, ret,
610 "Failed to create a random iv");
611 goto out;
614 ret = hx509_crypto_encrypt(crypto,
615 data,
616 length,
617 &ivec,
618 &ed.encryptedContentInfo.encryptedContent);
619 if (ret) {
620 hx509_set_error_string(context, 0, ret,
621 "Failed to encrypt EnvelopedData content");
622 goto out;
626 AlgorithmIdentifier *enc_alg;
627 enc_alg = &ed.encryptedContentInfo.contentEncryptionAlgorithm;
628 ret = der_copy_oid(encryption_type, &enc_alg->algorithm);
629 if (ret) {
630 hx509_set_error_string(context, 0, ret,
631 "Failed to set crypto oid "
632 "for EnvelopedData");
633 goto out;
635 ALLOC(enc_alg->parameters, 1);
636 if (enc_alg->parameters == NULL) {
637 ret = ENOMEM;
638 hx509_set_error_string(context, 0, ret,
639 "Failed to allocate crypto parameters "
640 "for EnvelopedData");
641 goto out;
644 ret = hx509_crypto_get_params(context,
645 crypto,
646 &ivec,
647 enc_alg->parameters);
648 if (ret) {
649 goto out;
653 ALLOC_SEQ(&ed.recipientInfos, 1);
654 if (ed.recipientInfos.val == NULL) {
655 ret = ENOMEM;
656 hx509_set_error_string(context, 0, ret,
657 "Failed to allocate recipients info "
658 "for EnvelopedData");
659 goto out;
662 ri = &ed.recipientInfos.val[0];
664 if (flags & HX509_CMS_EV_ID_NAME) {
665 ri->version = 0;
666 cmsidflag = CMS_ID_NAME;
667 } else {
668 ri->version = 2;
669 cmsidflag = CMS_ID_SKI;
672 ret = fill_CMSIdentifier(cert, cmsidflag, &ri->rid);
673 if (ret) {
674 hx509_set_error_string(context, 0, ret,
675 "Failed to set CMS identifier info "
676 "for EnvelopedData");
677 goto out;
680 ret = hx509_cert_public_encrypt(context,
681 &key, cert,
682 &ri->keyEncryptionAlgorithm.algorithm,
683 &ri->encryptedKey);
684 if (ret) {
685 hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
686 "Failed to encrypt transport key for "
687 "EnvelopedData");
688 goto out;
695 ed.version = 0;
696 ed.originatorInfo = NULL;
698 ret = der_copy_oid(contentType, &ed.encryptedContentInfo.contentType);
699 if (ret) {
700 hx509_set_error_string(context, 0, ret,
701 "Failed to copy content oid for "
702 "EnvelopedData");
703 goto out;
706 ed.unprotectedAttrs = NULL;
708 ASN1_MALLOC_ENCODE(EnvelopedData, content->data, content->length,
709 &ed, &size, ret);
710 if (ret) {
711 hx509_set_error_string(context, 0, ret,
712 "Failed to encode EnvelopedData");
713 goto out;
715 if (size != content->length)
716 _hx509_abort("internal ASN.1 encoder error");
718 out:
719 if (crypto)
720 hx509_crypto_destroy(crypto);
721 if (ret)
722 der_free_octet_string(content);
723 der_free_octet_string(&key);
724 der_free_octet_string(&ivec);
725 free_EnvelopedData(&ed);
727 return ret;
730 static int
731 any_to_certs(hx509_context context, const SignedData *sd, hx509_certs certs)
733 int ret;
734 size_t i;
736 if (sd->certificates == NULL)
737 return 0;
739 for (i = 0; i < sd->certificates->len; i++) {
740 heim_error_t error;
741 hx509_cert c;
743 c = hx509_cert_init_data(context,
744 sd->certificates->val[i].data,
745 sd->certificates->val[i].length,
746 &error);
747 if (c == NULL) {
748 ret = heim_error_get_code(error);
749 heim_release(error);
750 return ret;
752 ret = hx509_certs_add(context, certs, c);
753 hx509_cert_free(c);
754 if (ret)
755 return ret;
758 return 0;
761 static const Attribute *
762 find_attribute(const CMSAttributes *attr, const heim_oid *oid)
764 size_t i;
765 for (i = 0; i < attr->len; i++)
766 if (der_heim_oid_cmp(&attr->val[i].type, oid) == 0)
767 return &attr->val[i];
768 return NULL;
772 * Decode SignedData and verify that the signature is correct.
774 * @param context A hx509 context.
775 * @param ctx a hx509 verify context.
776 * @param flags to control the behavior of the function.
777 * - HX509_CMS_VS_NO_KU_CHECK - Don't check KeyUsage
778 * - HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH - allow oid mismatch
779 * - HX509_CMS_VS_ALLOW_ZERO_SIGNER - no signer, see below.
780 * @param data pointer to CMS SignedData encoded data.
781 * @param length length of the data that data points to.
782 * @param signedContent external data used for signature.
783 * @param pool certificate pool to build certificates paths.
784 * @param contentType free with der_free_oid().
785 * @param content the output of the function, free with
786 * der_free_octet_string().
787 * @param signer_certs list of the cerficates used to sign this
788 * request, free with hx509_certs_free().
790 * @return an hx509 error code.
792 * @ingroup hx509_cms
795 HX509_LIB_FUNCTION int HX509_LIB_CALL
796 hx509_cms_verify_signed(hx509_context context,
797 hx509_verify_ctx ctx,
798 unsigned int flags,
799 const void *data,
800 size_t length,
801 const heim_octet_string *signedContent,
802 hx509_certs pool,
803 heim_oid *contentType,
804 heim_octet_string *content,
805 hx509_certs *signer_certs)
807 unsigned int verify_flags;
809 return hx509_cms_verify_signed_ext(context,
810 ctx,
811 flags,
812 data,
813 length,
814 signedContent,
815 pool,
816 contentType,
817 content,
818 signer_certs,
819 &verify_flags);
823 * Decode SignedData and verify that the signature is correct.
825 * @param context A hx509 context.
826 * @param ctx a hx509 verify context.
827 * @param flags to control the behaivor of the function.
828 * - HX509_CMS_VS_NO_KU_CHECK - Don't check KeyUsage
829 * - HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH - allow oid mismatch
830 * - HX509_CMS_VS_ALLOW_ZERO_SIGNER - no signer, see below.
831 * @param data pointer to CMS SignedData encoded data.
832 * @param length length of the data that data points to.
833 * @param signedContent external data used for signature.
834 * @param pool certificate pool to build certificates paths.
835 * @param contentType free with der_free_oid().
836 * @param content the output of the function, free with
837 * der_free_octet_string().
838 * @param signer_certs list of the cerficates used to sign this
839 * request, free with hx509_certs_free().
840 * @param verify_flags flags indicating whether the certificate
841 * was verified or not
843 * @return an hx509 error code.
845 * @ingroup hx509_cms
848 HX509_LIB_FUNCTION int HX509_LIB_CALL
849 hx509_cms_verify_signed_ext(hx509_context context,
850 hx509_verify_ctx ctx,
851 unsigned int flags,
852 const void *data,
853 size_t length,
854 const heim_octet_string *signedContent,
855 hx509_certs pool,
856 heim_oid *contentType,
857 heim_octet_string *content,
858 hx509_certs *signer_certs,
859 unsigned int *verify_flags)
861 SignerInfo *signer_info;
862 hx509_cert cert = NULL;
863 hx509_certs certs = NULL;
864 SignedData sd;
865 size_t size;
866 int ret, found_valid_sig;
867 size_t i;
869 *signer_certs = NULL;
870 *verify_flags = 0;
872 content->data = NULL;
873 content->length = 0;
874 contentType->length = 0;
875 contentType->components = NULL;
877 memset(&sd, 0, sizeof(sd));
879 ret = decode_SignedData(data, length, &sd, &size);
880 if (ret) {
881 hx509_set_error_string(context, 0, ret,
882 "Failed to decode SignedData");
883 goto out;
886 if (sd.encapContentInfo.eContent == NULL && signedContent == NULL) {
887 ret = HX509_CMS_NO_DATA_AVAILABLE;
888 hx509_set_error_string(context, 0, ret,
889 "No content data in SignedData");
890 goto out;
892 if (sd.encapContentInfo.eContent && signedContent) {
893 ret = HX509_CMS_NO_DATA_AVAILABLE;
894 hx509_set_error_string(context, 0, ret,
895 "Both external and internal SignedData");
896 goto out;
899 if (sd.encapContentInfo.eContent)
900 ret = der_copy_octet_string(sd.encapContentInfo.eContent, content);
901 else
902 ret = der_copy_octet_string(signedContent, content);
903 if (ret) {
904 hx509_set_error_string(context, 0, ret, "malloc: out of memory");
905 goto out;
908 ret = hx509_certs_init(context, "MEMORY:cms-cert-buffer",
909 0, NULL, &certs);
910 if (ret)
911 goto out;
913 ret = hx509_certs_init(context, "MEMORY:cms-signer-certs",
914 0, NULL, signer_certs);
915 if (ret)
916 goto out;
918 /* XXX Check CMS version */
920 ret = any_to_certs(context, &sd, certs);
921 if (ret)
922 goto out;
924 if (pool) {
925 ret = hx509_certs_merge(context, certs, pool);
926 if (ret)
927 goto out;
930 for (found_valid_sig = 0, i = 0; i < sd.signerInfos.len; i++) {
931 heim_octet_string signed_data = { 0, NULL };
932 const heim_oid *match_oid;
933 heim_oid decode_oid;
935 signer_info = &sd.signerInfos.val[i];
936 match_oid = NULL;
938 if (signer_info->signature.length == 0) {
939 ret = HX509_CMS_MISSING_SIGNER_DATA;
940 hx509_set_error_string(context, 0, ret,
941 "SignerInfo %zu in SignedData "
942 "missing signature", i);
943 continue;
946 ret = find_CMSIdentifier(context, &signer_info->sid, certs,
947 _hx509_verify_get_time(ctx), &cert,
948 HX509_QUERY_KU_DIGITALSIGNATURE);
949 if (ret) {
951 * If HX509_CMS_VS_NO_KU_CHECK is set, allow more liberal
952 * search for matching certificates by not considering
953 * KeyUsage bits on the certificates.
955 if ((flags & HX509_CMS_VS_NO_KU_CHECK) == 0)
956 continue;
958 ret = find_CMSIdentifier(context, &signer_info->sid, certs,
959 _hx509_verify_get_time(ctx), &cert,
961 if (ret)
962 continue;
966 if (signer_info->signedAttrs) {
967 const Attribute *attr;
969 CMSAttributes sa;
970 heim_octet_string os;
972 sa.val = signer_info->signedAttrs->val;
973 sa.len = signer_info->signedAttrs->len;
975 /* verify that signature exists */
976 attr = find_attribute(&sa, &asn1_oid_id_pkcs9_messageDigest);
977 if (attr == NULL) {
978 ret = HX509_CRYPTO_SIGNATURE_MISSING;
979 hx509_set_error_string(context, 0, ret,
980 "SignerInfo has signed attributes "
981 "but messageDigest (signature) "
982 "is missing");
983 goto next_signature;
985 if (attr->value.len != 1) {
986 ret = HX509_CRYPTO_SIGNATURE_MISSING;
987 hx509_set_error_string(context, 0, ret,
988 "SignerInfo has more than one "
989 "messageDigest (signature)");
990 goto next_signature;
993 ret = decode_MessageDigest(attr->value.val[0].data,
994 attr->value.val[0].length,
995 &os,
996 &size);
997 if (ret) {
998 hx509_set_error_string(context, 0, ret,
999 "Failed to decode "
1000 "messageDigest (signature)");
1001 goto next_signature;
1004 ret = _hx509_verify_signature(context,
1005 NULL,
1006 &signer_info->digestAlgorithm,
1007 content,
1008 &os);
1009 der_free_octet_string(&os);
1010 if (ret) {
1011 hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
1012 "Failed to verify messageDigest");
1013 goto next_signature;
1017 * Fetch content oid inside signedAttrs or set it to
1018 * id-pkcs7-data.
1020 attr = find_attribute(&sa, &asn1_oid_id_pkcs9_contentType);
1021 if (attr == NULL) {
1022 match_oid = &asn1_oid_id_pkcs7_data;
1023 } else {
1024 if (attr->value.len != 1) {
1025 ret = HX509_CMS_DATA_OID_MISMATCH;
1026 hx509_set_error_string(context, 0, ret,
1027 "More than one oid in signedAttrs");
1028 goto next_signature;
1031 ret = decode_ContentType(attr->value.val[0].data,
1032 attr->value.val[0].length,
1033 &decode_oid,
1034 &size);
1035 if (ret) {
1036 hx509_set_error_string(context, 0, ret,
1037 "Failed to decode "
1038 "oid in signedAttrs");
1039 goto next_signature;
1041 match_oid = &decode_oid;
1044 ASN1_MALLOC_ENCODE(CMSAttributes,
1045 signed_data.data,
1046 signed_data.length,
1047 &sa,
1048 &size, ret);
1049 if (ret) {
1050 if (match_oid == &decode_oid)
1051 der_free_oid(&decode_oid);
1052 hx509_clear_error_string(context);
1053 goto next_signature;
1055 if (size != signed_data.length)
1056 _hx509_abort("internal ASN.1 encoder error");
1058 } else {
1059 signed_data.data = content->data;
1060 signed_data.length = content->length;
1061 match_oid = &asn1_oid_id_pkcs7_data;
1065 * If HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH, allow
1066 * encapContentInfo mismatch with the oid in signedAttributes
1067 * (or if no signedAttributes where use, pkcs7-data oid).
1068 * This is only needed to work with broken CMS implementations
1069 * that doesn't follow CMS signedAttributes rules.
1072 if (der_heim_oid_cmp(match_oid, &sd.encapContentInfo.eContentType) &&
1073 (flags & HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH) == 0) {
1074 ret = HX509_CMS_DATA_OID_MISMATCH;
1075 hx509_set_error_string(context, 0, ret,
1076 "Oid in message mismatch from the expected");
1078 if (match_oid == &decode_oid)
1079 der_free_oid(&decode_oid);
1081 if (ret == 0) {
1082 ret = hx509_verify_signature(context,
1083 cert,
1084 &signer_info->signatureAlgorithm,
1085 &signed_data,
1086 &signer_info->signature);
1087 if (ret)
1088 hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
1089 "Failed to verify signature in "
1090 "CMS SignedData");
1092 if (signed_data.data != NULL && content->data != signed_data.data) {
1093 free(signed_data.data);
1094 signed_data.data = NULL;
1096 if (ret)
1097 goto next_signature;
1100 * If HX509_CMS_VS_NO_VALIDATE flags is set, return the signer
1101 * certificate unconditionally but do not set HX509_CMS_VSE_VALIDATED.
1103 ret = hx509_verify_path(context, ctx, cert, certs);
1104 if (ret == 0 || (flags & HX509_CMS_VS_NO_VALIDATE)) {
1105 if (ret == 0)
1106 *verify_flags |= HX509_CMS_VSE_VALIDATED;
1108 ret = hx509_certs_add(context, *signer_certs, cert);
1109 if (ret == 0)
1110 found_valid_sig++;
1113 next_signature:
1114 if (cert)
1115 hx509_cert_free(cert);
1116 cert = NULL;
1119 * If HX509_CMS_VS_ALLOW_ZERO_SIGNER is set, allow empty
1120 * SignerInfo (no signatures). If SignedData has no signatures,
1121 * the function will return 0 with signer_certs set to NULL. Zero
1122 * signers is allowed by the standard, but since it's only useful
1123 * in corner cases, it's made into a flag that the caller has to
1124 * turn on.
1126 if (sd.signerInfos.len == 0 && (flags & HX509_CMS_VS_ALLOW_ZERO_SIGNER)) {
1127 if (*signer_certs)
1128 hx509_certs_free(signer_certs);
1129 } else if (found_valid_sig == 0) {
1130 if (ret == 0) {
1131 ret = HX509_CMS_SIGNER_NOT_FOUND;
1132 hx509_set_error_string(context, 0, ret,
1133 "No signers were found");
1135 goto out;
1138 ret = der_copy_oid(&sd.encapContentInfo.eContentType, contentType);
1139 if (ret) {
1140 hx509_clear_error_string(context);
1141 goto out;
1144 out:
1145 free_SignedData(&sd);
1146 if (certs)
1147 hx509_certs_free(&certs);
1148 if (ret) {
1149 if (content->data)
1150 der_free_octet_string(content);
1151 if (*signer_certs)
1152 hx509_certs_free(signer_certs);
1153 der_free_oid(contentType);
1154 der_free_octet_string(content);
1157 return ret;
1160 static int
1161 add_one_attribute(Attribute **attr,
1162 unsigned int *len,
1163 const heim_oid *oid,
1164 heim_octet_string *data)
1166 void *d;
1167 int ret;
1169 d = realloc(*attr, sizeof((*attr)[0]) * (*len + 1));
1170 if (d == NULL)
1171 return ENOMEM;
1172 (*attr) = d;
1174 ret = der_copy_oid(oid, &(*attr)[*len].type);
1175 if (ret)
1176 return ret;
1178 ALLOC_SEQ(&(*attr)[*len].value, 1);
1179 if ((*attr)[*len].value.val == NULL) {
1180 der_free_oid(&(*attr)[*len].type);
1181 return ENOMEM;
1184 (*attr)[*len].value.val[0].data = data->data;
1185 (*attr)[*len].value.val[0].length = data->length;
1187 *len += 1;
1189 return 0;
1193 * Decode SignedData and verify that the signature is correct.
1195 * @param context A hx509 context.
1196 * @param flags
1197 * @param eContentType the type of the data.
1198 * @param data data to sign
1199 * @param length length of the data that data points to.
1200 * @param digest_alg digest algorithm to use, use NULL to get the
1201 * default or the peer determined algorithm.
1202 * @param cert certificate to use for signing the data.
1203 * @param peer info about the peer the message to send the message to,
1204 * like what digest algorithm to use.
1205 * @param anchors trust anchors that the client will use, used to
1206 * polulate the certificates included in the message
1207 * @param pool certificates to use in try to build the path to the
1208 * trust anchors.
1209 * @param signed_data the output of the function, free with
1210 * der_free_octet_string().
1212 * @return Returns an hx509 error code.
1214 * @ingroup hx509_cms
1217 HX509_LIB_FUNCTION int HX509_LIB_CALL
1218 hx509_cms_create_signed_1(hx509_context context,
1219 int flags,
1220 const heim_oid *eContentType,
1221 const void *data, size_t length,
1222 const AlgorithmIdentifier *digest_alg,
1223 hx509_cert cert,
1224 hx509_peer_info peer,
1225 hx509_certs anchors,
1226 hx509_certs pool,
1227 heim_octet_string *signed_data)
1229 hx509_certs certs;
1230 int ret = 0;
1232 signed_data->data = NULL;
1233 signed_data->length = 0;
1235 ret = hx509_certs_init(context, "MEMORY:certs", 0, NULL, &certs);
1236 if (ret)
1237 return ret;
1238 ret = hx509_certs_add(context, certs, cert);
1239 if (ret)
1240 goto out;
1242 ret = hx509_cms_create_signed(context, flags, eContentType, data, length,
1243 digest_alg, certs, peer, anchors, pool,
1244 signed_data);
1246 out:
1247 hx509_certs_free(&certs);
1248 return ret;
1251 struct sigctx {
1252 SignedData sd;
1253 const AlgorithmIdentifier *digest_alg;
1254 const heim_oid *eContentType;
1255 heim_octet_string content;
1256 hx509_peer_info peer;
1257 int cmsidflag;
1258 int leafonly;
1259 hx509_certs certs;
1260 hx509_certs anchors;
1261 hx509_certs pool;
1264 static int HX509_LIB_CALL
1265 sig_process(hx509_context context, void *ctx, hx509_cert cert)
1267 struct sigctx *sigctx = ctx;
1268 heim_octet_string buf, sigdata = { 0, NULL };
1269 SignerInfo *signer_info = NULL;
1270 AlgorithmIdentifier digest;
1271 size_t size;
1272 void *ptr;
1273 int ret;
1274 SignedData *sd = &sigctx->sd;
1275 hx509_path path;
1277 memset(&digest, 0, sizeof(digest));
1278 memset(&path, 0, sizeof(path));
1280 if (_hx509_cert_private_key(cert) == NULL) {
1281 hx509_set_error_string(context, 0, HX509_PRIVATE_KEY_MISSING,
1282 "Private key missing for signing");
1283 return HX509_PRIVATE_KEY_MISSING;
1286 if (sigctx->digest_alg) {
1287 ret = copy_AlgorithmIdentifier(sigctx->digest_alg, &digest);
1288 if (ret)
1289 hx509_clear_error_string(context);
1290 } else {
1291 ret = hx509_crypto_select(context, HX509_SELECT_DIGEST,
1292 _hx509_cert_private_key(cert),
1293 sigctx->peer, &digest);
1295 if (ret)
1296 goto out;
1299 * Allocate on more signerInfo and do the signature processing
1302 ptr = realloc(sd->signerInfos.val,
1303 (sd->signerInfos.len + 1) * sizeof(sd->signerInfos.val[0]));
1304 if (ptr == NULL) {
1305 ret = ENOMEM;
1306 goto out;
1308 sd->signerInfos.val = ptr;
1310 signer_info = &sd->signerInfos.val[sd->signerInfos.len];
1312 memset(signer_info, 0, sizeof(*signer_info));
1314 signer_info->version = 1;
1316 ret = fill_CMSIdentifier(cert, sigctx->cmsidflag, &signer_info->sid);
1317 if (ret) {
1318 hx509_clear_error_string(context);
1319 goto out;
1322 signer_info->signedAttrs = NULL;
1323 signer_info->unsignedAttrs = NULL;
1325 ret = copy_AlgorithmIdentifier(&digest, &signer_info->digestAlgorithm);
1326 if (ret) {
1327 hx509_clear_error_string(context);
1328 goto out;
1332 * If it isn't pkcs7-data send signedAttributes
1335 if (der_heim_oid_cmp(sigctx->eContentType, &asn1_oid_id_pkcs7_data) != 0) {
1336 CMSAttributes sa;
1337 heim_octet_string sig;
1339 ALLOC(signer_info->signedAttrs, 1);
1340 if (signer_info->signedAttrs == NULL) {
1341 ret = ENOMEM;
1342 goto out;
1345 ret = _hx509_create_signature(context,
1346 NULL,
1347 &digest,
1348 &sigctx->content,
1349 NULL,
1350 &sig);
1351 if (ret)
1352 goto out;
1354 ASN1_MALLOC_ENCODE(MessageDigest,
1355 buf.data,
1356 buf.length,
1357 &sig,
1358 &size,
1359 ret);
1360 der_free_octet_string(&sig);
1361 if (ret) {
1362 hx509_clear_error_string(context);
1363 goto out;
1365 if (size != buf.length)
1366 _hx509_abort("internal ASN.1 encoder error");
1368 ret = add_one_attribute(&signer_info->signedAttrs->val,
1369 &signer_info->signedAttrs->len,
1370 &asn1_oid_id_pkcs9_messageDigest,
1371 &buf);
1372 if (ret) {
1373 free(buf.data);
1374 hx509_clear_error_string(context);
1375 goto out;
1379 ASN1_MALLOC_ENCODE(ContentType,
1380 buf.data,
1381 buf.length,
1382 sigctx->eContentType,
1383 &size,
1384 ret);
1385 if (ret)
1386 goto out;
1387 if (size != buf.length)
1388 _hx509_abort("internal ASN.1 encoder error");
1390 ret = add_one_attribute(&signer_info->signedAttrs->val,
1391 &signer_info->signedAttrs->len,
1392 &asn1_oid_id_pkcs9_contentType,
1393 &buf);
1394 if (ret) {
1395 free(buf.data);
1396 hx509_clear_error_string(context);
1397 goto out;
1400 sa.val = signer_info->signedAttrs->val;
1401 sa.len = signer_info->signedAttrs->len;
1403 ASN1_MALLOC_ENCODE(CMSAttributes,
1404 sigdata.data,
1405 sigdata.length,
1406 &sa,
1407 &size,
1408 ret);
1409 if (ret) {
1410 hx509_clear_error_string(context);
1411 goto out;
1413 if (size != sigdata.length)
1414 _hx509_abort("internal ASN.1 encoder error");
1415 } else {
1416 sigdata.data = sigctx->content.data;
1417 sigdata.length = sigctx->content.length;
1421 AlgorithmIdentifier sigalg;
1423 ret = hx509_crypto_select(context, HX509_SELECT_PUBLIC_SIG,
1424 _hx509_cert_private_key(cert), sigctx->peer,
1425 &sigalg);
1426 if (ret)
1427 goto out;
1429 ret = _hx509_create_signature(context,
1430 _hx509_cert_private_key(cert),
1431 &sigalg,
1432 &sigdata,
1433 &signer_info->signatureAlgorithm,
1434 &signer_info->signature);
1435 free_AlgorithmIdentifier(&sigalg);
1436 if (ret)
1437 goto out;
1440 sigctx->sd.signerInfos.len++;
1441 signer_info = NULL;
1444 * Provide best effort path
1446 if (sigctx->certs) {
1447 unsigned int i;
1449 if (sigctx->pool && sigctx->leafonly == 0) {
1450 _hx509_calculate_path(context,
1451 HX509_CALCULATE_PATH_NO_ANCHOR,
1452 time(NULL),
1453 sigctx->anchors,
1455 cert,
1456 sigctx->pool,
1457 &path);
1458 } else
1459 _hx509_path_append(context, &path, cert);
1461 for (i = 0; i < path.len; i++) {
1462 /* XXX remove dups */
1463 ret = hx509_certs_add(context, sigctx->certs, path.val[i]);
1464 if (ret) {
1465 hx509_clear_error_string(context);
1466 goto out;
1471 out:
1472 if (signer_info)
1473 free_SignerInfo(signer_info);
1474 if (sigdata.data != sigctx->content.data)
1475 der_free_octet_string(&sigdata);
1476 _hx509_path_free(&path);
1477 free_AlgorithmIdentifier(&digest);
1479 return ret;
1482 static int HX509_LIB_CALL
1483 cert_process(hx509_context context, void *ctx, hx509_cert cert)
1485 struct sigctx *sigctx = ctx;
1486 const unsigned int i = sigctx->sd.certificates->len;
1487 void *ptr;
1488 int ret;
1490 ptr = realloc(sigctx->sd.certificates->val,
1491 (i + 1) * sizeof(sigctx->sd.certificates->val[0]));
1492 if (ptr == NULL)
1493 return ENOMEM;
1494 sigctx->sd.certificates->val = ptr;
1496 ret = hx509_cert_binary(context, cert,
1497 &sigctx->sd.certificates->val[i]);
1498 if (ret == 0)
1499 sigctx->sd.certificates->len++;
1501 return ret;
1504 static int
1505 cmp_AlgorithmIdentifier(const AlgorithmIdentifier *p, const AlgorithmIdentifier *q)
1507 return der_heim_oid_cmp(&p->algorithm, &q->algorithm);
1510 HX509_LIB_FUNCTION int HX509_LIB_CALL
1511 hx509_cms_create_signed(hx509_context context,
1512 int flags,
1513 const heim_oid *eContentType,
1514 const void *data, size_t length,
1515 const AlgorithmIdentifier *digest_alg,
1516 hx509_certs certs,
1517 hx509_peer_info peer,
1518 hx509_certs anchors,
1519 hx509_certs pool,
1520 heim_octet_string *signed_data)
1522 unsigned int i, j;
1523 int ret;
1524 size_t size;
1525 struct sigctx sigctx;
1527 memset(&sigctx, 0, sizeof(sigctx));
1529 if (eContentType == NULL)
1530 eContentType = &asn1_oid_id_pkcs7_data;
1532 sigctx.digest_alg = digest_alg;
1533 sigctx.content.data = rk_UNCONST(data);
1534 sigctx.content.length = length;
1535 sigctx.eContentType = eContentType;
1536 sigctx.peer = peer;
1538 * Use HX509_CMS_SIGNATURE_ID_NAME to preferred use of issuer name
1539 * and serial number if possible. Otherwise subject key identifier
1540 * will preferred.
1542 if (flags & HX509_CMS_SIGNATURE_ID_NAME)
1543 sigctx.cmsidflag = CMS_ID_NAME;
1544 else
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);
1560 if (ret)
1561 return ret;
1564 sigctx.anchors = anchors;
1565 sigctx.pool = pool;
1567 sigctx.sd.version = cMSVersion_v3;
1569 ret = der_copy_oid(eContentType, &sigctx.sd.encapContentInfo.eContentType);
1570 if (ret)
1571 goto out;
1574 * Use HX509_CMS_SIGNATURE_DETACHED to create detached signatures.
1576 if ((flags & HX509_CMS_SIGNATURE_DETACHED) == 0) {
1577 ALLOC(sigctx.sd.encapContentInfo.eContent, 1);
1578 if (sigctx.sd.encapContentInfo.eContent == NULL) {
1579 hx509_clear_error_string(context);
1580 ret = ENOMEM;
1581 goto out;
1584 sigctx.sd.encapContentInfo.eContent->data = malloc(length);
1585 if (sigctx.sd.encapContentInfo.eContent->data == NULL) {
1586 hx509_clear_error_string(context);
1587 ret = ENOMEM;
1588 goto out;
1590 memcpy(sigctx.sd.encapContentInfo.eContent->data, data, length);
1591 sigctx.sd.encapContentInfo.eContent->length = length;
1595 * Use HX509_CMS_SIGNATURE_NO_SIGNER to create no sigInfo (no
1596 * signatures).
1598 if ((flags & HX509_CMS_SIGNATURE_NO_SIGNER) == 0) {
1599 ret = hx509_certs_iter_f(context, certs, sig_process, &sigctx);
1600 if (ret)
1601 goto out;
1604 if (sigctx.sd.signerInfos.len) {
1607 * For each signerInfo, collect all different digest types.
1609 for (i = 0; i < sigctx.sd.signerInfos.len; i++) {
1610 AlgorithmIdentifier *di =
1611 &sigctx.sd.signerInfos.val[i].digestAlgorithm;
1613 for (j = 0; j < sigctx.sd.digestAlgorithms.len; j++)
1614 if (cmp_AlgorithmIdentifier(di, &sigctx.sd.digestAlgorithms.val[j]) == 0)
1615 break;
1616 if (j == sigctx.sd.digestAlgorithms.len) {
1617 ret = add_DigestAlgorithmIdentifiers(&sigctx.sd.digestAlgorithms, di);
1618 if (ret) {
1619 hx509_clear_error_string(context);
1620 goto out;
1627 * Add certs we think are needed, build as part of sig_process
1629 if (sigctx.certs) {
1630 ALLOC(sigctx.sd.certificates, 1);
1631 if (sigctx.sd.certificates == NULL) {
1632 hx509_clear_error_string(context);
1633 ret = ENOMEM;
1634 goto out;
1637 ret = hx509_certs_iter_f(context, sigctx.certs, cert_process, &sigctx);
1638 if (ret)
1639 goto out;
1642 ASN1_MALLOC_ENCODE(SignedData,
1643 signed_data->data, signed_data->length,
1644 &sigctx.sd, &size, ret);
1645 if (ret) {
1646 hx509_clear_error_string(context);
1647 goto out;
1649 if (signed_data->length != size)
1650 _hx509_abort("internal ASN.1 encoder error");
1652 out:
1653 hx509_certs_free(&sigctx.certs);
1654 free_SignedData(&sigctx.sd);
1656 return ret;
1659 HX509_LIB_FUNCTION int HX509_LIB_CALL
1660 hx509_cms_decrypt_encrypted(hx509_context context,
1661 hx509_lock lock,
1662 const void *data,
1663 size_t length,
1664 heim_oid *contentType,
1665 heim_octet_string *content)
1667 heim_octet_string cont;
1668 CMSEncryptedData ed;
1669 AlgorithmIdentifier *ai;
1670 int ret;
1672 memset(content, 0, sizeof(*content));
1673 memset(&cont, 0, sizeof(cont));
1675 ret = decode_CMSEncryptedData(data, length, &ed, NULL);
1676 if (ret) {
1677 hx509_set_error_string(context, 0, ret,
1678 "Failed to decode CMSEncryptedData");
1679 return ret;
1682 if (ed.encryptedContentInfo.encryptedContent == NULL) {
1683 ret = HX509_CMS_NO_DATA_AVAILABLE;
1684 hx509_set_error_string(context, 0, ret,
1685 "No content in EncryptedData");
1686 goto out;
1689 ret = der_copy_oid(&ed.encryptedContentInfo.contentType, contentType);
1690 if (ret) {
1691 hx509_clear_error_string(context);
1692 goto out;
1695 ai = &ed.encryptedContentInfo.contentEncryptionAlgorithm;
1696 if (ai->parameters == NULL) {
1697 ret = HX509_ALG_NOT_SUPP;
1698 hx509_clear_error_string(context);
1699 goto out;
1702 ret = _hx509_pbe_decrypt(context,
1703 lock,
1705 ed.encryptedContentInfo.encryptedContent,
1706 &cont);
1707 if (ret)
1708 goto out;
1710 *content = cont;
1712 out:
1713 if (ret) {
1714 if (cont.data)
1715 free(cont.data);
1717 free_CMSEncryptedData(&ed);
1718 return ret;