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