302b93f805e730ff6d4b9e54da6b9c76f1f16449
[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                 sid->d.subjectKeyIdentifier = ASN1_STRING_dup(cert->skid);
230                 if (!sid->d.subjectKeyIdentifier)
231                         goto merr;
232                 break;
233
234                 default:
235                 CMSerr(CMS_F_CMS_SET1_SIGNERIDENTIFIER, CMS_R_UNKNOWN_ID);
236                 return 0;
237                 }
238
239         sid->type = type;
240
241         return 1;
242
243         merr:
244         CMSerr(CMS_F_CMS_SET1_SIGNERIDENTIFIER, ERR_R_MALLOC_FAILURE);
245         return 0;
246
247         }
248
249 int cms_SignerIdentifier_get0_signer_id(CMS_SignerIdentifier *sid,
250                                         ASN1_OCTET_STRING **keyid,
251                                         X509_NAME **issuer, ASN1_INTEGER **sno)
252         {
253         if (sid->type == CMS_SIGNERINFO_ISSUER_SERIAL)
254                 {
255                 if (issuer)
256                         *issuer = sid->d.issuerAndSerialNumber->issuer;
257                 if (sno)
258                         *sno = sid->d.issuerAndSerialNumber->serialNumber;
259                 }
260         else if (sid->type == CMS_SIGNERINFO_KEYIDENTIFIER)
261                 {
262                 if (keyid)
263                         *keyid = sid->d.subjectKeyIdentifier;
264                 }
265         else
266                 return 0;
267         return 1;
268         }
269
270 int cms_SignerIdentifier_cert_cmp(CMS_SignerIdentifier *sid, X509 *cert)
271         {
272         int ret;
273         if (sid->type == CMS_SIGNERINFO_ISSUER_SERIAL)
274                 {
275                 ret = X509_NAME_cmp(sid->d.issuerAndSerialNumber->issuer,
276                                         X509_get_issuer_name(cert));
277                 if (ret)
278                         return ret;
279                 return ASN1_INTEGER_cmp(sid->d.issuerAndSerialNumber->serialNumber,
280                                         X509_get_serialNumber(cert));
281                 }
282         else if (sid->type == CMS_SIGNERINFO_KEYIDENTIFIER)
283                 {
284                 X509_check_purpose(cert, -1, -1);
285                 if (!cert->skid)
286                         return -1;
287                 return ASN1_OCTET_STRING_cmp(sid->d.subjectKeyIdentifier,
288                                                         cert->skid);
289                 }
290         else
291                 return -1;
292         }
293
294 CMS_SignerInfo *CMS_add1_signer(CMS_ContentInfo *cms,
295                         X509 *signer, EVP_PKEY *pk, const EVP_MD *md,
296                         unsigned int flags)
297         {
298         CMS_SignedData *sd;
299         CMS_SignerInfo *si = NULL;
300         X509_ALGOR *alg;
301         int i, type;
302         if(!X509_check_private_key(signer, pk))
303                 {
304                 CMSerr(CMS_F_CMS_ADD1_SIGNER,
305                         CMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE);
306                 return NULL;
307                 }
308         sd = cms_signed_data_init(cms);
309         if (!sd)
310                 goto err;
311         si = M_ASN1_new_of(CMS_SignerInfo);
312         if (!si)
313                 goto merr;
314         X509_check_purpose(signer, -1, -1);
315
316         CRYPTO_add(&pk->references, 1, CRYPTO_LOCK_EVP_PKEY);
317         CRYPTO_add(&signer->references, 1, CRYPTO_LOCK_X509);
318
319         si->pkey = pk;
320         si->signer = signer;
321
322         if (flags & CMS_USE_KEYID)
323                 {
324                 si->version = 3;
325                 if (sd->version < 3)
326                         sd->version = 3;
327                 type = CMS_SIGNERINFO_KEYIDENTIFIER;
328                 }
329         else
330                 {
331                 type = CMS_SIGNERINFO_ISSUER_SERIAL;
332                 si->version = 1;
333                 }
334
335         if (!cms_set1_SignerIdentifier(si->sid, signer, type))
336                 goto err;
337
338         if (md == NULL)
339                 {
340                 int def_nid;
341                 if (EVP_PKEY_get_default_digest_nid(pk, &def_nid) <= 0)
342                         goto err;
343                 md = EVP_get_digestbynid(def_nid);
344                 if (md == NULL)
345                         {
346                         CMSerr(CMS_F_CMS_ADD1_SIGNER, CMS_R_NO_DEFAULT_DIGEST);
347                         goto err;
348                         }
349                 }
350
351         if (!md)
352                 {
353                 CMSerr(CMS_F_CMS_ADD1_SIGNER, CMS_R_NO_DIGEST_SET);
354                 goto err;
355                 }
356
357         cms_DigestAlgorithm_set(si->digestAlgorithm, md);
358
359         /* See if digest is present in digestAlgorithms */
360         for (i = 0; i < sk_X509_ALGOR_num(sd->digestAlgorithms); i++)
361                 {
362                 ASN1_OBJECT *aoid;
363                 alg = sk_X509_ALGOR_value(sd->digestAlgorithms, i);
364                 X509_ALGOR_get0(&aoid, NULL, NULL, alg);
365                 if (OBJ_obj2nid(aoid) == EVP_MD_type(md))
366                         break;
367                 }
368
369         if (i == sk_X509_ALGOR_num(sd->digestAlgorithms))
370                 {
371                 alg = X509_ALGOR_new();
372                 if (!alg)
373                         goto merr;
374                 cms_DigestAlgorithm_set(alg, md);
375                 if (!sk_X509_ALGOR_push(sd->digestAlgorithms, alg))
376                         {
377                         X509_ALGOR_free(alg);
378                         goto merr;
379                         }
380                 }
381
382         if (pk->ameth && pk->ameth->pkey_ctrl)
383                 {
384                 i = pk->ameth->pkey_ctrl(pk, ASN1_PKEY_CTRL_CMS_SIGN,
385                                                 0, si);
386                 if (i == -2)
387                         {
388                         CMSerr(CMS_F_CMS_ADD1_SIGNER,
389                                 CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE);
390                         goto err;
391                         }
392                 if (i <= 0)
393                         {
394                         CMSerr(CMS_F_CMS_ADD1_SIGNER, CMS_R_CTRL_FAILURE);
395                         goto err;
396                         }
397                 }
398
399         if (!(flags & CMS_NOATTR))
400                 {
401                 /* Copy content type across */
402                 ASN1_OBJECT *ctype =
403                                 OBJ_dup(sd->encapContentInfo->eContentType); 
404                 if (!ctype)
405                         goto merr;
406                 i = CMS_signed_add1_attr_by_NID(si, NID_pkcs9_contentType,
407                                                 V_ASN1_OBJECT, ctype, -1);
408                 ASN1_OBJECT_free(ctype);
409                 if (i <= 0)
410                         goto merr;
411                 if (!(flags & CMS_NOSMIMECAP))
412                         {
413                         STACK_OF(X509_ALGOR) *smcap = NULL;
414                         i = CMS_add_standard_smimecap(&smcap);
415                         if (i)
416                                 i = CMS_add_smimecap(si, smcap);
417                         sk_X509_ALGOR_pop_free(smcap, X509_ALGOR_free);
418                         if (!i)
419                                 goto merr;
420                         }
421                 if (flags & CMS_REUSE_DIGEST)
422                         {
423                         if (!cms_copy_messageDigest(cms, si))
424                                 goto err;
425                         if (!(flags & CMS_PARTIAL) &&
426                                         !CMS_SignerInfo_sign(si))
427                                 goto err;
428                         }
429                 }
430
431         if (!(flags & CMS_NOCERTS))
432                 {
433                 /* NB ignore -1 return for duplicate cert */
434                 if (!CMS_add1_cert(cms, signer))
435                         goto merr;
436                 }
437
438         if (!sd->signerInfos)
439                 sd->signerInfos = sk_CMS_SignerInfo_new_null();
440         if (!sd->signerInfos ||
441                 !sk_CMS_SignerInfo_push(sd->signerInfos, si))
442                 goto merr;
443
444         return si;
445
446         merr:
447         CMSerr(CMS_F_CMS_ADD1_SIGNER, ERR_R_MALLOC_FAILURE);
448         err:
449         if (si)
450                 M_ASN1_free_of(si, CMS_SignerInfo);
451         return NULL;
452
453         }
454
455 static int cms_add1_signingTime(CMS_SignerInfo *si, ASN1_TIME *t)
456         {
457         ASN1_TIME *tt;
458         int r = 0;
459         if (t)
460                 tt = t;
461         else
462                 tt = X509_gmtime_adj(NULL, 0);
463
464         if (!tt)
465                 goto merr;
466
467         if (CMS_signed_add1_attr_by_NID(si, NID_pkcs9_signingTime,
468                                                 tt->type, tt, -1) <= 0)
469                 goto merr;
470
471         r = 1;
472
473         merr:
474
475         if (!t)
476                 ASN1_TIME_free(tt);
477
478         if (!r)
479                 CMSerr(CMS_F_CMS_ADD1_SIGNINGTIME, ERR_R_MALLOC_FAILURE);
480
481         return r;
482
483         }
484
485 STACK_OF(CMS_SignerInfo) *CMS_get0_SignerInfos(CMS_ContentInfo *cms)
486         {
487         CMS_SignedData *sd;
488         sd = cms_get0_signed(cms);
489         if (!sd)
490                 return NULL;
491         return sd->signerInfos;
492         }
493
494 STACK_OF(X509) *CMS_get0_signers(CMS_ContentInfo *cms)
495         {
496         STACK_OF(X509) *signers = NULL;
497         STACK_OF(CMS_SignerInfo) *sinfos;
498         CMS_SignerInfo *si;
499         int i;
500         sinfos = CMS_get0_SignerInfos(cms);
501         for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++)
502                 {
503                 si = sk_CMS_SignerInfo_value(sinfos, i);
504                 if (si->signer)
505                         {
506                         if (!signers)
507                                 {
508                                 signers = sk_X509_new_null();
509                                 if (!signers)
510                                         return NULL;
511                                 }
512                         if (!sk_X509_push(signers, si->signer))
513                                 {
514                                 sk_X509_free(signers);
515                                 return NULL;
516                                 }
517                         }
518                 }
519         return signers;
520         }
521
522 void CMS_SignerInfo_set1_signer_cert(CMS_SignerInfo *si, X509 *signer)
523         {
524         if (signer)
525                 {
526                 CRYPTO_add(&signer->references, 1, CRYPTO_LOCK_X509);
527                 if (si->pkey)
528                         EVP_PKEY_free(si->pkey);
529                 si->pkey = X509_get_pubkey(signer);
530                 }
531         if (si->signer)
532                 X509_free(si->signer);
533         si->signer = signer;
534         }
535
536 int CMS_SignerInfo_get0_signer_id(CMS_SignerInfo *si,
537                                         ASN1_OCTET_STRING **keyid,
538                                         X509_NAME **issuer, ASN1_INTEGER **sno)
539         {
540         return cms_SignerIdentifier_get0_signer_id(si->sid, keyid, issuer, sno);
541         }
542
543 int CMS_SignerInfo_cert_cmp(CMS_SignerInfo *si, X509 *cert)
544         {
545         return cms_SignerIdentifier_cert_cmp(si->sid, cert);
546         }
547
548 int CMS_set1_signers_certs(CMS_ContentInfo *cms, STACK_OF(X509) *scerts,
549                                 unsigned int flags)
550         {
551         CMS_SignedData *sd;
552         CMS_SignerInfo *si;
553         CMS_CertificateChoices *cch;
554         STACK_OF(CMS_CertificateChoices) *certs;
555         X509 *x;
556         int i, j;
557         int ret = 0;
558         sd = cms_get0_signed(cms);
559         if (!sd)
560                 return -1;
561         certs = sd->certificates;
562         for (i = 0; i < sk_CMS_SignerInfo_num(sd->signerInfos); i++)
563                 {
564                 si = sk_CMS_SignerInfo_value(sd->signerInfos, i);
565                 if (si->signer)
566                         continue;
567
568                 for (j = 0; j < sk_X509_num(scerts); j++)
569                         {
570                         x = sk_X509_value(scerts, j);
571                         if (CMS_SignerInfo_cert_cmp(si, x) == 0)
572                                 {
573                                 CMS_SignerInfo_set1_signer_cert(si, x);
574                                 ret++;
575                                 break;
576                                 }
577                         }
578
579                 if (si->signer || (flags & CMS_NOINTERN))
580                         continue;
581
582                 for (j = 0; j < sk_CMS_CertificateChoices_num(certs); j++)
583                         {
584                         cch = sk_CMS_CertificateChoices_value(certs, j);
585                         if (cch->type != 0)
586                                 continue;
587                         x = cch->d.certificate;
588                         if (CMS_SignerInfo_cert_cmp(si, x) == 0)
589                                 {
590                                 CMS_SignerInfo_set1_signer_cert(si, x);
591                                 ret++;
592                                 break;
593                                 }
594                         }
595                 }
596         return ret;
597         }
598
599 void CMS_SignerInfo_get0_algs(CMS_SignerInfo *si, EVP_PKEY **pk, X509 **signer,
600                                         X509_ALGOR **pdig, X509_ALGOR **psig)
601         {
602         if (pk)
603                 *pk = si->pkey;
604         if (signer)
605                 *signer = si->signer;
606         if (pdig)
607                 *pdig = si->digestAlgorithm;
608         if (psig)
609                 *psig = si->signatureAlgorithm;
610         }
611
612 static int cms_SignerInfo_content_sign(CMS_SignerInfo *si, BIO *chain)
613         {
614         EVP_MD_CTX mctx;
615         int r = 0;
616         EVP_MD_CTX_init(&mctx);
617
618
619         if (!si->pkey)
620                 {
621                 CMSerr(CMS_F_CMS_SIGNERINFO_CONTENT_SIGN, CMS_R_NO_PRIVATE_KEY);
622                 return 0;
623                 }
624
625         if (!cms_DigestAlgorithm_find_ctx(&mctx, chain, si->digestAlgorithm))
626                 goto err;
627
628         /* If any signed attributes calculate and add messageDigest attribute */
629
630         if (CMS_signed_get_attr_count(si) >= 0)
631                 {
632                 unsigned char md[EVP_MAX_MD_SIZE];
633                 unsigned int mdlen;
634                 EVP_DigestFinal_ex(&mctx, md, &mdlen);
635                 if (!CMS_signed_add1_attr_by_NID(si, NID_pkcs9_messageDigest,
636                                                 V_ASN1_OCTET_STRING,
637                                                 md, mdlen))
638                         goto err;
639                 if (!CMS_SignerInfo_sign(si))
640                         goto err;
641                 }
642         else
643                 {
644                 unsigned char *sig;
645                 unsigned int siglen;
646                 sig = OPENSSL_malloc(EVP_PKEY_size(si->pkey));
647                 if (!sig)
648                         {
649                         CMSerr(CMS_F_CMS_SIGNERINFO_CONTENT_SIGN,
650                                         ERR_R_MALLOC_FAILURE);
651                         goto err;
652                         }
653                 if (!EVP_SignFinal(&mctx, sig, &siglen, si->pkey))
654                         {
655                         CMSerr(CMS_F_CMS_SIGNERINFO_CONTENT_SIGN,
656                                         CMS_R_SIGNFINAL_ERROR);
657                         OPENSSL_free(sig);
658                         goto err;
659                         }
660                 ASN1_STRING_set0(si->signature, sig, siglen);
661                 }
662
663         r = 1;
664
665         err:
666         EVP_MD_CTX_cleanup(&mctx);
667         return r;
668
669         }
670
671 int cms_SignedData_final(CMS_ContentInfo *cms, BIO *chain)
672         {
673         STACK_OF(CMS_SignerInfo) *sinfos;
674         CMS_SignerInfo *si;
675         int i;
676         sinfos = CMS_get0_SignerInfos(cms);
677         for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++)
678                 {
679                 si = sk_CMS_SignerInfo_value(sinfos, i);
680                 if (!cms_SignerInfo_content_sign(si, chain))
681                         return 0;
682                 }
683         cms->d.signedData->encapContentInfo->partial = 0;
684         return 1;
685         }
686
687 int CMS_SignerInfo_sign(CMS_SignerInfo *si)
688         {
689         EVP_MD_CTX mctx;
690         EVP_PKEY_CTX *pctx;
691         unsigned char *abuf = NULL;
692         int alen;
693         size_t siglen;
694         const EVP_MD *md = NULL;
695
696         md = EVP_get_digestbyobj(si->digestAlgorithm->algorithm);
697         if (md == NULL)
698                 return 0;
699
700         EVP_MD_CTX_init(&mctx);
701
702         if (CMS_signed_get_attr_by_NID(si, NID_pkcs9_signingTime, -1) < 0)
703                 {
704                 if (!cms_add1_signingTime(si, NULL))
705                         goto err;
706                 }
707
708         if (EVP_DigestSignInit(&mctx, &pctx, md, NULL, si->pkey) <= 0)
709                 goto err;
710
711         if (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_SIGN,
712                                 EVP_PKEY_CTRL_CMS_SIGN, 0, si) <= 0)
713                 {
714                 CMSerr(CMS_F_CMS_SIGNERINFO_SIGN, CMS_R_CTRL_ERROR);
715                 goto err;
716                 }
717
718         alen = ASN1_item_i2d((ASN1_VALUE *)si->signedAttrs,&abuf,
719                                 ASN1_ITEM_rptr(CMS_Attributes_Sign));
720         if(!abuf)
721                 goto err;
722         if (EVP_DigestSignUpdate(&mctx, abuf, alen) <= 0)
723                 goto err;
724         if (EVP_DigestSignFinal(&mctx, NULL, &siglen) <= 0)
725                 goto err;
726         OPENSSL_free(abuf);
727         abuf = OPENSSL_malloc(siglen);
728         if(!abuf)
729                 goto err;
730         if (EVP_DigestSignFinal(&mctx, abuf, &siglen) <= 0)
731                 goto err;
732
733         if (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_SIGN,
734                                 EVP_PKEY_CTRL_CMS_SIGN, 1, si) <= 0)
735                 {
736                 CMSerr(CMS_F_CMS_SIGNERINFO_SIGN, CMS_R_CTRL_ERROR);
737                 goto err;
738                 }
739
740         EVP_MD_CTX_cleanup(&mctx);
741
742         ASN1_STRING_set0(si->signature, abuf, siglen);
743
744         return 1;
745
746         err:
747         if (abuf)
748                 OPENSSL_free(abuf);
749         EVP_MD_CTX_cleanup(&mctx);
750         return 0;
751
752         }
753
754 int CMS_SignerInfo_verify(CMS_SignerInfo *si)
755         {
756         EVP_MD_CTX mctx;
757         EVP_PKEY_CTX *pctx;
758         unsigned char *abuf = NULL;
759         int alen, r = -1;
760         const EVP_MD *md = NULL;
761
762         if (!si->pkey)
763                 {
764                 CMSerr(CMS_F_CMS_SIGNERINFO_VERIFY, CMS_R_NO_PUBLIC_KEY);
765                 return -1;
766                 }
767
768         md = EVP_get_digestbyobj(si->digestAlgorithm->algorithm);
769         if (md == NULL)
770                 return -1;
771         EVP_MD_CTX_init(&mctx);
772         if (EVP_DigestVerifyInit(&mctx, &pctx, md, NULL, si->pkey) <= 0)
773                 goto err;
774
775         alen = ASN1_item_i2d((ASN1_VALUE *)si->signedAttrs,&abuf,
776                                 ASN1_ITEM_rptr(CMS_Attributes_Verify));
777         if(!abuf)
778                 goto err;
779         r = EVP_DigestVerifyUpdate(&mctx, abuf, alen);
780         OPENSSL_free(abuf);
781         if (r <= 0)
782                 {
783                 r = -1;
784                 goto err;
785                 }
786         r = EVP_DigestVerifyFinal(&mctx,
787                         si->signature->data, si->signature->length);
788         if (!r)
789                 CMSerr(CMS_F_CMS_SIGNERINFO_VERIFY, CMS_R_VERIFICATION_FAILURE);
790         err:
791         EVP_MD_CTX_cleanup(&mctx);
792         return r;
793         }
794
795 /* Create a chain of digest BIOs from a CMS ContentInfo */
796
797 BIO *cms_SignedData_init_bio(CMS_ContentInfo *cms)
798         {
799         int i;
800         CMS_SignedData *sd;
801         BIO *chain = NULL;
802         sd = cms_get0_signed(cms);
803         if (!sd)
804                 return NULL;
805         if (cms->d.signedData->encapContentInfo->partial)
806                 cms_sd_set_version(sd);
807         for (i = 0; i < sk_X509_ALGOR_num(sd->digestAlgorithms); i++)
808                 {
809                 X509_ALGOR *digestAlgorithm;
810                 BIO *mdbio;
811                 digestAlgorithm = sk_X509_ALGOR_value(sd->digestAlgorithms, i);
812                 mdbio = cms_DigestAlgorithm_init_bio(digestAlgorithm);
813                 if (!mdbio)
814                         goto err;       
815                 if (chain)
816                          BIO_push(chain, mdbio);
817                 else
818                         chain = mdbio;
819                 }
820         return chain;
821         err:
822         if (chain)
823                 BIO_free_all(chain);
824         return NULL;
825         }
826
827 int CMS_SignerInfo_verify_content(CMS_SignerInfo *si, BIO *chain)
828         {
829         ASN1_OCTET_STRING *os = NULL;
830         EVP_MD_CTX mctx;
831         int r = -1;
832         EVP_MD_CTX_init(&mctx);
833         /* If we have any signed attributes look for messageDigest value */
834         if (CMS_signed_get_attr_count(si) >= 0)
835                 {
836                 os = CMS_signed_get0_data_by_OBJ(si,
837                                         OBJ_nid2obj(NID_pkcs9_messageDigest),
838                                         -3, V_ASN1_OCTET_STRING);
839                 if (!os)
840                         {
841                         CMSerr(CMS_F_CMS_SIGNERINFO_VERIFY_CONTENT,
842                                 CMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE);
843                         goto err;
844                         }
845                 }
846
847         if (!cms_DigestAlgorithm_find_ctx(&mctx, chain, si->digestAlgorithm))
848                 goto err;
849
850         /* If messageDigest found compare it */
851
852         if (os)
853                 {
854                 unsigned char mval[EVP_MAX_MD_SIZE];
855                 unsigned int mlen;
856                 if (EVP_DigestFinal_ex(&mctx, mval, &mlen) <= 0)
857                         {
858                         CMSerr(CMS_F_CMS_SIGNERINFO_VERIFY_CONTENT,
859                                 CMS_R_UNABLE_TO_FINALIZE_CONTEXT);
860                         goto err;
861                         }
862                 if (mlen != (unsigned int)os->length)
863                         {
864                         CMSerr(CMS_F_CMS_SIGNERINFO_VERIFY_CONTENT,
865                                 CMS_R_MESSAGEDIGEST_ATTRIBUTE_WRONG_LENGTH);
866                         goto err;
867                         }
868
869                 if (memcmp(mval, os->data, mlen))
870                         {
871                         CMSerr(CMS_F_CMS_SIGNERINFO_VERIFY_CONTENT,
872                                 CMS_R_VERIFICATION_FAILURE);
873                         r = 0;
874                         }
875                 else
876                         r = 1;
877                 }
878         else
879                 {
880                 r = EVP_VerifyFinal(&mctx, si->signature->data,
881                                         si->signature->length, si->pkey);
882                 if (r <= 0)
883                         {
884                         CMSerr(CMS_F_CMS_SIGNERINFO_VERIFY_CONTENT,
885                                 CMS_R_VERIFICATION_FAILURE);
886                         r = 0;
887                         }
888                 }
889
890         err:
891         EVP_MD_CTX_cleanup(&mctx);
892         return r;
893
894         }
895
896 int CMS_add_smimecap(CMS_SignerInfo *si, STACK_OF(X509_ALGOR) *algs)
897         {
898         unsigned char *smder = NULL;
899         int smderlen, r;
900         smderlen = i2d_X509_ALGORS(algs, &smder);
901         if (smderlen <= 0)
902                 return 0;
903         r = CMS_signed_add1_attr_by_NID(si, NID_SMIMECapabilities,
904                                         V_ASN1_SEQUENCE, smder, smderlen);
905         OPENSSL_free(smder);
906         return r;
907         }
908
909 int CMS_add_simple_smimecap(STACK_OF(X509_ALGOR) **algs,
910                                 int algnid, int keysize)
911         {
912         X509_ALGOR *alg;
913         ASN1_INTEGER *key = NULL;
914         if (keysize > 0)
915                 {
916                 key = ASN1_INTEGER_new();
917                 if (!key || !ASN1_INTEGER_set(key, keysize))
918                         return 0;
919                 }
920         alg = X509_ALGOR_new();
921         if (!alg)
922                 {
923                 if (key)
924                         ASN1_INTEGER_free(key);
925                 return 0;
926                 }
927                 
928         X509_ALGOR_set0(alg, OBJ_nid2obj(algnid),
929                                 key ? V_ASN1_INTEGER : V_ASN1_UNDEF, key);
930         if (!*algs)
931                 *algs = sk_X509_ALGOR_new_null();
932         if (!*algs || !sk_X509_ALGOR_push(*algs, alg))
933                 {
934                 X509_ALGOR_free(alg);
935                 return 0;
936                 }
937         return 1;
938         }
939
940 /* Check to see if a cipher exists and if so add S/MIME capabilities */
941
942 static int cms_add_cipher_smcap(STACK_OF(X509_ALGOR) **sk, int nid, int arg)
943         {
944         if (EVP_get_cipherbynid(nid))
945                 return CMS_add_simple_smimecap(sk, nid, arg);
946         return 1;
947         }
948
949 static int cms_add_digest_smcap(STACK_OF(X509_ALGOR) **sk, int nid, int arg)
950         {
951         if (EVP_get_digestbynid(nid))
952                 return CMS_add_simple_smimecap(sk, nid, arg);
953         return 1;
954         }
955
956 int CMS_add_standard_smimecap(STACK_OF(X509_ALGOR) **smcap)
957         {
958         if (!cms_add_cipher_smcap(smcap, NID_aes_256_cbc, -1)
959                 || !cms_add_digest_smcap(smcap, NID_id_GostR3411_94, -1)
960                 || !cms_add_cipher_smcap(smcap, NID_id_Gost28147_89, -1)
961                 || !cms_add_cipher_smcap(smcap, NID_aes_192_cbc, -1)
962                 || !cms_add_cipher_smcap(smcap, NID_aes_128_cbc, -1)
963                 || !cms_add_cipher_smcap(smcap, NID_des_ede3_cbc, -1)
964                 || !cms_add_cipher_smcap(smcap, NID_rc2_cbc, 128)
965                 || !cms_add_cipher_smcap(smcap, NID_rc2_cbc, 64)
966                 || !cms_add_cipher_smcap(smcap, NID_des_cbc, -1)
967                 || !cms_add_cipher_smcap(smcap, NID_rc2_cbc, 40))
968                 return 0;
969         return 1;
970         }