Add libctx support to CMS.
[openssl.git] / crypto / cms / cms_sd.c
1 /*
2  * Copyright 2008-2020 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 "cms_local.h"
19 #include "crypto/asn1.h"
20 #include "crypto/evp.h"
21 #include "crypto/cms.h"
22 #include "crypto/ess.h"
23
24 DEFINE_STACK_OF(CMS_RevocationInfoChoice)
25 DEFINE_STACK_OF(CMS_SignerInfo)
26 DEFINE_STACK_OF(X509)
27 DEFINE_STACK_OF(X509_ALGOR)
28 DEFINE_STACK_OF(X509_ATTRIBUTE)
29
30 /* CMS SignedData Utilities */
31
32 static CMS_SignedData *cms_get0_signed(CMS_ContentInfo *cms)
33 {
34     if (OBJ_obj2nid(cms->contentType) != NID_pkcs7_signed) {
35         CMSerr(CMS_F_CMS_GET0_SIGNED, CMS_R_CONTENT_TYPE_NOT_SIGNED_DATA);
36         return NULL;
37     }
38     return cms->d.signedData;
39 }
40
41 static CMS_SignedData *cms_signed_data_init(CMS_ContentInfo *cms)
42 {
43     if (cms->d.other == NULL) {
44         cms->d.signedData = M_ASN1_new_of(CMS_SignedData);
45         if (!cms->d.signedData) {
46             CMSerr(CMS_F_CMS_SIGNED_DATA_INIT, ERR_R_MALLOC_FAILURE);
47             return NULL;
48         }
49         cms->d.signedData->version = 1;
50         cms->d.signedData->encapContentInfo->eContentType =
51             OBJ_nid2obj(NID_pkcs7_data);
52         cms->d.signedData->encapContentInfo->partial = 1;
53         ASN1_OBJECT_free(cms->contentType);
54         cms->contentType = OBJ_nid2obj(NID_pkcs7_signed);
55         return cms->d.signedData;
56     }
57     return cms_get0_signed(cms);
58 }
59
60 /* Just initialise SignedData e.g. for certs only structure */
61
62 int CMS_SignedData_init(CMS_ContentInfo *cms)
63 {
64     if (cms_signed_data_init(cms))
65         return 1;
66     else
67         return 0;
68 }
69
70
71 /* Check structures and fixup version numbers (if necessary) */
72
73 static void cms_sd_set_version(CMS_SignedData *sd)
74 {
75     int i;
76     CMS_CertificateChoices *cch;
77     CMS_RevocationInfoChoice *rch;
78     CMS_SignerInfo *si;
79
80     for (i = 0; i < sk_CMS_CertificateChoices_num(sd->certificates); i++) {
81         cch = sk_CMS_CertificateChoices_value(sd->certificates, i);
82         if (cch->type == CMS_CERTCHOICE_OTHER) {
83             if (sd->version < 5)
84                 sd->version = 5;
85         } else if (cch->type == CMS_CERTCHOICE_V2ACERT) {
86             if (sd->version < 4)
87                 sd->version = 4;
88         } else if (cch->type == CMS_CERTCHOICE_V1ACERT) {
89             if (sd->version < 3)
90                 sd->version = 3;
91         }
92     }
93
94     for (i = 0; i < sk_CMS_RevocationInfoChoice_num(sd->crls); i++) {
95         rch = sk_CMS_RevocationInfoChoice_value(sd->crls, i);
96         if (rch->type == CMS_REVCHOICE_OTHER) {
97             if (sd->version < 5)
98                 sd->version = 5;
99         }
100     }
101
102     if ((OBJ_obj2nid(sd->encapContentInfo->eContentType) != NID_pkcs7_data)
103         && (sd->version < 3))
104         sd->version = 3;
105
106     for (i = 0; i < sk_CMS_SignerInfo_num(sd->signerInfos); i++) {
107         si = sk_CMS_SignerInfo_value(sd->signerInfos, i);
108         if (si->sid->type == CMS_SIGNERINFO_KEYIDENTIFIER) {
109             if (si->version < 3)
110                 si->version = 3;
111             if (sd->version < 3)
112                 sd->version = 3;
113         } else if (si->version < 1)
114             si->version = 1;
115     }
116
117     if (sd->version < 1)
118         sd->version = 1;
119
120 }
121
122 /*
123  * RFC 5652 Section 11.1 Content Type
124  * The content-type attribute within signed-data MUST
125  *   1) be present if there are signed attributes
126  *   2) match the content type in the signed-data,
127  *   3) be a signed attribute.
128  *   4) not have more than one copy of the attribute.
129  *
130  * Note that since the CMS_SignerInfo_sign() always adds the "signing time"
131  * attribute, the content type attribute MUST be added also.
132  * Assumptions: This assumes that the attribute does not already exist.
133  */
134 static int cms_set_si_contentType_attr(CMS_ContentInfo *cms, CMS_SignerInfo *si)
135 {
136     ASN1_OBJECT *ctype = cms->d.signedData->encapContentInfo->eContentType;
137
138     /* Add the contentType attribute */
139     return CMS_signed_add1_attr_by_NID(si, NID_pkcs9_contentType,
140                                        V_ASN1_OBJECT, ctype, -1) > 0;
141 }
142
143 /* Copy an existing messageDigest value */
144
145 static int cms_copy_messageDigest(CMS_ContentInfo *cms, CMS_SignerInfo *si)
146 {
147     STACK_OF(CMS_SignerInfo) *sinfos;
148     CMS_SignerInfo *sitmp;
149     int i;
150
151     sinfos = CMS_get0_SignerInfos(cms);
152     for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) {
153         ASN1_OCTET_STRING *messageDigest;
154
155         sitmp = sk_CMS_SignerInfo_value(sinfos, i);
156         if (sitmp == si)
157             continue;
158         if (CMS_signed_get_attr_count(sitmp) < 0)
159             continue;
160         if (OBJ_cmp(si->digestAlgorithm->algorithm,
161                     sitmp->digestAlgorithm->algorithm))
162             continue;
163         messageDigest = CMS_signed_get0_data_by_OBJ(sitmp,
164                                                     OBJ_nid2obj
165                                                     (NID_pkcs9_messageDigest),
166                                                     -3, V_ASN1_OCTET_STRING);
167         if (!messageDigest) {
168             CMSerr(CMS_F_CMS_COPY_MESSAGEDIGEST,
169                    CMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE);
170             return 0;
171         }
172
173         if (CMS_signed_add1_attr_by_NID(si, NID_pkcs9_messageDigest,
174                                         V_ASN1_OCTET_STRING,
175                                         messageDigest, -1))
176             return 1;
177         else
178             return 0;
179     }
180     CMSerr(CMS_F_CMS_COPY_MESSAGEDIGEST, CMS_R_NO_MATCHING_DIGEST);
181     return 0;
182 }
183
184 int cms_set1_SignerIdentifier(CMS_SignerIdentifier *sid, X509 *cert, int type,
185                               const CMS_CTX *ctx)
186 {
187     switch (type) {
188     case CMS_SIGNERINFO_ISSUER_SERIAL:
189         if (!cms_set1_ias(&sid->d.issuerAndSerialNumber, cert))
190             return 0;
191         break;
192
193     case CMS_SIGNERINFO_KEYIDENTIFIER:
194         if (!cms_set1_keyid(&sid->d.subjectKeyIdentifier, cert))
195             return 0;
196         break;
197
198     default:
199         CMSerr(CMS_F_CMS_SET1_SIGNERIDENTIFIER, CMS_R_UNKNOWN_ID);
200         return 0;
201     }
202
203     sid->type = type;
204
205     return 1;
206 }
207
208 int cms_SignerIdentifier_get0_signer_id(CMS_SignerIdentifier *sid,
209                                         ASN1_OCTET_STRING **keyid,
210                                         X509_NAME **issuer,
211                                         ASN1_INTEGER **sno)
212 {
213     if (sid->type == CMS_SIGNERINFO_ISSUER_SERIAL) {
214         if (issuer)
215             *issuer = sid->d.issuerAndSerialNumber->issuer;
216         if (sno)
217             *sno = sid->d.issuerAndSerialNumber->serialNumber;
218     } else if (sid->type == CMS_SIGNERINFO_KEYIDENTIFIER) {
219         if (keyid)
220             *keyid = sid->d.subjectKeyIdentifier;
221     } else
222         return 0;
223     return 1;
224 }
225
226 int cms_SignerIdentifier_cert_cmp(CMS_SignerIdentifier *sid, X509 *cert)
227 {
228     if (sid->type == CMS_SIGNERINFO_ISSUER_SERIAL)
229         return cms_ias_cert_cmp(sid->d.issuerAndSerialNumber, cert);
230     else if (sid->type == CMS_SIGNERINFO_KEYIDENTIFIER)
231         return cms_keyid_cert_cmp(sid->d.subjectKeyIdentifier, cert);
232     else
233         return -1;
234 }
235
236 static int cms_sd_asn1_ctrl(CMS_SignerInfo *si, int cmd)
237 {
238     EVP_PKEY *pkey = si->pkey;
239     int i;
240
241     if (pkey->ameth == NULL || pkey->ameth->pkey_ctrl == NULL)
242         return 1;
243     i = pkey->ameth->pkey_ctrl(pkey, ASN1_PKEY_CTRL_CMS_SIGN, cmd, si);
244     if (i == -2) {
245         CMSerr(CMS_F_CMS_SD_ASN1_CTRL, CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE);
246         return 0;
247     }
248     if (i <= 0) {
249         CMSerr(CMS_F_CMS_SD_ASN1_CTRL, CMS_R_CTRL_FAILURE);
250         return 0;
251     }
252     return 1;
253 }
254
255 CMS_SignerInfo *CMS_add1_signer(CMS_ContentInfo *cms,
256                                 X509 *signer, EVP_PKEY *pk, const EVP_MD *md,
257                                 unsigned int flags)
258 {
259     CMS_SignedData *sd;
260     CMS_SignerInfo *si = NULL;
261     X509_ALGOR *alg;
262     int i, type;
263     const CMS_CTX *ctx = cms_get0_cmsctx(cms);
264
265     if (!X509_check_private_key(signer, pk)) {
266         CMSerr(CMS_F_CMS_ADD1_SIGNER,
267                CMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE);
268         return NULL;
269     }
270     sd = cms_signed_data_init(cms);
271     if (!sd)
272         goto err;
273     si = M_ASN1_new_of(CMS_SignerInfo);
274     if (!si)
275         goto merr;
276     /* Call for side-effect of computing hash and caching extensions */
277     X509_check_purpose(signer, -1, -1);
278
279     X509_up_ref(signer);
280     EVP_PKEY_up_ref(pk);
281
282     si->cms_ctx = ctx;
283     si->pkey = pk;
284     si->signer = signer;
285     si->mctx = EVP_MD_CTX_new();
286     si->pctx = NULL;
287
288     if (si->mctx == NULL) {
289         CMSerr(CMS_F_CMS_ADD1_SIGNER, ERR_R_MALLOC_FAILURE);
290         goto err;
291     }
292
293     if (flags & CMS_USE_KEYID) {
294         si->version = 3;
295         if (sd->version < 3)
296             sd->version = 3;
297         type = CMS_SIGNERINFO_KEYIDENTIFIER;
298     } else {
299         type = CMS_SIGNERINFO_ISSUER_SERIAL;
300         si->version = 1;
301     }
302
303     if (!cms_set1_SignerIdentifier(si->sid, signer, type, ctx))
304         goto err;
305
306     if (md == NULL) {
307         int def_nid;
308         if (EVP_PKEY_get_default_digest_nid(pk, &def_nid) <= 0)
309             goto err;
310         md = EVP_get_digestbynid(def_nid);
311         if (md == NULL) {
312             CMSerr(CMS_F_CMS_ADD1_SIGNER, CMS_R_NO_DEFAULT_DIGEST);
313             goto err;
314         }
315     }
316
317     if (!md) {
318         CMSerr(CMS_F_CMS_ADD1_SIGNER, CMS_R_NO_DIGEST_SET);
319         goto err;
320     }
321
322     if (md == NULL) {
323         CMSerr(CMS_F_CMS_ADD1_SIGNER, CMS_R_NO_DIGEST_SET);
324         goto err;
325     }
326
327     X509_ALGOR_set_md(si->digestAlgorithm, md);
328
329     /* See if digest is present in digestAlgorithms */
330     for (i = 0; i < sk_X509_ALGOR_num(sd->digestAlgorithms); i++) {
331         const ASN1_OBJECT *aoid;
332         alg = sk_X509_ALGOR_value(sd->digestAlgorithms, i);
333         X509_ALGOR_get0(&aoid, NULL, NULL, alg);
334         if (OBJ_obj2nid(aoid) == EVP_MD_type(md))
335             break;
336     }
337
338     if (i == sk_X509_ALGOR_num(sd->digestAlgorithms)) {
339         alg = X509_ALGOR_new();
340         if (alg == NULL)
341             goto merr;
342         X509_ALGOR_set_md(alg, md);
343         if (!sk_X509_ALGOR_push(sd->digestAlgorithms, alg)) {
344             X509_ALGOR_free(alg);
345             goto merr;
346         }
347     }
348
349     if (!(flags & CMS_KEY_PARAM) && !cms_sd_asn1_ctrl(si, 0))
350         goto err;
351     if (!(flags & CMS_NOATTR)) {
352         /*
353          * Initialize signed attributes structure so other attributes
354          * such as signing time etc are added later even if we add none here.
355          */
356         if (!si->signedAttrs) {
357             si->signedAttrs = sk_X509_ATTRIBUTE_new_null();
358             if (!si->signedAttrs)
359                 goto merr;
360         }
361
362         if (!(flags & CMS_NOSMIMECAP)) {
363             STACK_OF(X509_ALGOR) *smcap = NULL;
364             i = CMS_add_standard_smimecap(&smcap);
365             if (i)
366                 i = CMS_add_smimecap(si, smcap);
367             sk_X509_ALGOR_pop_free(smcap, X509_ALGOR_free);
368             if (!i)
369                 goto merr;
370         }
371         if (flags & CMS_CADES) {
372             ESS_SIGNING_CERT *sc = NULL;
373             ESS_SIGNING_CERT_V2 *sc2 = NULL;
374             int add_sc;
375
376             if (md == EVP_sha1() || md == NULL) {
377                 if ((sc = ESS_SIGNING_CERT_new_init(signer,
378                                                     NULL, 1)) == NULL)
379                     goto err;
380                 add_sc = cms_add1_signing_cert(si, sc);
381                 ESS_SIGNING_CERT_free(sc);
382             } else {
383                 if ((sc2 = ESS_SIGNING_CERT_V2_new_init(md, signer,
384                                                         NULL, 1)) == NULL)
385                     goto err;
386                 add_sc = cms_add1_signing_cert_v2(si, sc2);
387                 ESS_SIGNING_CERT_V2_free(sc2);
388             }
389             if (!add_sc)
390                 goto err;
391         }
392         if (flags & CMS_REUSE_DIGEST) {
393             if (!cms_copy_messageDigest(cms, si))
394                 goto err;
395             if (!cms_set_si_contentType_attr(cms, si))
396                 goto err;
397             if (!(flags & (CMS_PARTIAL | CMS_KEY_PARAM)) &&
398                 !CMS_SignerInfo_sign(si))
399                 goto err;
400         }
401     }
402
403     if (!(flags & CMS_NOCERTS)) {
404         /* NB ignore -1 return for duplicate cert */
405         if (!CMS_add1_cert(cms, signer))
406             goto merr;
407     }
408
409     if (flags & CMS_KEY_PARAM) {
410         if (flags & CMS_NOATTR) {
411             si->pctx = EVP_PKEY_CTX_new_from_pkey(ctx->libctx, si->pkey,
412                                                   ctx->propq);
413             if (si->pctx == NULL)
414                 goto err;
415             if (EVP_PKEY_sign_init(si->pctx) <= 0)
416                 goto err;
417             if (EVP_PKEY_CTX_set_signature_md(si->pctx, md) <= 0)
418                 goto err;
419         } else if (EVP_DigestSignInit_with_libctx(si->mctx, &si->pctx,
420                                                   EVP_MD_name(md),
421                                                   ctx->libctx, ctx->propq,
422                                                   pk) <= 0) {
423             goto err;
424         }
425     }
426
427     if (!sd->signerInfos)
428         sd->signerInfos = sk_CMS_SignerInfo_new_null();
429     if (!sd->signerInfos || !sk_CMS_SignerInfo_push(sd->signerInfos, si))
430         goto merr;
431
432     return si;
433
434  merr:
435     CMSerr(CMS_F_CMS_ADD1_SIGNER, ERR_R_MALLOC_FAILURE);
436  err:
437     M_ASN1_free_of(si, CMS_SignerInfo);
438     return NULL;
439
440 }
441
442 void cms_SignerInfos_set_cmsctx(CMS_ContentInfo *cms)
443 {
444     int i;
445     CMS_SignerInfo *si;
446     STACK_OF(CMS_SignerInfo) *sinfos = CMS_get0_SignerInfos(cms);
447     const CMS_CTX *ctx = cms_get0_cmsctx(cms);
448
449     for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) {
450         si = sk_CMS_SignerInfo_value(sinfos, i);
451         if (si != NULL)
452             si->cms_ctx = ctx;
453     }
454 }
455
456 static int cms_add1_signingTime(CMS_SignerInfo *si, ASN1_TIME *t)
457 {
458     ASN1_TIME *tt;
459     int r = 0;
460
461     if (t != NULL)
462         tt = t;
463     else
464         tt = X509_gmtime_adj(NULL, 0);
465
466     if (tt == NULL)
467         goto merr;
468
469     if (CMS_signed_add1_attr_by_NID(si, NID_pkcs9_signingTime,
470                                     tt->type, tt, -1) <= 0)
471         goto merr;
472
473     r = 1;
474  merr:
475     if (t == NULL)
476         ASN1_TIME_free(tt);
477
478     if (!r)
479         CMSerr(CMS_F_CMS_ADD1_SIGNINGTIME, ERR_R_MALLOC_FAILURE);
480
481     return r;
482
483 }
484
485 EVP_PKEY_CTX *CMS_SignerInfo_get0_pkey_ctx(CMS_SignerInfo *si)
486 {
487     return si->pctx;
488 }
489
490 EVP_MD_CTX *CMS_SignerInfo_get0_md_ctx(CMS_SignerInfo *si)
491 {
492     return si->mctx;
493 }
494
495 STACK_OF(CMS_SignerInfo) *CMS_get0_SignerInfos(CMS_ContentInfo *cms)
496 {
497     CMS_SignedData *sd = cms_get0_signed(cms);
498
499     return sd != NULL ? sd->signerInfos : NULL;
500 }
501
502 STACK_OF(X509) *CMS_get0_signers(CMS_ContentInfo *cms)
503 {
504     STACK_OF(X509) *signers = NULL;
505     STACK_OF(CMS_SignerInfo) *sinfos;
506     CMS_SignerInfo *si;
507     int i;
508
509     sinfos = CMS_get0_SignerInfos(cms);
510     for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) {
511         si = sk_CMS_SignerInfo_value(sinfos, i);
512         if (si->signer != NULL) {
513             if (signers == NULL) {
514                 signers = sk_X509_new_null();
515                 if (signers == NULL)
516                     return NULL;
517             }
518             if (!sk_X509_push(signers, si->signer)) {
519                 sk_X509_free(signers);
520                 return NULL;
521             }
522         }
523     }
524     return signers;
525 }
526
527 void CMS_SignerInfo_set1_signer_cert(CMS_SignerInfo *si, X509 *signer)
528 {
529     if (signer != NULL) {
530         X509_up_ref(signer);
531         EVP_PKEY_free(si->pkey);
532         si->pkey = X509_get_pubkey(signer);
533     }
534     X509_free(si->signer);
535     si->signer = signer;
536 }
537
538 int CMS_SignerInfo_get0_signer_id(CMS_SignerInfo *si,
539                                   ASN1_OCTET_STRING **keyid,
540                                   X509_NAME **issuer, ASN1_INTEGER **sno)
541 {
542     return cms_SignerIdentifier_get0_signer_id(si->sid, keyid, issuer, sno);
543 }
544
545 int CMS_SignerInfo_cert_cmp(CMS_SignerInfo *si, X509 *cert)
546 {
547     return cms_SignerIdentifier_cert_cmp(si->sid, cert);
548 }
549
550 int CMS_set1_signers_certs(CMS_ContentInfo *cms, STACK_OF(X509) *scerts,
551                            unsigned int flags)
552 {
553     CMS_SignedData *sd;
554     CMS_SignerInfo *si;
555     CMS_CertificateChoices *cch;
556     STACK_OF(CMS_CertificateChoices) *certs;
557     X509 *x;
558     int i, j;
559     int ret = 0;
560
561     sd = cms_get0_signed(cms);
562     if (sd == NULL)
563         return -1;
564     certs = sd->certificates;
565     for (i = 0; i < sk_CMS_SignerInfo_num(sd->signerInfos); i++) {
566         si = sk_CMS_SignerInfo_value(sd->signerInfos, i);
567         if (si->signer != NULL)
568             continue;
569
570         for (j = 0; j < sk_X509_num(scerts); j++) {
571             x = sk_X509_value(scerts, j);
572             if (CMS_SignerInfo_cert_cmp(si, x) == 0) {
573                 CMS_SignerInfo_set1_signer_cert(si, x);
574                 ret++;
575                 break;
576             }
577         }
578
579         if (si->signer != NULL || (flags & CMS_NOINTERN))
580             continue;
581
582         for (j = 0; j < sk_CMS_CertificateChoices_num(certs); j++) {
583             cch = sk_CMS_CertificateChoices_value(certs, j);
584             if (cch->type != 0)
585                 continue;
586             x = cch->d.certificate;
587             if (CMS_SignerInfo_cert_cmp(si, x) == 0) {
588                 CMS_SignerInfo_set1_signer_cert(si, x);
589                 ret++;
590                 break;
591             }
592         }
593     }
594     return ret;
595 }
596
597 void CMS_SignerInfo_get0_algs(CMS_SignerInfo *si, EVP_PKEY **pk,
598                               X509 **signer, X509_ALGOR **pdig,
599                               X509_ALGOR **psig)
600 {
601     if (pk != NULL)
602         *pk = si->pkey;
603     if (signer != NULL)
604         *signer = si->signer;
605     if (pdig != NULL)
606         *pdig = si->digestAlgorithm;
607     if (psig != NULL)
608         *psig = si->signatureAlgorithm;
609 }
610
611 ASN1_OCTET_STRING *CMS_SignerInfo_get0_signature(CMS_SignerInfo *si)
612 {
613     return si->signature;
614 }
615
616 static int cms_SignerInfo_content_sign(CMS_ContentInfo *cms,
617                                        CMS_SignerInfo *si, BIO *chain)
618 {
619     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
620     int r = 0;
621     EVP_PKEY_CTX *pctx = NULL;
622     const CMS_CTX *ctx = cms_get0_cmsctx(cms);
623
624     if (mctx == NULL) {
625         CMSerr(CMS_F_CMS_SIGNERINFO_CONTENT_SIGN, ERR_R_MALLOC_FAILURE);
626         return 0;
627     }
628
629     if (si->pkey == NULL) {
630         CMSerr(CMS_F_CMS_SIGNERINFO_CONTENT_SIGN, CMS_R_NO_PRIVATE_KEY);
631         goto err;
632     }
633
634     if (!cms_DigestAlgorithm_find_ctx(mctx, chain, si->digestAlgorithm))
635         goto err;
636     /* Set SignerInfo algorithm details if we used custom parameter */
637     if (si->pctx && !cms_sd_asn1_ctrl(si, 0))
638         goto err;
639
640     /*
641      * If any signed attributes calculate and add messageDigest attribute
642      */
643
644     if (CMS_signed_get_attr_count(si) >= 0) {
645         unsigned char md[EVP_MAX_MD_SIZE];
646         unsigned int mdlen;
647
648         if (!EVP_DigestFinal_ex(mctx, md, &mdlen))
649             goto err;
650         if (!CMS_signed_add1_attr_by_NID(si, NID_pkcs9_messageDigest,
651                                          V_ASN1_OCTET_STRING, md, mdlen))
652             goto err;
653         /* Copy content type across */
654         if (!cms_set_si_contentType_attr(cms, si))
655             goto err;
656
657         if (!CMS_SignerInfo_sign(si))
658             goto err;
659     } else if (si->pctx) {
660         unsigned char *sig;
661         size_t siglen;
662         unsigned char md[EVP_MAX_MD_SIZE];
663         unsigned int mdlen;
664
665         pctx = si->pctx;
666         if (!EVP_DigestFinal_ex(mctx, md, &mdlen))
667             goto err;
668         siglen = EVP_PKEY_size(si->pkey);
669         sig = OPENSSL_malloc(siglen);
670         if (sig == NULL) {
671             CMSerr(CMS_F_CMS_SIGNERINFO_CONTENT_SIGN, ERR_R_MALLOC_FAILURE);
672             goto err;
673         }
674         if (EVP_PKEY_sign(pctx, sig, &siglen, md, mdlen) <= 0) {
675             OPENSSL_free(sig);
676             goto err;
677         }
678         ASN1_STRING_set0(si->signature, sig, siglen);
679     } else {
680         unsigned char *sig;
681         unsigned int siglen;
682
683         sig = OPENSSL_malloc(EVP_PKEY_size(si->pkey));
684         if (sig == NULL) {
685             CMSerr(CMS_F_CMS_SIGNERINFO_CONTENT_SIGN, ERR_R_MALLOC_FAILURE);
686             goto err;
687         }
688         if (!EVP_SignFinal_with_libctx(mctx, sig, &siglen, si->pkey,
689                                        ctx->libctx, ctx->propq)) {
690             CMSerr(CMS_F_CMS_SIGNERINFO_CONTENT_SIGN, CMS_R_SIGNFINAL_ERROR);
691             OPENSSL_free(sig);
692             goto err;
693         }
694         ASN1_STRING_set0(si->signature, sig, siglen);
695     }
696
697     r = 1;
698
699  err:
700     EVP_MD_CTX_free(mctx);
701     EVP_PKEY_CTX_free(pctx);
702     return r;
703
704 }
705
706 int cms_SignedData_final(CMS_ContentInfo *cms, BIO *chain)
707 {
708     STACK_OF(CMS_SignerInfo) *sinfos;
709     CMS_SignerInfo *si;
710     int i;
711
712     sinfos = CMS_get0_SignerInfos(cms);
713     for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) {
714         si = sk_CMS_SignerInfo_value(sinfos, i);
715         if (!cms_SignerInfo_content_sign(cms, si, chain))
716             return 0;
717     }
718     cms->d.signedData->encapContentInfo->partial = 0;
719     return 1;
720 }
721
722 int CMS_SignerInfo_sign(CMS_SignerInfo *si)
723 {
724     EVP_MD_CTX *mctx = si->mctx;
725     EVP_PKEY_CTX *pctx = NULL;
726     unsigned char *abuf = NULL;
727     int alen;
728     size_t siglen;
729     const CMS_CTX *ctx = si->cms_ctx;
730     const char *md_name = OBJ_nid2sn(OBJ_obj2nid(si->digestAlgorithm->algorithm));
731
732     if (md_name == NULL)
733         return 0;
734
735     if (CMS_signed_get_attr_by_NID(si, NID_pkcs9_signingTime, -1) < 0) {
736         if (!cms_add1_signingTime(si, NULL))
737             goto err;
738     }
739
740     if (!CMS_si_check_attributes(si))
741         goto err;
742
743     if (si->pctx)
744         pctx = si->pctx;
745     else {
746         EVP_MD_CTX_reset(mctx);
747         if (EVP_DigestSignInit_with_libctx(mctx, &pctx,
748                                            md_name, ctx->libctx, ctx->propq,
749                                            si->pkey) <= 0)
750             goto err;
751         si->pctx = pctx;
752     }
753
754     /*
755      * TODO(3.0): This causes problems when providers are in use, so disabled
756      * for now. Can we get rid of this completely? AFAICT this ctrl has been
757      * present since CMS was first put in - but has never been used to do
758      * anything. All internal implementations just return 1 and ignore this ctrl
759      * and have always done so by the looks of things. To fix this we could
760      * convert this ctrl into a param, which would require us to send all the
761      * signer info data as a set of params...but that is non-trivial and since
762      * this isn't used by anything it may be better just to remove it.
763      */
764 #if 0
765     if (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_SIGN,
766                           EVP_PKEY_CTRL_CMS_SIGN, 0, si) <= 0) {
767         CMSerr(CMS_F_CMS_SIGNERINFO_SIGN, CMS_R_CTRL_ERROR);
768         goto err;
769     }
770 #endif
771
772     alen = ASN1_item_i2d((ASN1_VALUE *)si->signedAttrs, &abuf,
773                          ASN1_ITEM_rptr(CMS_Attributes_Sign));
774     if (!abuf)
775         goto err;
776     if (EVP_DigestSignUpdate(mctx, abuf, alen) <= 0)
777         goto err;
778     if (EVP_DigestSignFinal(mctx, NULL, &siglen) <= 0)
779         goto err;
780     OPENSSL_free(abuf);
781     abuf = OPENSSL_malloc(siglen);
782     if (abuf == NULL)
783         goto err;
784     if (EVP_DigestSignFinal(mctx, abuf, &siglen) <= 0)
785         goto err;
786
787     /*
788      * TODO(3.0): This causes problems when providers are in use, so disabled
789      * for now. Can we get rid of this completely? AFAICT this ctrl has been
790      * present since CMS was first put in - but has never been used to do
791      * anything. All internal implementations just return 1 and ignore this ctrl
792      * and have always done so by the looks of things. To fix this we could
793      * convert this ctrl into a param, which would require us to send all the
794      * signer info data as a set of params...but that is non-trivial and since
795      * this isn't used by anything it may be better just to remove it.
796      */
797 #if 0
798     if (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_SIGN,
799                           EVP_PKEY_CTRL_CMS_SIGN, 1, si) <= 0) {
800         CMSerr(CMS_F_CMS_SIGNERINFO_SIGN, CMS_R_CTRL_ERROR);
801         goto err;
802     }
803 #endif
804
805     EVP_MD_CTX_reset(mctx);
806
807     ASN1_STRING_set0(si->signature, abuf, siglen);
808
809     return 1;
810
811  err:
812     OPENSSL_free(abuf);
813     EVP_MD_CTX_reset(mctx);
814     return 0;
815 }
816
817 int CMS_SignerInfo_verify(CMS_SignerInfo *si)
818 {
819     EVP_MD_CTX *mctx = NULL;
820     unsigned char *abuf = NULL;
821     int alen, r = -1;
822     const char *name;
823     EVP_MD *md = NULL;
824     const CMS_CTX *ctx = si->cms_ctx;
825
826     if (si->pkey == NULL) {
827         CMSerr(CMS_F_CMS_SIGNERINFO_VERIFY, CMS_R_NO_PUBLIC_KEY);
828         return -1;
829     }
830
831     if (!CMS_si_check_attributes(si))
832         return -1;
833
834     name = OBJ_nid2sn(OBJ_obj2nid(si->digestAlgorithm->algorithm));
835     md = EVP_MD_fetch(ctx->libctx, name, ctx->propq);
836     if (md == NULL)
837         return -1;
838     if (si->mctx == NULL && (si->mctx = EVP_MD_CTX_new()) == NULL) {
839         CMSerr(CMS_F_CMS_SIGNERINFO_VERIFY, ERR_R_MALLOC_FAILURE);
840         goto err;
841     }
842     mctx = si->mctx;
843     if (EVP_DigestVerifyInit_with_libctx(mctx, &si->pctx,
844                                          EVP_MD_name(md), ctx->libctx, NULL,
845                                          si->pkey) <= 0)
846         goto err;
847
848     if (!cms_sd_asn1_ctrl(si, 1))
849         goto err;
850
851     alen = ASN1_item_i2d((ASN1_VALUE *)si->signedAttrs, &abuf,
852                          ASN1_ITEM_rptr(CMS_Attributes_Verify));
853     if (!abuf)
854         goto err;
855     r = EVP_DigestVerifyUpdate(mctx, abuf, alen);
856     OPENSSL_free(abuf);
857     if (r <= 0) {
858         r = -1;
859         goto err;
860     }
861     r = EVP_DigestVerifyFinal(mctx,
862                               si->signature->data, si->signature->length);
863     if (r <= 0)
864         CMSerr(CMS_F_CMS_SIGNERINFO_VERIFY, CMS_R_VERIFICATION_FAILURE);
865  err:
866     EVP_MD_free(md);
867     EVP_MD_CTX_reset(mctx);
868     return r;
869 }
870
871 /* Create a chain of digest BIOs from a CMS ContentInfo */
872
873 BIO *cms_SignedData_init_bio(CMS_ContentInfo *cms)
874 {
875     int i;
876     CMS_SignedData *sd;
877     BIO *chain = NULL;
878
879     sd = cms_get0_signed(cms);
880     if (sd == NULL)
881         return NULL;
882     if (cms->d.signedData->encapContentInfo->partial)
883         cms_sd_set_version(sd);
884     for (i = 0; i < sk_X509_ALGOR_num(sd->digestAlgorithms); i++) {
885         X509_ALGOR *digestAlgorithm;
886         BIO *mdbio;
887
888         digestAlgorithm = sk_X509_ALGOR_value(sd->digestAlgorithms, i);
889         mdbio = cms_DigestAlgorithm_init_bio(digestAlgorithm, cms_get0_cmsctx(cms));
890         if (mdbio == NULL)
891             goto err;
892         if (chain != NULL)
893             BIO_push(chain, mdbio);
894         else
895             chain = mdbio;
896     }
897     return chain;
898  err:
899     BIO_free_all(chain);
900     return NULL;
901 }
902
903 int CMS_SignerInfo_verify_content(CMS_SignerInfo *si, BIO *chain)
904 {
905     ASN1_OCTET_STRING *os = NULL;
906     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
907     EVP_PKEY_CTX *pkctx = NULL;
908     int r = -1;
909     unsigned char mval[EVP_MAX_MD_SIZE];
910     unsigned int mlen;
911
912     if (mctx == NULL) {
913         CMSerr(CMS_F_CMS_SIGNERINFO_VERIFY_CONTENT, ERR_R_MALLOC_FAILURE);
914         goto err;
915     }
916     /* If we have any signed attributes look for messageDigest value */
917     if (CMS_signed_get_attr_count(si) >= 0) {
918         os = CMS_signed_get0_data_by_OBJ(si,
919                                          OBJ_nid2obj(NID_pkcs9_messageDigest),
920                                          -3, V_ASN1_OCTET_STRING);
921         if (os == NULL) {
922             CMSerr(CMS_F_CMS_SIGNERINFO_VERIFY_CONTENT,
923                    CMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE);
924             goto err;
925         }
926     }
927
928     if (!cms_DigestAlgorithm_find_ctx(mctx, chain, si->digestAlgorithm))
929         goto err;
930
931     if (EVP_DigestFinal_ex(mctx, mval, &mlen) <= 0) {
932         CMSerr(CMS_F_CMS_SIGNERINFO_VERIFY_CONTENT,
933                CMS_R_UNABLE_TO_FINALIZE_CONTEXT);
934         goto err;
935     }
936
937     /* If messageDigest found compare it */
938
939     if (os != NULL) {
940         if (mlen != (unsigned int)os->length) {
941             CMSerr(CMS_F_CMS_SIGNERINFO_VERIFY_CONTENT,
942                    CMS_R_MESSAGEDIGEST_ATTRIBUTE_WRONG_LENGTH);
943             goto err;
944         }
945
946         if (memcmp(mval, os->data, mlen)) {
947             CMSerr(CMS_F_CMS_SIGNERINFO_VERIFY_CONTENT,
948                    CMS_R_VERIFICATION_FAILURE);
949             r = 0;
950         } else
951             r = 1;
952     } else {
953         const EVP_MD *md = EVP_MD_CTX_md(mctx);
954         const CMS_CTX *ctx = si->cms_ctx;
955
956         pkctx = EVP_PKEY_CTX_new_from_pkey(ctx->libctx, si->pkey, ctx->propq);
957         if (pkctx == NULL)
958             goto err;
959         if (EVP_PKEY_verify_init(pkctx) <= 0)
960             goto err;
961         if (EVP_PKEY_CTX_set_signature_md(pkctx, md) <= 0)
962             goto err;
963         si->pctx = pkctx;
964         if (!cms_sd_asn1_ctrl(si, 1))
965             goto err;
966         r = EVP_PKEY_verify(pkctx, si->signature->data,
967                             si->signature->length, mval, mlen);
968         if (r <= 0) {
969             CMSerr(CMS_F_CMS_SIGNERINFO_VERIFY_CONTENT,
970                    CMS_R_VERIFICATION_FAILURE);
971             r = 0;
972         }
973     }
974
975  err:
976     EVP_PKEY_CTX_free(pkctx);
977     EVP_MD_CTX_free(mctx);
978     return r;
979
980 }
981
982 int CMS_add_smimecap(CMS_SignerInfo *si, STACK_OF(X509_ALGOR) *algs)
983 {
984     unsigned char *smder = NULL;
985     int smderlen, r;
986
987     smderlen = i2d_X509_ALGORS(algs, &smder);
988     if (smderlen <= 0)
989         return 0;
990     r = CMS_signed_add1_attr_by_NID(si, NID_SMIMECapabilities,
991                                     V_ASN1_SEQUENCE, smder, smderlen);
992     OPENSSL_free(smder);
993     return r;
994 }
995
996 int CMS_add_simple_smimecap(STACK_OF(X509_ALGOR) **algs,
997                             int algnid, int keysize)
998 {
999     X509_ALGOR *alg;
1000     ASN1_INTEGER *key = NULL;
1001
1002     if (keysize > 0) {
1003         key = ASN1_INTEGER_new();
1004         if (key == NULL || !ASN1_INTEGER_set(key, keysize)) {
1005             ASN1_INTEGER_free(key);
1006             return 0;
1007         }
1008     }
1009     alg = X509_ALGOR_new();
1010     if (alg == NULL) {
1011         ASN1_INTEGER_free(key);
1012         return 0;
1013     }
1014
1015     X509_ALGOR_set0(alg, OBJ_nid2obj(algnid),
1016                     key ? V_ASN1_INTEGER : V_ASN1_UNDEF, key);
1017     if (*algs == NULL)
1018         *algs = sk_X509_ALGOR_new_null();
1019     if (*algs == NULL || !sk_X509_ALGOR_push(*algs, alg)) {
1020         X509_ALGOR_free(alg);
1021         return 0;
1022     }
1023     return 1;
1024 }
1025
1026 /* Check to see if a cipher exists and if so add S/MIME capabilities */
1027
1028 static int cms_add_cipher_smcap(STACK_OF(X509_ALGOR) **sk, int nid, int arg)
1029 {
1030     if (EVP_get_cipherbynid(nid))
1031         return CMS_add_simple_smimecap(sk, nid, arg);
1032     return 1;
1033 }
1034
1035 static int cms_add_digest_smcap(STACK_OF(X509_ALGOR) **sk, int nid, int arg)
1036 {
1037     if (EVP_get_digestbynid(nid))
1038         return CMS_add_simple_smimecap(sk, nid, arg);
1039     return 1;
1040 }
1041
1042 int CMS_add_standard_smimecap(STACK_OF(X509_ALGOR) **smcap)
1043 {
1044     if (!cms_add_cipher_smcap(smcap, NID_aes_256_cbc, -1)
1045         || !cms_add_digest_smcap(smcap, NID_id_GostR3411_2012_256, -1)
1046         || !cms_add_digest_smcap(smcap, NID_id_GostR3411_2012_512, -1)
1047         || !cms_add_digest_smcap(smcap, NID_id_GostR3411_94, -1)
1048         || !cms_add_cipher_smcap(smcap, NID_id_Gost28147_89, -1)
1049         || !cms_add_cipher_smcap(smcap, NID_aes_192_cbc, -1)
1050         || !cms_add_cipher_smcap(smcap, NID_aes_128_cbc, -1)
1051         || !cms_add_cipher_smcap(smcap, NID_des_ede3_cbc, -1)
1052         || !cms_add_cipher_smcap(smcap, NID_rc2_cbc, 128)
1053         || !cms_add_cipher_smcap(smcap, NID_rc2_cbc, 64)
1054         || !cms_add_cipher_smcap(smcap, NID_des_cbc, -1)
1055         || !cms_add_cipher_smcap(smcap, NID_rc2_cbc, 40))
1056         return 0;
1057     return 1;
1058 }