kafs: Fix a warning
[heimdal.git] / lib / hx509 / cms.c
blobc38c2b98dc337c9d9c477641b80468fa068bfad6
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 flags show dthe
121 * diffrence 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 /* FALLTHROUGH */
186 fallthrough
187 case CMS_ID_NAME: {
188 hx509_name name;
190 id->element = choice_CMSIdentifier_issuerAndSerialNumber;
191 ret = hx509_cert_get_issuer(cert, &name);
192 if (ret)
193 return ret;
194 ret = hx509_name_to_Name(name, &id->u.issuerAndSerialNumber.issuer);
195 hx509_name_free(&name);
196 if (ret)
197 return ret;
199 ret = hx509_cert_get_serialnumber(cert, &id->u.issuerAndSerialNumber.serialNumber);
200 break;
202 default:
203 _hx509_abort("CMS fill identifier with unknown type");
205 return ret;
208 static int
209 unparse_CMSIdentifier(hx509_context context,
210 CMSIdentifier *id,
211 char **str)
213 int ret = -1;
215 *str = NULL;
216 switch (id->element) {
217 case choice_CMSIdentifier_issuerAndSerialNumber: {
218 IssuerAndSerialNumber *iasn;
219 char *serial, *name;
221 iasn = &id->u.issuerAndSerialNumber;
223 ret = _hx509_Name_to_string(&iasn->issuer, &name);
224 if(ret)
225 return ret;
226 ret = der_print_hex_heim_integer(&iasn->serialNumber, &serial);
227 if (ret) {
228 free(name);
229 return ret;
231 ret = asprintf(str, "certificate issued by %s with serial number %s",
232 name, serial);
233 free(name);
234 free(serial);
235 break;
237 case choice_CMSIdentifier_subjectKeyIdentifier: {
238 KeyIdentifier *ki = &id->u.subjectKeyIdentifier;
239 char *keyid;
240 ssize_t len;
242 len = hex_encode(ki->data, ki->length, &keyid);
243 if (len < 0)
244 return ENOMEM;
246 ret = asprintf(str, "certificate with id %s", keyid);
247 free(keyid);
248 break;
250 default:
251 ret = asprintf(str, "certificate have unknown CMSidentifier type");
252 break;
255 * In the following if, we check ret and *str which should be returned/set
256 * by asprintf(3) in every branch of the switch statement.
258 if (ret == -1 || *str == NULL)
259 return ENOMEM;
260 return 0;
263 static int
264 find_CMSIdentifier(hx509_context context,
265 CMSIdentifier *client,
266 hx509_certs certs,
267 time_t time_now,
268 hx509_cert *signer_cert,
269 int match)
271 hx509_query q;
272 hx509_cert cert;
273 Certificate c;
274 int ret;
276 memset(&c, 0, sizeof(c));
277 _hx509_query_clear(&q);
279 *signer_cert = NULL;
281 switch (client->element) {
282 case choice_CMSIdentifier_issuerAndSerialNumber:
283 q.serial = &client->u.issuerAndSerialNumber.serialNumber;
284 q.issuer_name = &client->u.issuerAndSerialNumber.issuer;
285 q.match = HX509_QUERY_MATCH_SERIALNUMBER|HX509_QUERY_MATCH_ISSUER_NAME;
286 break;
287 case choice_CMSIdentifier_subjectKeyIdentifier:
288 q.subject_id = &client->u.subjectKeyIdentifier;
289 q.match = HX509_QUERY_MATCH_SUBJECT_KEY_ID;
290 break;
291 default:
292 hx509_set_error_string(context, 0, HX509_CMS_NO_RECIPIENT_CERTIFICATE,
293 "unknown CMS identifier element");
294 return HX509_CMS_NO_RECIPIENT_CERTIFICATE;
297 q.match |= match;
299 q.match |= HX509_QUERY_MATCH_TIME;
300 if (time_now)
301 q.timenow = time_now;
302 else
303 q.timenow = time(NULL);
305 ret = hx509_certs_find(context, certs, &q, &cert);
306 if (ret == HX509_CERT_NOT_FOUND) {
307 char *str;
309 ret = unparse_CMSIdentifier(context, client, &str);
310 if (ret == 0) {
311 hx509_set_error_string(context, 0,
312 HX509_CMS_NO_RECIPIENT_CERTIFICATE,
313 "Failed to find %s", str);
314 } else
315 hx509_clear_error_string(context);
316 return HX509_CMS_NO_RECIPIENT_CERTIFICATE;
317 } else if (ret) {
318 hx509_set_error_string(context, HX509_ERROR_APPEND,
319 HX509_CMS_NO_RECIPIENT_CERTIFICATE,
320 "Failed to find CMS id in cert store");
321 return HX509_CMS_NO_RECIPIENT_CERTIFICATE;
324 *signer_cert = cert;
326 return 0;
330 * Decode and unencrypt EnvelopedData.
332 * Extract data and parameteres from from the EnvelopedData. Also
333 * supports using detached EnvelopedData.
335 * @param context A hx509 context.
336 * @param certs Certificate that can decrypt the EnvelopedData
337 * encryption key.
338 * @param flags HX509_CMS_UE flags to control the behavior.
339 * @param data pointer the structure the contains the DER/BER encoded
340 * EnvelopedData stucture.
341 * @param length length of the data that data point to.
342 * @param encryptedContent in case of detached signature, this
343 * contains the actual encrypted data, othersize its should be NULL.
344 * @param time_now set the current time, if zero the library uses now as the date.
345 * @param contentType output type oid, should be freed with der_free_oid().
346 * @param content the data, free with der_free_octet_string().
348 * @return an hx509 error code.
350 * @ingroup hx509_cms
353 HX509_LIB_FUNCTION int HX509_LIB_CALL
354 hx509_cms_unenvelope(hx509_context context,
355 hx509_certs certs,
356 int flags,
357 const void *data,
358 size_t length,
359 const heim_octet_string *encryptedContent,
360 time_t time_now,
361 heim_oid *contentType,
362 heim_octet_string *content)
364 heim_octet_string key;
365 EnvelopedData ed;
366 hx509_cert cert;
367 AlgorithmIdentifier *ai;
368 const heim_octet_string *enccontent;
369 heim_octet_string *params, params_data;
370 heim_octet_string ivec;
371 size_t size;
372 int ret, matched = 0, findflags = 0;
373 size_t i;
376 memset(&key, 0, sizeof(key));
377 memset(&ed, 0, sizeof(ed));
378 memset(&ivec, 0, sizeof(ivec));
379 memset(content, 0, sizeof(*content));
380 memset(contentType, 0, sizeof(*contentType));
382 if ((flags & HX509_CMS_UE_DONT_REQUIRE_KU_ENCIPHERMENT) == 0)
383 findflags |= HX509_QUERY_KU_ENCIPHERMENT;
385 ret = decode_EnvelopedData(data, length, &ed, &size);
386 if (ret) {
387 hx509_set_error_string(context, 0, ret,
388 "Failed to decode EnvelopedData");
389 return ret;
392 if (ed.recipientInfos.len == 0) {
393 ret = HX509_CMS_NO_RECIPIENT_CERTIFICATE;
394 hx509_set_error_string(context, 0, ret,
395 "No recipient info in enveloped data");
396 goto out;
399 enccontent = ed.encryptedContentInfo.encryptedContent;
400 if (enccontent == NULL) {
401 if (encryptedContent == NULL) {
402 ret = HX509_CMS_NO_DATA_AVAILABLE;
403 hx509_set_error_string(context, 0, ret,
404 "Content missing from encrypted data");
405 goto out;
407 enccontent = encryptedContent;
408 } else if (encryptedContent != NULL) {
409 ret = HX509_CMS_NO_DATA_AVAILABLE;
410 hx509_set_error_string(context, 0, ret,
411 "Both internal and external encrypted data");
412 goto out;
415 cert = NULL;
416 for (i = 0; i < ed.recipientInfos.len; i++) {
417 KeyTransRecipientInfo *ri;
418 char *str;
419 int ret2;
421 ri = &ed.recipientInfos.val[i];
423 ret = find_CMSIdentifier(context, &ri->rid, certs,
424 time_now, &cert,
425 HX509_QUERY_PRIVATE_KEY|findflags);
426 if (ret)
427 continue;
429 matched = 1; /* found a matching certificate, let decrypt */
431 ret = _hx509_cert_private_decrypt(context,
432 &ri->encryptedKey,
433 &ri->keyEncryptionAlgorithm.algorithm,
434 cert, &key);
436 hx509_cert_free(cert);
437 if (ret == 0)
438 break; /* succuessfully decrypted cert */
439 cert = NULL;
440 ret2 = unparse_CMSIdentifier(context, &ri->rid, &str);
441 if (ret2 == 0) {
442 hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
443 "Failed to decrypt with %s", str);
444 free(str);
448 if (!matched) {
449 ret = HX509_CMS_NO_RECIPIENT_CERTIFICATE;
450 hx509_set_error_string(context, 0, ret,
451 "No private key matched any certificate");
452 goto out;
455 if (cert == NULL) {
456 ret = HX509_CMS_NO_RECIPIENT_CERTIFICATE;
457 hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
458 "No private key decrypted the transfer key");
459 goto out;
462 ret = der_copy_oid(&ed.encryptedContentInfo.contentType, contentType);
463 if (ret) {
464 hx509_set_error_string(context, 0, ret,
465 "Failed to copy EnvelopedData content oid");
466 goto out;
469 ai = &ed.encryptedContentInfo.contentEncryptionAlgorithm;
470 if (ai->parameters) {
471 params_data.data = ai->parameters->data;
472 params_data.length = ai->parameters->length;
473 params = &params_data;
474 } else
475 params = NULL;
478 hx509_crypto crypto;
480 ret = hx509_crypto_init(context, NULL, &ai->algorithm, &crypto);
481 if (ret)
482 goto out;
484 if (flags & HX509_CMS_UE_ALLOW_WEAK)
485 hx509_crypto_allow_weak(crypto);
487 if (params) {
488 ret = hx509_crypto_set_params(context, crypto, params, &ivec);
489 if (ret) {
490 hx509_crypto_destroy(crypto);
491 goto out;
495 ret = hx509_crypto_set_key_data(crypto, key.data, key.length);
496 if (ret) {
497 hx509_crypto_destroy(crypto);
498 hx509_set_error_string(context, 0, ret,
499 "Failed to set key for decryption "
500 "of EnvelopedData");
501 goto out;
504 ret = hx509_crypto_decrypt(crypto,
505 enccontent->data,
506 enccontent->length,
507 ivec.length ? &ivec : NULL,
508 content);
509 hx509_crypto_destroy(crypto);
510 if (ret) {
511 hx509_set_error_string(context, 0, ret,
512 "Failed to decrypt EnvelopedData");
513 goto out;
517 out:
519 free_EnvelopedData(&ed);
520 der_free_octet_string(&key);
521 if (ivec.length)
522 der_free_octet_string(&ivec);
523 if (ret) {
524 der_free_oid(contentType);
525 der_free_octet_string(content);
528 return ret;
532 * Encrypt end encode EnvelopedData.
534 * Encrypt and encode EnvelopedData. The data is encrypted with a
535 * random key and the the random key is encrypted with the
536 * certificates private key. This limits what private key type can be
537 * used to RSA.
539 * @param context A hx509 context.
540 * @param flags flags to control the behavior.
541 * - HX509_CMS_EV_NO_KU_CHECK - Don't check KU on certificate
542 * - HX509_CMS_EV_ALLOW_WEAK - Allow weak crytpo
543 * - HX509_CMS_EV_ID_NAME - prefer issuer name and serial number
544 * @param cert Certificate to encrypt the EnvelopedData encryption key
545 * with.
546 * @param data pointer the data to encrypt.
547 * @param length length of the data that data point to.
548 * @param encryption_type Encryption cipher to use for the bulk data,
549 * use NULL to get default.
550 * @param contentType type of the data that is encrypted
551 * @param content the output of the function,
552 * free with der_free_octet_string().
554 * @return an hx509 error code.
556 * @ingroup hx509_cms
559 HX509_LIB_FUNCTION int HX509_LIB_CALL
560 hx509_cms_envelope_1(hx509_context context,
561 int flags,
562 hx509_cert cert,
563 const void *data,
564 size_t length,
565 const heim_oid *encryption_type,
566 const heim_oid *contentType,
567 heim_octet_string *content)
569 KeyTransRecipientInfo *ri;
570 heim_octet_string ivec;
571 heim_octet_string key;
572 hx509_crypto crypto = NULL;
573 int ret, cmsidflag;
574 EnvelopedData ed;
575 size_t size;
577 memset(&ivec, 0, sizeof(ivec));
578 memset(&key, 0, sizeof(key));
579 memset(&ed, 0, sizeof(ed));
580 memset(content, 0, sizeof(*content));
582 if (encryption_type == NULL)
583 encryption_type = &asn1_oid_id_aes_256_cbc;
585 if ((flags & HX509_CMS_EV_NO_KU_CHECK) == 0) {
586 ret = _hx509_check_key_usage(context, cert, 1 << 2, TRUE);
587 if (ret)
588 goto out;
591 ret = hx509_crypto_init(context, NULL, encryption_type, &crypto);
592 if (ret)
593 goto out;
595 if (flags & HX509_CMS_EV_ALLOW_WEAK)
596 hx509_crypto_allow_weak(crypto);
598 ret = hx509_crypto_set_random_key(crypto, &key);
599 if (ret) {
600 hx509_set_error_string(context, 0, ret,
601 "Create random key for EnvelopedData content");
602 goto out;
605 ret = hx509_crypto_random_iv(crypto, &ivec);
606 if (ret) {
607 hx509_set_error_string(context, 0, ret,
608 "Failed to create a random iv");
609 goto out;
612 ret = hx509_crypto_encrypt(crypto,
613 data,
614 length,
615 &ivec,
616 &ed.encryptedContentInfo.encryptedContent);
617 if (ret) {
618 hx509_set_error_string(context, 0, ret,
619 "Failed to encrypt EnvelopedData content");
620 goto out;
624 AlgorithmIdentifier *enc_alg;
625 enc_alg = &ed.encryptedContentInfo.contentEncryptionAlgorithm;
626 ret = der_copy_oid(encryption_type, &enc_alg->algorithm);
627 if (ret) {
628 hx509_set_error_string(context, 0, ret,
629 "Failed to set crypto oid "
630 "for EnvelopedData");
631 goto out;
633 ALLOC(enc_alg->parameters, 1);
634 if (enc_alg->parameters == NULL) {
635 ret = ENOMEM;
636 hx509_set_error_string(context, 0, ret,
637 "Failed to allocate crypto parameters "
638 "for EnvelopedData");
639 goto out;
642 ret = hx509_crypto_get_params(context,
643 crypto,
644 &ivec,
645 enc_alg->parameters);
646 if (ret) {
647 goto out;
651 ALLOC_SEQ(&ed.recipientInfos, 1);
652 if (ed.recipientInfos.val == NULL) {
653 ret = ENOMEM;
654 hx509_set_error_string(context, 0, ret,
655 "Failed to allocate recipients info "
656 "for EnvelopedData");
657 goto out;
660 ri = &ed.recipientInfos.val[0];
662 if (flags & HX509_CMS_EV_ID_NAME) {
663 ri->version = 0;
664 cmsidflag = CMS_ID_NAME;
665 } else {
666 ri->version = 2;
667 cmsidflag = CMS_ID_SKI;
670 ret = fill_CMSIdentifier(cert, cmsidflag, &ri->rid);
671 if (ret) {
672 hx509_set_error_string(context, 0, ret,
673 "Failed to set CMS identifier info "
674 "for EnvelopedData");
675 goto out;
678 ret = hx509_cert_public_encrypt(context,
679 &key, cert,
680 &ri->keyEncryptionAlgorithm.algorithm,
681 &ri->encryptedKey);
682 if (ret) {
683 hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
684 "Failed to encrypt transport key for "
685 "EnvelopedData");
686 goto out;
693 ed.version = 0;
694 ed.originatorInfo = NULL;
696 ret = der_copy_oid(contentType, &ed.encryptedContentInfo.contentType);
697 if (ret) {
698 hx509_set_error_string(context, 0, ret,
699 "Failed to copy content oid for "
700 "EnvelopedData");
701 goto out;
704 ed.unprotectedAttrs = NULL;
706 ASN1_MALLOC_ENCODE(EnvelopedData, content->data, content->length,
707 &ed, &size, ret);
708 if (ret) {
709 hx509_set_error_string(context, 0, ret,
710 "Failed to encode EnvelopedData");
711 goto out;
713 if (size != content->length)
714 _hx509_abort("internal ASN.1 encoder error");
716 out:
717 if (crypto)
718 hx509_crypto_destroy(crypto);
719 if (ret)
720 der_free_octet_string(content);
721 der_free_octet_string(&key);
722 der_free_octet_string(&ivec);
723 free_EnvelopedData(&ed);
725 return ret;
728 static int
729 any_to_certs(hx509_context context, const SignedData *sd, hx509_certs certs)
731 int ret;
732 size_t i;
734 if (sd->certificates == NULL)
735 return 0;
737 for (i = 0; i < sd->certificates->len; i++) {
738 heim_error_t error;
739 hx509_cert c;
741 c = hx509_cert_init_data(context,
742 sd->certificates->val[i].data,
743 sd->certificates->val[i].length,
744 &error);
745 if (c == NULL) {
746 ret = heim_error_get_code(error);
747 heim_release(error);
748 return ret;
750 ret = hx509_certs_add(context, certs, c);
751 hx509_cert_free(c);
752 if (ret)
753 return ret;
756 return 0;
759 static const Attribute *
760 find_attribute(const CMSAttributes *attr, const heim_oid *oid)
762 size_t i;
763 for (i = 0; i < attr->len; i++)
764 if (der_heim_oid_cmp(&attr->val[i].type, oid) == 0)
765 return &attr->val[i];
766 return NULL;
770 * Decode SignedData and verify that the signature is correct.
772 * @param context A hx509 context.
773 * @param ctx a hx509 verify context.
774 * @param flags to control the behaivor of the function.
775 * - HX509_CMS_VS_NO_KU_CHECK - Don't check KeyUsage
776 * - HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH - allow oid mismatch
777 * - HX509_CMS_VS_ALLOW_ZERO_SIGNER - no signer, see below.
778 * @param data pointer to CMS SignedData encoded data.
779 * @param length length of the data that data point to.
780 * @param signedContent external data used for signature.
781 * @param pool certificate pool to build certificates paths.
782 * @param contentType free with der_free_oid().
783 * @param content the output of the function, free with
784 * der_free_octet_string().
785 * @param signer_certs list of the cerficates used to sign this
786 * request, free with hx509_certs_free().
788 * @return an hx509 error code.
790 * @ingroup hx509_cms
793 HX509_LIB_FUNCTION int HX509_LIB_CALL
794 hx509_cms_verify_signed(hx509_context context,
795 hx509_verify_ctx ctx,
796 unsigned int flags,
797 const void *data,
798 size_t length,
799 const heim_octet_string *signedContent,
800 hx509_certs pool,
801 heim_oid *contentType,
802 heim_octet_string *content,
803 hx509_certs *signer_certs)
805 unsigned int verify_flags;
807 return hx509_cms_verify_signed_ext(context,
808 ctx,
809 flags,
810 data,
811 length,
812 signedContent,
813 pool,
814 contentType,
815 content,
816 signer_certs,
817 &verify_flags);
821 * Decode SignedData and verify that the signature is correct.
823 * @param context A hx509 context.
824 * @param ctx a hx509 verify context.
825 * @param flags to control the behaivor of the function.
826 * - HX509_CMS_VS_NO_KU_CHECK - Don't check KeyUsage
827 * - HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH - allow oid mismatch
828 * - HX509_CMS_VS_ALLOW_ZERO_SIGNER - no signer, see below.
829 * @param data pointer to CMS SignedData encoded data.
830 * @param length length of the data that data point to.
831 * @param signedContent external data used for signature.
832 * @param pool certificate pool to build certificates paths.
833 * @param contentType free with der_free_oid().
834 * @param content the output of the function, free with
835 * der_free_octet_string().
836 * @param signer_certs list of the cerficates used to sign this
837 * request, free with hx509_certs_free().
838 * @param verify_flags flags indicating whether the certificate
839 * was verified or not
841 * @return an hx509 error code.
843 * @ingroup hx509_cms
846 HX509_LIB_FUNCTION int HX509_LIB_CALL
847 hx509_cms_verify_signed_ext(hx509_context context,
848 hx509_verify_ctx ctx,
849 unsigned int flags,
850 const void *data,
851 size_t length,
852 const heim_octet_string *signedContent,
853 hx509_certs pool,
854 heim_oid *contentType,
855 heim_octet_string *content,
856 hx509_certs *signer_certs,
857 unsigned int *verify_flags)
859 SignerInfo *signer_info;
860 hx509_cert cert = NULL;
861 hx509_certs certs = NULL;
862 SignedData sd;
863 size_t size;
864 int ret, found_valid_sig;
865 size_t i;
867 *signer_certs = NULL;
868 *verify_flags = 0;
870 content->data = NULL;
871 content->length = 0;
872 contentType->length = 0;
873 contentType->components = NULL;
875 memset(&sd, 0, sizeof(sd));
877 ret = decode_SignedData(data, length, &sd, &size);
878 if (ret) {
879 hx509_set_error_string(context, 0, ret,
880 "Failed to decode SignedData");
881 goto out;
884 if (sd.encapContentInfo.eContent == NULL && signedContent == NULL) {
885 ret = HX509_CMS_NO_DATA_AVAILABLE;
886 hx509_set_error_string(context, 0, ret,
887 "No content data in SignedData");
888 goto out;
890 if (sd.encapContentInfo.eContent && signedContent) {
891 ret = HX509_CMS_NO_DATA_AVAILABLE;
892 hx509_set_error_string(context, 0, ret,
893 "Both external and internal SignedData");
894 goto out;
897 if (sd.encapContentInfo.eContent)
898 ret = der_copy_octet_string(sd.encapContentInfo.eContent, content);
899 else
900 ret = der_copy_octet_string(signedContent, content);
901 if (ret) {
902 hx509_set_error_string(context, 0, ret, "malloc: out of memory");
903 goto out;
906 ret = hx509_certs_init(context, "MEMORY:cms-cert-buffer",
907 0, NULL, &certs);
908 if (ret)
909 goto out;
911 ret = hx509_certs_init(context, "MEMORY:cms-signer-certs",
912 0, NULL, signer_certs);
913 if (ret)
914 goto out;
916 /* XXX Check CMS version */
918 ret = any_to_certs(context, &sd, certs);
919 if (ret)
920 goto out;
922 if (pool) {
923 ret = hx509_certs_merge(context, certs, pool);
924 if (ret)
925 goto out;
928 for (found_valid_sig = 0, i = 0; i < sd.signerInfos.len; i++) {
929 heim_octet_string signed_data = { 0, 0 };
930 const heim_oid *match_oid;
931 heim_oid decode_oid;
933 signer_info = &sd.signerInfos.val[i];
934 match_oid = NULL;
936 if (signer_info->signature.length == 0) {
937 ret = HX509_CMS_MISSING_SIGNER_DATA;
938 hx509_set_error_string(context, 0, ret,
939 "SignerInfo %d in SignedData "
940 "missing sigature", i);
941 continue;
944 ret = find_CMSIdentifier(context, &signer_info->sid, certs,
945 _hx509_verify_get_time(ctx), &cert,
946 HX509_QUERY_KU_DIGITALSIGNATURE);
947 if (ret) {
949 * If HX509_CMS_VS_NO_KU_CHECK is set, allow more liberal
950 * search for matching certificates by not considering
951 * KeyUsage bits on the certificates.
953 if ((flags & HX509_CMS_VS_NO_KU_CHECK) == 0)
954 continue;
956 ret = find_CMSIdentifier(context, &signer_info->sid, certs,
957 _hx509_verify_get_time(ctx), &cert,
959 if (ret)
960 continue;
964 if (signer_info->signedAttrs) {
965 const Attribute *attr;
967 CMSAttributes sa;
968 heim_octet_string os;
970 sa.val = signer_info->signedAttrs->val;
971 sa.len = signer_info->signedAttrs->len;
973 /* verify that sigature exists */
974 attr = find_attribute(&sa, &asn1_oid_id_pkcs9_messageDigest);
975 if (attr == NULL) {
976 ret = HX509_CRYPTO_SIGNATURE_MISSING;
977 hx509_set_error_string(context, 0, ret,
978 "SignerInfo have signed attributes "
979 "but messageDigest (signature) "
980 "is missing");
981 goto next_sigature;
983 if (attr->value.len != 1) {
984 ret = HX509_CRYPTO_SIGNATURE_MISSING;
985 hx509_set_error_string(context, 0, ret,
986 "SignerInfo have more then one "
987 "messageDigest (signature)");
988 goto next_sigature;
991 ret = decode_MessageDigest(attr->value.val[0].data,
992 attr->value.val[0].length,
993 &os,
994 &size);
995 if (ret) {
996 hx509_set_error_string(context, 0, ret,
997 "Failed to decode "
998 "messageDigest (signature)");
999 goto next_sigature;
1002 ret = _hx509_verify_signature(context,
1003 NULL,
1004 &signer_info->digestAlgorithm,
1005 content,
1006 &os);
1007 der_free_octet_string(&os);
1008 if (ret) {
1009 hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
1010 "Failed to verify messageDigest");
1011 goto next_sigature;
1015 * Fetch content oid inside signedAttrs or set it to
1016 * id-pkcs7-data.
1018 attr = find_attribute(&sa, &asn1_oid_id_pkcs9_contentType);
1019 if (attr == NULL) {
1020 match_oid = &asn1_oid_id_pkcs7_data;
1021 } else {
1022 if (attr->value.len != 1) {
1023 ret = HX509_CMS_DATA_OID_MISMATCH;
1024 hx509_set_error_string(context, 0, ret,
1025 "More then one oid in signedAttrs");
1026 goto next_sigature;
1029 ret = decode_ContentType(attr->value.val[0].data,
1030 attr->value.val[0].length,
1031 &decode_oid,
1032 &size);
1033 if (ret) {
1034 hx509_set_error_string(context, 0, ret,
1035 "Failed to decode "
1036 "oid in signedAttrs");
1037 goto next_sigature;
1039 match_oid = &decode_oid;
1042 ASN1_MALLOC_ENCODE(CMSAttributes,
1043 signed_data.data,
1044 signed_data.length,
1045 &sa,
1046 &size, ret);
1047 if (ret) {
1048 if (match_oid == &decode_oid)
1049 der_free_oid(&decode_oid);
1050 hx509_clear_error_string(context);
1051 goto next_sigature;
1053 if (size != signed_data.length)
1054 _hx509_abort("internal ASN.1 encoder error");
1056 } else {
1057 signed_data.data = content->data;
1058 signed_data.length = content->length;
1059 match_oid = &asn1_oid_id_pkcs7_data;
1063 * If HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH, allow
1064 * encapContentInfo mismatch with the oid in signedAttributes
1065 * (or if no signedAttributes where use, pkcs7-data oid).
1066 * This is only needed to work with broken CMS implementations
1067 * that doesn't follow CMS signedAttributes rules.
1070 if (der_heim_oid_cmp(match_oid, &sd.encapContentInfo.eContentType) &&
1071 (flags & HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH) == 0) {
1072 ret = HX509_CMS_DATA_OID_MISMATCH;
1073 hx509_set_error_string(context, 0, ret,
1074 "Oid in message mismatch from the expected");
1076 if (match_oid == &decode_oid)
1077 der_free_oid(&decode_oid);
1079 if (ret == 0) {
1080 ret = hx509_verify_signature(context,
1081 cert,
1082 &signer_info->signatureAlgorithm,
1083 &signed_data,
1084 &signer_info->signature);
1085 if (ret)
1086 hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
1087 "Failed to verify signature in "
1088 "CMS SignedData");
1090 if (signed_data.data != NULL && content->data != signed_data.data) {
1091 free(signed_data.data);
1092 signed_data.data = NULL;
1094 if (ret)
1095 goto next_sigature;
1098 * If HX509_CMS_VS_NO_VALIDATE flags is set, return the signer
1099 * certificate unconditionally but do not set HX509_CMS_VSE_VALIDATED.
1101 ret = hx509_verify_path(context, ctx, cert, certs);
1102 if (ret == 0 || (flags & HX509_CMS_VS_NO_VALIDATE)) {
1103 if (ret == 0)
1104 *verify_flags |= HX509_CMS_VSE_VALIDATED;
1106 ret = hx509_certs_add(context, *signer_certs, cert);
1107 if (ret == 0)
1108 found_valid_sig++;
1111 next_sigature:
1112 if (cert)
1113 hx509_cert_free(cert);
1114 cert = NULL;
1117 * If HX509_CMS_VS_ALLOW_ZERO_SIGNER is set, allow empty
1118 * SignerInfo (no signatures). If SignedData have no signatures,
1119 * the function will return 0 with signer_certs set to NULL. Zero
1120 * signers is allowed by the standard, but since its only useful
1121 * in corner cases, it make into a flag that the caller have to
1122 * turn on.
1124 if (sd.signerInfos.len == 0 && (flags & HX509_CMS_VS_ALLOW_ZERO_SIGNER)) {
1125 if (*signer_certs)
1126 hx509_certs_free(signer_certs);
1127 } else if (found_valid_sig == 0) {
1128 if (ret == 0) {
1129 ret = HX509_CMS_SIGNER_NOT_FOUND;
1130 hx509_set_error_string(context, 0, ret,
1131 "No signers where found");
1133 goto out;
1136 ret = der_copy_oid(&sd.encapContentInfo.eContentType, contentType);
1137 if (ret) {
1138 hx509_clear_error_string(context);
1139 goto out;
1142 out:
1143 free_SignedData(&sd);
1144 if (certs)
1145 hx509_certs_free(&certs);
1146 if (ret) {
1147 if (content->data)
1148 der_free_octet_string(content);
1149 if (*signer_certs)
1150 hx509_certs_free(signer_certs);
1151 der_free_oid(contentType);
1152 der_free_octet_string(content);
1155 return ret;
1158 static int
1159 add_one_attribute(Attribute **attr,
1160 unsigned int *len,
1161 const heim_oid *oid,
1162 heim_octet_string *data)
1164 void *d;
1165 int ret;
1167 d = realloc(*attr, sizeof((*attr)[0]) * (*len + 1));
1168 if (d == NULL)
1169 return ENOMEM;
1170 (*attr) = d;
1172 ret = der_copy_oid(oid, &(*attr)[*len].type);
1173 if (ret)
1174 return ret;
1176 ALLOC_SEQ(&(*attr)[*len].value, 1);
1177 if ((*attr)[*len].value.val == NULL) {
1178 der_free_oid(&(*attr)[*len].type);
1179 return ENOMEM;
1182 (*attr)[*len].value.val[0].data = data->data;
1183 (*attr)[*len].value.val[0].length = data->length;
1185 *len += 1;
1187 return 0;
1191 * Decode SignedData and verify that the signature is correct.
1193 * @param context A hx509 context.
1194 * @param flags
1195 * @param eContentType the type of the data.
1196 * @param data data to sign
1197 * @param length length of the data that data point to.
1198 * @param digest_alg digest algorithm to use, use NULL to get the
1199 * default or the peer determined algorithm.
1200 * @param cert certificate to use for sign the data.
1201 * @param peer info about the peer the message to send the message to,
1202 * like what digest algorithm to use.
1203 * @param anchors trust anchors that the client will use, used to
1204 * polulate the certificates included in the message
1205 * @param pool certificates to use in try to build the path to the
1206 * trust anchors.
1207 * @param signed_data the output of the function, free with
1208 * der_free_octet_string().
1210 * @return Returns an hx509 error code.
1212 * @ingroup hx509_cms
1215 HX509_LIB_FUNCTION int HX509_LIB_CALL
1216 hx509_cms_create_signed_1(hx509_context context,
1217 int flags,
1218 const heim_oid *eContentType,
1219 const void *data, size_t length,
1220 const AlgorithmIdentifier *digest_alg,
1221 hx509_cert cert,
1222 hx509_peer_info peer,
1223 hx509_certs anchors,
1224 hx509_certs pool,
1225 heim_octet_string *signed_data)
1227 hx509_certs certs;
1228 int ret = 0;
1230 signed_data->data = NULL;
1231 signed_data->length = 0;
1233 ret = hx509_certs_init(context, "MEMORY:certs", 0, NULL, &certs);
1234 if (ret)
1235 return ret;
1236 ret = hx509_certs_add(context, certs, cert);
1237 if (ret)
1238 goto out;
1240 ret = hx509_cms_create_signed(context, flags, eContentType, data, length,
1241 digest_alg, certs, peer, anchors, pool,
1242 signed_data);
1244 out:
1245 hx509_certs_free(&certs);
1246 return ret;
1249 struct sigctx {
1250 SignedData sd;
1251 const AlgorithmIdentifier *digest_alg;
1252 const heim_oid *eContentType;
1253 heim_octet_string content;
1254 hx509_peer_info peer;
1255 int cmsidflag;
1256 int leafonly;
1257 hx509_certs certs;
1258 hx509_certs anchors;
1259 hx509_certs pool;
1262 static int HX509_LIB_CALL
1263 sig_process(hx509_context context, void *ctx, hx509_cert cert)
1265 struct sigctx *sigctx = ctx;
1266 heim_octet_string buf, sigdata = { 0, NULL };
1267 SignerInfo *signer_info = NULL;
1268 AlgorithmIdentifier digest;
1269 size_t size;
1270 void *ptr;
1271 int ret;
1272 SignedData *sd = &sigctx->sd;
1273 hx509_path path;
1275 memset(&digest, 0, sizeof(digest));
1276 memset(&path, 0, sizeof(path));
1278 if (_hx509_cert_private_key(cert) == NULL) {
1279 hx509_set_error_string(context, 0, HX509_PRIVATE_KEY_MISSING,
1280 "Private key missing for signing");
1281 return HX509_PRIVATE_KEY_MISSING;
1284 if (sigctx->digest_alg) {
1285 ret = copy_AlgorithmIdentifier(sigctx->digest_alg, &digest);
1286 if (ret)
1287 hx509_clear_error_string(context);
1288 } else {
1289 ret = hx509_crypto_select(context, HX509_SELECT_DIGEST,
1290 _hx509_cert_private_key(cert),
1291 sigctx->peer, &digest);
1293 if (ret)
1294 goto out;
1297 * Allocate on more signerInfo and do the signature processing
1300 ptr = realloc(sd->signerInfos.val,
1301 (sd->signerInfos.len + 1) * sizeof(sd->signerInfos.val[0]));
1302 if (ptr == NULL) {
1303 ret = ENOMEM;
1304 goto out;
1306 sd->signerInfos.val = ptr;
1308 signer_info = &sd->signerInfos.val[sd->signerInfos.len];
1310 memset(signer_info, 0, sizeof(*signer_info));
1312 signer_info->version = 1;
1314 ret = fill_CMSIdentifier(cert, sigctx->cmsidflag, &signer_info->sid);
1315 if (ret) {
1316 hx509_clear_error_string(context);
1317 goto out;
1320 signer_info->signedAttrs = NULL;
1321 signer_info->unsignedAttrs = NULL;
1323 ret = copy_AlgorithmIdentifier(&digest, &signer_info->digestAlgorithm);
1324 if (ret) {
1325 hx509_clear_error_string(context);
1326 goto out;
1330 * If it isn't pkcs7-data send signedAttributes
1333 if (der_heim_oid_cmp(sigctx->eContentType, &asn1_oid_id_pkcs7_data) != 0) {
1334 CMSAttributes sa;
1335 heim_octet_string sig;
1337 ALLOC(signer_info->signedAttrs, 1);
1338 if (signer_info->signedAttrs == NULL) {
1339 ret = ENOMEM;
1340 goto out;
1343 ret = _hx509_create_signature(context,
1344 NULL,
1345 &digest,
1346 &sigctx->content,
1347 NULL,
1348 &sig);
1349 if (ret)
1350 goto out;
1352 ASN1_MALLOC_ENCODE(MessageDigest,
1353 buf.data,
1354 buf.length,
1355 &sig,
1356 &size,
1357 ret);
1358 der_free_octet_string(&sig);
1359 if (ret) {
1360 hx509_clear_error_string(context);
1361 goto out;
1363 if (size != buf.length)
1364 _hx509_abort("internal ASN.1 encoder error");
1366 ret = add_one_attribute(&signer_info->signedAttrs->val,
1367 &signer_info->signedAttrs->len,
1368 &asn1_oid_id_pkcs9_messageDigest,
1369 &buf);
1370 if (ret) {
1371 free(buf.data);
1372 hx509_clear_error_string(context);
1373 goto out;
1377 ASN1_MALLOC_ENCODE(ContentType,
1378 buf.data,
1379 buf.length,
1380 sigctx->eContentType,
1381 &size,
1382 ret);
1383 if (ret)
1384 goto out;
1385 if (size != buf.length)
1386 _hx509_abort("internal ASN.1 encoder error");
1388 ret = add_one_attribute(&signer_info->signedAttrs->val,
1389 &signer_info->signedAttrs->len,
1390 &asn1_oid_id_pkcs9_contentType,
1391 &buf);
1392 if (ret) {
1393 free(buf.data);
1394 hx509_clear_error_string(context);
1395 goto out;
1398 sa.val = signer_info->signedAttrs->val;
1399 sa.len = signer_info->signedAttrs->len;
1401 ASN1_MALLOC_ENCODE(CMSAttributes,
1402 sigdata.data,
1403 sigdata.length,
1404 &sa,
1405 &size,
1406 ret);
1407 if (ret) {
1408 hx509_clear_error_string(context);
1409 goto out;
1411 if (size != sigdata.length)
1412 _hx509_abort("internal ASN.1 encoder error");
1413 } else {
1414 sigdata.data = sigctx->content.data;
1415 sigdata.length = sigctx->content.length;
1419 AlgorithmIdentifier sigalg;
1421 ret = hx509_crypto_select(context, HX509_SELECT_PUBLIC_SIG,
1422 _hx509_cert_private_key(cert), sigctx->peer,
1423 &sigalg);
1424 if (ret)
1425 goto out;
1427 ret = _hx509_create_signature(context,
1428 _hx509_cert_private_key(cert),
1429 &sigalg,
1430 &sigdata,
1431 &signer_info->signatureAlgorithm,
1432 &signer_info->signature);
1433 free_AlgorithmIdentifier(&sigalg);
1434 if (ret)
1435 goto out;
1438 sigctx->sd.signerInfos.len++;
1439 signer_info = NULL;
1442 * Provide best effort path
1444 if (sigctx->certs) {
1445 unsigned int i;
1447 if (sigctx->pool && sigctx->leafonly == 0) {
1448 _hx509_calculate_path(context,
1449 HX509_CALCULATE_PATH_NO_ANCHOR,
1450 time(NULL),
1451 sigctx->anchors,
1453 cert,
1454 sigctx->pool,
1455 &path);
1456 } else
1457 _hx509_path_append(context, &path, cert);
1459 for (i = 0; i < path.len; i++) {
1460 /* XXX remove dups */
1461 ret = hx509_certs_add(context, sigctx->certs, path.val[i]);
1462 if (ret) {
1463 hx509_clear_error_string(context);
1464 goto out;
1469 out:
1470 if (signer_info)
1471 free_SignerInfo(signer_info);
1472 if (sigdata.data != sigctx->content.data)
1473 der_free_octet_string(&sigdata);
1474 _hx509_path_free(&path);
1475 free_AlgorithmIdentifier(&digest);
1477 return ret;
1480 static int HX509_LIB_CALL
1481 cert_process(hx509_context context, void *ctx, hx509_cert cert)
1483 struct sigctx *sigctx = ctx;
1484 const unsigned int i = sigctx->sd.certificates->len;
1485 void *ptr;
1486 int ret;
1488 ptr = realloc(sigctx->sd.certificates->val,
1489 (i + 1) * sizeof(sigctx->sd.certificates->val[0]));
1490 if (ptr == NULL)
1491 return ENOMEM;
1492 sigctx->sd.certificates->val = ptr;
1494 ret = hx509_cert_binary(context, cert,
1495 &sigctx->sd.certificates->val[i]);
1496 if (ret == 0)
1497 sigctx->sd.certificates->len++;
1499 return ret;
1502 static int
1503 cmp_AlgorithmIdentifier(const AlgorithmIdentifier *p, const AlgorithmIdentifier *q)
1505 return der_heim_oid_cmp(&p->algorithm, &q->algorithm);
1508 HX509_LIB_FUNCTION int HX509_LIB_CALL
1509 hx509_cms_create_signed(hx509_context context,
1510 int flags,
1511 const heim_oid *eContentType,
1512 const void *data, size_t length,
1513 const AlgorithmIdentifier *digest_alg,
1514 hx509_certs certs,
1515 hx509_peer_info peer,
1516 hx509_certs anchors,
1517 hx509_certs pool,
1518 heim_octet_string *signed_data)
1520 unsigned int i, j;
1521 hx509_name name;
1522 int ret;
1523 size_t size;
1524 struct sigctx sigctx;
1526 memset(&sigctx, 0, sizeof(sigctx));
1527 memset(&name, 0, sizeof(name));
1529 if (eContentType == NULL)
1530 eContentType = &asn1_oid_id_pkcs7_data;
1532 sigctx.digest_alg = digest_alg;
1533 sigctx.content.data = rk_UNCONST(data);
1534 sigctx.content.length = length;
1535 sigctx.eContentType = eContentType;
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 der_copy_oid(eContentType, &sigctx.sd.encapContentInfo.eContentType);
1572 * Use HX509_CMS_SIGNATURE_DETACHED to create detached signatures.
1574 if ((flags & HX509_CMS_SIGNATURE_DETACHED) == 0) {
1575 ALLOC(sigctx.sd.encapContentInfo.eContent, 1);
1576 if (sigctx.sd.encapContentInfo.eContent == NULL) {
1577 hx509_clear_error_string(context);
1578 ret = ENOMEM;
1579 goto out;
1582 sigctx.sd.encapContentInfo.eContent->data = malloc(length);
1583 if (sigctx.sd.encapContentInfo.eContent->data == NULL) {
1584 hx509_clear_error_string(context);
1585 ret = ENOMEM;
1586 goto out;
1588 memcpy(sigctx.sd.encapContentInfo.eContent->data, data, length);
1589 sigctx.sd.encapContentInfo.eContent->length = length;
1593 * Use HX509_CMS_SIGNATURE_NO_SIGNER to create no sigInfo (no
1594 * signatures).
1596 if ((flags & HX509_CMS_SIGNATURE_NO_SIGNER) == 0) {
1597 ret = hx509_certs_iter_f(context, certs, sig_process, &sigctx);
1598 if (ret)
1599 goto out;
1602 if (sigctx.sd.signerInfos.len) {
1605 * For each signerInfo, collect all different digest types.
1607 for (i = 0; i < sigctx.sd.signerInfos.len; i++) {
1608 AlgorithmIdentifier *di =
1609 &sigctx.sd.signerInfos.val[i].digestAlgorithm;
1611 for (j = 0; j < sigctx.sd.digestAlgorithms.len; j++)
1612 if (cmp_AlgorithmIdentifier(di, &sigctx.sd.digestAlgorithms.val[j]) == 0)
1613 break;
1614 if (j == sigctx.sd.digestAlgorithms.len) {
1615 ret = add_DigestAlgorithmIdentifiers(&sigctx.sd.digestAlgorithms, di);
1616 if (ret) {
1617 hx509_clear_error_string(context);
1618 goto out;
1625 * Add certs we think are needed, build as part of sig_process
1627 if (sigctx.certs) {
1628 ALLOC(sigctx.sd.certificates, 1);
1629 if (sigctx.sd.certificates == NULL) {
1630 hx509_clear_error_string(context);
1631 ret = ENOMEM;
1632 goto out;
1635 ret = hx509_certs_iter_f(context, sigctx.certs, cert_process, &sigctx);
1636 if (ret)
1637 goto out;
1640 ASN1_MALLOC_ENCODE(SignedData,
1641 signed_data->data, signed_data->length,
1642 &sigctx.sd, &size, ret);
1643 if (ret) {
1644 hx509_clear_error_string(context);
1645 goto out;
1647 if (signed_data->length != size)
1648 _hx509_abort("internal ASN.1 encoder error");
1650 out:
1651 hx509_certs_free(&sigctx.certs);
1652 free_SignedData(&sigctx.sd);
1654 return ret;
1657 HX509_LIB_FUNCTION int HX509_LIB_CALL
1658 hx509_cms_decrypt_encrypted(hx509_context context,
1659 hx509_lock lock,
1660 const void *data,
1661 size_t length,
1662 heim_oid *contentType,
1663 heim_octet_string *content)
1665 heim_octet_string cont;
1666 CMSEncryptedData ed;
1667 AlgorithmIdentifier *ai;
1668 int ret;
1670 memset(content, 0, sizeof(*content));
1671 memset(&cont, 0, sizeof(cont));
1673 ret = decode_CMSEncryptedData(data, length, &ed, NULL);
1674 if (ret) {
1675 hx509_set_error_string(context, 0, ret,
1676 "Failed to decode CMSEncryptedData");
1677 return ret;
1680 if (ed.encryptedContentInfo.encryptedContent == NULL) {
1681 ret = HX509_CMS_NO_DATA_AVAILABLE;
1682 hx509_set_error_string(context, 0, ret,
1683 "No content in EncryptedData");
1684 goto out;
1687 ret = der_copy_oid(&ed.encryptedContentInfo.contentType, contentType);
1688 if (ret) {
1689 hx509_clear_error_string(context);
1690 goto out;
1693 ai = &ed.encryptedContentInfo.contentEncryptionAlgorithm;
1694 if (ai->parameters == NULL) {
1695 ret = HX509_ALG_NOT_SUPP;
1696 hx509_clear_error_string(context);
1697 goto out;
1700 ret = _hx509_pbe_decrypt(context,
1701 lock,
1703 ed.encryptedContentInfo.encryptedContent,
1704 &cont);
1705 if (ret)
1706 goto out;
1708 *content = cont;
1710 out:
1711 if (ret) {
1712 if (cont.data)
1713 free(cont.data);
1715 free_CMSEncryptedData(&ed);
1716 return ret;