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