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