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