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