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