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