Fix a padding oracle in PKCS7_dataDecode and CMS_decrypt_set1_pkey
[openssl.git] / crypto / pkcs7 / pk7_doit.c
1 /*
2  * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (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 <stdio.h>
11 #include "internal/cryptlib.h"
12 #include <openssl/rand.h>
13 #include <openssl/objects.h>
14 #include <openssl/x509.h>
15 #include <openssl/x509v3.h>
16 #include <openssl/err.h>
17
18 static int add_attribute(STACK_OF(X509_ATTRIBUTE) **sk, int nid, int atrtype,
19                          void *value);
20 static ASN1_TYPE *get_attribute(STACK_OF(X509_ATTRIBUTE) *sk, int nid);
21
22 static int PKCS7_type_is_other(PKCS7 *p7)
23 {
24     int isOther = 1;
25
26     int nid = OBJ_obj2nid(p7->type);
27
28     switch (nid) {
29     case NID_pkcs7_data:
30     case NID_pkcs7_signed:
31     case NID_pkcs7_enveloped:
32     case NID_pkcs7_signedAndEnveloped:
33     case NID_pkcs7_digest:
34     case NID_pkcs7_encrypted:
35         isOther = 0;
36         break;
37     default:
38         isOther = 1;
39     }
40
41     return isOther;
42
43 }
44
45 static ASN1_OCTET_STRING *PKCS7_get_octet_string(PKCS7 *p7)
46 {
47     if (PKCS7_type_is_data(p7))
48         return p7->d.data;
49     if (PKCS7_type_is_other(p7) && p7->d.other
50         && (p7->d.other->type == V_ASN1_OCTET_STRING))
51         return p7->d.other->value.octet_string;
52     return NULL;
53 }
54
55 static int PKCS7_bio_add_digest(BIO **pbio, X509_ALGOR *alg)
56 {
57     BIO *btmp;
58     const EVP_MD *md;
59     if ((btmp = BIO_new(BIO_f_md())) == NULL) {
60         PKCS7err(PKCS7_F_PKCS7_BIO_ADD_DIGEST, ERR_R_BIO_LIB);
61         goto err;
62     }
63
64     md = EVP_get_digestbyobj(alg->algorithm);
65     if (md == NULL) {
66         PKCS7err(PKCS7_F_PKCS7_BIO_ADD_DIGEST, PKCS7_R_UNKNOWN_DIGEST_TYPE);
67         goto err;
68     }
69
70     BIO_set_md(btmp, md);
71     if (*pbio == NULL)
72         *pbio = btmp;
73     else if (!BIO_push(*pbio, btmp)) {
74         PKCS7err(PKCS7_F_PKCS7_BIO_ADD_DIGEST, ERR_R_BIO_LIB);
75         goto err;
76     }
77     btmp = NULL;
78
79     return 1;
80
81  err:
82     BIO_free(btmp);
83     return 0;
84
85 }
86
87 static int pkcs7_encode_rinfo(PKCS7_RECIP_INFO *ri,
88                               unsigned char *key, int keylen)
89 {
90     EVP_PKEY_CTX *pctx = NULL;
91     EVP_PKEY *pkey = NULL;
92     unsigned char *ek = NULL;
93     int ret = 0;
94     size_t eklen;
95
96     pkey = X509_get0_pubkey(ri->cert);
97
98     if (!pkey)
99         return 0;
100
101     pctx = EVP_PKEY_CTX_new(pkey, NULL);
102     if (!pctx)
103         return 0;
104
105     if (EVP_PKEY_encrypt_init(pctx) <= 0)
106         goto err;
107
108     if (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_ENCRYPT,
109                           EVP_PKEY_CTRL_PKCS7_ENCRYPT, 0, ri) <= 0) {
110         PKCS7err(PKCS7_F_PKCS7_ENCODE_RINFO, PKCS7_R_CTRL_ERROR);
111         goto err;
112     }
113
114     if (EVP_PKEY_encrypt(pctx, NULL, &eklen, key, keylen) <= 0)
115         goto err;
116
117     ek = OPENSSL_malloc(eklen);
118
119     if (ek == NULL) {
120         PKCS7err(PKCS7_F_PKCS7_ENCODE_RINFO, ERR_R_MALLOC_FAILURE);
121         goto err;
122     }
123
124     if (EVP_PKEY_encrypt(pctx, ek, &eklen, key, keylen) <= 0)
125         goto err;
126
127     ASN1_STRING_set0(ri->enc_key, ek, eklen);
128     ek = NULL;
129
130     ret = 1;
131
132  err:
133     EVP_PKEY_CTX_free(pctx);
134     OPENSSL_free(ek);
135     return ret;
136
137 }
138
139 static int pkcs7_decrypt_rinfo(unsigned char **pek, int *peklen,
140                                PKCS7_RECIP_INFO *ri, EVP_PKEY *pkey,
141                                size_t fixlen)
142 {
143     EVP_PKEY_CTX *pctx = NULL;
144     unsigned char *ek = NULL;
145     size_t eklen;
146
147     int ret = -1;
148
149     pctx = EVP_PKEY_CTX_new(pkey, NULL);
150     if (!pctx)
151         return -1;
152
153     if (EVP_PKEY_decrypt_init(pctx) <= 0)
154         goto err;
155
156     if (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_DECRYPT,
157                           EVP_PKEY_CTRL_PKCS7_DECRYPT, 0, ri) <= 0) {
158         PKCS7err(PKCS7_F_PKCS7_DECRYPT_RINFO, PKCS7_R_CTRL_ERROR);
159         goto err;
160     }
161
162     if (EVP_PKEY_decrypt(pctx, NULL, &eklen,
163                          ri->enc_key->data, ri->enc_key->length) <= 0)
164         goto err;
165
166     ek = OPENSSL_malloc(eklen);
167
168     if (ek == NULL) {
169         PKCS7err(PKCS7_F_PKCS7_DECRYPT_RINFO, ERR_R_MALLOC_FAILURE);
170         goto err;
171     }
172
173     if (EVP_PKEY_decrypt(pctx, ek, &eklen,
174                          ri->enc_key->data, ri->enc_key->length) <= 0
175             || eklen == 0
176             || (fixlen != 0 && eklen != fixlen)) {
177         ret = 0;
178         PKCS7err(PKCS7_F_PKCS7_DECRYPT_RINFO, ERR_R_EVP_LIB);
179         goto err;
180     }
181
182     ret = 1;
183
184     OPENSSL_clear_free(*pek, *peklen);
185     *pek = ek;
186     *peklen = eklen;
187
188  err:
189     EVP_PKEY_CTX_free(pctx);
190     if (!ret)
191         OPENSSL_free(ek);
192
193     return ret;
194 }
195
196 BIO *PKCS7_dataInit(PKCS7 *p7, BIO *bio)
197 {
198     int i;
199     BIO *out = NULL, *btmp = NULL;
200     X509_ALGOR *xa = NULL;
201     const EVP_CIPHER *evp_cipher = NULL;
202     STACK_OF(X509_ALGOR) *md_sk = NULL;
203     STACK_OF(PKCS7_RECIP_INFO) *rsk = NULL;
204     X509_ALGOR *xalg = NULL;
205     PKCS7_RECIP_INFO *ri = NULL;
206     ASN1_OCTET_STRING *os = NULL;
207
208     if (p7 == NULL) {
209         PKCS7err(PKCS7_F_PKCS7_DATAINIT, PKCS7_R_INVALID_NULL_POINTER);
210         return NULL;
211     }
212     /*
213      * The content field in the PKCS7 ContentInfo is optional, but that really
214      * only applies to inner content (precisely, detached signatures).
215      *
216      * When reading content, missing outer content is therefore treated as an
217      * error.
218      *
219      * When creating content, PKCS7_content_new() must be called before
220      * calling this method, so a NULL p7->d is always an error.
221      */
222     if (p7->d.ptr == NULL) {
223         PKCS7err(PKCS7_F_PKCS7_DATAINIT, PKCS7_R_NO_CONTENT);
224         return NULL;
225     }
226
227     i = OBJ_obj2nid(p7->type);
228     p7->state = PKCS7_S_HEADER;
229
230     switch (i) {
231     case NID_pkcs7_signed:
232         md_sk = p7->d.sign->md_algs;
233         os = PKCS7_get_octet_string(p7->d.sign->contents);
234         break;
235     case NID_pkcs7_signedAndEnveloped:
236         rsk = p7->d.signed_and_enveloped->recipientinfo;
237         md_sk = p7->d.signed_and_enveloped->md_algs;
238         xalg = p7->d.signed_and_enveloped->enc_data->algorithm;
239         evp_cipher = p7->d.signed_and_enveloped->enc_data->cipher;
240         if (evp_cipher == NULL) {
241             PKCS7err(PKCS7_F_PKCS7_DATAINIT, PKCS7_R_CIPHER_NOT_INITIALIZED);
242             goto err;
243         }
244         break;
245     case NID_pkcs7_enveloped:
246         rsk = p7->d.enveloped->recipientinfo;
247         xalg = p7->d.enveloped->enc_data->algorithm;
248         evp_cipher = p7->d.enveloped->enc_data->cipher;
249         if (evp_cipher == NULL) {
250             PKCS7err(PKCS7_F_PKCS7_DATAINIT, PKCS7_R_CIPHER_NOT_INITIALIZED);
251             goto err;
252         }
253         break;
254     case NID_pkcs7_digest:
255         xa = p7->d.digest->md;
256         os = PKCS7_get_octet_string(p7->d.digest->contents);
257         break;
258     case NID_pkcs7_data:
259         break;
260     default:
261         PKCS7err(PKCS7_F_PKCS7_DATAINIT, PKCS7_R_UNSUPPORTED_CONTENT_TYPE);
262         goto err;
263     }
264
265     for (i = 0; i < sk_X509_ALGOR_num(md_sk); i++)
266         if (!PKCS7_bio_add_digest(&out, sk_X509_ALGOR_value(md_sk, i)))
267             goto err;
268
269     if (xa && !PKCS7_bio_add_digest(&out, xa))
270         goto err;
271
272     if (evp_cipher != NULL) {
273         unsigned char key[EVP_MAX_KEY_LENGTH];
274         unsigned char iv[EVP_MAX_IV_LENGTH];
275         int keylen, ivlen;
276         EVP_CIPHER_CTX *ctx;
277
278         if ((btmp = BIO_new(BIO_f_cipher())) == NULL) {
279             PKCS7err(PKCS7_F_PKCS7_DATAINIT, ERR_R_BIO_LIB);
280             goto err;
281         }
282         BIO_get_cipher_ctx(btmp, &ctx);
283         keylen = EVP_CIPHER_key_length(evp_cipher);
284         ivlen = EVP_CIPHER_iv_length(evp_cipher);
285         xalg->algorithm = OBJ_nid2obj(EVP_CIPHER_type(evp_cipher));
286         if (ivlen > 0)
287             if (RAND_bytes(iv, ivlen) <= 0)
288                 goto err;
289         if (EVP_CipherInit_ex(ctx, evp_cipher, NULL, NULL, NULL, 1) <= 0)
290             goto err;
291         if (EVP_CIPHER_CTX_rand_key(ctx, key) <= 0)
292             goto err;
293         if (EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, 1) <= 0)
294             goto err;
295
296         if (ivlen > 0) {
297             if (xalg->parameter == NULL) {
298                 xalg->parameter = ASN1_TYPE_new();
299                 if (xalg->parameter == NULL)
300                     goto err;
301             }
302             if (EVP_CIPHER_param_to_asn1(ctx, xalg->parameter) < 0)
303                 goto err;
304         }
305
306         /* Lets do the pub key stuff :-) */
307         for (i = 0; i < sk_PKCS7_RECIP_INFO_num(rsk); i++) {
308             ri = sk_PKCS7_RECIP_INFO_value(rsk, i);
309             if (pkcs7_encode_rinfo(ri, key, keylen) <= 0)
310                 goto err;
311         }
312         OPENSSL_cleanse(key, keylen);
313
314         if (out == NULL)
315             out = btmp;
316         else
317             BIO_push(out, btmp);
318         btmp = NULL;
319     }
320
321     if (bio == NULL) {
322         if (PKCS7_is_detached(p7)) {
323             bio = BIO_new(BIO_s_null());
324         } else if (os && os->length > 0) {
325             bio = BIO_new_mem_buf(os->data, os->length);
326         } else {
327             bio = BIO_new(BIO_s_mem());
328             if (bio == NULL)
329                 goto err;
330             BIO_set_mem_eof_return(bio, 0);
331         }
332         if (bio == NULL)
333             goto err;
334     }
335     if (out)
336         BIO_push(out, bio);
337     else
338         out = bio;
339     return out;
340
341  err:
342     BIO_free_all(out);
343     BIO_free_all(btmp);
344     return NULL;
345 }
346
347 static int pkcs7_cmp_ri(PKCS7_RECIP_INFO *ri, X509 *pcert)
348 {
349     int ret;
350     ret = X509_NAME_cmp(ri->issuer_and_serial->issuer,
351                         X509_get_issuer_name(pcert));
352     if (ret)
353         return ret;
354     return ASN1_INTEGER_cmp(X509_get_serialNumber(pcert),
355                             ri->issuer_and_serial->serial);
356 }
357
358 /* int */
359 BIO *PKCS7_dataDecode(PKCS7 *p7, EVP_PKEY *pkey, BIO *in_bio, X509 *pcert)
360 {
361     int i, j;
362     BIO *out = NULL, *btmp = NULL, *etmp = NULL, *bio = NULL;
363     X509_ALGOR *xa;
364     ASN1_OCTET_STRING *data_body = NULL;
365     const EVP_MD *evp_md;
366     const EVP_CIPHER *evp_cipher = NULL;
367     EVP_CIPHER_CTX *evp_ctx = NULL;
368     X509_ALGOR *enc_alg = NULL;
369     STACK_OF(X509_ALGOR) *md_sk = NULL;
370     STACK_OF(PKCS7_RECIP_INFO) *rsk = NULL;
371     PKCS7_RECIP_INFO *ri = NULL;
372     unsigned char *ek = NULL, *tkey = NULL;
373     int eklen = 0, tkeylen = 0;
374
375     if (p7 == NULL) {
376         PKCS7err(PKCS7_F_PKCS7_DATADECODE, PKCS7_R_INVALID_NULL_POINTER);
377         return NULL;
378     }
379
380     if (p7->d.ptr == NULL) {
381         PKCS7err(PKCS7_F_PKCS7_DATADECODE, PKCS7_R_NO_CONTENT);
382         return NULL;
383     }
384
385     i = OBJ_obj2nid(p7->type);
386     p7->state = PKCS7_S_HEADER;
387
388     switch (i) {
389     case NID_pkcs7_signed:
390         /*
391          * p7->d.sign->contents is a PKCS7 structure consisting of a contentType
392          * field and optional content.
393          * data_body is NULL if that structure has no (=detached) content
394          * or if the contentType is wrong (i.e., not "data").
395          */
396         data_body = PKCS7_get_octet_string(p7->d.sign->contents);
397         if (!PKCS7_is_detached(p7) && data_body == NULL) {
398             PKCS7err(PKCS7_F_PKCS7_DATADECODE,
399                      PKCS7_R_INVALID_SIGNED_DATA_TYPE);
400             goto err;
401         }
402         md_sk = p7->d.sign->md_algs;
403         break;
404     case NID_pkcs7_signedAndEnveloped:
405         rsk = p7->d.signed_and_enveloped->recipientinfo;
406         md_sk = p7->d.signed_and_enveloped->md_algs;
407         /* data_body is NULL if the optional EncryptedContent is missing. */
408         data_body = p7->d.signed_and_enveloped->enc_data->enc_data;
409         enc_alg = p7->d.signed_and_enveloped->enc_data->algorithm;
410         evp_cipher = EVP_get_cipherbyobj(enc_alg->algorithm);
411         if (evp_cipher == NULL) {
412             PKCS7err(PKCS7_F_PKCS7_DATADECODE,
413                      PKCS7_R_UNSUPPORTED_CIPHER_TYPE);
414             goto err;
415         }
416         break;
417     case NID_pkcs7_enveloped:
418         rsk = p7->d.enveloped->recipientinfo;
419         enc_alg = p7->d.enveloped->enc_data->algorithm;
420         /* data_body is NULL if the optional EncryptedContent is missing. */
421         data_body = p7->d.enveloped->enc_data->enc_data;
422         evp_cipher = EVP_get_cipherbyobj(enc_alg->algorithm);
423         if (evp_cipher == NULL) {
424             PKCS7err(PKCS7_F_PKCS7_DATADECODE,
425                      PKCS7_R_UNSUPPORTED_CIPHER_TYPE);
426             goto err;
427         }
428         break;
429     default:
430         PKCS7err(PKCS7_F_PKCS7_DATADECODE, PKCS7_R_UNSUPPORTED_CONTENT_TYPE);
431         goto err;
432     }
433
434     /* Detached content must be supplied via in_bio instead. */
435     if (data_body == NULL && in_bio == NULL) {
436         PKCS7err(PKCS7_F_PKCS7_DATADECODE, PKCS7_R_NO_CONTENT);
437         goto err;
438     }
439
440     /* We will be checking the signature */
441     if (md_sk != NULL) {
442         for (i = 0; i < sk_X509_ALGOR_num(md_sk); i++) {
443             xa = sk_X509_ALGOR_value(md_sk, i);
444             if ((btmp = BIO_new(BIO_f_md())) == NULL) {
445                 PKCS7err(PKCS7_F_PKCS7_DATADECODE, ERR_R_BIO_LIB);
446                 goto err;
447             }
448
449             j = OBJ_obj2nid(xa->algorithm);
450             evp_md = EVP_get_digestbynid(j);
451             if (evp_md == NULL) {
452                 PKCS7err(PKCS7_F_PKCS7_DATADECODE,
453                          PKCS7_R_UNKNOWN_DIGEST_TYPE);
454                 goto err;
455             }
456
457             BIO_set_md(btmp, evp_md);
458             if (out == NULL)
459                 out = btmp;
460             else
461                 BIO_push(out, btmp);
462             btmp = NULL;
463         }
464     }
465
466     if (evp_cipher != NULL) {
467         if ((etmp = BIO_new(BIO_f_cipher())) == NULL) {
468             PKCS7err(PKCS7_F_PKCS7_DATADECODE, ERR_R_BIO_LIB);
469             goto err;
470         }
471
472         /*
473          * It was encrypted, we need to decrypt the secret key with the
474          * private key
475          */
476
477         /*
478          * Find the recipientInfo which matches the passed certificate (if
479          * any)
480          */
481
482         if (pcert) {
483             for (i = 0; i < sk_PKCS7_RECIP_INFO_num(rsk); i++) {
484                 ri = sk_PKCS7_RECIP_INFO_value(rsk, i);
485                 if (!pkcs7_cmp_ri(ri, pcert))
486                     break;
487                 ri = NULL;
488             }
489             if (ri == NULL) {
490                 PKCS7err(PKCS7_F_PKCS7_DATADECODE,
491                          PKCS7_R_NO_RECIPIENT_MATCHES_CERTIFICATE);
492                 goto err;
493             }
494         }
495
496         /* If we haven't got a certificate try each ri in turn */
497         if (pcert == NULL) {
498             /*
499              * Always attempt to decrypt all rinfo even after success as a
500              * defence against MMA timing attacks.
501              */
502             for (i = 0; i < sk_PKCS7_RECIP_INFO_num(rsk); i++) {
503                 ri = sk_PKCS7_RECIP_INFO_value(rsk, i);
504
505                 if (pkcs7_decrypt_rinfo(&ek, &eklen, ri, pkey,
506                         EVP_CIPHER_key_length(evp_cipher)) < 0)
507                     goto err;
508                 ERR_clear_error();
509             }
510         } else {
511             /* Only exit on fatal errors, not decrypt failure */
512             if (pkcs7_decrypt_rinfo(&ek, &eklen, ri, pkey, 0) < 0)
513                 goto err;
514             ERR_clear_error();
515         }
516
517         evp_ctx = NULL;
518         BIO_get_cipher_ctx(etmp, &evp_ctx);
519         if (EVP_CipherInit_ex(evp_ctx, evp_cipher, NULL, NULL, NULL, 0) <= 0)
520             goto err;
521         if (EVP_CIPHER_asn1_to_param(evp_ctx, enc_alg->parameter) < 0)
522             goto err;
523         /* Generate random key as MMA defence */
524         tkeylen = EVP_CIPHER_CTX_key_length(evp_ctx);
525         tkey = OPENSSL_malloc(tkeylen);
526         if (tkey == NULL)
527             goto err;
528         if (EVP_CIPHER_CTX_rand_key(evp_ctx, tkey) <= 0)
529             goto err;
530         if (ek == NULL) {
531             ek = tkey;
532             eklen = tkeylen;
533             tkey = NULL;
534         }
535
536         if (eklen != EVP_CIPHER_CTX_key_length(evp_ctx)) {
537             /*
538              * Some S/MIME clients don't use the same key and effective key
539              * length. The key length is determined by the size of the
540              * decrypted RSA key.
541              */
542             if (!EVP_CIPHER_CTX_set_key_length(evp_ctx, eklen)) {
543                 /* Use random key as MMA defence */
544                 OPENSSL_clear_free(ek, eklen);
545                 ek = tkey;
546                 eklen = tkeylen;
547                 tkey = NULL;
548             }
549         }
550         /* Clear errors so we don't leak information useful in MMA */
551         ERR_clear_error();
552         if (EVP_CipherInit_ex(evp_ctx, NULL, NULL, ek, NULL, 0) <= 0)
553             goto err;
554
555         OPENSSL_clear_free(ek, eklen);
556         ek = NULL;
557         OPENSSL_clear_free(tkey, tkeylen);
558         tkey = NULL;
559
560         if (out == NULL)
561             out = etmp;
562         else
563             BIO_push(out, etmp);
564         etmp = NULL;
565     }
566     if (in_bio != NULL) {
567         bio = in_bio;
568     } else {
569         if (data_body->length > 0)
570             bio = BIO_new_mem_buf(data_body->data, data_body->length);
571         else {
572             bio = BIO_new(BIO_s_mem());
573             if (bio == NULL)
574                 goto err;
575             BIO_set_mem_eof_return(bio, 0);
576         }
577         if (bio == NULL)
578             goto err;
579     }
580     BIO_push(out, bio);
581     bio = NULL;
582     return out;
583
584  err:
585     OPENSSL_clear_free(ek, eklen);
586     OPENSSL_clear_free(tkey, tkeylen);
587     BIO_free_all(out);
588     BIO_free_all(btmp);
589     BIO_free_all(etmp);
590     BIO_free_all(bio);
591     return NULL;
592 }
593
594 static BIO *PKCS7_find_digest(EVP_MD_CTX **pmd, BIO *bio, int nid)
595 {
596     for (;;) {
597         bio = BIO_find_type(bio, BIO_TYPE_MD);
598         if (bio == NULL) {
599             PKCS7err(PKCS7_F_PKCS7_FIND_DIGEST,
600                      PKCS7_R_UNABLE_TO_FIND_MESSAGE_DIGEST);
601             return NULL;
602         }
603         BIO_get_md_ctx(bio, pmd);
604         if (*pmd == NULL) {
605             PKCS7err(PKCS7_F_PKCS7_FIND_DIGEST, ERR_R_INTERNAL_ERROR);
606             return NULL;
607         }
608         if (EVP_MD_CTX_type(*pmd) == nid)
609             return bio;
610         bio = BIO_next(bio);
611     }
612     return NULL;
613 }
614
615 static int do_pkcs7_signed_attrib(PKCS7_SIGNER_INFO *si, EVP_MD_CTX *mctx)
616 {
617     unsigned char md_data[EVP_MAX_MD_SIZE];
618     unsigned int md_len;
619
620     /* Add signing time if not already present */
621     if (!PKCS7_get_signed_attribute(si, NID_pkcs9_signingTime)) {
622         if (!PKCS7_add0_attrib_signing_time(si, NULL)) {
623             PKCS7err(PKCS7_F_DO_PKCS7_SIGNED_ATTRIB, ERR_R_MALLOC_FAILURE);
624             return 0;
625         }
626     }
627
628     /* Add digest */
629     if (!EVP_DigestFinal_ex(mctx, md_data, &md_len)) {
630         PKCS7err(PKCS7_F_DO_PKCS7_SIGNED_ATTRIB, ERR_R_EVP_LIB);
631         return 0;
632     }
633     if (!PKCS7_add1_attrib_digest(si, md_data, md_len)) {
634         PKCS7err(PKCS7_F_DO_PKCS7_SIGNED_ATTRIB, ERR_R_MALLOC_FAILURE);
635         return 0;
636     }
637
638     /* Now sign the attributes */
639     if (!PKCS7_SIGNER_INFO_sign(si))
640         return 0;
641
642     return 1;
643 }
644
645 int PKCS7_dataFinal(PKCS7 *p7, BIO *bio)
646 {
647     int ret = 0;
648     int i, j;
649     BIO *btmp;
650     PKCS7_SIGNER_INFO *si;
651     EVP_MD_CTX *mdc, *ctx_tmp;
652     STACK_OF(X509_ATTRIBUTE) *sk;
653     STACK_OF(PKCS7_SIGNER_INFO) *si_sk = NULL;
654     ASN1_OCTET_STRING *os = NULL;
655
656     if (p7 == NULL) {
657         PKCS7err(PKCS7_F_PKCS7_DATAFINAL, PKCS7_R_INVALID_NULL_POINTER);
658         return 0;
659     }
660
661     if (p7->d.ptr == NULL) {
662         PKCS7err(PKCS7_F_PKCS7_DATAFINAL, PKCS7_R_NO_CONTENT);
663         return 0;
664     }
665
666     ctx_tmp = EVP_MD_CTX_new();
667     if (ctx_tmp == NULL) {
668         PKCS7err(PKCS7_F_PKCS7_DATAFINAL, ERR_R_MALLOC_FAILURE);
669         return 0;
670     }
671
672     i = OBJ_obj2nid(p7->type);
673     p7->state = PKCS7_S_HEADER;
674
675     switch (i) {
676     case NID_pkcs7_data:
677         os = p7->d.data;
678         break;
679     case NID_pkcs7_signedAndEnveloped:
680         /* XXXXXXXXXXXXXXXX */
681         si_sk = p7->d.signed_and_enveloped->signer_info;
682         os = p7->d.signed_and_enveloped->enc_data->enc_data;
683         if (os == NULL) {
684             os = ASN1_OCTET_STRING_new();
685             if (os == NULL) {
686                 PKCS7err(PKCS7_F_PKCS7_DATAFINAL, ERR_R_MALLOC_FAILURE);
687                 goto err;
688             }
689             p7->d.signed_and_enveloped->enc_data->enc_data = os;
690         }
691         break;
692     case NID_pkcs7_enveloped:
693         /* XXXXXXXXXXXXXXXX */
694         os = p7->d.enveloped->enc_data->enc_data;
695         if (os == NULL) {
696             os = ASN1_OCTET_STRING_new();
697             if (os == NULL) {
698                 PKCS7err(PKCS7_F_PKCS7_DATAFINAL, ERR_R_MALLOC_FAILURE);
699                 goto err;
700             }
701             p7->d.enveloped->enc_data->enc_data = os;
702         }
703         break;
704     case NID_pkcs7_signed:
705         si_sk = p7->d.sign->signer_info;
706         os = PKCS7_get_octet_string(p7->d.sign->contents);
707         /* If detached data then the content is excluded */
708         if (PKCS7_type_is_data(p7->d.sign->contents) && p7->detached) {
709             ASN1_OCTET_STRING_free(os);
710             os = NULL;
711             p7->d.sign->contents->d.data = NULL;
712         }
713         break;
714
715     case NID_pkcs7_digest:
716         os = PKCS7_get_octet_string(p7->d.digest->contents);
717         /* If detached data then the content is excluded */
718         if (PKCS7_type_is_data(p7->d.digest->contents) && p7->detached) {
719             ASN1_OCTET_STRING_free(os);
720             os = NULL;
721             p7->d.digest->contents->d.data = NULL;
722         }
723         break;
724
725     default:
726         PKCS7err(PKCS7_F_PKCS7_DATAFINAL, PKCS7_R_UNSUPPORTED_CONTENT_TYPE);
727         goto err;
728     }
729
730     if (si_sk != NULL) {
731         for (i = 0; i < sk_PKCS7_SIGNER_INFO_num(si_sk); i++) {
732             si = sk_PKCS7_SIGNER_INFO_value(si_sk, i);
733             if (si->pkey == NULL)
734                 continue;
735
736             j = OBJ_obj2nid(si->digest_alg->algorithm);
737
738             btmp = bio;
739
740             btmp = PKCS7_find_digest(&mdc, btmp, j);
741
742             if (btmp == NULL)
743                 goto err;
744
745             /*
746              * We now have the EVP_MD_CTX, lets do the signing.
747              */
748             if (!EVP_MD_CTX_copy_ex(ctx_tmp, mdc))
749                 goto err;
750
751             sk = si->auth_attr;
752
753             /*
754              * If there are attributes, we add the digest attribute and only
755              * sign the attributes
756              */
757             if (sk_X509_ATTRIBUTE_num(sk) > 0) {
758                 if (!do_pkcs7_signed_attrib(si, ctx_tmp))
759                     goto err;
760             } else {
761                 unsigned char *abuf = NULL;
762                 unsigned int abuflen;
763                 abuflen = EVP_PKEY_size(si->pkey);
764                 abuf = OPENSSL_malloc(abuflen);
765                 if (abuf == NULL)
766                     goto err;
767
768                 if (!EVP_SignFinal(ctx_tmp, abuf, &abuflen, si->pkey)) {
769                     OPENSSL_free(abuf);
770                     PKCS7err(PKCS7_F_PKCS7_DATAFINAL, ERR_R_EVP_LIB);
771                     goto err;
772                 }
773                 ASN1_STRING_set0(si->enc_digest, abuf, abuflen);
774             }
775         }
776     } else if (i == NID_pkcs7_digest) {
777         unsigned char md_data[EVP_MAX_MD_SIZE];
778         unsigned int md_len;
779         if (!PKCS7_find_digest(&mdc, bio,
780                                OBJ_obj2nid(p7->d.digest->md->algorithm)))
781             goto err;
782         if (!EVP_DigestFinal_ex(mdc, md_data, &md_len))
783             goto err;
784         if (!ASN1_OCTET_STRING_set(p7->d.digest->digest, md_data, md_len))
785             goto err;
786     }
787
788     if (!PKCS7_is_detached(p7)) {
789         /*
790          * NOTE(emilia): I think we only reach os == NULL here because detached
791          * digested data support is broken.
792          */
793         if (os == NULL)
794             goto err;
795         if (!(os->flags & ASN1_STRING_FLAG_NDEF)) {
796             char *cont;
797             long contlen;
798             btmp = BIO_find_type(bio, BIO_TYPE_MEM);
799             if (btmp == NULL) {
800                 PKCS7err(PKCS7_F_PKCS7_DATAFINAL, PKCS7_R_UNABLE_TO_FIND_MEM_BIO);
801                 goto err;
802             }
803             contlen = BIO_get_mem_data(btmp, &cont);
804             /*
805              * Mark the BIO read only then we can use its copy of the data
806              * instead of making an extra copy.
807              */
808             BIO_set_flags(btmp, BIO_FLAGS_MEM_RDONLY);
809             BIO_set_mem_eof_return(btmp, 0);
810             ASN1_STRING_set0(os, (unsigned char *)cont, contlen);
811         }
812     }
813     ret = 1;
814  err:
815     EVP_MD_CTX_free(ctx_tmp);
816     return ret;
817 }
818
819 int PKCS7_SIGNER_INFO_sign(PKCS7_SIGNER_INFO *si)
820 {
821     EVP_MD_CTX *mctx;
822     EVP_PKEY_CTX *pctx = NULL;
823     unsigned char *abuf = NULL;
824     int alen;
825     size_t siglen;
826     const EVP_MD *md = NULL;
827
828     md = EVP_get_digestbyobj(si->digest_alg->algorithm);
829     if (md == NULL)
830         return 0;
831
832     mctx = EVP_MD_CTX_new();
833     if (mctx == NULL) {
834         PKCS7err(PKCS7_F_PKCS7_SIGNER_INFO_SIGN, ERR_R_MALLOC_FAILURE);
835         goto err;
836     }
837
838     if (EVP_DigestSignInit(mctx, &pctx, md, NULL, si->pkey) <= 0)
839         goto err;
840
841     if (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_SIGN,
842                           EVP_PKEY_CTRL_PKCS7_SIGN, 0, si) <= 0) {
843         PKCS7err(PKCS7_F_PKCS7_SIGNER_INFO_SIGN, PKCS7_R_CTRL_ERROR);
844         goto err;
845     }
846
847     alen = ASN1_item_i2d((ASN1_VALUE *)si->auth_attr, &abuf,
848                          ASN1_ITEM_rptr(PKCS7_ATTR_SIGN));
849     if (!abuf)
850         goto err;
851     if (EVP_DigestSignUpdate(mctx, abuf, alen) <= 0)
852         goto err;
853     OPENSSL_free(abuf);
854     abuf = NULL;
855     if (EVP_DigestSignFinal(mctx, NULL, &siglen) <= 0)
856         goto err;
857     abuf = OPENSSL_malloc(siglen);
858     if (abuf == NULL)
859         goto err;
860     if (EVP_DigestSignFinal(mctx, abuf, &siglen) <= 0)
861         goto err;
862
863     if (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_SIGN,
864                           EVP_PKEY_CTRL_PKCS7_SIGN, 1, si) <= 0) {
865         PKCS7err(PKCS7_F_PKCS7_SIGNER_INFO_SIGN, PKCS7_R_CTRL_ERROR);
866         goto err;
867     }
868
869     EVP_MD_CTX_free(mctx);
870
871     ASN1_STRING_set0(si->enc_digest, abuf, siglen);
872
873     return 1;
874
875  err:
876     OPENSSL_free(abuf);
877     EVP_MD_CTX_free(mctx);
878     return 0;
879
880 }
881
882 int PKCS7_dataVerify(X509_STORE *cert_store, X509_STORE_CTX *ctx, BIO *bio,
883                      PKCS7 *p7, PKCS7_SIGNER_INFO *si)
884 {
885     PKCS7_ISSUER_AND_SERIAL *ias;
886     int ret = 0, i;
887     STACK_OF(X509) *cert;
888     X509 *x509;
889
890     if (p7 == NULL) {
891         PKCS7err(PKCS7_F_PKCS7_DATAVERIFY, PKCS7_R_INVALID_NULL_POINTER);
892         return 0;
893     }
894
895     if (p7->d.ptr == NULL) {
896         PKCS7err(PKCS7_F_PKCS7_DATAVERIFY, PKCS7_R_NO_CONTENT);
897         return 0;
898     }
899
900     if (PKCS7_type_is_signed(p7)) {
901         cert = p7->d.sign->cert;
902     } else if (PKCS7_type_is_signedAndEnveloped(p7)) {
903         cert = p7->d.signed_and_enveloped->cert;
904     } else {
905         PKCS7err(PKCS7_F_PKCS7_DATAVERIFY, PKCS7_R_WRONG_PKCS7_TYPE);
906         goto err;
907     }
908     /* XXXXXXXXXXXXXXXXXXXXXXX */
909     ias = si->issuer_and_serial;
910
911     x509 = X509_find_by_issuer_and_serial(cert, ias->issuer, ias->serial);
912
913     /* were we able to find the cert in passed to us */
914     if (x509 == NULL) {
915         PKCS7err(PKCS7_F_PKCS7_DATAVERIFY,
916                  PKCS7_R_UNABLE_TO_FIND_CERTIFICATE);
917         goto err;
918     }
919
920     /* Lets verify */
921     if (!X509_STORE_CTX_init(ctx, cert_store, x509, cert)) {
922         PKCS7err(PKCS7_F_PKCS7_DATAVERIFY, ERR_R_X509_LIB);
923         goto err;
924     }
925     X509_STORE_CTX_set_purpose(ctx, X509_PURPOSE_SMIME_SIGN);
926     i = X509_verify_cert(ctx);
927     if (i <= 0) {
928         PKCS7err(PKCS7_F_PKCS7_DATAVERIFY, ERR_R_X509_LIB);
929         X509_STORE_CTX_cleanup(ctx);
930         goto err;
931     }
932     X509_STORE_CTX_cleanup(ctx);
933
934     return PKCS7_signatureVerify(bio, p7, si, x509);
935  err:
936     return ret;
937 }
938
939 int PKCS7_signatureVerify(BIO *bio, PKCS7 *p7, PKCS7_SIGNER_INFO *si,
940                           X509 *x509)
941 {
942     ASN1_OCTET_STRING *os;
943     EVP_MD_CTX *mdc_tmp, *mdc;
944     int ret = 0, i;
945     int md_type;
946     STACK_OF(X509_ATTRIBUTE) *sk;
947     BIO *btmp;
948     EVP_PKEY *pkey;
949
950     mdc_tmp = EVP_MD_CTX_new();
951     if (mdc_tmp == NULL) {
952         PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY, ERR_R_MALLOC_FAILURE);
953         goto err;
954     }
955
956     if (!PKCS7_type_is_signed(p7) && !PKCS7_type_is_signedAndEnveloped(p7)) {
957         PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY, PKCS7_R_WRONG_PKCS7_TYPE);
958         goto err;
959     }
960
961     md_type = OBJ_obj2nid(si->digest_alg->algorithm);
962
963     btmp = bio;
964     for (;;) {
965         if ((btmp == NULL) ||
966             ((btmp = BIO_find_type(btmp, BIO_TYPE_MD)) == NULL)) {
967             PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY,
968                      PKCS7_R_UNABLE_TO_FIND_MESSAGE_DIGEST);
969             goto err;
970         }
971         BIO_get_md_ctx(btmp, &mdc);
972         if (mdc == NULL) {
973             PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY, ERR_R_INTERNAL_ERROR);
974             goto err;
975         }
976         if (EVP_MD_CTX_type(mdc) == md_type)
977             break;
978         /*
979          * Workaround for some broken clients that put the signature OID
980          * instead of the digest OID in digest_alg->algorithm
981          */
982         if (EVP_MD_pkey_type(EVP_MD_CTX_md(mdc)) == md_type)
983             break;
984         btmp = BIO_next(btmp);
985     }
986
987     /*
988      * mdc is the digest ctx that we want, unless there are attributes, in
989      * which case the digest is the signed attributes
990      */
991     if (!EVP_MD_CTX_copy_ex(mdc_tmp, mdc))
992         goto err;
993
994     sk = si->auth_attr;
995     if ((sk != NULL) && (sk_X509_ATTRIBUTE_num(sk) != 0)) {
996         unsigned char md_dat[EVP_MAX_MD_SIZE], *abuf = NULL;
997         unsigned int md_len;
998         int alen;
999         ASN1_OCTET_STRING *message_digest;
1000
1001         if (!EVP_DigestFinal_ex(mdc_tmp, md_dat, &md_len))
1002             goto err;
1003         message_digest = PKCS7_digest_from_attributes(sk);
1004         if (!message_digest) {
1005             PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY,
1006                      PKCS7_R_UNABLE_TO_FIND_MESSAGE_DIGEST);
1007             goto err;
1008         }
1009         if ((message_digest->length != (int)md_len) ||
1010             (memcmp(message_digest->data, md_dat, md_len))) {
1011             PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY, PKCS7_R_DIGEST_FAILURE);
1012             ret = -1;
1013             goto err;
1014         }
1015
1016         if (!EVP_VerifyInit_ex(mdc_tmp, EVP_get_digestbynid(md_type), NULL))
1017             goto err;
1018
1019         alen = ASN1_item_i2d((ASN1_VALUE *)sk, &abuf,
1020                              ASN1_ITEM_rptr(PKCS7_ATTR_VERIFY));
1021         if (alen <= 0) {
1022             PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY, ERR_R_ASN1_LIB);
1023             ret = -1;
1024             goto err;
1025         }
1026         if (!EVP_VerifyUpdate(mdc_tmp, abuf, alen))
1027             goto err;
1028
1029         OPENSSL_free(abuf);
1030     }
1031
1032     os = si->enc_digest;
1033     pkey = X509_get0_pubkey(x509);
1034     if (!pkey) {
1035         ret = -1;
1036         goto err;
1037     }
1038
1039     i = EVP_VerifyFinal(mdc_tmp, os->data, os->length, pkey);
1040     if (i <= 0) {
1041         PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY, PKCS7_R_SIGNATURE_FAILURE);
1042         ret = -1;
1043         goto err;
1044     }
1045     ret = 1;
1046  err:
1047     EVP_MD_CTX_free(mdc_tmp);
1048     return ret;
1049 }
1050
1051 PKCS7_ISSUER_AND_SERIAL *PKCS7_get_issuer_and_serial(PKCS7 *p7, int idx)
1052 {
1053     STACK_OF(PKCS7_RECIP_INFO) *rsk;
1054     PKCS7_RECIP_INFO *ri;
1055     int i;
1056
1057     i = OBJ_obj2nid(p7->type);
1058     if (i != NID_pkcs7_signedAndEnveloped)
1059         return NULL;
1060     if (p7->d.signed_and_enveloped == NULL)
1061         return NULL;
1062     rsk = p7->d.signed_and_enveloped->recipientinfo;
1063     if (rsk == NULL)
1064         return NULL;
1065     if (sk_PKCS7_RECIP_INFO_num(rsk) <= idx)
1066         return NULL;
1067     ri = sk_PKCS7_RECIP_INFO_value(rsk, idx);
1068     return ri->issuer_and_serial;
1069 }
1070
1071 ASN1_TYPE *PKCS7_get_signed_attribute(PKCS7_SIGNER_INFO *si, int nid)
1072 {
1073     return get_attribute(si->auth_attr, nid);
1074 }
1075
1076 ASN1_TYPE *PKCS7_get_attribute(PKCS7_SIGNER_INFO *si, int nid)
1077 {
1078     return get_attribute(si->unauth_attr, nid);
1079 }
1080
1081 static ASN1_TYPE *get_attribute(STACK_OF(X509_ATTRIBUTE) *sk, int nid)
1082 {
1083     int idx;
1084     X509_ATTRIBUTE *xa;
1085     idx = X509at_get_attr_by_NID(sk, nid, -1);
1086     xa = X509at_get_attr(sk, idx);
1087     return X509_ATTRIBUTE_get0_type(xa, 0);
1088 }
1089
1090 ASN1_OCTET_STRING *PKCS7_digest_from_attributes(STACK_OF(X509_ATTRIBUTE) *sk)
1091 {
1092     ASN1_TYPE *astype;
1093     if ((astype = get_attribute(sk, NID_pkcs9_messageDigest)) == NULL)
1094         return NULL;
1095     return astype->value.octet_string;
1096 }
1097
1098 int PKCS7_set_signed_attributes(PKCS7_SIGNER_INFO *p7si,
1099                                 STACK_OF(X509_ATTRIBUTE) *sk)
1100 {
1101     int i;
1102
1103     sk_X509_ATTRIBUTE_pop_free(p7si->auth_attr, X509_ATTRIBUTE_free);
1104     p7si->auth_attr = sk_X509_ATTRIBUTE_dup(sk);
1105     if (p7si->auth_attr == NULL)
1106         return 0;
1107     for (i = 0; i < sk_X509_ATTRIBUTE_num(sk); i++) {
1108         if ((sk_X509_ATTRIBUTE_set(p7si->auth_attr, i,
1109                                    X509_ATTRIBUTE_dup(sk_X509_ATTRIBUTE_value
1110                                                       (sk, i))))
1111             == NULL)
1112             return 0;
1113     }
1114     return 1;
1115 }
1116
1117 int PKCS7_set_attributes(PKCS7_SIGNER_INFO *p7si,
1118                          STACK_OF(X509_ATTRIBUTE) *sk)
1119 {
1120     int i;
1121
1122     sk_X509_ATTRIBUTE_pop_free(p7si->unauth_attr, X509_ATTRIBUTE_free);
1123     p7si->unauth_attr = sk_X509_ATTRIBUTE_dup(sk);
1124     if (p7si->unauth_attr == NULL)
1125         return 0;
1126     for (i = 0; i < sk_X509_ATTRIBUTE_num(sk); i++) {
1127         if ((sk_X509_ATTRIBUTE_set(p7si->unauth_attr, i,
1128                                    X509_ATTRIBUTE_dup(sk_X509_ATTRIBUTE_value
1129                                                       (sk, i))))
1130             == NULL)
1131             return 0;
1132     }
1133     return 1;
1134 }
1135
1136 int PKCS7_add_signed_attribute(PKCS7_SIGNER_INFO *p7si, int nid, int atrtype,
1137                                void *value)
1138 {
1139     return add_attribute(&(p7si->auth_attr), nid, atrtype, value);
1140 }
1141
1142 int PKCS7_add_attribute(PKCS7_SIGNER_INFO *p7si, int nid, int atrtype,
1143                         void *value)
1144 {
1145     return add_attribute(&(p7si->unauth_attr), nid, atrtype, value);
1146 }
1147
1148 static int add_attribute(STACK_OF(X509_ATTRIBUTE) **sk, int nid, int atrtype,
1149                          void *value)
1150 {
1151     X509_ATTRIBUTE *attr = NULL;
1152
1153     if (*sk == NULL) {
1154         if ((*sk = sk_X509_ATTRIBUTE_new_null()) == NULL)
1155             return 0;
1156  new_attrib:
1157         if ((attr = X509_ATTRIBUTE_create(nid, atrtype, value)) == NULL)
1158             return 0;
1159         if (!sk_X509_ATTRIBUTE_push(*sk, attr)) {
1160             X509_ATTRIBUTE_free(attr);
1161             return 0;
1162         }
1163     } else {
1164         int i;
1165
1166         for (i = 0; i < sk_X509_ATTRIBUTE_num(*sk); i++) {
1167             attr = sk_X509_ATTRIBUTE_value(*sk, i);
1168             if (OBJ_obj2nid(X509_ATTRIBUTE_get0_object(attr)) == nid) {
1169                 X509_ATTRIBUTE_free(attr);
1170                 attr = X509_ATTRIBUTE_create(nid, atrtype, value);
1171                 if (attr == NULL)
1172                     return 0;
1173                 if (!sk_X509_ATTRIBUTE_set(*sk, i, attr)) {
1174                     X509_ATTRIBUTE_free(attr);
1175                     return 0;
1176                 }
1177                 goto end;
1178             }
1179         }
1180         goto new_attrib;
1181     }
1182  end:
1183     return 1;
1184 }