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