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