Various PKCS#7 fixes to properly (maybe!) handle PKCS#7 enveloped data.
[openssl.git] / crypto / pkcs7 / pk7_doit.c
1 /* crypto/pkcs7/pk7_doit.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  * 
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  * 
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  * 
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from 
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  * 
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * 
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58
59 #include <stdio.h>
60 #include "cryptlib.h"
61 #include <openssl/rand.h>
62 #include <openssl/objects.h>
63 #include <openssl/x509.h>
64
65 static int add_attribute(STACK **sk, int nid, int atrtype, void *value);
66 static ASN1_TYPE *get_attribute(STACK *sk, int nid);
67
68 #if 1
69 BIO *PKCS7_dataInit(PKCS7 *p7, BIO *bio)
70         {
71         int i,j;
72         BIO *out=NULL,*btmp=NULL;
73         X509_ALGOR *xa;
74         const EVP_MD *evp_md;
75         const EVP_CIPHER *evp_cipher=NULL;
76         STACK *md_sk=NULL,*rsk=NULL;
77         X509_ALGOR *xalg=NULL;
78         PKCS7_RECIP_INFO *ri=NULL;
79         EVP_PKEY *pkey;
80
81         i=OBJ_obj2nid(p7->type);
82         p7->state=PKCS7_S_HEADER;
83
84         switch (i)
85                 {
86         case NID_pkcs7_signed:
87                 md_sk=p7->d.sign->md_algs;
88                 break;
89         case NID_pkcs7_signedAndEnveloped:
90                 rsk=p7->d.signed_and_enveloped->recipientinfo;
91                 md_sk=p7->d.signed_and_enveloped->md_algs;
92                 evp_cipher=EVP_get_cipherbyname(OBJ_nid2sn(OBJ_obj2nid(p7->d.signed_and_enveloped->enc_data->algorithm->algorithm)));
93                 if (evp_cipher == NULL)
94                         {
95                         PKCS7err(PKCS7_F_PKCS7_DATAINIT,PKCS7_R_UNSUPPORTED_CIPHER_TYPE);
96                         goto err;
97                         }
98                 xalg=p7->d.signed_and_enveloped->enc_data->algorithm;
99                 break;
100         case NID_pkcs7_enveloped:
101                 rsk=p7->d.enveloped->recipientinfo;
102                 evp_cipher=EVP_get_cipherbyname(OBJ_nid2sn(OBJ_obj2nid(p7->d.enveloped->enc_data->algorithm->algorithm)));
103                 if (evp_cipher == NULL)
104                         {
105                         PKCS7err(PKCS7_F_PKCS7_DATAINIT,PKCS7_R_UNSUPPORTED_CIPHER_TYPE);
106                         goto err;
107                         }
108                 xalg=p7->d.enveloped->enc_data->algorithm;
109                 break;
110         default:
111                 PKCS7err(PKCS7_F_PKCS7_DATAINIT,PKCS7_R_UNSUPPORTED_CONTENT_TYPE);
112                 goto err;
113                 }
114
115         if (md_sk != NULL)
116                 {
117                 for (i=0; i<sk_num(md_sk); i++)
118                         {
119                         xa=(X509_ALGOR *)sk_value(md_sk,i);
120                         if ((btmp=BIO_new(BIO_f_md())) == NULL)
121                                 {
122                                 PKCS7err(PKCS7_F_PKCS7_DATAINIT,ERR_R_BIO_LIB);
123                                 goto err;
124                                 }
125
126                         j=OBJ_obj2nid(xa->algorithm);
127                         evp_md=EVP_get_digestbyname(OBJ_nid2sn(j));
128                         if (evp_md == NULL)
129                                 {
130                                 PKCS7err(PKCS7_F_PKCS7_DATAINIT,PKCS7_R_UNKNOWN_DIGEST_TYPE);
131                                 goto err;
132                                 }
133
134                         BIO_set_md(btmp,evp_md);
135                         if (out == NULL)
136                                 out=btmp;
137                         else
138                                 BIO_push(out,btmp);
139                         btmp=NULL;
140                         }
141                 }
142
143         if (evp_cipher != NULL)
144                 {
145                 unsigned char key[EVP_MAX_KEY_LENGTH];
146                 unsigned char iv[EVP_MAX_IV_LENGTH];
147                 int keylen,ivlen;
148                 int jj,max;
149                 unsigned char *tmp;
150
151                 if ((btmp=BIO_new(BIO_f_cipher())) == NULL)
152                         {
153                         PKCS7err(PKCS7_F_PKCS7_DATAINIT,ERR_R_BIO_LIB);
154                         goto err;
155                         }
156                 keylen=EVP_CIPHER_key_length(evp_cipher);
157                 ivlen=EVP_CIPHER_iv_length(evp_cipher);
158
159                 if (ivlen > 0) {
160                         EVP_CIPHER_CTX *ctx;
161                         BIO_get_cipher_ctx(btmp, &ctx);
162                         if (xalg->parameter == NULL) 
163                                                 xalg->parameter=ASN1_TYPE_new();
164                         if(EVP_CIPHER_param_to_asn1(ctx, xalg->parameter) < 0)
165                                                                        goto err;
166                 }
167                 RAND_bytes(key,keylen);
168
169                 /* Lets do the pub key stuff :-) */
170                 max=0;
171                 for (i=0; i<sk_num(rsk); i++)
172                         {
173                         ri=(PKCS7_RECIP_INFO *)sk_value(rsk,i);
174                         if (ri->cert == NULL)
175                                 {
176                                 PKCS7err(PKCS7_F_PKCS7_DATAINIT,PKCS7_R_MISSING_CERIPEND_INFO);
177                                 goto err;
178                                 }
179                         pkey=X509_get_pubkey(ri->cert);
180                         jj=EVP_PKEY_size(pkey);
181                         EVP_PKEY_free(pkey);
182                         if (max < jj) max=jj;
183                         }
184                 if ((tmp=(unsigned char *)Malloc(max)) == NULL)
185                         {
186                         PKCS7err(PKCS7_F_PKCS7_DATAINIT,ERR_R_MALLOC_FAILURE);
187                         goto err;
188                         }
189                 for (i=0; i<sk_num(rsk); i++)
190                         {
191                         ri=(PKCS7_RECIP_INFO *)sk_value(rsk,i);
192                         pkey=X509_get_pubkey(ri->cert);
193                         jj=EVP_PKEY_encrypt(tmp,key,keylen,pkey);
194                         EVP_PKEY_free(pkey);
195                         if (jj <= 0)
196                                 {
197                                 PKCS7err(PKCS7_F_PKCS7_DATAINIT,ERR_R_EVP_LIB);
198                                 Free(tmp);
199                                 goto err;
200                                 }
201                         ASN1_OCTET_STRING_set(ri->enc_key,tmp,jj);
202                         }
203                 Free(tmp);
204
205                 BIO_set_cipher(btmp,evp_cipher,key,iv,1);
206
207                 if (out == NULL)
208                         out=btmp;
209                 else
210                         BIO_push(out,btmp);
211                 btmp=NULL;
212                 }
213
214         if (bio == NULL) /* ??????????? */
215                 {
216                 if (p7->detached)
217                         bio=BIO_new(BIO_s_null());
218                 else
219                         {
220                         bio=BIO_new(BIO_s_mem());
221                         /* We need to set this so that when we have read all
222                          * the data, the encrypt BIO, if present, will read
223                          * EOF and encode the last few bytes */
224                         BIO_set_mem_eof_return(bio,0);
225
226                         if (PKCS7_type_is_signed(p7) &&
227                                 PKCS7_type_is_data(p7->d.sign->contents))
228                                 {
229                                 ASN1_OCTET_STRING *os;
230
231                                 os=p7->d.sign->contents->d.data;
232                                 if (os->length > 0)
233                                         BIO_write(bio,(char *)os->data,
234                                                 os->length);
235                                 }
236                         }
237                 }
238         BIO_push(out,bio);
239         bio=NULL;
240         if (0)
241                 {
242 err:
243                 if (out != NULL)
244                         BIO_free_all(out);
245                 if (btmp != NULL)
246                         BIO_free_all(btmp);
247                 out=NULL;
248                 }
249         return(out);
250         }
251
252 /* int */
253 BIO *PKCS7_dataDecode(PKCS7 *p7, EVP_PKEY *pkey, BIO *in_bio,
254              X509_STORE *xs)
255         {
256         int i,j;
257         BIO *out=NULL,*btmp=NULL,*etmp=NULL,*bio=NULL;
258         char *tmp=NULL;
259         X509_ALGOR *xa;
260         ASN1_OCTET_STRING *data_body=NULL;
261         const EVP_MD *evp_md;
262         const EVP_CIPHER *evp_cipher=NULL;
263         EVP_CIPHER_CTX *evp_ctx=NULL;
264         X509_ALGOR *enc_alg=NULL;
265         STACK *md_sk=NULL,*rsk=NULL;
266         X509_ALGOR *xalg=NULL;
267         PKCS7_RECIP_INFO *ri=NULL;
268 /*      EVP_PKEY *pkey; */
269 #if 0
270         X509_STORE_CTX s_ctx;
271 #endif
272
273         i=OBJ_obj2nid(p7->type);
274         p7->state=PKCS7_S_HEADER;
275
276         switch (i)
277                 {
278         case NID_pkcs7_signed:
279                 data_body=p7->d.sign->contents->d.data;
280                 md_sk=p7->d.sign->md_algs;
281                 break;
282         case NID_pkcs7_signedAndEnveloped:
283                 rsk=p7->d.signed_and_enveloped->recipientinfo;
284                 md_sk=p7->d.signed_and_enveloped->md_algs;
285                 data_body=p7->d.signed_and_enveloped->enc_data->enc_data;
286                 enc_alg=p7->d.signed_and_enveloped->enc_data->algorithm;
287                 evp_cipher=EVP_get_cipherbyname(OBJ_nid2sn(OBJ_obj2nid(enc_alg->algorithm)));
288                 if (evp_cipher == NULL)
289                         {
290                         PKCS7err(PKCS7_F_PKCS7_SIGNENVELOPEDECRYPT,PKCS7_R_UNSUPPORTED_CIPHER_TYPE);
291                         goto err;
292                         }
293                 xalg=p7->d.signed_and_enveloped->enc_data->algorithm;
294                 break;
295         case NID_pkcs7_enveloped:
296                 rsk=p7->d.enveloped->recipientinfo;
297                 enc_alg=p7->d.enveloped->enc_data->algorithm;
298                 data_body=p7->d.enveloped->enc_data->enc_data;
299                 evp_cipher=EVP_get_cipherbyname(OBJ_nid2sn(OBJ_obj2nid(enc_alg->algorithm)));
300                 if (evp_cipher == NULL)
301                         {
302                         PKCS7err(PKCS7_F_PKCS7_SIGNENVELOPEDECRYPT,PKCS7_R_UNSUPPORTED_CIPHER_TYPE);
303                         goto err;
304                         }
305                 xalg=p7->d.enveloped->enc_data->algorithm;
306                 break;
307         default:
308                 PKCS7err(PKCS7_F_PKCS7_SIGNENVELOPEDECRYPT,PKCS7_R_UNSUPPORTED_CONTENT_TYPE);
309                 goto err;
310                 }
311
312         /* We will be checking the signature */
313         if (md_sk != NULL)
314                 {
315                 for (i=0; i<sk_num(md_sk); i++)
316                         {
317                         xa=(X509_ALGOR *)sk_value(md_sk,i);
318                         if ((btmp=BIO_new(BIO_f_md())) == NULL)
319                                 {
320                                 PKCS7err(PKCS7_F_PKCS7_SIGNENVELOPEDECRYPT,ERR_R_BIO_LIB);
321                                 goto err;
322                                 }
323
324                         j=OBJ_obj2nid(xa->algorithm);
325                         evp_md=EVP_get_digestbyname(OBJ_nid2sn(j));
326                         if (evp_md == NULL)
327                                 {
328                                 PKCS7err(PKCS7_F_PKCS7_SIGNENVELOPEDECRYPT,PKCS7_R_UNKNOWN_DIGEST_TYPE);
329                                 goto err;
330                                 }
331
332                         BIO_set_md(btmp,evp_md);
333                         if (out == NULL)
334                                 out=btmp;
335                         else
336                                 BIO_push(out,btmp);
337                         btmp=NULL;
338                         }
339                 }
340
341         if (evp_cipher != NULL)
342                 {
343 #if 0
344                 unsigned char key[EVP_MAX_KEY_LENGTH];
345                 unsigned char iv[EVP_MAX_IV_LENGTH];
346                 unsigned char *p;
347                 int keylen,ivlen;
348                 int max;
349                 X509_OBJECT ret;
350 #endif
351                 int jj;
352
353                 if ((etmp=BIO_new(BIO_f_cipher())) == NULL)
354                         {
355                         PKCS7err(PKCS7_F_PKCS7_SIGNENVELOPEDECRYPT,ERR_R_BIO_LIB);
356                         goto err;
357                         }
358
359                 /* It was encrypted, we need to decrypt the secret key
360                  * with the private key */
361
362                 /* We need to find a private key for one of the people in the
363                  * recipentinfo list */
364                 if (rsk == NULL)
365                         return(NULL);
366
367                 ri=(PKCS7_RECIP_INFO *)sk_value(rsk,0);
368 #if 0
369                 X509_STORE_CTX_init(&s_ctx,xs,NULL,NULL);
370                 for (i=0; i<sk_num(rsk); i++)
371                         {
372                         ri=(PKCS7_RECIP_INFO *)sk_value(rsk,i);
373                         uf (X509_STORE_get_by_issuer_serial(&s_ctx,
374                                 X509_LU_PKEY,
375                                 ri->issuer_and_serial->issuer,
376                                 ri->issuer_and_serial->serial,
377                                 &ret))
378                                 break;
379                         ri=NULL;
380                         }
381                 if (ri == NULL) return(NULL);   
382                 pkey=ret.data.pkey;
383 #endif
384                 if (pkey == NULL)
385                         {
386                         return(NULL);
387                         }
388
389                 jj=EVP_PKEY_size(pkey);
390                 tmp=Malloc(jj+10);
391                 if (tmp == NULL)
392                         {
393                         PKCS7err(PKCS7_F_PKCS7_SIGNENVELOPEDECRYPT,ERR_R_MALLOC_FAILURE);
394                         goto err;
395                         }
396
397                 jj=EVP_PKEY_decrypt((unsigned char *)tmp,
398                         ASN1_STRING_data(ri->enc_key),
399                         ASN1_STRING_length(ri->enc_key),
400                         pkey);
401                 if (jj <= 0)
402                         {
403                         PKCS7err(PKCS7_F_PKCS7_SIGNENVELOPEDECRYPT,ERR_R_EVP_LIB);
404                         goto err;
405                         }
406
407                 evp_ctx=NULL;
408                 BIO_get_cipher_ctx(etmp,&evp_ctx);
409                 EVP_CipherInit(evp_ctx,evp_cipher,NULL,NULL,0);
410                 if (EVP_CIPHER_asn1_to_param(evp_ctx,enc_alg->parameter) < 0)
411                         return(NULL);
412
413                 if (jj != EVP_CIPHER_CTX_key_length(evp_ctx))
414                         {
415                         PKCS7err(PKCS7_F_PKCS7_SIGNENVELOPEDECRYPT,PKCS7_R_DECRYPTED_KEY_IS_WRONG_LENGTH);
416                         goto err;
417                         }
418                 EVP_CipherInit(evp_ctx,NULL,(unsigned char *)tmp,NULL,0);
419
420                 memset(tmp,0,jj);
421
422                 if (out == NULL)
423                         out=etmp;
424                 else
425                         BIO_push(out,etmp);
426                 etmp=NULL;
427                 }
428
429 #if 1
430         if (p7->detached || (in_bio != NULL))
431                 {
432                 bio=in_bio;
433                 }
434         else 
435                 {
436                 bio=BIO_new(BIO_s_mem());
437                 /* We need to set this so that when we have read all
438                  * the data, the encrypt BIO, if present, will read
439                  * EOF and encode the last few bytes */
440                 BIO_set_mem_eof_return(bio,0);
441
442                 if (data_body->length > 0)
443                         BIO_write(bio,(char *)data_body->data,data_body->length);
444                 }
445         BIO_push(out,bio);
446         bio=NULL;
447 #endif
448         if (0)
449                 {
450 err:
451                 if (out != NULL) BIO_free_all(out);
452                 if (btmp != NULL) BIO_free_all(btmp);
453                 if (etmp != NULL) BIO_free_all(etmp);
454                 if (bio != NULL) BIO_free_all(bio);
455                 out=NULL;
456                 }
457         if (tmp != NULL)
458                 Free(tmp);
459         return(out);
460         }
461 #endif
462
463 int PKCS7_dataFinal(PKCS7 *p7, BIO *bio)
464         {
465         int ret=0;
466         int i,j;
467         BIO *btmp;
468         BUF_MEM *buf_mem=NULL;
469         BUF_MEM *buf=NULL;
470         PKCS7_SIGNER_INFO *si;
471         EVP_MD_CTX *mdc,ctx_tmp;
472         STACK *sk,*si_sk=NULL;
473         unsigned char *p,*pp=NULL;
474         int x;
475         ASN1_OCTET_STRING *os=NULL;
476
477         i=OBJ_obj2nid(p7->type);
478         p7->state=PKCS7_S_HEADER;
479
480         switch (i)
481                 {
482         case NID_pkcs7_signedAndEnveloped:
483                 /* XXXXXXXXXXXXXXXX */
484                 si_sk=p7->d.signed_and_enveloped->signer_info;
485                 os=ASN1_OCTET_STRING_new();
486                 p7->d.signed_and_enveloped->enc_data->enc_data=os;
487                 break;
488         case NID_pkcs7_enveloped:
489                 /* XXXXXXXXXXXXXXXX */
490                 os=ASN1_OCTET_STRING_new();
491                 p7->d.enveloped->enc_data->enc_data=os;
492                 break;
493         case NID_pkcs7_signed:
494                 si_sk=p7->d.sign->signer_info;
495                 os=p7->d.sign->contents->d.data;
496                 /* If detached data then the content is excluded */
497                 if(p7->detached) {
498                         ASN1_OCTET_STRING_free(os);
499                         p7->d.sign->contents->d.data = NULL;
500                 }
501                 break;
502                 }
503
504         if (si_sk != NULL)
505                 {
506                 if ((buf=BUF_MEM_new()) == NULL)
507                         {
508                         PKCS7err(PKCS7_F_PKCS7_DATASIGN,ERR_R_BIO_LIB);
509                         goto err;
510                         }
511                 for (i=0; i<sk_num(si_sk); i++)
512                         {
513                         si=(PKCS7_SIGNER_INFO *)
514                                 sk_value(si_sk,i);
515                         if (si->pkey == NULL) continue;
516
517                         j=OBJ_obj2nid(si->digest_alg->algorithm);
518
519                         btmp=bio;
520                         for (;;)
521                                 {
522                                 if ((btmp=BIO_find_type(btmp,BIO_TYPE_MD)) 
523                                         == NULL)
524                                         {
525                                         PKCS7err(PKCS7_F_PKCS7_DATASIGN,PKCS7_R_UNABLE_TO_FIND_MESSAGE_DIGEST);
526                                         goto err;
527                                         }
528                                 BIO_get_md_ctx(btmp,&mdc);
529                                 if (mdc == NULL)
530                                         {
531                                         PKCS7err(PKCS7_F_PKCS7_DATASIGN,PKCS7_R_INTERNAL_ERROR);
532                                         goto err;
533                                         }
534                                 if (EVP_MD_type(EVP_MD_CTX_type(mdc)) == j)
535                                         break;
536                                 else
537                                         btmp=btmp->next_bio;
538                                 }
539                         
540                         /* We now have the EVP_MD_CTX, lets do the
541                          * signing. */
542                         memcpy(&ctx_tmp,mdc,sizeof(ctx_tmp));
543                         if (!BUF_MEM_grow(buf,EVP_PKEY_size(si->pkey)))
544                                 {
545                                 PKCS7err(PKCS7_F_PKCS7_DATASIGN,ERR_R_BIO_LIB);
546                                 goto err;
547                                 }
548
549                         sk=si->auth_attr;
550
551                         /* If there are attributes, we add the digest
552                          * attribute and only sign the attributes */
553                         if ((sk != NULL) && (sk_num(sk) != 0))
554                                 {
555                                 unsigned char md_data[EVP_MAX_MD_SIZE];
556                                 unsigned int md_len;
557                                 ASN1_OCTET_STRING *digest;
558                                 ASN1_UTCTIME *sign_time;
559                                 const EVP_MD *md_tmp;
560
561                                 /* Add signing time */
562                                 sign_time=X509_gmtime_adj(NULL,0);
563                                 PKCS7_add_signed_attribute(si,
564                                         NID_pkcs9_signingTime,
565                                         V_ASN1_UTCTIME,sign_time);
566
567                                 /* Add digest */
568                                 md_tmp=EVP_MD_CTX_type(&ctx_tmp);
569                                 EVP_DigestFinal(&ctx_tmp,md_data,&md_len);
570                                 digest=ASN1_OCTET_STRING_new();
571                                 ASN1_OCTET_STRING_set(digest,md_data,md_len);
572                                 PKCS7_add_signed_attribute(si,NID_pkcs9_messageDigest,
573                                         V_ASN1_OCTET_STRING,digest);
574
575                                 /* Now sign the mess */
576                                 EVP_SignInit(&ctx_tmp,md_tmp);
577                                 x=i2d_ASN1_SET(sk,NULL,i2d_X509_ATTRIBUTE,
578                                         V_ASN1_SET,V_ASN1_UNIVERSAL, IS_SET);
579                                 pp=(unsigned char *)Malloc(x);
580                                 p=pp;
581                                 i2d_ASN1_SET(sk,&p,i2d_X509_ATTRIBUTE,
582                                         V_ASN1_SET,V_ASN1_UNIVERSAL, IS_SET);
583                                 EVP_SignUpdate(&ctx_tmp,pp,x);
584                                 Free(pp);
585                                 pp=NULL;
586                                 }
587
588                         if (si->pkey->type == EVP_PKEY_DSA)
589                                 ctx_tmp.digest=EVP_dss1();
590
591                         if (!EVP_SignFinal(&ctx_tmp,(unsigned char *)buf->data,
592                                 (unsigned int *)&buf->length,si->pkey))
593                                 {
594                                 PKCS7err(PKCS7_F_PKCS7_DATASIGN,ERR_R_EVP_LIB);
595                                 goto err;
596                                 }
597                         if (!ASN1_STRING_set(si->enc_digest,
598                                 (unsigned char *)buf->data,buf->length))
599                                 {
600                                 PKCS7err(PKCS7_F_PKCS7_DATASIGN,ERR_R_ASN1_LIB);
601                                 goto err;
602                                 }
603                         }
604                 }
605
606         if (!p7->detached)
607                 {
608                 btmp=BIO_find_type(bio,BIO_TYPE_MEM);
609                 if (btmp == NULL)
610                         {
611                         PKCS7err(PKCS7_F_PKCS7_DATASIGN,PKCS7_R_UNABLE_TO_FIND_MEM_BIO);
612                         goto err;
613                         }
614                 BIO_get_mem_ptr(btmp,&buf_mem);
615                 ASN1_OCTET_STRING_set(os,
616                         (unsigned char *)buf_mem->data,buf_mem->length);
617                 }
618         if (pp != NULL) Free(pp);
619         pp=NULL;
620
621         ret=1;
622 err:
623         if (buf != NULL) BUF_MEM_free(buf);
624         return(ret);
625         }
626
627 int PKCS7_dataVerify(X509_STORE *cert_store, X509_STORE_CTX *ctx, BIO *bio,
628              PKCS7 *p7, PKCS7_SIGNER_INFO *si)
629         {
630 /*      PKCS7_SIGNED *s; */
631         ASN1_OCTET_STRING *os;
632         EVP_MD_CTX mdc_tmp,*mdc;
633         unsigned char *pp,*p;
634         PKCS7_ISSUER_AND_SERIAL *ias;
635         int ret=0,i;
636         int md_type;
637         STACK *sk;
638         STACK_OF(X509) *cert;
639         BIO *btmp;
640         X509 *x509;
641         EVP_PKEY *pkey;
642
643         if (PKCS7_type_is_signed(p7))
644                 {
645                 cert=p7->d.sign->cert;
646                 }
647         else if (PKCS7_type_is_signedAndEnveloped(p7))
648                 {
649                 cert=p7->d.signed_and_enveloped->cert;
650                 }
651         else
652                 {
653                 PKCS7err(PKCS7_F_PKCS7_DATAVERIFY,PKCS7_R_WRONG_PKCS7_TYPE);
654                 goto err;
655                 }
656         /* XXXXXXXXXXXXXXXXXXXXXXX */
657         ias=si->issuer_and_serial;
658
659         x509=X509_find_by_issuer_and_serial(cert,ias->issuer,ias->serial);
660
661         /* were we able to find the cert in passed to us */
662         if (x509 == NULL)
663                 {
664                 PKCS7err(PKCS7_F_PKCS7_DATAVERIFY,PKCS7_R_UNABLE_TO_FIND_CERTIFICATE);
665                 goto err;
666                 }
667
668         /* Lets verify */
669         X509_STORE_CTX_init(ctx,cert_store,x509,cert);
670         i=X509_verify_cert(ctx);
671         if (i <= 0) 
672                 {
673                 PKCS7err(PKCS7_F_PKCS7_DATAVERIFY,ERR_R_X509_LIB);
674                 goto err;
675                 }
676         X509_STORE_CTX_cleanup(ctx);
677
678         /* So we like 'x509', lets check the signature. */
679         md_type=OBJ_obj2nid(si->digest_alg->algorithm);
680
681         btmp=bio;
682         for (;;)
683                 {
684                 if ((btmp == NULL) ||
685                         ((btmp=BIO_find_type(btmp,BIO_TYPE_MD)) == NULL))
686                         {
687                         PKCS7err(PKCS7_F_PKCS7_DATAVERIFY,PKCS7_R_UNABLE_TO_FIND_MESSAGE_DIGEST);
688                         goto err;
689                         }
690                 BIO_get_md_ctx(btmp,&mdc);
691                 if (mdc == NULL)
692                         {
693                         PKCS7err(PKCS7_F_PKCS7_DATAVERIFY,PKCS7_R_INTERNAL_ERROR);
694                         goto err;
695                         }
696                 if (EVP_MD_type(EVP_MD_CTX_type(mdc)) == md_type)
697                         break;
698                 btmp=btmp->next_bio;    
699                 }
700
701         /* mdc is the digest ctx that we want, unless there are attributes,
702          * in which case the digest is the signed attributes */
703         memcpy(&mdc_tmp,mdc,sizeof(mdc_tmp));
704
705         sk=si->auth_attr;
706         if ((sk != NULL) && (sk_num(sk) != 0))
707                 {
708                 unsigned char md_dat[EVP_MAX_MD_SIZE];
709                 unsigned int md_len;
710                 ASN1_OCTET_STRING *message_digest;
711
712                 EVP_DigestFinal(&mdc_tmp,md_dat,&md_len);
713                 message_digest=PKCS7_digest_from_attributes(sk);
714                 if (!message_digest)
715                         {
716                         PKCS7err(PKCS7_F_PKCS7_DATAVERIFY,PKCS7_R_UNABLE_TO_FIND_MESSAGE_DIGEST);
717                         goto err;
718                         }
719                 if ((message_digest->length != (int)md_len) ||
720                         (memcmp(message_digest->data,md_dat,md_len)))
721                         {
722 #if 0
723 {
724 int ii;
725 for (ii=0; ii<message_digest->length; ii++)
726         printf("%02X",message_digest->data[ii]); printf(" sent\n");
727 for (ii=0; ii<md_len; ii++) printf("%02X",md_dat[ii]); printf(" calc\n");
728 }
729 #endif
730                         PKCS7err(PKCS7_F_PKCS7_DATAVERIFY,PKCS7_R_DIGEST_FAILURE);
731                         ret= -1;
732                         goto err;
733                         }
734
735                 EVP_VerifyInit(&mdc_tmp,EVP_get_digestbynid(md_type));
736                 /* Note: when forming the encoding of the attributes we
737                  * shouldn't reorder them or this will break the signature.
738                  * This is done by using the IS_SEQUENCE flag.
739                  */
740                 i=i2d_ASN1_SET(sk,NULL,i2d_X509_ATTRIBUTE,
741                         V_ASN1_SET,V_ASN1_UNIVERSAL, IS_SEQUENCE);
742                 pp=(unsigned char *)Malloc(i);
743                 p=pp;
744                 i2d_ASN1_SET(sk,&p,i2d_X509_ATTRIBUTE,
745                         V_ASN1_SET,V_ASN1_UNIVERSAL, IS_SEQUENCE);
746                 EVP_VerifyUpdate(&mdc_tmp,pp,i);
747
748                 Free(pp);
749                 }
750
751         os=si->enc_digest;
752         pkey = X509_get_pubkey(x509);
753         if(pkey->type == EVP_PKEY_DSA) mdc_tmp.digest=EVP_dss1();
754
755         i=EVP_VerifyFinal(&mdc_tmp,os->data,os->length, pkey);
756         EVP_PKEY_free(pkey);
757         if (i <= 0)
758                 {
759                 PKCS7err(PKCS7_F_PKCS7_DATAVERIFY,PKCS7_R_SIGNATURE_FAILURE);
760                 ret= -1;
761                 goto err;
762                 }
763         else
764                 ret=1;
765 err:
766         return(ret);
767         }
768
769 PKCS7_ISSUER_AND_SERIAL *PKCS7_get_issuer_and_serial(PKCS7 *p7, int idx)
770         {
771         STACK *rsk;
772         PKCS7_RECIP_INFO *ri;
773         int i;
774
775         i=OBJ_obj2nid(p7->type);
776         if (i != NID_pkcs7_signedAndEnveloped) return(NULL);
777         rsk=p7->d.signed_and_enveloped->recipientinfo;
778         ri=(PKCS7_RECIP_INFO *)sk_value(rsk,0);
779         if (sk_num(rsk) <= idx) return(NULL);
780         ri=(PKCS7_RECIP_INFO *)sk_value(rsk,idx);
781         return(ri->issuer_and_serial);
782         }
783
784 ASN1_TYPE *PKCS7_get_signed_attribute(PKCS7_SIGNER_INFO *si, int nid)
785         {
786         return(get_attribute(si->auth_attr,nid));
787         }
788
789 ASN1_TYPE *PKCS7_get_attribute(PKCS7_SIGNER_INFO *si, int nid)
790         {
791         return(get_attribute(si->unauth_attr,nid));
792         }
793
794 static ASN1_TYPE *get_attribute(STACK *sk, int nid)
795         {
796         int i;
797         X509_ATTRIBUTE *xa;
798         ASN1_OBJECT *o;
799
800         o=OBJ_nid2obj(nid);
801         if (o == NULL) return(NULL);
802         for (i=0; i<sk_num(sk); i++)
803                 {
804                 xa=(X509_ATTRIBUTE *)sk_value(sk,i);
805                 if (OBJ_cmp(xa->object,o) == 0)
806                         {
807                         if (xa->set && sk_ASN1_TYPE_num(xa->value.set))
808                                 return(sk_ASN1_TYPE_value(xa->value.set,0));
809                         else
810                                 return(NULL);
811                         }
812                 }
813         return(NULL);
814         }
815
816 ASN1_OCTET_STRING *PKCS7_digest_from_attributes(STACK *sk)
817         {
818         X509_ATTRIBUTE *attr;
819         ASN1_TYPE *astype;
820         int i;
821         if (!sk || !sk_num(sk)) return NULL;
822         /* Search the attributes for a digest */
823         for (i = 0; i < sk_num(sk); i++)
824                 {
825                 attr = (X509_ATTRIBUTE *) sk_value(sk, i);
826                 if (OBJ_obj2nid(attr->object) == NID_pkcs9_messageDigest)
827                         {
828                         if (!attr->set) return NULL;
829                         if (!attr->value.set
830                             || !sk_ASN1_TYPE_num(attr->value.set) )
831                             return NULL;
832                         astype = sk_ASN1_TYPE_value(attr->value.set, 0);
833                         return astype->value.octet_string;
834                         }
835                 }
836         return NULL;
837         }
838
839 int PKCS7_set_signed_attributes(PKCS7_SIGNER_INFO *p7si, STACK *sk)
840         {
841         int i;
842
843         if (p7si->auth_attr != NULL)
844                 sk_pop_free(p7si->auth_attr,X509_ATTRIBUTE_free);
845         p7si->auth_attr=sk_dup(sk);
846         for (i=0; i<sk_num(sk); i++)
847                 {
848                 if ((sk_value(p7si->auth_attr,i)=(char *)X509_ATTRIBUTE_dup(
849                         (X509_ATTRIBUTE *)sk_value(sk,i))) == NULL)
850                         return(0);
851                 }
852         return(1);
853         }
854
855 int PKCS7_set_attributes(PKCS7_SIGNER_INFO *p7si, STACK *sk)
856         {
857         int i;
858
859         if (p7si->unauth_attr != NULL)
860                 sk_pop_free(p7si->unauth_attr,X509_ATTRIBUTE_free);
861         p7si->unauth_attr=sk_dup(sk);
862         for (i=0; i<sk_num(sk); i++)
863                 {
864                 if ((sk_value(p7si->unauth_attr,i)=(char *)X509_ATTRIBUTE_dup(
865                         (X509_ATTRIBUTE *)sk_value(sk,i))) == NULL)
866                         return(0);
867                 }
868         return(1);
869         }
870
871 int PKCS7_add_signed_attribute(PKCS7_SIGNER_INFO *p7si, int nid, int atrtype,
872              void *value)
873         {
874         return(add_attribute(&(p7si->auth_attr),nid,atrtype,value));
875         }
876
877 int PKCS7_add_attribute(PKCS7_SIGNER_INFO *p7si, int nid, int atrtype,
878              void *value)
879         {
880         return(add_attribute(&(p7si->unauth_attr),nid,atrtype,value));
881         }
882
883 static int add_attribute(STACK **sk, int nid, int atrtype, void *value)
884         {
885         X509_ATTRIBUTE *attr=NULL;
886
887         if (*sk == NULL)
888                 {
889                 *sk = sk_new(NULL);
890 new_attrib:
891                 attr=X509_ATTRIBUTE_create(nid,atrtype,value);
892                 sk_push(*sk,(char *)attr);
893                 }
894         else
895                 {
896                 int i;
897
898                 for (i=0; i<sk_num(*sk); i++)
899                         {
900                         attr=(X509_ATTRIBUTE *)sk_value(*sk,i);
901                         if (OBJ_obj2nid(attr->object) == nid)
902                                 {
903                                 X509_ATTRIBUTE_free(attr);
904                                 attr=X509_ATTRIBUTE_create(nid,atrtype,value);
905                                 sk_value(*sk,i)=(char *)attr;
906                                 goto end;
907                                 }
908                         }
909                 goto new_attrib;
910                 }
911 end:
912         return(1);
913         }
914