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