1570fb6fe584163763a4a375a7bcdca7a438ac5c
[openssl.git] / crypto / cms / cms_sd.c
1 /* crypto/cms/cms_sd.c */
2 /*
3  * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
4  * project.
5  */
6 /* ====================================================================
7  * Copyright (c) 2008 The OpenSSL Project.  All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in
18  *    the documentation and/or other materials provided with the
19  *    distribution.
20  *
21  * 3. All advertising materials mentioning features or use of this
22  *    software must display the following acknowledgment:
23  *    "This product includes software developed by the OpenSSL Project
24  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
25  *
26  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
27  *    endorse or promote products derived from this software without
28  *    prior written permission. For written permission, please contact
29  *    licensing@OpenSSL.org.
30  *
31  * 5. Products derived from this software may not be called "OpenSSL"
32  *    nor may "OpenSSL" appear in their names without prior written
33  *    permission of the OpenSSL Project.
34  *
35  * 6. Redistributions of any form whatsoever must retain the following
36  *    acknowledgment:
37  *    "This product includes software developed by the OpenSSL Project
38  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
41  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
44  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
46  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
49  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
50  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
51  * OF THE POSSIBILITY OF SUCH DAMAGE.
52  * ====================================================================
53  */
54
55 #include "internal/cryptlib.h"
56 #include <openssl/asn1t.h>
57 #include <openssl/pem.h>
58 #include <openssl/x509.h>
59 #include <openssl/x509v3.h>
60 #include <openssl/err.h>
61 #include <openssl/cms.h>
62 #include "cms_lcl.h"
63 #include "internal/asn1_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 initialize 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     X509_check_purpose(signer, -1, -1);
284
285     CRYPTO_add(&pk->references, 1, CRYPTO_LOCK_EVP_PKEY);
286     X509_up_ref(signer);
287
288     si->pkey = pk;
289     si->signer = signer;
290     si->mctx = EVP_MD_CTX_create();
291     si->pctx = NULL;
292
293     if (si->mctx == NULL) {
294         CMSerr(CMS_F_CMS_ADD1_SIGNER, ERR_R_MALLOC_FAILURE);
295         goto err;
296     }
297
298     if (flags & CMS_USE_KEYID) {
299         si->version = 3;
300         if (sd->version < 3)
301             sd->version = 3;
302         type = CMS_SIGNERINFO_KEYIDENTIFIER;
303     } else {
304         type = CMS_SIGNERINFO_ISSUER_SERIAL;
305         si->version = 1;
306     }
307
308     if (!cms_set1_SignerIdentifier(si->sid, signer, type))
309         goto err;
310
311     if (md == NULL) {
312         int def_nid;
313         if (EVP_PKEY_get_default_digest_nid(pk, &def_nid) <= 0)
314             goto err;
315         md = EVP_get_digestbynid(def_nid);
316         if (md == NULL) {
317             CMSerr(CMS_F_CMS_ADD1_SIGNER, CMS_R_NO_DEFAULT_DIGEST);
318             goto err;
319         }
320     }
321
322     if (!md) {
323         CMSerr(CMS_F_CMS_ADD1_SIGNER, CMS_R_NO_DIGEST_SET);
324         goto err;
325     }
326
327     X509_ALGOR_set_md(si->digestAlgorithm, md);
328
329     /* See if digest is present in digestAlgorithms */
330     for (i = 0; i < sk_X509_ALGOR_num(sd->digestAlgorithms); i++) {
331         ASN1_OBJECT *aoid;
332         alg = sk_X509_ALGOR_value(sd->digestAlgorithms, i);
333         X509_ALGOR_get0(&aoid, NULL, NULL, alg);
334         if (OBJ_obj2nid(aoid) == EVP_MD_type(md))
335             break;
336     }
337
338     if (i == sk_X509_ALGOR_num(sd->digestAlgorithms)) {
339         alg = X509_ALGOR_new();
340         if (alg == NULL)
341             goto merr;
342         X509_ALGOR_set_md(alg, md);
343         if (!sk_X509_ALGOR_push(sd->digestAlgorithms, alg)) {
344             X509_ALGOR_free(alg);
345             goto merr;
346         }
347     }
348
349     if (!(flags & CMS_KEY_PARAM) && !cms_sd_asn1_ctrl(si, 0))
350         goto err;
351     if (!(flags & CMS_NOATTR)) {
352         /*
353          * Initialialize signed attributes strutucture so other attributes
354          * such as signing time etc are added later even if we add none here.
355          */
356         if (!si->signedAttrs) {
357             si->signedAttrs = sk_X509_ATTRIBUTE_new_null();
358             if (!si->signedAttrs)
359                 goto merr;
360         }
361
362         if (!(flags & CMS_NOSMIMECAP)) {
363             STACK_OF(X509_ALGOR) *smcap = NULL;
364             i = CMS_add_standard_smimecap(&smcap);
365             if (i)
366                 i = CMS_add_smimecap(si, smcap);
367             sk_X509_ALGOR_pop_free(smcap, X509_ALGOR_free);
368             if (!i)
369                 goto merr;
370         }
371         if (flags & CMS_REUSE_DIGEST) {
372             if (!cms_copy_messageDigest(cms, si))
373                 goto err;
374             if (!(flags & (CMS_PARTIAL | CMS_KEY_PARAM)) &&
375                 !CMS_SignerInfo_sign(si))
376                 goto err;
377         }
378     }
379
380     if (!(flags & CMS_NOCERTS)) {
381         /* NB ignore -1 return for duplicate cert */
382         if (!CMS_add1_cert(cms, signer))
383             goto merr;
384     }
385
386     if (flags & CMS_KEY_PARAM) {
387         if (flags & CMS_NOATTR) {
388             si->pctx = EVP_PKEY_CTX_new(si->pkey, NULL);
389             if (si->pctx == NULL)
390                 goto err;
391             if (EVP_PKEY_sign_init(si->pctx) <= 0)
392                 goto err;
393             if (EVP_PKEY_CTX_set_signature_md(si->pctx, md) <= 0)
394                 goto err;
395         } else if (EVP_DigestSignInit(si->mctx, &si->pctx, md, NULL, pk) <=
396                    0)
397             goto err;
398     }
399
400     if (!sd->signerInfos)
401         sd->signerInfos = sk_CMS_SignerInfo_new_null();
402     if (!sd->signerInfos || !sk_CMS_SignerInfo_push(sd->signerInfos, si))
403         goto merr;
404
405     return si;
406
407  merr:
408     CMSerr(CMS_F_CMS_ADD1_SIGNER, ERR_R_MALLOC_FAILURE);
409  err:
410     M_ASN1_free_of(si, CMS_SignerInfo);
411     return NULL;
412
413 }
414
415 static int cms_add1_signingTime(CMS_SignerInfo *si, ASN1_TIME *t)
416 {
417     ASN1_TIME *tt;
418     int r = 0;
419     if (t)
420         tt = t;
421     else
422         tt = X509_gmtime_adj(NULL, 0);
423
424     if (!tt)
425         goto merr;
426
427     if (CMS_signed_add1_attr_by_NID(si, NID_pkcs9_signingTime,
428                                     tt->type, tt, -1) <= 0)
429         goto merr;
430
431     r = 1;
432
433  merr:
434
435     if (!t)
436         ASN1_TIME_free(tt);
437
438     if (!r)
439         CMSerr(CMS_F_CMS_ADD1_SIGNINGTIME, ERR_R_MALLOC_FAILURE);
440
441     return r;
442
443 }
444
445 EVP_PKEY_CTX *CMS_SignerInfo_get0_pkey_ctx(CMS_SignerInfo *si)
446 {
447     return si->pctx;
448 }
449
450 EVP_MD_CTX *CMS_SignerInfo_get0_md_ctx(CMS_SignerInfo *si)
451 {
452     return si->mctx;
453 }
454
455 STACK_OF(CMS_SignerInfo) *CMS_get0_SignerInfos(CMS_ContentInfo *cms)
456 {
457     CMS_SignedData *sd;
458     sd = cms_get0_signed(cms);
459     if (!sd)
460         return NULL;
461     return sd->signerInfos;
462 }
463
464 STACK_OF(X509) *CMS_get0_signers(CMS_ContentInfo *cms)
465 {
466     STACK_OF(X509) *signers = NULL;
467     STACK_OF(CMS_SignerInfo) *sinfos;
468     CMS_SignerInfo *si;
469     int i;
470     sinfos = CMS_get0_SignerInfos(cms);
471     for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) {
472         si = sk_CMS_SignerInfo_value(sinfos, i);
473         if (si->signer) {
474             if (!signers) {
475                 signers = sk_X509_new_null();
476                 if (!signers)
477                     return NULL;
478             }
479             if (!sk_X509_push(signers, si->signer)) {
480                 sk_X509_free(signers);
481                 return NULL;
482             }
483         }
484     }
485     return signers;
486 }
487
488 void CMS_SignerInfo_set1_signer_cert(CMS_SignerInfo *si, X509 *signer)
489 {
490     if (signer) {
491         X509_up_ref(signer);
492         EVP_PKEY_free(si->pkey);
493         si->pkey = X509_get_pubkey(signer);
494     }
495     X509_free(si->signer);
496     si->signer = signer;
497 }
498
499 int CMS_SignerInfo_get0_signer_id(CMS_SignerInfo *si,
500                                   ASN1_OCTET_STRING **keyid,
501                                   X509_NAME **issuer, ASN1_INTEGER **sno)
502 {
503     return cms_SignerIdentifier_get0_signer_id(si->sid, keyid, issuer, sno);
504 }
505
506 int CMS_SignerInfo_cert_cmp(CMS_SignerInfo *si, X509 *cert)
507 {
508     return cms_SignerIdentifier_cert_cmp(si->sid, cert);
509 }
510
511 int CMS_set1_signers_certs(CMS_ContentInfo *cms, STACK_OF(X509) *scerts,
512                            unsigned int flags)
513 {
514     CMS_SignedData *sd;
515     CMS_SignerInfo *si;
516     CMS_CertificateChoices *cch;
517     STACK_OF(CMS_CertificateChoices) *certs;
518     X509 *x;
519     int i, j;
520     int ret = 0;
521     sd = cms_get0_signed(cms);
522     if (!sd)
523         return -1;
524     certs = sd->certificates;
525     for (i = 0; i < sk_CMS_SignerInfo_num(sd->signerInfos); i++) {
526         si = sk_CMS_SignerInfo_value(sd->signerInfos, i);
527         if (si->signer)
528             continue;
529
530         for (j = 0; j < sk_X509_num(scerts); j++) {
531             x = sk_X509_value(scerts, j);
532             if (CMS_SignerInfo_cert_cmp(si, x) == 0) {
533                 CMS_SignerInfo_set1_signer_cert(si, x);
534                 ret++;
535                 break;
536             }
537         }
538
539         if (si->signer || (flags & CMS_NOINTERN))
540             continue;
541
542         for (j = 0; j < sk_CMS_CertificateChoices_num(certs); j++) {
543             cch = sk_CMS_CertificateChoices_value(certs, j);
544             if (cch->type != 0)
545                 continue;
546             x = cch->d.certificate;
547             if (CMS_SignerInfo_cert_cmp(si, x) == 0) {
548                 CMS_SignerInfo_set1_signer_cert(si, x);
549                 ret++;
550                 break;
551             }
552         }
553     }
554     return ret;
555 }
556
557 void CMS_SignerInfo_get0_algs(CMS_SignerInfo *si, EVP_PKEY **pk,
558                               X509 **signer, X509_ALGOR **pdig,
559                               X509_ALGOR **psig)
560 {
561     if (pk)
562         *pk = si->pkey;
563     if (signer)
564         *signer = si->signer;
565     if (pdig)
566         *pdig = si->digestAlgorithm;
567     if (psig)
568         *psig = si->signatureAlgorithm;
569 }
570
571 ASN1_OCTET_STRING *CMS_SignerInfo_get0_signature(CMS_SignerInfo *si)
572 {
573     return si->signature;
574 }
575
576 static int cms_SignerInfo_content_sign(CMS_ContentInfo *cms,
577                                        CMS_SignerInfo *si, BIO *chain)
578 {
579     EVP_MD_CTX *mctx = EVP_MD_CTX_create();
580     int r = 0;
581     EVP_PKEY_CTX *pctx = NULL;
582
583     if (mctx == NULL) {
584         CMSerr(CMS_F_CMS_SIGNERINFO_CONTENT_SIGN, ERR_R_MALLOC_FAILURE);
585         return 0;
586     }
587
588     if (!si->pkey) {
589         CMSerr(CMS_F_CMS_SIGNERINFO_CONTENT_SIGN, CMS_R_NO_PRIVATE_KEY);
590         return 0;
591     }
592
593     if (!cms_DigestAlgorithm_find_ctx(mctx, chain, si->digestAlgorithm))
594         goto err;
595     /* Set SignerInfo algortihm details if we used custom parametsr */
596     if (si->pctx && !cms_sd_asn1_ctrl(si, 0))
597         goto err;
598
599     /*
600      * If any signed attributes calculate and add messageDigest attribute
601      */
602
603     if (CMS_signed_get_attr_count(si) >= 0) {
604         ASN1_OBJECT *ctype =
605             cms->d.signedData->encapContentInfo->eContentType;
606         unsigned char md[EVP_MAX_MD_SIZE];
607         unsigned int mdlen;
608         if (!EVP_DigestFinal_ex(mctx, md, &mdlen))
609             goto err;
610         if (!CMS_signed_add1_attr_by_NID(si, NID_pkcs9_messageDigest,
611                                          V_ASN1_OCTET_STRING, md, mdlen))
612             goto err;
613         /* Copy content type across */
614         if (CMS_signed_add1_attr_by_NID(si, NID_pkcs9_contentType,
615                                         V_ASN1_OBJECT, ctype, -1) <= 0)
616             goto err;
617         if (!CMS_SignerInfo_sign(si))
618             goto err;
619     } else if (si->pctx) {
620         unsigned char *sig;
621         size_t siglen;
622         unsigned char md[EVP_MAX_MD_SIZE];
623         unsigned int mdlen;
624         pctx = si->pctx;
625         if (!EVP_DigestFinal_ex(mctx, md, &mdlen))
626             goto err;
627         siglen = EVP_PKEY_size(si->pkey);
628         sig = OPENSSL_malloc(siglen);
629         if (sig == NULL) {
630             CMSerr(CMS_F_CMS_SIGNERINFO_CONTENT_SIGN, ERR_R_MALLOC_FAILURE);
631             goto err;
632         }
633         if (EVP_PKEY_sign(pctx, sig, &siglen, md, mdlen) <= 0) {
634             OPENSSL_free(sig);
635             goto err;
636         }
637         ASN1_STRING_set0(si->signature, sig, siglen);
638     } else {
639         unsigned char *sig;
640         unsigned int siglen;
641         sig = OPENSSL_malloc(EVP_PKEY_size(si->pkey));
642         if (sig == NULL) {
643             CMSerr(CMS_F_CMS_SIGNERINFO_CONTENT_SIGN, ERR_R_MALLOC_FAILURE);
644             goto err;
645         }
646         if (!EVP_SignFinal(mctx, sig, &siglen, si->pkey)) {
647             CMSerr(CMS_F_CMS_SIGNERINFO_CONTENT_SIGN, CMS_R_SIGNFINAL_ERROR);
648             OPENSSL_free(sig);
649             goto err;
650         }
651         ASN1_STRING_set0(si->signature, sig, siglen);
652     }
653
654     r = 1;
655
656  err:
657     EVP_MD_CTX_destroy(mctx);
658     EVP_PKEY_CTX_free(pctx);
659     return r;
660
661 }
662
663 int cms_SignedData_final(CMS_ContentInfo *cms, BIO *chain)
664 {
665     STACK_OF(CMS_SignerInfo) *sinfos;
666     CMS_SignerInfo *si;
667     int i;
668     sinfos = CMS_get0_SignerInfos(cms);
669     for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) {
670         si = sk_CMS_SignerInfo_value(sinfos, i);
671         if (!cms_SignerInfo_content_sign(cms, si, chain))
672             return 0;
673     }
674     cms->d.signedData->encapContentInfo->partial = 0;
675     return 1;
676 }
677
678 int CMS_SignerInfo_sign(CMS_SignerInfo *si)
679 {
680     EVP_MD_CTX *mctx = si->mctx;
681     EVP_PKEY_CTX *pctx;
682     unsigned char *abuf = NULL;
683     int alen;
684     size_t siglen;
685     const EVP_MD *md = NULL;
686
687     md = EVP_get_digestbyobj(si->digestAlgorithm->algorithm);
688     if (md == NULL)
689         return 0;
690
691     if (CMS_signed_get_attr_by_NID(si, NID_pkcs9_signingTime, -1) < 0) {
692         if (!cms_add1_signingTime(si, NULL))
693             goto err;
694     }
695
696     if (si->pctx)
697         pctx = si->pctx;
698     else {
699         EVP_MD_CTX_init(mctx);
700         if (EVP_DigestSignInit(mctx, &pctx, md, NULL, si->pkey) <= 0)
701             goto err;
702     }
703
704     if (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_SIGN,
705                           EVP_PKEY_CTRL_CMS_SIGN, 0, si) <= 0) {
706         CMSerr(CMS_F_CMS_SIGNERINFO_SIGN, CMS_R_CTRL_ERROR);
707         goto err;
708     }
709
710     alen = ASN1_item_i2d((ASN1_VALUE *)si->signedAttrs, &abuf,
711                          ASN1_ITEM_rptr(CMS_Attributes_Sign));
712     if (!abuf)
713         goto err;
714     if (EVP_DigestSignUpdate(mctx, abuf, alen) <= 0)
715         goto err;
716     if (EVP_DigestSignFinal(mctx, NULL, &siglen) <= 0)
717         goto err;
718     OPENSSL_free(abuf);
719     abuf = OPENSSL_malloc(siglen);
720     if (abuf == NULL)
721         goto err;
722     if (EVP_DigestSignFinal(mctx, abuf, &siglen) <= 0)
723         goto err;
724
725     if (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_SIGN,
726                           EVP_PKEY_CTRL_CMS_SIGN, 1, si) <= 0) {
727         CMSerr(CMS_F_CMS_SIGNERINFO_SIGN, CMS_R_CTRL_ERROR);
728         goto err;
729     }
730
731     EVP_MD_CTX_init(mctx);
732
733     ASN1_STRING_set0(si->signature, abuf, siglen);
734
735     return 1;
736
737  err:
738     OPENSSL_free(abuf);
739     EVP_MD_CTX_init(mctx);
740     return 0;
741
742 }
743
744 int CMS_SignerInfo_verify(CMS_SignerInfo *si)
745 {
746     EVP_MD_CTX *mctx = NULL;
747     unsigned char *abuf = NULL;
748     int alen, r = -1;
749     const EVP_MD *md = NULL;
750
751     if (!si->pkey) {
752         CMSerr(CMS_F_CMS_SIGNERINFO_VERIFY, CMS_R_NO_PUBLIC_KEY);
753         return -1;
754     }
755
756     md = EVP_get_digestbyobj(si->digestAlgorithm->algorithm);
757     if (md == NULL)
758         return -1;
759     if (si->mctx == NULL)
760         si->mctx = EVP_MD_CTX_create();
761     mctx = si->mctx;
762     if (EVP_DigestVerifyInit(mctx, &si->pctx, md, NULL, si->pkey) <= 0)
763         goto err;
764
765     if (!cms_sd_asn1_ctrl(si, 1))
766         goto err;
767
768     alen = ASN1_item_i2d((ASN1_VALUE *)si->signedAttrs, &abuf,
769                          ASN1_ITEM_rptr(CMS_Attributes_Verify));
770     if (!abuf)
771         goto err;
772     r = EVP_DigestVerifyUpdate(mctx, abuf, alen);
773     OPENSSL_free(abuf);
774     if (r <= 0) {
775         r = -1;
776         goto err;
777     }
778     r = EVP_DigestVerifyFinal(mctx,
779                               si->signature->data, si->signature->length);
780     if (r <= 0)
781         CMSerr(CMS_F_CMS_SIGNERINFO_VERIFY, CMS_R_VERIFICATION_FAILURE);
782  err:
783     EVP_MD_CTX_init(mctx);
784     return r;
785 }
786
787 /* Create a chain of digest BIOs from a CMS ContentInfo */
788
789 BIO *cms_SignedData_init_bio(CMS_ContentInfo *cms)
790 {
791     int i;
792     CMS_SignedData *sd;
793     BIO *chain = NULL;
794     sd = cms_get0_signed(cms);
795     if (!sd)
796         return NULL;
797     if (cms->d.signedData->encapContentInfo->partial)
798         cms_sd_set_version(sd);
799     for (i = 0; i < sk_X509_ALGOR_num(sd->digestAlgorithms); i++) {
800         X509_ALGOR *digestAlgorithm;
801         BIO *mdbio;
802         digestAlgorithm = sk_X509_ALGOR_value(sd->digestAlgorithms, i);
803         mdbio = cms_DigestAlgorithm_init_bio(digestAlgorithm);
804         if (!mdbio)
805             goto err;
806         if (chain)
807             BIO_push(chain, mdbio);
808         else
809             chain = mdbio;
810     }
811     return chain;
812  err:
813     BIO_free_all(chain);
814     return NULL;
815 }
816
817 int CMS_SignerInfo_verify_content(CMS_SignerInfo *si, BIO *chain)
818 {
819     ASN1_OCTET_STRING *os = NULL;
820     EVP_MD_CTX *mctx = EVP_MD_CTX_create();
821     EVP_PKEY_CTX *pkctx = NULL;
822     int r = -1;
823     unsigned char mval[EVP_MAX_MD_SIZE];
824     unsigned int mlen;
825
826     if (mctx == NULL) {
827         CMSerr(CMS_F_CMS_SIGNERINFO_VERIFY_CONTENT, ERR_R_MALLOC_FAILURE);
828         goto err;
829     }
830     /* If we have any signed attributes look for messageDigest value */
831     if (CMS_signed_get_attr_count(si) >= 0) {
832         os = CMS_signed_get0_data_by_OBJ(si,
833                                          OBJ_nid2obj(NID_pkcs9_messageDigest),
834                                          -3, V_ASN1_OCTET_STRING);
835         if (!os) {
836             CMSerr(CMS_F_CMS_SIGNERINFO_VERIFY_CONTENT,
837                    CMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE);
838             goto err;
839         }
840     }
841
842     if (!cms_DigestAlgorithm_find_ctx(mctx, chain, si->digestAlgorithm))
843         goto err;
844
845     if (EVP_DigestFinal_ex(mctx, mval, &mlen) <= 0) {
846         CMSerr(CMS_F_CMS_SIGNERINFO_VERIFY_CONTENT,
847                CMS_R_UNABLE_TO_FINALIZE_CONTEXT);
848         goto err;
849     }
850
851     /* If messageDigest found compare it */
852
853     if (os) {
854         if (mlen != (unsigned int)os->length) {
855             CMSerr(CMS_F_CMS_SIGNERINFO_VERIFY_CONTENT,
856                    CMS_R_MESSAGEDIGEST_ATTRIBUTE_WRONG_LENGTH);
857             goto err;
858         }
859
860         if (memcmp(mval, os->data, mlen)) {
861             CMSerr(CMS_F_CMS_SIGNERINFO_VERIFY_CONTENT,
862                    CMS_R_VERIFICATION_FAILURE);
863             r = 0;
864         } else
865             r = 1;
866     } else {
867         const EVP_MD *md = EVP_MD_CTX_md(mctx);
868         pkctx = EVP_PKEY_CTX_new(si->pkey, NULL);
869         if (pkctx == NULL)
870             goto err;
871         if (EVP_PKEY_verify_init(pkctx) <= 0)
872             goto err;
873         if (EVP_PKEY_CTX_set_signature_md(pkctx, md) <= 0)
874             goto err;
875         si->pctx = pkctx;
876         if (!cms_sd_asn1_ctrl(si, 1))
877             goto err;
878         r = EVP_PKEY_verify(pkctx, si->signature->data,
879                             si->signature->length, mval, mlen);
880         if (r <= 0) {
881             CMSerr(CMS_F_CMS_SIGNERINFO_VERIFY_CONTENT,
882                    CMS_R_VERIFICATION_FAILURE);
883             r = 0;
884         }
885     }
886
887  err:
888     EVP_PKEY_CTX_free(pkctx);
889     EVP_MD_CTX_destroy(mctx);
890     return r;
891
892 }
893
894 int CMS_add_smimecap(CMS_SignerInfo *si, STACK_OF(X509_ALGOR) *algs)
895 {
896     unsigned char *smder = NULL;
897     int smderlen, r;
898     smderlen = i2d_X509_ALGORS(algs, &smder);
899     if (smderlen <= 0)
900         return 0;
901     r = CMS_signed_add1_attr_by_NID(si, NID_SMIMECapabilities,
902                                     V_ASN1_SEQUENCE, smder, smderlen);
903     OPENSSL_free(smder);
904     return r;
905 }
906
907 int CMS_add_simple_smimecap(STACK_OF(X509_ALGOR) **algs,
908                             int algnid, int keysize)
909 {
910     X509_ALGOR *alg;
911     ASN1_INTEGER *key = NULL;
912     if (keysize > 0) {
913         key = ASN1_INTEGER_new();
914         if (key == NULL || !ASN1_INTEGER_set(key, keysize))
915             return 0;
916     }
917     alg = X509_ALGOR_new();
918     if (alg == NULL) {
919         ASN1_INTEGER_free(key);
920         return 0;
921     }
922
923     X509_ALGOR_set0(alg, OBJ_nid2obj(algnid),
924                     key ? V_ASN1_INTEGER : V_ASN1_UNDEF, key);
925     if (*algs == NULL)
926         *algs = sk_X509_ALGOR_new_null();
927     if (*algs == NULL || !sk_X509_ALGOR_push(*algs, alg)) {
928         X509_ALGOR_free(alg);
929         return 0;
930     }
931     return 1;
932 }
933
934 /* Check to see if a cipher exists and if so add S/MIME capabilities */
935
936 static int cms_add_cipher_smcap(STACK_OF(X509_ALGOR) **sk, int nid, int arg)
937 {
938     if (EVP_get_cipherbynid(nid))
939         return CMS_add_simple_smimecap(sk, nid, arg);
940     return 1;
941 }
942
943 static int cms_add_digest_smcap(STACK_OF(X509_ALGOR) **sk, int nid, int arg)
944 {
945     if (EVP_get_digestbynid(nid))
946         return CMS_add_simple_smimecap(sk, nid, arg);
947     return 1;
948 }
949
950 int CMS_add_standard_smimecap(STACK_OF(X509_ALGOR) **smcap)
951 {
952     if (!cms_add_cipher_smcap(smcap, NID_aes_256_cbc, -1)
953         || !cms_add_digest_smcap(smcap, NID_id_GostR3411_2012_256, -1)
954         || !cms_add_digest_smcap(smcap, NID_id_GostR3411_2012_512, -1)
955         || !cms_add_digest_smcap(smcap, NID_id_GostR3411_94, -1)
956         || !cms_add_cipher_smcap(smcap, NID_id_Gost28147_89, -1)
957         || !cms_add_cipher_smcap(smcap, NID_aes_192_cbc, -1)
958         || !cms_add_cipher_smcap(smcap, NID_aes_128_cbc, -1)
959         || !cms_add_cipher_smcap(smcap, NID_des_ede3_cbc, -1)
960         || !cms_add_cipher_smcap(smcap, NID_rc2_cbc, 128)
961         || !cms_add_cipher_smcap(smcap, NID_rc2_cbc, 64)
962         || !cms_add_cipher_smcap(smcap, NID_des_cbc, -1)
963         || !cms_add_cipher_smcap(smcap, NID_rc2_cbc, 40))
964         return 0;
965     return 1;
966 }