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