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