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