Invoke tear_down when exiting test_encode_tls_sct() prematurely
[openssl.git] / crypto / cms / cms_sd.c
1 /*
2  * Copyright 2008-2023 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include "internal/cryptlib.h"
11 #include <openssl/asn1t.h>
12 #include <openssl/pem.h>
13 #include <openssl/x509.h>
14 #include <openssl/x509v3.h>
15 #include <openssl/err.h>
16 #include <openssl/cms.h>
17 #include <openssl/ess.h>
18 #include "internal/sizes.h"
19 #include "crypto/asn1.h"
20 #include "crypto/evp.h"
21 #include "crypto/ess.h"
22 #include "crypto/x509.h" /* for ossl_x509_add_cert_new() */
23 #include "cms_local.h"
24
25 /* CMS SignedData Utilities */
26
27 static CMS_SignedData *cms_get0_signed(CMS_ContentInfo *cms)
28 {
29     if (OBJ_obj2nid(cms->contentType) != NID_pkcs7_signed) {
30         ERR_raise(ERR_LIB_CMS, CMS_R_CONTENT_TYPE_NOT_SIGNED_DATA);
31         return NULL;
32     }
33     return cms->d.signedData;
34 }
35
36 static CMS_SignedData *cms_signed_data_init(CMS_ContentInfo *cms)
37 {
38     if (cms->d.other == NULL) {
39         cms->d.signedData = M_ASN1_new_of(CMS_SignedData);
40         if (!cms->d.signedData) {
41             ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB);
42             return NULL;
43         }
44         cms->d.signedData->version = 1;
45         cms->d.signedData->encapContentInfo->eContentType =
46             OBJ_nid2obj(NID_pkcs7_data);
47         cms->d.signedData->encapContentInfo->partial = 1;
48         ASN1_OBJECT_free(cms->contentType);
49         cms->contentType = OBJ_nid2obj(NID_pkcs7_signed);
50         return cms->d.signedData;
51     }
52     return cms_get0_signed(cms);
53 }
54
55 /* Just initialise SignedData e.g. for certs only structure */
56 int CMS_SignedData_init(CMS_ContentInfo *cms)
57 {
58     if (cms_signed_data_init(cms))
59         return 1;
60     else
61         return 0;
62 }
63
64 /* Check structures and fixup version numbers (if necessary) */
65 static void cms_sd_set_version(CMS_SignedData *sd)
66 {
67     int i;
68     CMS_CertificateChoices *cch;
69     CMS_RevocationInfoChoice *rch;
70     CMS_SignerInfo *si;
71
72     for (i = 0; i < sk_CMS_CertificateChoices_num(sd->certificates); i++) {
73         cch = sk_CMS_CertificateChoices_value(sd->certificates, i);
74         if (cch->type == CMS_CERTCHOICE_OTHER) {
75             if (sd->version < 5)
76                 sd->version = 5;
77         } else if (cch->type == CMS_CERTCHOICE_V2ACERT) {
78             if (sd->version < 4)
79                 sd->version = 4;
80         } else if (cch->type == CMS_CERTCHOICE_V1ACERT) {
81             if (sd->version < 3)
82                 sd->version = 3;
83         }
84     }
85
86     for (i = 0; i < sk_CMS_RevocationInfoChoice_num(sd->crls); i++) {
87         rch = sk_CMS_RevocationInfoChoice_value(sd->crls, i);
88         if (rch->type == CMS_REVCHOICE_OTHER) {
89             if (sd->version < 5)
90                 sd->version = 5;
91         }
92     }
93
94     if ((OBJ_obj2nid(sd->encapContentInfo->eContentType) != NID_pkcs7_data)
95         && (sd->version < 3))
96         sd->version = 3;
97
98     for (i = 0; i < sk_CMS_SignerInfo_num(sd->signerInfos); i++) {
99         si = sk_CMS_SignerInfo_value(sd->signerInfos, i);
100         if (si->sid->type == CMS_SIGNERINFO_KEYIDENTIFIER) {
101             if (si->version < 3)
102                 si->version = 3;
103             if (sd->version < 3)
104                 sd->version = 3;
105         } else if (si->version < 1) {
106             si->version = 1;
107         }
108     }
109
110     if (sd->version < 1)
111         sd->version = 1;
112
113 }
114
115 /*
116  * RFC 5652 Section 11.1 Content Type
117  * The content-type attribute within signed-data MUST
118  *   1) be present if there are signed attributes
119  *   2) match the content type in the signed-data,
120  *   3) be a signed attribute.
121  *   4) not have more than one copy of the attribute.
122  *
123  * Note that since the CMS_SignerInfo_sign() always adds the "signing time"
124  * attribute, the content type attribute MUST be added also.
125  * Assumptions: This assumes that the attribute does not already exist.
126  */
127 static int cms_set_si_contentType_attr(CMS_ContentInfo *cms, CMS_SignerInfo *si)
128 {
129     ASN1_OBJECT *ctype = cms->d.signedData->encapContentInfo->eContentType;
130
131     /* Add the contentType attribute */
132     return CMS_signed_add1_attr_by_NID(si, NID_pkcs9_contentType,
133                                        V_ASN1_OBJECT, ctype, -1) > 0;
134 }
135
136 /* Copy an existing messageDigest value */
137 static int cms_copy_messageDigest(CMS_ContentInfo *cms, CMS_SignerInfo *si)
138 {
139     STACK_OF(CMS_SignerInfo) *sinfos;
140     CMS_SignerInfo *sitmp;
141     int i;
142
143     sinfos = CMS_get0_SignerInfos(cms);
144     for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) {
145         ASN1_OCTET_STRING *messageDigest;
146
147         sitmp = sk_CMS_SignerInfo_value(sinfos, i);
148         if (sitmp == si)
149             continue;
150         if (CMS_signed_get_attr_count(sitmp) < 0)
151             continue;
152         if (OBJ_cmp(si->digestAlgorithm->algorithm,
153                     sitmp->digestAlgorithm->algorithm))
154             continue;
155         messageDigest = CMS_signed_get0_data_by_OBJ(sitmp,
156                                                     OBJ_nid2obj
157                                                     (NID_pkcs9_messageDigest),
158                                                     -3, V_ASN1_OCTET_STRING);
159         if (!messageDigest) {
160             ERR_raise(ERR_LIB_CMS, CMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE);
161             return 0;
162         }
163
164         if (CMS_signed_add1_attr_by_NID(si, NID_pkcs9_messageDigest,
165                                         V_ASN1_OCTET_STRING,
166                                         messageDigest, -1))
167             return 1;
168         else
169             return 0;
170     }
171     ERR_raise(ERR_LIB_CMS, CMS_R_NO_MATCHING_DIGEST);
172     return 0;
173 }
174
175 int ossl_cms_set1_SignerIdentifier(CMS_SignerIdentifier *sid, X509 *cert,
176                                    int type, const CMS_CTX *ctx)
177 {
178     switch (type) {
179     case CMS_SIGNERINFO_ISSUER_SERIAL:
180         if (!ossl_cms_set1_ias(&sid->d.issuerAndSerialNumber, cert))
181             return 0;
182         break;
183
184     case CMS_SIGNERINFO_KEYIDENTIFIER:
185         if (!ossl_cms_set1_keyid(&sid->d.subjectKeyIdentifier, cert))
186             return 0;
187         break;
188
189     default:
190         ERR_raise(ERR_LIB_CMS, CMS_R_UNKNOWN_ID);
191         return 0;
192     }
193
194     sid->type = type;
195
196     return 1;
197 }
198
199 int ossl_cms_SignerIdentifier_get0_signer_id(CMS_SignerIdentifier *sid,
200                                              ASN1_OCTET_STRING **keyid,
201                                              X509_NAME **issuer,
202                                              ASN1_INTEGER **sno)
203 {
204     if (sid->type == CMS_SIGNERINFO_ISSUER_SERIAL) {
205         if (issuer)
206             *issuer = sid->d.issuerAndSerialNumber->issuer;
207         if (sno)
208             *sno = sid->d.issuerAndSerialNumber->serialNumber;
209     } else if (sid->type == CMS_SIGNERINFO_KEYIDENTIFIER) {
210         if (keyid)
211             *keyid = sid->d.subjectKeyIdentifier;
212     } else {
213         return 0;
214     }
215     return 1;
216 }
217
218 int ossl_cms_SignerIdentifier_cert_cmp(CMS_SignerIdentifier *sid, X509 *cert)
219 {
220     if (sid->type == CMS_SIGNERINFO_ISSUER_SERIAL)
221         return ossl_cms_ias_cert_cmp(sid->d.issuerAndSerialNumber, cert);
222     else if (sid->type == CMS_SIGNERINFO_KEYIDENTIFIER)
223         return ossl_cms_keyid_cert_cmp(sid->d.subjectKeyIdentifier, cert);
224     else
225         return -1;
226 }
227
228 /* Method to map any, incl. provider-implemented PKEY types to OIDs */
229 /* (EC)DSA and all provider-delivered signatures implementation is the same */
230 static int cms_generic_sign(CMS_SignerInfo *si, int verify)
231 {
232     if (!ossl_assert(verify == 0 || verify == 1))
233         return -1;
234
235     if (!verify) {
236         EVP_PKEY *pkey = si->pkey;
237         int snid, hnid, pknid = EVP_PKEY_get_id(pkey);
238         X509_ALGOR *alg1, *alg2;
239
240         CMS_SignerInfo_get0_algs(si, NULL, NULL, &alg1, &alg2);
241         if (alg1 == NULL || alg1->algorithm == NULL)
242             return -1;
243         hnid = OBJ_obj2nid(alg1->algorithm);
244         if (hnid == NID_undef)
245             return -1;
246         if (pknid <= 0) { /* check whether a provider registered a NID */
247             const char *typename = EVP_PKEY_get0_type_name(pkey);
248
249             if (typename != NULL)
250                 pknid = OBJ_txt2nid(typename);
251         }
252         if (!OBJ_find_sigid_by_algs(&snid, hnid, pknid))
253             return -1;
254         return X509_ALGOR_set0(alg2, OBJ_nid2obj(snid), V_ASN1_UNDEF, NULL);
255     }
256     return 1;
257 }
258
259 static int cms_sd_asn1_ctrl(CMS_SignerInfo *si, int cmd)
260 {
261     EVP_PKEY *pkey = si->pkey;
262     int i;
263
264     if (EVP_PKEY_is_a(pkey, "DSA") || EVP_PKEY_is_a(pkey, "EC"))
265         return cms_generic_sign(si, cmd) > 0;
266     else if (EVP_PKEY_is_a(pkey, "RSA") || EVP_PKEY_is_a(pkey, "RSA-PSS"))
267         return ossl_cms_rsa_sign(si, cmd) > 0;
268
269     /* Now give engines, providers, etc a chance to handle this */
270     if (pkey->ameth == NULL || pkey->ameth->pkey_ctrl == NULL)
271         return cms_generic_sign(si, cmd) > 0;
272     i = pkey->ameth->pkey_ctrl(pkey, ASN1_PKEY_CTRL_CMS_SIGN, cmd, si);
273     if (i == -2) {
274         ERR_raise(ERR_LIB_CMS, CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE);
275         return 0;
276     }
277     if (i <= 0) {
278         ERR_raise(ERR_LIB_CMS, CMS_R_CTRL_FAILURE);
279         return 0;
280     }
281     return 1;
282 }
283
284 /* Add SigningCertificate signed attribute to the signer info. */
285 static int ossl_cms_add1_signing_cert(CMS_SignerInfo *si,
286                                       const ESS_SIGNING_CERT *sc)
287 {
288     ASN1_STRING *seq = NULL;
289     unsigned char *p, *pp = NULL;
290     int ret, len = i2d_ESS_SIGNING_CERT(sc, NULL);
291
292     if (len <= 0 || (pp = OPENSSL_malloc(len)) == NULL)
293         return 0;
294
295     p = pp;
296     i2d_ESS_SIGNING_CERT(sc, &p);
297     if (!(seq = ASN1_STRING_new()) || !ASN1_STRING_set(seq, pp, len)) {
298         ASN1_STRING_free(seq);
299         OPENSSL_free(pp);
300         return 0;
301     }
302     OPENSSL_free(pp);
303     ret = CMS_signed_add1_attr_by_NID(si, NID_id_smime_aa_signingCertificate,
304                                       V_ASN1_SEQUENCE, seq, -1);
305     ASN1_STRING_free(seq);
306     return ret;
307 }
308
309 /* Add SigningCertificateV2 signed attribute to the signer info. */
310 static int ossl_cms_add1_signing_cert_v2(CMS_SignerInfo *si,
311                                          const ESS_SIGNING_CERT_V2 *sc)
312 {
313     ASN1_STRING *seq = NULL;
314     unsigned char *p, *pp = NULL;
315     int ret, len = i2d_ESS_SIGNING_CERT_V2(sc, NULL);
316
317     if (len <= 0 || (pp = OPENSSL_malloc(len)) == NULL)
318         return 0;
319
320     p = pp;
321     i2d_ESS_SIGNING_CERT_V2(sc, &p);
322     if (!(seq = ASN1_STRING_new()) || !ASN1_STRING_set(seq, pp, len)) {
323         ASN1_STRING_free(seq);
324         OPENSSL_free(pp);
325         return 0;
326     }
327     OPENSSL_free(pp);
328     ret = CMS_signed_add1_attr_by_NID(si, NID_id_smime_aa_signingCertificateV2,
329                                       V_ASN1_SEQUENCE, seq, -1);
330     ASN1_STRING_free(seq);
331     return ret;
332 }
333
334 CMS_SignerInfo *CMS_add1_signer(CMS_ContentInfo *cms,
335                                 X509 *signer, EVP_PKEY *pk, const EVP_MD *md,
336                                 unsigned int flags)
337 {
338     CMS_SignedData *sd;
339     CMS_SignerInfo *si = NULL;
340     X509_ALGOR *alg;
341     int i, type;
342     const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms);
343
344     if (!X509_check_private_key(signer, pk)) {
345         ERR_raise(ERR_LIB_CMS, CMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE);
346         return NULL;
347     }
348     sd = cms_signed_data_init(cms);
349     if (!sd)
350         goto err;
351     si = M_ASN1_new_of(CMS_SignerInfo);
352     if (!si) {
353         ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB);
354         goto err;
355     }
356     /* Call for side-effect of computing hash and caching extensions */
357     X509_check_purpose(signer, -1, -1);
358
359     X509_up_ref(signer);
360     EVP_PKEY_up_ref(pk);
361
362     si->cms_ctx = ctx;
363     si->pkey = pk;
364     si->signer = signer;
365     si->mctx = EVP_MD_CTX_new();
366     si->pctx = NULL;
367
368     if (si->mctx == NULL) {
369         ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB);
370         goto err;
371     }
372
373     if (flags & CMS_USE_KEYID) {
374         si->version = 3;
375         if (sd->version < 3)
376             sd->version = 3;
377         type = CMS_SIGNERINFO_KEYIDENTIFIER;
378     } else {
379         type = CMS_SIGNERINFO_ISSUER_SERIAL;
380         si->version = 1;
381     }
382
383     if (!ossl_cms_set1_SignerIdentifier(si->sid, signer, type, ctx))
384         goto err;
385
386     if (md == NULL) {
387         int def_nid;
388
389         if (EVP_PKEY_get_default_digest_nid(pk, &def_nid) <= 0) {
390             ERR_raise_data(ERR_LIB_CMS, CMS_R_NO_DEFAULT_DIGEST,
391                            "pkey nid=%d", EVP_PKEY_get_id(pk));
392             goto err;
393         }
394         md = EVP_get_digestbynid(def_nid);
395         if (md == NULL) {
396             ERR_raise_data(ERR_LIB_CMS, CMS_R_NO_DEFAULT_DIGEST,
397                            "default md nid=%d", def_nid);
398             goto err;
399         }
400     }
401
402     X509_ALGOR_set_md(si->digestAlgorithm, md);
403
404     /* See if digest is present in digestAlgorithms */
405     for (i = 0; i < sk_X509_ALGOR_num(sd->digestAlgorithms); i++) {
406         const ASN1_OBJECT *aoid;
407         char name[OSSL_MAX_NAME_SIZE];
408
409         alg = sk_X509_ALGOR_value(sd->digestAlgorithms, i);
410         X509_ALGOR_get0(&aoid, NULL, NULL, alg);
411         OBJ_obj2txt(name, sizeof(name), aoid, 0);
412         if (EVP_MD_is_a(md, name))
413             break;
414     }
415
416     if (i == sk_X509_ALGOR_num(sd->digestAlgorithms)) {
417         if ((alg = X509_ALGOR_new()) == NULL) {
418             ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB);
419             goto err;
420         }
421         X509_ALGOR_set_md(alg, md);
422         if (!sk_X509_ALGOR_push(sd->digestAlgorithms, alg)) {
423             X509_ALGOR_free(alg);
424             ERR_raise(ERR_LIB_CMS, ERR_R_CRYPTO_LIB);
425             goto err;
426         }
427     }
428
429     if (!(flags & CMS_KEY_PARAM) && !cms_sd_asn1_ctrl(si, 0)) {
430         ERR_raise_data(ERR_LIB_CMS, CMS_R_UNSUPPORTED_SIGNATURE_ALGORITHM,
431                        "pkey nid=%d", EVP_PKEY_get_id(pk));
432         goto err;
433     }
434     if (!(flags & CMS_NOATTR)) {
435         /*
436          * Initialize signed attributes structure so other attributes
437          * such as signing time etc are added later even if we add none here.
438          */
439         if (!si->signedAttrs) {
440             si->signedAttrs = sk_X509_ATTRIBUTE_new_null();
441             if (!si->signedAttrs) {
442                 ERR_raise(ERR_LIB_CMS, ERR_R_CRYPTO_LIB);
443                 goto err;
444             }
445         }
446
447         if (!(flags & CMS_NOSMIMECAP)) {
448             STACK_OF(X509_ALGOR) *smcap = NULL;
449
450             i = CMS_add_standard_smimecap(&smcap);
451             if (i)
452                 i = CMS_add_smimecap(si, smcap);
453             sk_X509_ALGOR_pop_free(smcap, X509_ALGOR_free);
454             if (!i) {
455                 ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB);
456                 goto err;
457             }
458         }
459         if (flags & CMS_CADES) {
460             ESS_SIGNING_CERT *sc = NULL;
461             ESS_SIGNING_CERT_V2 *sc2 = NULL;
462             int add_sc;
463
464             if (md == NULL || EVP_MD_is_a(md, SN_sha1)) {
465                 if ((sc = OSSL_ESS_signing_cert_new_init(signer,
466                                                          NULL, 1)) == NULL)
467                     goto err;
468                 add_sc = ossl_cms_add1_signing_cert(si, sc);
469                 ESS_SIGNING_CERT_free(sc);
470             } else {
471                 if ((sc2 = OSSL_ESS_signing_cert_v2_new_init(md, signer,
472                                                              NULL, 1)) == NULL)
473                     goto err;
474                 add_sc = ossl_cms_add1_signing_cert_v2(si, sc2);
475                 ESS_SIGNING_CERT_V2_free(sc2);
476             }
477             if (!add_sc)
478                 goto err;
479         }
480         if (flags & CMS_REUSE_DIGEST) {
481             if (!cms_copy_messageDigest(cms, si))
482                 goto err;
483             if (!cms_set_si_contentType_attr(cms, si))
484                 goto err;
485             if (!(flags & (CMS_PARTIAL | CMS_KEY_PARAM)) &&
486                 !CMS_SignerInfo_sign(si))
487                 goto err;
488         }
489     }
490
491     if (!(flags & CMS_NOCERTS)) {
492         /* NB ignore -1 return for duplicate cert */
493         if (!CMS_add1_cert(cms, signer)) {
494             ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB);
495             goto err;
496         }
497     }
498
499     if (flags & CMS_KEY_PARAM) {
500         if (flags & CMS_NOATTR) {
501             si->pctx = EVP_PKEY_CTX_new_from_pkey(ossl_cms_ctx_get0_libctx(ctx),
502                                                   si->pkey,
503                                                   ossl_cms_ctx_get0_propq(ctx));
504             if (si->pctx == NULL)
505                 goto err;
506             if (EVP_PKEY_sign_init(si->pctx) <= 0)
507                 goto err;
508             if (EVP_PKEY_CTX_set_signature_md(si->pctx, md) <= 0)
509                 goto err;
510         } else if (EVP_DigestSignInit_ex(si->mctx, &si->pctx,
511                                          EVP_MD_get0_name(md),
512                                          ossl_cms_ctx_get0_libctx(ctx),
513                                          ossl_cms_ctx_get0_propq(ctx),
514                                          pk, NULL) <= 0) {
515             goto err;
516         }
517     }
518
519     if (sd->signerInfos == NULL)
520         sd->signerInfos = sk_CMS_SignerInfo_new_null();
521     if (sd->signerInfos == NULL || !sk_CMS_SignerInfo_push(sd->signerInfos, si)) {
522         ERR_raise(ERR_LIB_CMS, ERR_R_CRYPTO_LIB);
523         goto err;
524     }
525
526     return si;
527
528  err:
529     M_ASN1_free_of(si, CMS_SignerInfo);
530     return NULL;
531
532 }
533
534 void ossl_cms_SignerInfos_set_cmsctx(CMS_ContentInfo *cms)
535 {
536     int i;
537     CMS_SignerInfo *si;
538     STACK_OF(CMS_SignerInfo) *sinfos;
539     const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms);
540
541     ERR_set_mark();
542     sinfos = CMS_get0_SignerInfos(cms);
543     ERR_pop_to_mark(); /* removes error in case sinfos == NULL */
544
545     for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) {
546         si = sk_CMS_SignerInfo_value(sinfos, i);
547         if (si != NULL)
548             si->cms_ctx = ctx;
549     }
550 }
551
552 static int cms_add1_signingTime(CMS_SignerInfo *si, ASN1_TIME *t)
553 {
554     ASN1_TIME *tt;
555     int r = 0;
556
557     if (t != NULL)
558         tt = t;
559     else
560         tt = X509_gmtime_adj(NULL, 0);
561
562     if (tt == NULL) {
563         ERR_raise(ERR_LIB_CMS, ERR_R_X509_LIB);
564         goto err;
565     }
566
567     if (CMS_signed_add1_attr_by_NID(si, NID_pkcs9_signingTime,
568                                     tt->type, tt, -1) <= 0) {
569         ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB);
570         goto err;
571     }
572
573     r = 1;
574  err:
575     if (t == NULL)
576         ASN1_TIME_free(tt);
577
578     return r;
579
580 }
581
582 EVP_PKEY_CTX *CMS_SignerInfo_get0_pkey_ctx(CMS_SignerInfo *si)
583 {
584     return si->pctx;
585 }
586
587 EVP_MD_CTX *CMS_SignerInfo_get0_md_ctx(CMS_SignerInfo *si)
588 {
589     return si->mctx;
590 }
591
592 STACK_OF(CMS_SignerInfo) *CMS_get0_SignerInfos(CMS_ContentInfo *cms)
593 {
594     CMS_SignedData *sd = cms_get0_signed(cms);
595
596     return sd != NULL ? sd->signerInfos : NULL;
597 }
598
599 STACK_OF(X509) *CMS_get0_signers(CMS_ContentInfo *cms)
600 {
601     STACK_OF(X509) *signers = NULL;
602     STACK_OF(CMS_SignerInfo) *sinfos;
603     CMS_SignerInfo *si;
604     int i;
605
606     sinfos = CMS_get0_SignerInfos(cms);
607     for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) {
608         si = sk_CMS_SignerInfo_value(sinfos, i);
609         if (si->signer != NULL) {
610             if (!ossl_x509_add_cert_new(&signers, si->signer,
611                                         X509_ADD_FLAG_DEFAULT)) {
612                 sk_X509_free(signers);
613                 return NULL;
614             }
615         }
616     }
617     return signers;
618 }
619
620 void CMS_SignerInfo_set1_signer_cert(CMS_SignerInfo *si, X509 *signer)
621 {
622     if (signer != NULL) {
623         X509_up_ref(signer);
624         EVP_PKEY_free(si->pkey);
625         si->pkey = X509_get_pubkey(signer);
626     }
627     X509_free(si->signer);
628     si->signer = signer;
629 }
630
631 int CMS_SignerInfo_get0_signer_id(CMS_SignerInfo *si,
632                                   ASN1_OCTET_STRING **keyid,
633                                   X509_NAME **issuer, ASN1_INTEGER **sno)
634 {
635     return ossl_cms_SignerIdentifier_get0_signer_id(si->sid, keyid, issuer, sno);
636 }
637
638 int CMS_SignerInfo_cert_cmp(CMS_SignerInfo *si, X509 *cert)
639 {
640     return ossl_cms_SignerIdentifier_cert_cmp(si->sid, cert);
641 }
642
643 int CMS_set1_signers_certs(CMS_ContentInfo *cms, STACK_OF(X509) *scerts,
644                            unsigned int flags)
645 {
646     CMS_SignedData *sd;
647     CMS_SignerInfo *si;
648     CMS_CertificateChoices *cch;
649     STACK_OF(CMS_CertificateChoices) *certs;
650     X509 *x;
651     int i, j;
652     int ret = 0;
653
654     sd = cms_get0_signed(cms);
655     if (sd == NULL)
656         return -1;
657     certs = sd->certificates;
658     for (i = 0; i < sk_CMS_SignerInfo_num(sd->signerInfos); i++) {
659         si = sk_CMS_SignerInfo_value(sd->signerInfos, i);
660         if (si->signer != NULL)
661             continue;
662
663         for (j = 0; j < sk_X509_num(scerts); j++) {
664             x = sk_X509_value(scerts, j);
665             if (CMS_SignerInfo_cert_cmp(si, x) == 0) {
666                 CMS_SignerInfo_set1_signer_cert(si, x);
667                 ret++;
668                 break;
669             }
670         }
671
672         if (si->signer != NULL || (flags & CMS_NOINTERN))
673             continue;
674
675         for (j = 0; j < sk_CMS_CertificateChoices_num(certs); j++) {
676             cch = sk_CMS_CertificateChoices_value(certs, j);
677             if (cch->type != CMS_CERTCHOICE_CERT)
678                 continue;
679             x = cch->d.certificate;
680             if (CMS_SignerInfo_cert_cmp(si, x) == 0) {
681                 CMS_SignerInfo_set1_signer_cert(si, x);
682                 ret++;
683                 break;
684             }
685         }
686     }
687     return ret;
688 }
689
690 void CMS_SignerInfo_get0_algs(CMS_SignerInfo *si, EVP_PKEY **pk,
691                               X509 **signer, X509_ALGOR **pdig,
692                               X509_ALGOR **psig)
693 {
694     if (pk != NULL)
695         *pk = si->pkey;
696     if (signer != NULL)
697         *signer = si->signer;
698     if (pdig != NULL)
699         *pdig = si->digestAlgorithm;
700     if (psig != NULL)
701         *psig = si->signatureAlgorithm;
702 }
703
704 ASN1_OCTET_STRING *CMS_SignerInfo_get0_signature(CMS_SignerInfo *si)
705 {
706     return si->signature;
707 }
708
709 static int cms_SignerInfo_content_sign(CMS_ContentInfo *cms,
710                                        CMS_SignerInfo *si, BIO *chain,
711                                        const unsigned char *md,
712                                        unsigned int mdlen)
713 {
714     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
715     int r = 0;
716     EVP_PKEY_CTX *pctx = NULL;
717     const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms);
718
719     if (mctx == NULL) {
720         ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB);
721         return 0;
722     }
723
724     if (si->pkey == NULL) {
725         ERR_raise(ERR_LIB_CMS, CMS_R_NO_PRIVATE_KEY);
726         goto err;
727     }
728
729     if (!ossl_cms_DigestAlgorithm_find_ctx(mctx, chain, si->digestAlgorithm))
730         goto err;
731     /* Set SignerInfo algorithm details if we used custom parameter */
732     if (si->pctx && !cms_sd_asn1_ctrl(si, 0))
733         goto err;
734
735     /*
736      * If any signed attributes calculate and add messageDigest attribute
737      */
738     if (CMS_signed_get_attr_count(si) >= 0) {
739         unsigned char computed_md[EVP_MAX_MD_SIZE];
740
741         if (md == NULL) {
742             if (!EVP_DigestFinal_ex(mctx, computed_md, &mdlen))
743                 goto err;
744             md = computed_md;
745         }
746         if (!CMS_signed_add1_attr_by_NID(si, NID_pkcs9_messageDigest,
747                                          V_ASN1_OCTET_STRING, md, mdlen))
748             goto err;
749         /* Copy content type across */
750         if (!cms_set_si_contentType_attr(cms, si))
751             goto err;
752
753         if (!CMS_SignerInfo_sign(si))
754             goto err;
755     } else if (si->pctx) {
756         unsigned char *sig;
757         size_t siglen;
758         unsigned char computed_md[EVP_MAX_MD_SIZE];
759
760         pctx = si->pctx;
761         if (md == NULL) {
762             if (!EVP_DigestFinal_ex(mctx, computed_md, &mdlen))
763                 goto err;
764             md = computed_md;
765         }
766         siglen = EVP_PKEY_get_size(si->pkey);
767         if (siglen == 0 || (sig = OPENSSL_malloc(siglen)) == NULL)
768             goto err;
769         if (EVP_PKEY_sign(pctx, sig, &siglen, md, mdlen) <= 0) {
770             OPENSSL_free(sig);
771             goto err;
772         }
773         ASN1_STRING_set0(si->signature, sig, siglen);
774     } else {
775         unsigned char *sig;
776         unsigned int siglen;
777
778         if (md != NULL) {
779             ERR_raise(ERR_LIB_CMS, CMS_R_OPERATION_UNSUPPORTED);
780             goto err;
781         }
782         siglen = EVP_PKEY_get_size(si->pkey);
783         if (siglen == 0 || (sig = OPENSSL_malloc(siglen)) == NULL)
784             goto err;
785         if (!EVP_SignFinal_ex(mctx, sig, &siglen, si->pkey,
786                               ossl_cms_ctx_get0_libctx(ctx),
787                               ossl_cms_ctx_get0_propq(ctx))) {
788             ERR_raise(ERR_LIB_CMS, CMS_R_SIGNFINAL_ERROR);
789             OPENSSL_free(sig);
790             goto err;
791         }
792         ASN1_STRING_set0(si->signature, sig, siglen);
793     }
794
795     r = 1;
796
797  err:
798     EVP_MD_CTX_free(mctx);
799     EVP_PKEY_CTX_free(pctx);
800     return r;
801
802 }
803
804 int ossl_cms_SignedData_final(CMS_ContentInfo *cms, BIO *chain,
805                               const unsigned char *precomp_md,
806                               unsigned int precomp_mdlen)
807 {
808     STACK_OF(CMS_SignerInfo) *sinfos;
809     CMS_SignerInfo *si;
810     int i;
811
812     sinfos = CMS_get0_SignerInfos(cms);
813     for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) {
814         si = sk_CMS_SignerInfo_value(sinfos, i);
815         if (!cms_SignerInfo_content_sign(cms, si, chain,
816                                          precomp_md, precomp_mdlen))
817             return 0;
818     }
819     cms->d.signedData->encapContentInfo->partial = 0;
820     return 1;
821 }
822
823 int CMS_SignerInfo_sign(CMS_SignerInfo *si)
824 {
825     EVP_MD_CTX *mctx = si->mctx;
826     EVP_PKEY_CTX *pctx = NULL;
827     unsigned char *abuf = NULL;
828     int alen;
829     size_t siglen;
830     const CMS_CTX *ctx = si->cms_ctx;
831     char md_name[OSSL_MAX_NAME_SIZE];
832
833     if (OBJ_obj2txt(md_name, sizeof(md_name),
834                     si->digestAlgorithm->algorithm, 0) <= 0)
835         return 0;
836
837     if (CMS_signed_get_attr_by_NID(si, NID_pkcs9_signingTime, -1) < 0) {
838         if (!cms_add1_signingTime(si, NULL))
839             goto err;
840     }
841
842     if (!ossl_cms_si_check_attributes(si))
843         goto err;
844
845     if (si->pctx) {
846         pctx = si->pctx;
847     } else {
848         EVP_MD_CTX_reset(mctx);
849         if (EVP_DigestSignInit_ex(mctx, &pctx, md_name,
850                                   ossl_cms_ctx_get0_libctx(ctx),
851                                   ossl_cms_ctx_get0_propq(ctx), si->pkey,
852                                   NULL) <= 0)
853             goto err;
854         si->pctx = pctx;
855     }
856
857     alen = ASN1_item_i2d((ASN1_VALUE *)si->signedAttrs, &abuf,
858                          ASN1_ITEM_rptr(CMS_Attributes_Sign));
859     if (!abuf)
860         goto err;
861     if (EVP_DigestSignUpdate(mctx, abuf, alen) <= 0)
862         goto err;
863     if (EVP_DigestSignFinal(mctx, NULL, &siglen) <= 0)
864         goto err;
865     OPENSSL_free(abuf);
866     abuf = OPENSSL_malloc(siglen);
867     if (abuf == NULL)
868         goto err;
869     if (EVP_DigestSignFinal(mctx, abuf, &siglen) <= 0)
870         goto err;
871
872     EVP_MD_CTX_reset(mctx);
873
874     ASN1_STRING_set0(si->signature, abuf, siglen);
875
876     return 1;
877
878  err:
879     OPENSSL_free(abuf);
880     EVP_MD_CTX_reset(mctx);
881     return 0;
882 }
883
884 int CMS_SignerInfo_verify(CMS_SignerInfo *si)
885 {
886     EVP_MD_CTX *mctx = NULL;
887     unsigned char *abuf = NULL;
888     int alen, r = -1;
889     char name[OSSL_MAX_NAME_SIZE];
890     const EVP_MD *md;
891     EVP_MD *fetched_md = NULL;
892     const CMS_CTX *ctx = si->cms_ctx;
893     OSSL_LIB_CTX *libctx = ossl_cms_ctx_get0_libctx(ctx);
894     const char *propq = ossl_cms_ctx_get0_propq(ctx);
895
896     if (si->pkey == NULL) {
897         ERR_raise(ERR_LIB_CMS, CMS_R_NO_PUBLIC_KEY);
898         return -1;
899     }
900
901     if (!ossl_cms_si_check_attributes(si))
902         return -1;
903
904     OBJ_obj2txt(name, sizeof(name), si->digestAlgorithm->algorithm, 0);
905
906     (void)ERR_set_mark();
907     fetched_md = EVP_MD_fetch(libctx, name, propq);
908
909     if (fetched_md != NULL)
910         md = fetched_md;
911     else
912         md = EVP_get_digestbyobj(si->digestAlgorithm->algorithm);
913     if (md == NULL) {
914         (void)ERR_clear_last_mark();
915         ERR_raise(ERR_LIB_CMS, CMS_R_UNKNOWN_DIGEST_ALGORITHM);
916         return -1;
917     }
918     (void)ERR_pop_to_mark();
919
920     if (si->mctx == NULL && (si->mctx = EVP_MD_CTX_new()) == NULL) {
921         ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB);
922         goto err;
923     }
924     mctx = si->mctx;
925     if (EVP_DigestVerifyInit_ex(mctx, &si->pctx, EVP_MD_get0_name(md), libctx,
926                                 propq, si->pkey, NULL) <= 0)
927         goto err;
928
929     if (!cms_sd_asn1_ctrl(si, 1))
930         goto err;
931
932     alen = ASN1_item_i2d((ASN1_VALUE *)si->signedAttrs, &abuf,
933                          ASN1_ITEM_rptr(CMS_Attributes_Verify));
934     if (abuf == NULL || alen < 0)
935         goto err;
936     r = EVP_DigestVerifyUpdate(mctx, abuf, alen);
937     OPENSSL_free(abuf);
938     if (r <= 0) {
939         r = -1;
940         goto err;
941     }
942     r = EVP_DigestVerifyFinal(mctx,
943                               si->signature->data, si->signature->length);
944     if (r <= 0)
945         ERR_raise(ERR_LIB_CMS, CMS_R_VERIFICATION_FAILURE);
946  err:
947     EVP_MD_free(fetched_md);
948     EVP_MD_CTX_reset(mctx);
949     return r;
950 }
951
952 /* Create a chain of digest BIOs from a CMS ContentInfo */
953 BIO *ossl_cms_SignedData_init_bio(CMS_ContentInfo *cms)
954 {
955     int i;
956     CMS_SignedData *sd;
957     BIO *chain = NULL;
958
959     sd = cms_get0_signed(cms);
960     if (sd == NULL)
961         return NULL;
962     if (cms->d.signedData->encapContentInfo->partial)
963         cms_sd_set_version(sd);
964     for (i = 0; i < sk_X509_ALGOR_num(sd->digestAlgorithms); i++) {
965         X509_ALGOR *digestAlgorithm;
966         BIO *mdbio;
967
968         digestAlgorithm = sk_X509_ALGOR_value(sd->digestAlgorithms, i);
969         mdbio = ossl_cms_DigestAlgorithm_init_bio(digestAlgorithm,
970                                                   ossl_cms_get0_cmsctx(cms));
971         if (mdbio == NULL)
972             goto err;
973         if (chain != NULL)
974             BIO_push(chain, mdbio);
975         else
976             chain = mdbio;
977     }
978     return chain;
979  err:
980     BIO_free_all(chain);
981     return NULL;
982 }
983
984 int CMS_SignerInfo_verify_content(CMS_SignerInfo *si, BIO *chain)
985 {
986     ASN1_OCTET_STRING *os = NULL;
987     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
988     EVP_PKEY_CTX *pkctx = NULL;
989     int r = -1;
990     unsigned char mval[EVP_MAX_MD_SIZE];
991     unsigned int mlen;
992
993     if (mctx == NULL) {
994         ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB);
995         goto err;
996     }
997     /* If we have any signed attributes look for messageDigest value */
998     if (CMS_signed_get_attr_count(si) >= 0) {
999         os = CMS_signed_get0_data_by_OBJ(si,
1000                                          OBJ_nid2obj(NID_pkcs9_messageDigest),
1001                                          -3, V_ASN1_OCTET_STRING);
1002         if (os == NULL) {
1003             ERR_raise(ERR_LIB_CMS, CMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE);
1004             goto err;
1005         }
1006     }
1007
1008     if (!ossl_cms_DigestAlgorithm_find_ctx(mctx, chain, si->digestAlgorithm))
1009         goto err;
1010
1011     if (EVP_DigestFinal_ex(mctx, mval, &mlen) <= 0) {
1012         ERR_raise(ERR_LIB_CMS, CMS_R_UNABLE_TO_FINALIZE_CONTEXT);
1013         goto err;
1014     }
1015
1016     /* If messageDigest found compare it */
1017     if (os != NULL) {
1018         if (mlen != (unsigned int)os->length) {
1019             ERR_raise(ERR_LIB_CMS, CMS_R_MESSAGEDIGEST_ATTRIBUTE_WRONG_LENGTH);
1020             goto err;
1021         }
1022
1023         if (memcmp(mval, os->data, mlen)) {
1024             ERR_raise(ERR_LIB_CMS, CMS_R_VERIFICATION_FAILURE);
1025             r = 0;
1026         } else {
1027             r = 1;
1028         }
1029     } else {
1030         const EVP_MD *md = EVP_MD_CTX_get0_md(mctx);
1031         const CMS_CTX *ctx = si->cms_ctx;
1032
1033         pkctx = EVP_PKEY_CTX_new_from_pkey(ossl_cms_ctx_get0_libctx(ctx),
1034                                            si->pkey,
1035                                            ossl_cms_ctx_get0_propq(ctx));
1036         if (pkctx == NULL)
1037             goto err;
1038         if (EVP_PKEY_verify_init(pkctx) <= 0)
1039             goto err;
1040         if (EVP_PKEY_CTX_set_signature_md(pkctx, md) <= 0)
1041             goto err;
1042         si->pctx = pkctx;
1043         if (!cms_sd_asn1_ctrl(si, 1))
1044             goto err;
1045         r = EVP_PKEY_verify(pkctx, si->signature->data,
1046                             si->signature->length, mval, mlen);
1047         if (r <= 0) {
1048             ERR_raise(ERR_LIB_CMS, CMS_R_VERIFICATION_FAILURE);
1049             r = 0;
1050         }
1051     }
1052
1053  err:
1054     EVP_PKEY_CTX_free(pkctx);
1055     EVP_MD_CTX_free(mctx);
1056     return r;
1057
1058 }
1059
1060 BIO *CMS_SignedData_verify(CMS_SignedData *sd, BIO *detached_data,
1061                            STACK_OF(X509) *scerts, X509_STORE *store,
1062                            STACK_OF(X509) *extra, STACK_OF(X509_CRL) *crls,
1063                            unsigned int flags,
1064                            OSSL_LIB_CTX *libctx, const char *propq)
1065 {
1066     CMS_ContentInfo *ci;
1067     BIO *bio = NULL;
1068     int i, res = 0;
1069
1070     if (sd == NULL) {
1071         ERR_raise(ERR_LIB_CMS, ERR_R_PASSED_NULL_PARAMETER);
1072         return NULL;
1073     }
1074
1075     if ((ci = CMS_ContentInfo_new_ex(libctx, propq)) == NULL)
1076         return NULL;
1077     if ((bio = BIO_new(BIO_s_mem())) == NULL)
1078         goto end;
1079     ci->contentType = OBJ_nid2obj(NID_pkcs7_signed);
1080     ci->d.signedData = sd;
1081
1082     for (i = 0; i < sk_X509_num(extra); i++)
1083         if (!CMS_add1_cert(ci, sk_X509_value(extra, i)))
1084             goto end;
1085     for (i = 0; i < sk_X509_CRL_num(crls); i++)
1086         if (!CMS_add1_crl(ci, sk_X509_CRL_value(crls, i)))
1087             goto end;
1088     res = CMS_verify(ci, scerts, store, detached_data, bio, flags);
1089
1090  end:
1091     if (ci != NULL)
1092         ci->d.signedData = NULL; /* do not indirectly free |sd| */
1093     CMS_ContentInfo_free(ci);
1094     if (!res) {
1095         BIO_free(bio);
1096         bio = NULL;
1097     }
1098     return bio;
1099 }
1100
1101 int CMS_add_smimecap(CMS_SignerInfo *si, STACK_OF(X509_ALGOR) *algs)
1102 {
1103     unsigned char *smder = NULL;
1104     int smderlen, r;
1105
1106     smderlen = i2d_X509_ALGORS(algs, &smder);
1107     if (smderlen <= 0)
1108         return 0;
1109     r = CMS_signed_add1_attr_by_NID(si, NID_SMIMECapabilities,
1110                                     V_ASN1_SEQUENCE, smder, smderlen);
1111     OPENSSL_free(smder);
1112     return r;
1113 }
1114
1115 int CMS_add_simple_smimecap(STACK_OF(X509_ALGOR) **algs,
1116                             int algnid, int keysize)
1117 {
1118     X509_ALGOR *alg;
1119     ASN1_INTEGER *key = NULL;
1120
1121     if (keysize > 0) {
1122         key = ASN1_INTEGER_new();
1123         if (key == NULL || !ASN1_INTEGER_set(key, keysize)) {
1124             ASN1_INTEGER_free(key);
1125             return 0;
1126         }
1127     }
1128     alg = ossl_X509_ALGOR_from_nid(algnid, key != NULL ? V_ASN1_INTEGER :
1129                                    V_ASN1_UNDEF, key);
1130     if (alg == NULL) {
1131         ASN1_INTEGER_free(key);
1132         return 0;
1133     }
1134
1135     if (*algs == NULL)
1136         *algs = sk_X509_ALGOR_new_null();
1137     if (*algs == NULL || !sk_X509_ALGOR_push(*algs, alg)) {
1138         X509_ALGOR_free(alg);
1139         return 0;
1140     }
1141     return 1;
1142 }
1143
1144 /* Check to see if a cipher exists and if so add S/MIME capabilities */
1145 static int cms_add_cipher_smcap(STACK_OF(X509_ALGOR) **sk, int nid, int arg)
1146 {
1147     if (EVP_get_cipherbynid(nid))
1148         return CMS_add_simple_smimecap(sk, nid, arg);
1149     return 1;
1150 }
1151
1152 static int cms_add_digest_smcap(STACK_OF(X509_ALGOR) **sk, int nid, int arg)
1153 {
1154     if (EVP_get_digestbynid(nid))
1155         return CMS_add_simple_smimecap(sk, nid, arg);
1156     return 1;
1157 }
1158
1159 int CMS_add_standard_smimecap(STACK_OF(X509_ALGOR) **smcap)
1160 {
1161     if (!cms_add_cipher_smcap(smcap, NID_aes_256_cbc, -1)
1162         || !cms_add_digest_smcap(smcap, NID_id_GostR3411_2012_256, -1)
1163         || !cms_add_digest_smcap(smcap, NID_id_GostR3411_2012_512, -1)
1164         || !cms_add_digest_smcap(smcap, NID_id_GostR3411_94, -1)
1165         || !cms_add_cipher_smcap(smcap, NID_id_Gost28147_89, -1)
1166         || !cms_add_cipher_smcap(smcap, NID_aes_192_cbc, -1)
1167         || !cms_add_cipher_smcap(smcap, NID_aes_128_cbc, -1)
1168         || !cms_add_cipher_smcap(smcap, NID_des_ede3_cbc, -1)
1169         || !cms_add_cipher_smcap(smcap, NID_rc2_cbc, 128)
1170         || !cms_add_cipher_smcap(smcap, NID_rc2_cbc, 64)
1171         || !cms_add_cipher_smcap(smcap, NID_des_cbc, -1)
1172         || !cms_add_cipher_smcap(smcap, NID_rc2_cbc, 40))
1173         return 0;
1174     return 1;
1175 }