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