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