Run the withlibctx.pl script
[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_ex(si->mctx, &si->pctx, EVP_MD_name(md),
415                                          ctx->libctx, ctx->propq, pk) <= 0) {
416             goto err;
417         }
418     }
419
420     if (!sd->signerInfos)
421         sd->signerInfos = sk_CMS_SignerInfo_new_null();
422     if (!sd->signerInfos || !sk_CMS_SignerInfo_push(sd->signerInfos, si))
423         goto merr;
424
425     return si;
426
427  merr:
428     CMSerr(CMS_F_CMS_ADD1_SIGNER, ERR_R_MALLOC_FAILURE);
429  err:
430     M_ASN1_free_of(si, CMS_SignerInfo);
431     return NULL;
432
433 }
434
435 void cms_SignerInfos_set_cmsctx(CMS_ContentInfo *cms)
436 {
437     int i;
438     CMS_SignerInfo *si;
439     STACK_OF(CMS_SignerInfo) *sinfos = CMS_get0_SignerInfos(cms);
440     const CMS_CTX *ctx = cms_get0_cmsctx(cms);
441
442     for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) {
443         si = sk_CMS_SignerInfo_value(sinfos, i);
444         if (si != NULL)
445             si->cms_ctx = ctx;
446     }
447 }
448
449 static int cms_add1_signingTime(CMS_SignerInfo *si, ASN1_TIME *t)
450 {
451     ASN1_TIME *tt;
452     int r = 0;
453
454     if (t != NULL)
455         tt = t;
456     else
457         tt = X509_gmtime_adj(NULL, 0);
458
459     if (tt == NULL)
460         goto merr;
461
462     if (CMS_signed_add1_attr_by_NID(si, NID_pkcs9_signingTime,
463                                     tt->type, tt, -1) <= 0)
464         goto merr;
465
466     r = 1;
467  merr:
468     if (t == NULL)
469         ASN1_TIME_free(tt);
470
471     if (!r)
472         CMSerr(CMS_F_CMS_ADD1_SIGNINGTIME, ERR_R_MALLOC_FAILURE);
473
474     return r;
475
476 }
477
478 EVP_PKEY_CTX *CMS_SignerInfo_get0_pkey_ctx(CMS_SignerInfo *si)
479 {
480     return si->pctx;
481 }
482
483 EVP_MD_CTX *CMS_SignerInfo_get0_md_ctx(CMS_SignerInfo *si)
484 {
485     return si->mctx;
486 }
487
488 STACK_OF(CMS_SignerInfo) *CMS_get0_SignerInfos(CMS_ContentInfo *cms)
489 {
490     CMS_SignedData *sd = cms_get0_signed(cms);
491
492     return sd != NULL ? sd->signerInfos : NULL;
493 }
494
495 STACK_OF(X509) *CMS_get0_signers(CMS_ContentInfo *cms)
496 {
497     STACK_OF(X509) *signers = NULL;
498     STACK_OF(CMS_SignerInfo) *sinfos;
499     CMS_SignerInfo *si;
500     int i;
501
502     sinfos = CMS_get0_SignerInfos(cms);
503     for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) {
504         si = sk_CMS_SignerInfo_value(sinfos, i);
505         if (si->signer != NULL) {
506             if (!X509_add_cert_new(&signers, si->signer,
507                                    X509_ADD_FLAG_DEFAULT)) {
508                 sk_X509_free(signers);
509                 return NULL;
510             }
511         }
512     }
513     return signers;
514 }
515
516 void CMS_SignerInfo_set1_signer_cert(CMS_SignerInfo *si, X509 *signer)
517 {
518     if (signer != NULL) {
519         X509_up_ref(signer);
520         EVP_PKEY_free(si->pkey);
521         si->pkey = X509_get_pubkey(signer);
522     }
523     X509_free(si->signer);
524     si->signer = signer;
525 }
526
527 int CMS_SignerInfo_get0_signer_id(CMS_SignerInfo *si,
528                                   ASN1_OCTET_STRING **keyid,
529                                   X509_NAME **issuer, ASN1_INTEGER **sno)
530 {
531     return cms_SignerIdentifier_get0_signer_id(si->sid, keyid, issuer, sno);
532 }
533
534 int CMS_SignerInfo_cert_cmp(CMS_SignerInfo *si, X509 *cert)
535 {
536     return cms_SignerIdentifier_cert_cmp(si->sid, cert);
537 }
538
539 int CMS_set1_signers_certs(CMS_ContentInfo *cms, STACK_OF(X509) *scerts,
540                            unsigned int flags)
541 {
542     CMS_SignedData *sd;
543     CMS_SignerInfo *si;
544     CMS_CertificateChoices *cch;
545     STACK_OF(CMS_CertificateChoices) *certs;
546     X509 *x;
547     int i, j;
548     int ret = 0;
549
550     sd = cms_get0_signed(cms);
551     if (sd == NULL)
552         return -1;
553     certs = sd->certificates;
554     for (i = 0; i < sk_CMS_SignerInfo_num(sd->signerInfos); i++) {
555         si = sk_CMS_SignerInfo_value(sd->signerInfos, i);
556         if (si->signer != NULL)
557             continue;
558
559         for (j = 0; j < sk_X509_num(scerts); j++) {
560             x = sk_X509_value(scerts, j);
561             if (CMS_SignerInfo_cert_cmp(si, x) == 0) {
562                 CMS_SignerInfo_set1_signer_cert(si, x);
563                 ret++;
564                 break;
565             }
566         }
567
568         if (si->signer != NULL || (flags & CMS_NOINTERN))
569             continue;
570
571         for (j = 0; j < sk_CMS_CertificateChoices_num(certs); j++) {
572             cch = sk_CMS_CertificateChoices_value(certs, j);
573             if (cch->type != 0)
574                 continue;
575             x = cch->d.certificate;
576             if (CMS_SignerInfo_cert_cmp(si, x) == 0) {
577                 CMS_SignerInfo_set1_signer_cert(si, x);
578                 ret++;
579                 break;
580             }
581         }
582     }
583     return ret;
584 }
585
586 void CMS_SignerInfo_get0_algs(CMS_SignerInfo *si, EVP_PKEY **pk,
587                               X509 **signer, X509_ALGOR **pdig,
588                               X509_ALGOR **psig)
589 {
590     if (pk != NULL)
591         *pk = si->pkey;
592     if (signer != NULL)
593         *signer = si->signer;
594     if (pdig != NULL)
595         *pdig = si->digestAlgorithm;
596     if (psig != NULL)
597         *psig = si->signatureAlgorithm;
598 }
599
600 ASN1_OCTET_STRING *CMS_SignerInfo_get0_signature(CMS_SignerInfo *si)
601 {
602     return si->signature;
603 }
604
605 static int cms_SignerInfo_content_sign(CMS_ContentInfo *cms,
606                                        CMS_SignerInfo *si, BIO *chain)
607 {
608     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
609     int r = 0;
610     EVP_PKEY_CTX *pctx = NULL;
611     const CMS_CTX *ctx = cms_get0_cmsctx(cms);
612
613     if (mctx == NULL) {
614         CMSerr(CMS_F_CMS_SIGNERINFO_CONTENT_SIGN, ERR_R_MALLOC_FAILURE);
615         return 0;
616     }
617
618     if (si->pkey == NULL) {
619         CMSerr(CMS_F_CMS_SIGNERINFO_CONTENT_SIGN, CMS_R_NO_PRIVATE_KEY);
620         goto err;
621     }
622
623     if (!cms_DigestAlgorithm_find_ctx(mctx, chain, si->digestAlgorithm))
624         goto err;
625     /* Set SignerInfo algorithm details if we used custom parameter */
626     if (si->pctx && !cms_sd_asn1_ctrl(si, 0))
627         goto err;
628
629     /*
630      * If any signed attributes calculate and add messageDigest attribute
631      */
632
633     if (CMS_signed_get_attr_count(si) >= 0) {
634         unsigned char md[EVP_MAX_MD_SIZE];
635         unsigned int mdlen;
636
637         if (!EVP_DigestFinal_ex(mctx, md, &mdlen))
638             goto err;
639         if (!CMS_signed_add1_attr_by_NID(si, NID_pkcs9_messageDigest,
640                                          V_ASN1_OCTET_STRING, md, mdlen))
641             goto err;
642         /* Copy content type across */
643         if (!cms_set_si_contentType_attr(cms, si))
644             goto err;
645
646         if (!CMS_SignerInfo_sign(si))
647             goto err;
648     } else if (si->pctx) {
649         unsigned char *sig;
650         size_t siglen;
651         unsigned char md[EVP_MAX_MD_SIZE];
652         unsigned int mdlen;
653
654         pctx = si->pctx;
655         if (!EVP_DigestFinal_ex(mctx, md, &mdlen))
656             goto err;
657         siglen = EVP_PKEY_size(si->pkey);
658         sig = OPENSSL_malloc(siglen);
659         if (sig == NULL) {
660             CMSerr(CMS_F_CMS_SIGNERINFO_CONTENT_SIGN, ERR_R_MALLOC_FAILURE);
661             goto err;
662         }
663         if (EVP_PKEY_sign(pctx, sig, &siglen, md, mdlen) <= 0) {
664             OPENSSL_free(sig);
665             goto err;
666         }
667         ASN1_STRING_set0(si->signature, sig, siglen);
668     } else {
669         unsigned char *sig;
670         unsigned int siglen;
671
672         sig = OPENSSL_malloc(EVP_PKEY_size(si->pkey));
673         if (sig == NULL) {
674             CMSerr(CMS_F_CMS_SIGNERINFO_CONTENT_SIGN, ERR_R_MALLOC_FAILURE);
675             goto err;
676         }
677         if (!EVP_SignFinal_ex(mctx, sig, &siglen, si->pkey, ctx->libctx,
678                               ctx->propq)) {
679             CMSerr(CMS_F_CMS_SIGNERINFO_CONTENT_SIGN, CMS_R_SIGNFINAL_ERROR);
680             OPENSSL_free(sig);
681             goto err;
682         }
683         ASN1_STRING_set0(si->signature, sig, siglen);
684     }
685
686     r = 1;
687
688  err:
689     EVP_MD_CTX_free(mctx);
690     EVP_PKEY_CTX_free(pctx);
691     return r;
692
693 }
694
695 int cms_SignedData_final(CMS_ContentInfo *cms, BIO *chain)
696 {
697     STACK_OF(CMS_SignerInfo) *sinfos;
698     CMS_SignerInfo *si;
699     int i;
700
701     sinfos = CMS_get0_SignerInfos(cms);
702     for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) {
703         si = sk_CMS_SignerInfo_value(sinfos, i);
704         if (!cms_SignerInfo_content_sign(cms, si, chain))
705             return 0;
706     }
707     cms->d.signedData->encapContentInfo->partial = 0;
708     return 1;
709 }
710
711 int CMS_SignerInfo_sign(CMS_SignerInfo *si)
712 {
713     EVP_MD_CTX *mctx = si->mctx;
714     EVP_PKEY_CTX *pctx = NULL;
715     unsigned char *abuf = NULL;
716     int alen;
717     size_t siglen;
718     const CMS_CTX *ctx = si->cms_ctx;
719     const char *md_name = OBJ_nid2sn(OBJ_obj2nid(si->digestAlgorithm->algorithm));
720
721     if (md_name == NULL)
722         return 0;
723
724     if (CMS_signed_get_attr_by_NID(si, NID_pkcs9_signingTime, -1) < 0) {
725         if (!cms_add1_signingTime(si, NULL))
726             goto err;
727     }
728
729     if (!CMS_si_check_attributes(si))
730         goto err;
731
732     if (si->pctx)
733         pctx = si->pctx;
734     else {
735         EVP_MD_CTX_reset(mctx);
736         if (EVP_DigestSignInit_ex(mctx, &pctx, md_name, ctx->libctx, ctx->propq,
737                                   si->pkey) <= 0)
738             goto err;
739         si->pctx = pctx;
740     }
741
742     /*
743      * TODO(3.0): This causes problems when providers are in use, so disabled
744      * for now. Can we get rid of this completely? AFAICT this ctrl has been
745      * present since CMS was first put in - but has never been used to do
746      * anything. All internal implementations just return 1 and ignore this ctrl
747      * and have always done so by the looks of things. To fix this we could
748      * convert this ctrl into a param, which would require us to send all the
749      * signer info data as a set of params...but that is non-trivial and since
750      * this isn't used by anything it may be better just to remove it.
751      */
752 #if 0
753     if (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_SIGN,
754                           EVP_PKEY_CTRL_CMS_SIGN, 0, si) <= 0) {
755         CMSerr(CMS_F_CMS_SIGNERINFO_SIGN, CMS_R_CTRL_ERROR);
756         goto err;
757     }
758 #endif
759
760     alen = ASN1_item_i2d((ASN1_VALUE *)si->signedAttrs, &abuf,
761                          ASN1_ITEM_rptr(CMS_Attributes_Sign));
762     if (!abuf)
763         goto err;
764     if (EVP_DigestSignUpdate(mctx, abuf, alen) <= 0)
765         goto err;
766     if (EVP_DigestSignFinal(mctx, NULL, &siglen) <= 0)
767         goto err;
768     OPENSSL_free(abuf);
769     abuf = OPENSSL_malloc(siglen);
770     if (abuf == NULL)
771         goto err;
772     if (EVP_DigestSignFinal(mctx, abuf, &siglen) <= 0)
773         goto err;
774
775     /*
776      * TODO(3.0): This causes problems when providers are in use, so disabled
777      * for now. Can we get rid of this completely? AFAICT this ctrl has been
778      * present since CMS was first put in - but has never been used to do
779      * anything. All internal implementations just return 1 and ignore this ctrl
780      * and have always done so by the looks of things. To fix this we could
781      * convert this ctrl into a param, which would require us to send all the
782      * signer info data as a set of params...but that is non-trivial and since
783      * this isn't used by anything it may be better just to remove it.
784      */
785 #if 0
786     if (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_SIGN,
787                           EVP_PKEY_CTRL_CMS_SIGN, 1, si) <= 0) {
788         CMSerr(CMS_F_CMS_SIGNERINFO_SIGN, CMS_R_CTRL_ERROR);
789         goto err;
790     }
791 #endif
792
793     EVP_MD_CTX_reset(mctx);
794
795     ASN1_STRING_set0(si->signature, abuf, siglen);
796
797     return 1;
798
799  err:
800     OPENSSL_free(abuf);
801     EVP_MD_CTX_reset(mctx);
802     return 0;
803 }
804
805 int CMS_SignerInfo_verify(CMS_SignerInfo *si)
806 {
807     EVP_MD_CTX *mctx = NULL;
808     unsigned char *abuf = NULL;
809     int alen, r = -1;
810     const char *name;
811     const EVP_MD *md;
812     EVP_MD *fetched_md = NULL;
813     const CMS_CTX *ctx = si->cms_ctx;
814
815     if (si->pkey == NULL) {
816         CMSerr(CMS_F_CMS_SIGNERINFO_VERIFY, CMS_R_NO_PUBLIC_KEY);
817         return -1;
818     }
819
820     if (!CMS_si_check_attributes(si))
821         return -1;
822
823     name = OBJ_nid2sn(OBJ_obj2nid(si->digestAlgorithm->algorithm));
824
825     (void)ERR_set_mark();
826     fetched_md = EVP_MD_fetch(ctx->libctx, name, ctx->propq);
827
828     if (fetched_md != NULL)
829         md = fetched_md;
830     else
831         md = EVP_get_digestbyobj(si->digestAlgorithm->algorithm);
832     if (md == NULL) {
833         (void)ERR_clear_last_mark();
834         CMSerr(0, CMS_R_UNKNOWN_DIGEST_ALGORITHM);
835         return -1;
836     }
837     (void)ERR_pop_to_mark();
838
839     if (si->mctx == NULL && (si->mctx = EVP_MD_CTX_new()) == NULL) {
840         CMSerr(CMS_F_CMS_SIGNERINFO_VERIFY, ERR_R_MALLOC_FAILURE);
841         goto err;
842     }
843     mctx = si->mctx;
844     if (EVP_DigestVerifyInit_ex(mctx, &si->pctx, EVP_MD_name(md), ctx->libctx,
845                                 NULL, 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 == NULL || alen < 0)
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(fetched_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 }