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