xref: /openbsd/lib/libcrypto/cms/cms_sd.c (revision 379777c0)
1 /* $OpenBSD: cms_sd.c,v 1.29 2023/10/18 07:30:49 tb Exp $ */
2 /*
3  * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
4  * project.
5  */
6 /* ====================================================================
7  * Copyright (c) 2008 The OpenSSL Project.  All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in
18  *    the documentation and/or other materials provided with the
19  *    distribution.
20  *
21  * 3. All advertising materials mentioning features or use of this
22  *    software must display the following acknowledgment:
23  *    "This product includes software developed by the OpenSSL Project
24  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
25  *
26  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
27  *    endorse or promote products derived from this software without
28  *    prior written permission. For written permission, please contact
29  *    licensing@OpenSSL.org.
30  *
31  * 5. Products derived from this software may not be called "OpenSSL"
32  *    nor may "OpenSSL" appear in their names without prior written
33  *    permission of the OpenSSL Project.
34  *
35  * 6. Redistributions of any form whatsoever must retain the following
36  *    acknowledgment:
37  *    "This product includes software developed by the OpenSSL Project
38  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
41  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
44  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
46  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
49  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
50  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
51  * OF THE POSSIBILITY OF SUCH DAMAGE.
52  * ====================================================================
53  */
54 
55 #include <stdlib.h>
56 #include <string.h>
57 
58 #include <openssl/asn1.h>
59 #include <openssl/bio.h>
60 #include <openssl/err.h>
61 #include <openssl/evp.h>
62 #include <openssl/cms.h>
63 #include <openssl/objects.h>
64 #include <openssl/x509.h>
65 #include <openssl/x509v3.h>
66 
67 #include "asn1_local.h"
68 #include "cms_local.h"
69 #include "evp_local.h"
70 #include "x509_local.h"
71 
72 /* CMS SignedData Utilities */
73 
74 static CMS_SignedData *
75 cms_get0_signed(CMS_ContentInfo *cms)
76 {
77 	if (OBJ_obj2nid(cms->contentType) != NID_pkcs7_signed) {
78 		CMSerror(CMS_R_CONTENT_TYPE_NOT_SIGNED_DATA);
79 		return NULL;
80 	}
81 	return cms->d.signedData;
82 }
83 
84 static CMS_SignedData *
85 cms_signed_data_init(CMS_ContentInfo *cms)
86 {
87 	if (cms->d.other == NULL) {
88 		cms->d.signedData = (CMS_SignedData *)ASN1_item_new(&CMS_SignedData_it);
89 		if (!cms->d.signedData) {
90 			CMSerror(ERR_R_MALLOC_FAILURE);
91 			return NULL;
92 		}
93 		cms->d.signedData->version = 1;
94 		cms->d.signedData->encapContentInfo->eContentType =
95 		    OBJ_nid2obj(NID_pkcs7_data);
96 		cms->d.signedData->encapContentInfo->partial = 1;
97 		ASN1_OBJECT_free(cms->contentType);
98 		cms->contentType = OBJ_nid2obj(NID_pkcs7_signed);
99 		return cms->d.signedData;
100 	}
101 	return cms_get0_signed(cms);
102 }
103 
104 /* Just initialise SignedData e.g. for certs only structure */
105 
106 int
107 CMS_SignedData_init(CMS_ContentInfo *cms)
108 {
109 	if (cms_signed_data_init(cms))
110 		return 1;
111 	else
112 		return 0;
113 }
114 LCRYPTO_ALIAS(CMS_SignedData_init);
115 
116 /* Check structures and fixup version numbers (if necessary) */
117 
118 static void
119 cms_sd_set_version(CMS_SignedData *sd)
120 {
121 	int i;
122 	CMS_CertificateChoices *cch;
123 	CMS_RevocationInfoChoice *rch;
124 	CMS_SignerInfo *si;
125 
126 	for (i = 0; i < sk_CMS_CertificateChoices_num(sd->certificates); i++) {
127 		cch = sk_CMS_CertificateChoices_value(sd->certificates, i);
128 		if (cch->type == CMS_CERTCHOICE_OTHER) {
129 			if (sd->version < 5)
130 			    sd->version = 5;
131 		} else if (cch->type == CMS_CERTCHOICE_V2ACERT) {
132 			if (sd->version < 4)
133 			    sd->version = 4;
134 		} else if (cch->type == CMS_CERTCHOICE_V1ACERT) {
135 			if (sd->version < 3)
136 			    sd->version = 3;
137 		}
138 	}
139 
140 	for (i = 0; i < sk_CMS_RevocationInfoChoice_num(sd->crls); i++) {
141 		rch = sk_CMS_RevocationInfoChoice_value(sd->crls, i);
142 		if (rch->type == CMS_REVCHOICE_OTHER) {
143 			if (sd->version < 5)
144 			    sd->version = 5;
145 		}
146 	}
147 
148 	if ((OBJ_obj2nid(sd->encapContentInfo->eContentType) != NID_pkcs7_data)
149 		&& (sd->version < 3))
150 		sd->version = 3;
151 
152 	for (i = 0; i < sk_CMS_SignerInfo_num(sd->signerInfos); i++) {
153 		si = sk_CMS_SignerInfo_value(sd->signerInfos, i);
154 		if (si->sid->type == CMS_SIGNERINFO_KEYIDENTIFIER) {
155 			if (si->version < 3)
156 			    si->version = 3;
157 			if (sd->version < 3)
158 			    sd->version = 3;
159 		} else if (si->version < 1)
160 			si->version = 1;
161 	}
162 
163 	if (sd->version < 1)
164 		sd->version = 1;
165 }
166 
167 /* Copy an existing messageDigest value */
168 
169 static int
170 cms_copy_messageDigest(CMS_ContentInfo *cms, CMS_SignerInfo *si)
171 {
172 	STACK_OF(CMS_SignerInfo) *sinfos;
173 	CMS_SignerInfo *sitmp;
174 	int i;
175 
176 	sinfos = CMS_get0_SignerInfos(cms);
177 	for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) {
178 		ASN1_OCTET_STRING *messageDigest;
179 		sitmp = sk_CMS_SignerInfo_value(sinfos, i);
180 		if (sitmp == si)
181 			continue;
182 		if (CMS_signed_get_attr_count(sitmp) < 0)
183 			continue;
184 		if (OBJ_cmp(si->digestAlgorithm->algorithm,
185 		    sitmp->digestAlgorithm->algorithm))
186 			continue;
187 		messageDigest = CMS_signed_get0_data_by_OBJ(sitmp,
188 		    OBJ_nid2obj(NID_pkcs9_messageDigest), -3, V_ASN1_OCTET_STRING);
189 		if (!messageDigest) {
190 			CMSerror(CMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE);
191 			return 0;
192 		}
193 
194 		if (CMS_signed_add1_attr_by_NID(si, NID_pkcs9_messageDigest,
195 		    V_ASN1_OCTET_STRING, messageDigest, -1))
196 			return 1;
197 		else
198 			return 0;
199 	}
200 
201 	CMSerror(CMS_R_NO_MATCHING_DIGEST);
202 
203 	return 0;
204 }
205 
206 int
207 cms_set1_SignerIdentifier(CMS_SignerIdentifier *sid, X509 *cert, int type)
208 {
209 	switch (type) {
210 	case CMS_SIGNERINFO_ISSUER_SERIAL:
211 		if (!cms_set1_ias(&sid->d.issuerAndSerialNumber, cert))
212 			return 0;
213 		break;
214 
215 	case CMS_SIGNERINFO_KEYIDENTIFIER:
216 		if (!cms_set1_keyid(&sid->d.subjectKeyIdentifier, cert))
217 			return 0;
218 		break;
219 
220 	default:
221 		CMSerror(CMS_R_UNKNOWN_ID);
222 		return 0;
223 	}
224 
225 	sid->type = type;
226 
227 	return 1;
228 }
229 
230 int
231 cms_SignerIdentifier_get0_signer_id(CMS_SignerIdentifier *sid,
232     ASN1_OCTET_STRING **keyid, X509_NAME **issuer, ASN1_INTEGER **sno)
233 {
234 	if (sid->type == CMS_SIGNERINFO_ISSUER_SERIAL) {
235 		if (issuer)
236 			*issuer = sid->d.issuerAndSerialNumber->issuer;
237 		if (sno)
238 			*sno = sid->d.issuerAndSerialNumber->serialNumber;
239 	} else if (sid->type == CMS_SIGNERINFO_KEYIDENTIFIER) {
240 		if (keyid)
241 			*keyid = sid->d.subjectKeyIdentifier;
242 	} else
243 		return 0;
244 
245 	return 1;
246 }
247 
248 int
249 cms_SignerIdentifier_cert_cmp(CMS_SignerIdentifier *sid, X509 *cert)
250 {
251 	if (sid->type == CMS_SIGNERINFO_ISSUER_SERIAL)
252 		return cms_ias_cert_cmp(sid->d.issuerAndSerialNumber, cert);
253 	else if (sid->type == CMS_SIGNERINFO_KEYIDENTIFIER)
254 		return cms_keyid_cert_cmp(sid->d.subjectKeyIdentifier, cert);
255 	else
256 		return -1;
257 }
258 
259 static int
260 cms_sd_asn1_ctrl(CMS_SignerInfo *si, int cmd)
261 {
262 	EVP_PKEY *pkey = si->pkey;
263 	int ret;
264 
265 	if (pkey->ameth == NULL || pkey->ameth->pkey_ctrl == NULL)
266 		return 1;
267 	ret = pkey->ameth->pkey_ctrl(pkey, ASN1_PKEY_CTRL_CMS_SIGN, cmd, si);
268 	if (ret == -2) {
269 		CMSerror(CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE);
270 		return 0;
271 	}
272 	if (ret <= 0) {
273 		CMSerror(CMS_R_CTRL_FAILURE);
274 		return 0;
275 	}
276 
277 	return 1;
278 }
279 
280 CMS_SignerInfo *
281 CMS_add1_signer(CMS_ContentInfo *cms, X509 *signer, EVP_PKEY *pk,
282     const EVP_MD *md, unsigned int flags)
283 {
284 	CMS_SignedData *sd;
285 	CMS_SignerInfo *si = NULL;
286 	X509_ALGOR *alg = NULL;
287 	int i, type;
288 
289 	if (!X509_check_private_key(signer, pk)) {
290 		CMSerror(CMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE);
291 		return NULL;
292 	}
293 	sd = cms_signed_data_init(cms);
294 	if (!sd)
295 		goto err;
296 	si = (CMS_SignerInfo *)ASN1_item_new(&CMS_SignerInfo_it);
297 	if (!si)
298 		goto merr;
299 	/* Call for side-effect of computing hash and caching extensions */
300 	X509_check_purpose(signer, -1, -1);
301 
302 	X509_up_ref(signer);
303 	EVP_PKEY_up_ref(pk);
304 
305 	si->pkey = pk;
306 	si->signer = signer;
307 	si->mctx = EVP_MD_CTX_new();
308 	si->pctx = NULL;
309 
310 	if (si->mctx == NULL) {
311 		CMSerror(ERR_R_MALLOC_FAILURE);
312 		goto err;
313 	}
314 
315 	if (flags & CMS_USE_KEYID) {
316 		si->version = 3;
317 		if (sd->version < 3)
318 			sd->version = 3;
319 		type = CMS_SIGNERINFO_KEYIDENTIFIER;
320 	} else {
321 		type = CMS_SIGNERINFO_ISSUER_SERIAL;
322 		si->version = 1;
323 	}
324 
325 	if (!cms_set1_SignerIdentifier(si->sid, signer, type))
326 		goto err;
327 
328 	if (md == NULL) {
329 		int def_nid;
330 		if (EVP_PKEY_get_default_digest_nid(pk, &def_nid) <= 0)
331 			goto err;
332 		md = EVP_get_digestbynid(def_nid);
333 		if (md == NULL) {
334 			CMSerror(CMS_R_NO_DEFAULT_DIGEST);
335 			goto err;
336 		}
337 	}
338 
339 	if (!md) {
340 		CMSerror(CMS_R_NO_DIGEST_SET);
341 		goto err;
342 	}
343 
344 	if (!X509_ALGOR_set_evp_md(si->digestAlgorithm, md))
345 		goto err;
346 
347 	/* See if digest is present in digestAlgorithms */
348 	for (i = 0; i < sk_X509_ALGOR_num(sd->digestAlgorithms); i++) {
349 		const X509_ALGOR *x509_alg;
350 		const ASN1_OBJECT *aoid;
351 
352 		x509_alg = sk_X509_ALGOR_value(sd->digestAlgorithms, i);
353 		X509_ALGOR_get0(&aoid, NULL, NULL, x509_alg);
354 		if (OBJ_obj2nid(aoid) == EVP_MD_type(md))
355 			break;
356 	}
357 
358 	if (i == sk_X509_ALGOR_num(sd->digestAlgorithms)) {
359 		if ((alg = X509_ALGOR_new()) == NULL)
360 			goto merr;
361 		if (!X509_ALGOR_set_evp_md(alg, md))
362 			goto merr;
363 		if (!sk_X509_ALGOR_push(sd->digestAlgorithms, alg)) {
364 			goto merr;
365 		}
366 		alg = NULL;
367 	}
368 
369 	if (!(flags & CMS_KEY_PARAM) && !cms_sd_asn1_ctrl(si, 0))
370 		goto err;
371 	if (!(flags & CMS_NOATTR)) {
372 		/*
373 		 * Initialize signed attributes structure so other attributes
374 		 * such as signing time etc are added later even if we add none here.
375 		 */
376 		if (!si->signedAttrs) {
377 			si->signedAttrs = sk_X509_ATTRIBUTE_new_null();
378 			if (!si->signedAttrs)
379 				goto merr;
380 		}
381 
382 		if (!(flags & CMS_NOSMIMECAP)) {
383 			STACK_OF(X509_ALGOR) *smcap = NULL;
384 
385 			i = CMS_add_standard_smimecap(&smcap);
386 			if (i)
387 			    i = CMS_add_smimecap(si, smcap);
388 			sk_X509_ALGOR_pop_free(smcap, X509_ALGOR_free);
389 			if (!i)
390 				goto merr;
391 		}
392 		if (flags & CMS_REUSE_DIGEST) {
393 			if (!cms_copy_messageDigest(cms, si))
394 				goto err;
395 			if (!(flags & (CMS_PARTIAL | CMS_KEY_PARAM)) &&
396 			    !CMS_SignerInfo_sign(si))
397 				goto err;
398 		}
399 	}
400 
401 	if (!(flags & CMS_NOCERTS)) {
402 		/* NB ignore -1 return for duplicate cert */
403 		if (!CMS_add1_cert(cms, signer))
404 			goto merr;
405 	}
406 
407 	if (flags & CMS_KEY_PARAM) {
408 		if (flags & CMS_NOATTR) {
409 			si->pctx = EVP_PKEY_CTX_new(si->pkey, NULL);
410 			if (si->pctx == NULL)
411 				goto err;
412 			if (EVP_PKEY_sign_init(si->pctx) <= 0)
413 				goto err;
414 			if (EVP_PKEY_CTX_set_signature_md(si->pctx, md) <= 0)
415 				goto err;
416 		} else if (EVP_DigestSignInit(si->mctx, &si->pctx, md,
417 		    NULL, pk) <= 0)
418 			goto err;
419 	}
420 
421 	if (!sd->signerInfos)
422 		sd->signerInfos = sk_CMS_SignerInfo_new_null();
423 	if (!sd->signerInfos || !sk_CMS_SignerInfo_push(sd->signerInfos, si))
424 		goto merr;
425 
426 	return si;
427 
428  merr:
429 	CMSerror(ERR_R_MALLOC_FAILURE);
430  err:
431 	ASN1_item_free((ASN1_VALUE *)si, &CMS_SignerInfo_it);
432 	X509_ALGOR_free(alg);
433 
434 	return NULL;
435 }
436 LCRYPTO_ALIAS(CMS_add1_signer);
437 
438 static int
439 cms_add1_signingTime(CMS_SignerInfo *si, ASN1_TIME *t)
440 {
441 	ASN1_TIME *tt;
442 	int r = 0;
443 
444 	if (t)
445 		tt = t;
446 	else
447 		tt = X509_gmtime_adj(NULL, 0);
448 
449 	if (!tt)
450 		goto merr;
451 
452 	if (CMS_signed_add1_attr_by_NID(si, NID_pkcs9_signingTime,
453 			                        tt->type, tt, -1) <= 0)
454 		goto merr;
455 
456 	r = 1;
457 
458  merr:
459 	if (!t)
460 		ASN1_TIME_free(tt);
461 	if (!r)
462 		CMSerror(ERR_R_MALLOC_FAILURE);
463 
464 	return r;
465 }
466 
467 EVP_PKEY_CTX *
468 CMS_SignerInfo_get0_pkey_ctx(CMS_SignerInfo *si)
469 {
470 	return si->pctx;
471 }
472 LCRYPTO_ALIAS(CMS_SignerInfo_get0_pkey_ctx);
473 
474 EVP_MD_CTX *
475 CMS_SignerInfo_get0_md_ctx(CMS_SignerInfo *si)
476 {
477 	return si->mctx;
478 }
479 LCRYPTO_ALIAS(CMS_SignerInfo_get0_md_ctx);
480 
481 STACK_OF(CMS_SignerInfo) *
482 CMS_get0_SignerInfos(CMS_ContentInfo *cms)
483 {
484 	CMS_SignedData *sd;
485 
486 	sd = cms_get0_signed(cms);
487 	if (!sd)
488 		return NULL;
489 
490 	return sd->signerInfos;
491 }
492 LCRYPTO_ALIAS(CMS_get0_SignerInfos);
493 
494 STACK_OF(X509) *
495 CMS_get0_signers(CMS_ContentInfo *cms)
496 {
497 	STACK_OF(X509) *signers = NULL;
498 	STACK_OF(CMS_SignerInfo) *sinfos;
499 	CMS_SignerInfo *si;
500 	int i;
501 
502 	sinfos = CMS_get0_SignerInfos(cms);
503 	for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) {
504 		si = sk_CMS_SignerInfo_value(sinfos, i);
505 		if (si->signer) {
506 			if (!signers) {
507 				signers = sk_X509_new_null();
508 				if (!signers)
509 					return NULL;
510 			}
511 			if (!sk_X509_push(signers, si->signer)) {
512 				sk_X509_free(signers);
513 				return NULL;
514 			}
515 		}
516 	}
517 
518 	return signers;
519 }
520 LCRYPTO_ALIAS(CMS_get0_signers);
521 
522 void
523 CMS_SignerInfo_set1_signer_cert(CMS_SignerInfo *si, X509 *signer)
524 {
525 	if (signer) {
526 		X509_up_ref(signer);
527 		EVP_PKEY_free(si->pkey);
528 		si->pkey = X509_get_pubkey(signer);
529 	}
530 	X509_free(si->signer);
531 	si->signer = signer;
532 }
533 LCRYPTO_ALIAS(CMS_SignerInfo_set1_signer_cert);
534 
535 int
536 CMS_SignerInfo_get0_signer_id(CMS_SignerInfo *si, ASN1_OCTET_STRING **keyid,
537     X509_NAME **issuer, ASN1_INTEGER **sno)
538 {
539 	return cms_SignerIdentifier_get0_signer_id(si->sid, keyid, issuer, sno);
540 }
541 LCRYPTO_ALIAS(CMS_SignerInfo_get0_signer_id);
542 
543 int
544 CMS_SignerInfo_cert_cmp(CMS_SignerInfo *si, X509 *cert)
545 {
546 	return cms_SignerIdentifier_cert_cmp(si->sid, cert);
547 }
548 LCRYPTO_ALIAS(CMS_SignerInfo_cert_cmp);
549 
550 int
551 CMS_set1_signers_certs(CMS_ContentInfo *cms, STACK_OF(X509) *scerts,
552     unsigned int flags)
553 {
554 	CMS_SignedData *sd;
555 	CMS_SignerInfo *si;
556 	CMS_CertificateChoices *cch;
557 	STACK_OF(CMS_CertificateChoices) *certs;
558 	X509 *x;
559 	int i, j;
560 	int ret = 0;
561 
562 	sd = cms_get0_signed(cms);
563 	if (!sd)
564 		return -1;
565 	certs = sd->certificates;
566 	for (i = 0; i < sk_CMS_SignerInfo_num(sd->signerInfos); i++) {
567 		si = sk_CMS_SignerInfo_value(sd->signerInfos, i);
568 		if (si->signer)
569 			continue;
570 
571 		for (j = 0; j < sk_X509_num(scerts); j++) {
572 			x = sk_X509_value(scerts, j);
573 			if (CMS_SignerInfo_cert_cmp(si, x) == 0) {
574 				CMS_SignerInfo_set1_signer_cert(si, x);
575 				ret++;
576 				break;
577 			}
578 		}
579 
580 		if (si->signer || (flags & CMS_NOINTERN))
581 			continue;
582 
583 		for (j = 0; j < sk_CMS_CertificateChoices_num(certs); j++) {
584 			cch = sk_CMS_CertificateChoices_value(certs, j);
585 			if (cch->type != 0)
586 				continue;
587 			x = cch->d.certificate;
588 			if (CMS_SignerInfo_cert_cmp(si, x) == 0) {
589 				CMS_SignerInfo_set1_signer_cert(si, x);
590 				ret++;
591 				break;
592 			}
593 		}
594 	}
595 	return ret;
596 }
597 LCRYPTO_ALIAS(CMS_set1_signers_certs);
598 
599 void
600 CMS_SignerInfo_get0_algs(CMS_SignerInfo *si, EVP_PKEY **pk, X509 **signer,
601 X509_ALGOR **pdig, X509_ALGOR **psig)
602 {
603 	if (pk)
604 		*pk = si->pkey;
605 	if (signer)
606 		*signer = si->signer;
607 	if (pdig)
608 		*pdig = si->digestAlgorithm;
609 	if (psig)
610 		*psig = si->signatureAlgorithm;
611 }
612 LCRYPTO_ALIAS(CMS_SignerInfo_get0_algs);
613 
614 ASN1_OCTET_STRING *
615 CMS_SignerInfo_get0_signature(CMS_SignerInfo *si)
616 {
617 	return si->signature;
618 }
619 LCRYPTO_ALIAS(CMS_SignerInfo_get0_signature);
620 
621 static int
622 cms_SignerInfo_content_sign(CMS_ContentInfo *cms, CMS_SignerInfo *si, BIO *chain)
623 {
624 	EVP_MD_CTX *mctx = EVP_MD_CTX_new();
625 	int r = 0;
626 	EVP_PKEY_CTX *pctx = NULL;
627 
628 	if (mctx == NULL) {
629 		CMSerror(ERR_R_MALLOC_FAILURE);
630 		return 0;
631 	}
632 
633 	if (!si->pkey) {
634 		CMSerror(CMS_R_NO_PRIVATE_KEY);
635 		goto err;
636 	}
637 
638 	if (!cms_DigestAlgorithm_find_ctx(mctx, chain, si->digestAlgorithm))
639 		goto err;
640 	/* Set SignerInfo algorithm details if we used custom parameter */
641 	if (si->pctx && !cms_sd_asn1_ctrl(si, 0))
642 		goto err;
643 
644 	/*
645 	 * If any signed attributes calculate and add messageDigest attribute
646 	 */
647 
648 	if (CMS_signed_get_attr_count(si) >= 0) {
649 		ASN1_OBJECT *ctype =
650 		    cms->d.signedData->encapContentInfo->eContentType;
651 		unsigned char md[EVP_MAX_MD_SIZE];
652 		unsigned int mdlen;
653 
654 		if (!EVP_DigestFinal_ex(mctx, md, &mdlen))
655 			goto err;
656 		if (!CMS_signed_add1_attr_by_NID(si, NID_pkcs9_messageDigest,
657 		    V_ASN1_OCTET_STRING, md, mdlen))
658 			goto err;
659 		/* Copy content type across */
660 		if (CMS_signed_add1_attr_by_NID(si, NID_pkcs9_contentType,
661 		    V_ASN1_OBJECT, ctype, -1) <= 0)
662 			goto err;
663 		if (!CMS_SignerInfo_sign(si))
664 			goto err;
665 	} else if (si->pctx) {
666 		unsigned char *sig;
667 		size_t siglen;
668 		unsigned char md[EVP_MAX_MD_SIZE];
669 		unsigned int mdlen;
670 
671 		pctx = si->pctx;
672 		if (!EVP_DigestFinal_ex(mctx, md, &mdlen))
673 			goto err;
674 		siglen = EVP_PKEY_size(si->pkey);
675 		sig = malloc(siglen);
676 		if (sig == NULL) {
677 			CMSerror(ERR_R_MALLOC_FAILURE);
678 			goto err;
679 		}
680 		if (EVP_PKEY_sign(pctx, sig, &siglen, md, mdlen) <= 0) {
681 			free(sig);
682 			goto err;
683 		}
684 		ASN1_STRING_set0(si->signature, sig, siglen);
685 	} else {
686 		unsigned char *sig;
687 		unsigned int siglen;
688 
689 		sig = malloc(EVP_PKEY_size(si->pkey));
690 		if (sig == NULL) {
691 			CMSerror(ERR_R_MALLOC_FAILURE);
692 			goto err;
693 		}
694 		if (!EVP_SignFinal(mctx, sig, &siglen, si->pkey)) {
695 			CMSerror(CMS_R_SIGNFINAL_ERROR);
696 			free(sig);
697 			goto err;
698 		}
699 		ASN1_STRING_set0(si->signature, sig, siglen);
700 	}
701 
702 	r = 1;
703 
704  err:
705 	EVP_MD_CTX_free(mctx);
706 	EVP_PKEY_CTX_free(pctx);
707 
708 	return r;
709 }
710 
711 int
712 cms_SignedData_final(CMS_ContentInfo *cms, BIO *chain)
713 {
714 	STACK_OF(CMS_SignerInfo) *sinfos;
715 	CMS_SignerInfo *si;
716 	int i;
717 
718 	sinfos = CMS_get0_SignerInfos(cms);
719 	for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) {
720 		si = sk_CMS_SignerInfo_value(sinfos, i);
721 		if (!cms_SignerInfo_content_sign(cms, si, chain))
722 			return 0;
723 	}
724 	cms->d.signedData->encapContentInfo->partial = 0;
725 
726 	return 1;
727 }
728 
729 int
730 CMS_SignerInfo_sign(CMS_SignerInfo *si)
731 {
732 	const EVP_MD *md;
733 	unsigned char *buf = NULL, *sig = NULL;
734 	int buf_len = 0;
735 	size_t sig_len = 0;
736 	int ret = 0;
737 
738 	if ((md = EVP_get_digestbyobj(si->digestAlgorithm->algorithm)) == NULL)
739 		goto err;
740 
741 	if (CMS_signed_get_attr_by_NID(si, NID_pkcs9_signingTime, -1) < 0) {
742 		if (!cms_add1_signingTime(si, NULL))
743 			goto err;
744 	}
745 
746 	if (si->pctx == NULL) {
747 		EVP_MD_CTX_reset(si->mctx);
748 		if (!EVP_DigestSignInit(si->mctx, &si->pctx, md, NULL, si->pkey))
749 			goto err;
750 	}
751 
752 	if (EVP_PKEY_CTX_ctrl(si->pctx, -1, EVP_PKEY_OP_SIGN,
753 	    EVP_PKEY_CTRL_CMS_SIGN, 0, si) <= 0) {
754 		CMSerror(CMS_R_CTRL_ERROR);
755 		goto err;
756 	}
757 
758 	if ((buf_len = ASN1_item_i2d((ASN1_VALUE *)si->signedAttrs, &buf,
759 	    &CMS_Attributes_Sign_it)) <= 0) {
760 		buf_len = 0;
761 		goto err;
762 	}
763 	if (!EVP_DigestSign(si->mctx, NULL, &sig_len, buf, buf_len))
764 		goto err;
765 	if ((sig = calloc(1, sig_len)) == NULL)
766 		goto err;
767 	if (!EVP_DigestSign(si->mctx, sig, &sig_len, buf, buf_len))
768 		goto err;
769 
770 	if (EVP_PKEY_CTX_ctrl(si->pctx, -1, EVP_PKEY_OP_SIGN,
771 	    EVP_PKEY_CTRL_CMS_SIGN, 1, si) <= 0) {
772 		CMSerror(CMS_R_CTRL_ERROR);
773 		goto err;
774 	}
775 
776 	ASN1_STRING_set0(si->signature, sig, sig_len);
777 	sig = NULL;
778 
779 	ret = 1;
780 
781  err:
782 	if (si->mctx != NULL)
783 		EVP_MD_CTX_reset(si->mctx);
784 	freezero(buf, buf_len);
785 	freezero(sig, sig_len);
786 
787 	return ret;
788 }
789 LCRYPTO_ALIAS(CMS_SignerInfo_sign);
790 
791 int
792 CMS_SignerInfo_verify(CMS_SignerInfo *si)
793 {
794 	const EVP_MD *md;
795 	unsigned char *buf = NULL;
796 	int buf_len = 0;
797 	int ret = -1;
798 
799 	if ((md = EVP_get_digestbyobj(si->digestAlgorithm->algorithm)) == NULL)
800 		goto err;
801 
802 	if (si->pkey == NULL) {
803 		CMSerror(CMS_R_NO_PUBLIC_KEY);
804 		goto err;
805 	}
806 
807 	if (si->mctx == NULL)
808 		si->mctx = EVP_MD_CTX_new();
809 	if (si->mctx == NULL) {
810 		CMSerror(ERR_R_MALLOC_FAILURE);
811 		goto err;
812 	}
813 
814 	if (EVP_DigestVerifyInit(si->mctx, &si->pctx, md, NULL, si->pkey) <= 0)
815 		goto err;
816 
817 	if (!cms_sd_asn1_ctrl(si, 1))
818 		goto err;
819 
820 	if ((buf_len = ASN1_item_i2d((ASN1_VALUE *)si->signedAttrs, &buf,
821 	    &CMS_Attributes_Verify_it)) <= 0) {
822 		buf_len = 0;
823 		goto err;
824 	}
825 
826 	ret = EVP_DigestVerify(si->mctx, si->signature->data, si->signature->length,
827 	    buf, buf_len);
828 	if (ret <= 0) {
829 		CMSerror(CMS_R_VERIFICATION_FAILURE);
830 		goto err;
831 	}
832 
833  err:
834 	if (si->mctx != NULL)
835 		EVP_MD_CTX_reset(si->mctx);
836 	freezero(buf, buf_len);
837 
838 	return ret;
839 }
840 LCRYPTO_ALIAS(CMS_SignerInfo_verify);
841 
842 /* Create a chain of digest BIOs from a CMS ContentInfo */
843 
844 BIO *
845 cms_SignedData_init_bio(CMS_ContentInfo *cms)
846 {
847 	int i;
848 	CMS_SignedData *sd;
849 	BIO *chain = NULL;
850 
851 	sd = cms_get0_signed(cms);
852 	if (!sd)
853 		return NULL;
854 	if (cms->d.signedData->encapContentInfo->partial)
855 		cms_sd_set_version(sd);
856 	for (i = 0; i < sk_X509_ALGOR_num(sd->digestAlgorithms); i++) {
857 		X509_ALGOR *digestAlgorithm;
858 		BIO *mdbio;
859 		digestAlgorithm = sk_X509_ALGOR_value(sd->digestAlgorithms, i);
860 		mdbio = cms_DigestAlgorithm_init_bio(digestAlgorithm);
861 		if (!mdbio)
862 			goto err;
863 		if (chain)
864 			BIO_push(chain, mdbio);
865 		else
866 			chain = mdbio;
867 	}
868 
869 	return chain;
870 
871  err:
872 	BIO_free_all(chain);
873 
874 	return NULL;
875 }
876 
877 int
878 CMS_SignerInfo_verify_content(CMS_SignerInfo *si, BIO *chain)
879 {
880 	ASN1_OCTET_STRING *os = NULL;
881 	EVP_MD_CTX *mctx = EVP_MD_CTX_new();
882 	EVP_PKEY_CTX *pkctx = NULL;
883 	int r = -1;
884 	unsigned char mval[EVP_MAX_MD_SIZE];
885 	unsigned int mlen;
886 
887 	if (mctx == NULL) {
888 		CMSerror(ERR_R_MALLOC_FAILURE);
889 		goto err;
890 	}
891 	/* If we have any signed attributes look for messageDigest value */
892 	if (CMS_signed_get_attr_count(si) >= 0) {
893 		os = CMS_signed_get0_data_by_OBJ(si,
894 		    OBJ_nid2obj(NID_pkcs9_messageDigest), -3,
895 		    V_ASN1_OCTET_STRING);
896 		if (!os) {
897 			CMSerror(CMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE);
898 			goto err;
899 		}
900 	}
901 
902 	if (!cms_DigestAlgorithm_find_ctx(mctx, chain, si->digestAlgorithm))
903 		goto err;
904 
905 	if (EVP_DigestFinal_ex(mctx, mval, &mlen) <= 0) {
906 		CMSerror(CMS_R_UNABLE_TO_FINALIZE_CONTEXT);
907 		goto err;
908 	}
909 
910 	/* If messageDigest found compare it */
911 
912 	if (os) {
913 		if (mlen != (unsigned int)os->length) {
914 			CMSerror(CMS_R_MESSAGEDIGEST_ATTRIBUTE_WRONG_LENGTH);
915 			goto err;
916 		}
917 
918 		if (memcmp(mval, os->data, mlen)) {
919 			CMSerror(CMS_R_VERIFICATION_FAILURE);
920 			r = 0;
921 		} else
922 			r = 1;
923 	} else {
924 		const EVP_MD *md = EVP_MD_CTX_md(mctx);
925 
926 		pkctx = EVP_PKEY_CTX_new(si->pkey, NULL);
927 		if (pkctx == NULL)
928 			goto err;
929 		if (EVP_PKEY_verify_init(pkctx) <= 0)
930 			goto err;
931 		if (EVP_PKEY_CTX_set_signature_md(pkctx, md) <= 0)
932 			goto err;
933 		si->pctx = pkctx;
934 		if (!cms_sd_asn1_ctrl(si, 1))
935 			goto err;
936 		r = EVP_PKEY_verify(pkctx, si->signature->data,
937 			                si->signature->length, mval, mlen);
938 		if (r <= 0) {
939 			CMSerror(CMS_R_VERIFICATION_FAILURE);
940 			r = 0;
941 		}
942 	}
943 
944  err:
945 	EVP_PKEY_CTX_free(pkctx);
946 	EVP_MD_CTX_free(mctx);
947 
948 	return r;
949 }
950 LCRYPTO_ALIAS(CMS_SignerInfo_verify_content);
951 
952 int
953 CMS_add_smimecap(CMS_SignerInfo *si, STACK_OF(X509_ALGOR) *algs)
954 {
955 	unsigned char *smder = NULL;
956 	int smderlen, r;
957 
958 	smderlen = i2d_X509_ALGORS(algs, &smder);
959 	if (smderlen <= 0)
960 		return 0;
961 	r = CMS_signed_add1_attr_by_NID(si, NID_SMIMECapabilities,
962 	    V_ASN1_SEQUENCE, smder, smderlen);
963 	free(smder);
964 
965 	return r;
966 }
967 LCRYPTO_ALIAS(CMS_add_smimecap);
968 
969 int
970 CMS_add_simple_smimecap(STACK_OF(X509_ALGOR) **algs, int algnid, int keysize)
971 {
972 	X509_ALGOR *alg;
973 	ASN1_INTEGER *key = NULL;
974 
975 	if (keysize > 0) {
976 		if ((key = ASN1_INTEGER_new()) == NULL)
977 			return 0;
978 		if (!ASN1_INTEGER_set(key, keysize)) {
979 			ASN1_INTEGER_free(key);
980 			return 0;
981 		}
982 	}
983 	alg = X509_ALGOR_new();
984 	if (alg == NULL) {
985 		ASN1_INTEGER_free(key);
986 		return 0;
987 	}
988 
989 	X509_ALGOR_set0(alg, OBJ_nid2obj(algnid),
990 	    key ? V_ASN1_INTEGER : V_ASN1_UNDEF, key);
991 	if (*algs == NULL)
992 		*algs = sk_X509_ALGOR_new_null();
993 	if (*algs == NULL || !sk_X509_ALGOR_push(*algs, alg)) {
994 		X509_ALGOR_free(alg);
995 		return 0;
996 	}
997 
998 	return 1;
999 }
1000 LCRYPTO_ALIAS(CMS_add_simple_smimecap);
1001 
1002 /* Check to see if a cipher exists and if so add S/MIME capabilities */
1003 
1004 static int
1005 cms_add_cipher_smcap(STACK_OF(X509_ALGOR) **sk, int nid, int arg)
1006 {
1007 	if (EVP_get_cipherbynid(nid))
1008 		return CMS_add_simple_smimecap(sk, nid, arg);
1009 	return 1;
1010 }
1011 
1012 static int
1013 cms_add_digest_smcap(STACK_OF(X509_ALGOR) **sk, int nid, int arg)
1014 {
1015 	if (EVP_get_digestbynid(nid))
1016 		return CMS_add_simple_smimecap(sk, nid, arg);
1017 	return 1;
1018 }
1019 
1020 int
1021 CMS_add_standard_smimecap(STACK_OF(X509_ALGOR) **smcap)
1022 {
1023 	if (!cms_add_cipher_smcap(smcap, NID_aes_256_cbc, -1) ||
1024 	    !cms_add_digest_smcap(smcap, NID_id_GostR3411_94, -1) ||
1025 	    !cms_add_cipher_smcap(smcap, NID_id_Gost28147_89, -1) ||
1026 	    !cms_add_cipher_smcap(smcap, NID_aes_192_cbc, -1) ||
1027 	    !cms_add_cipher_smcap(smcap, NID_aes_128_cbc, -1) ||
1028 	    !cms_add_cipher_smcap(smcap, NID_des_ede3_cbc, -1) ||
1029 	    !cms_add_cipher_smcap(smcap, NID_rc2_cbc, 128) ||
1030 	    !cms_add_cipher_smcap(smcap, NID_rc2_cbc, 64) ||
1031 	    !cms_add_cipher_smcap(smcap, NID_des_cbc, -1) ||
1032 	    !cms_add_cipher_smcap(smcap, NID_rc2_cbc, 40))
1033 		return 0;
1034 
1035 	return 1;
1036 }
1037 LCRYPTO_ALIAS(CMS_add_standard_smimecap);
1038