Allow memory bios to be read only and change PKCS#7 routines to use them.
[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_OF(X509_ATTRIBUTE) **sk, int nid, int atrtype,
66                          void *value);
67 static ASN1_TYPE *get_attribute(STACK_OF(X509_ATTRIBUTE) *sk, int nid);
68
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_OF(X509_ALGOR) *md_sk=NULL;
77         STACK_OF(PKCS7_RECIP_INFO) *rsk=NULL;
78         X509_ALGOR *xalg=NULL;
79         PKCS7_RECIP_INFO *ri=NULL;
80         EVP_PKEY *pkey;
81
82         i=OBJ_obj2nid(p7->type);
83         p7->state=PKCS7_S_HEADER;
84
85         switch (i)
86                 {
87         case NID_pkcs7_signed:
88                 md_sk=p7->d.sign->md_algs;
89                 break;
90         case NID_pkcs7_signedAndEnveloped:
91                 rsk=p7->d.signed_and_enveloped->recipientinfo;
92                 md_sk=p7->d.signed_and_enveloped->md_algs;
93                 xalg=p7->d.signed_and_enveloped->enc_data->algorithm;
94                 evp_cipher=p7->d.signed_and_enveloped->enc_data->cipher;
95                 if (evp_cipher == NULL)
96                         {
97                         PKCS7err(PKCS7_F_PKCS7_DATAINIT,
98                                                 PKCS7_R_CIPHER_NOT_INITIALIZED);
99                         goto err;
100                         }
101                 break;
102         case NID_pkcs7_enveloped:
103                 rsk=p7->d.enveloped->recipientinfo;
104                 xalg=p7->d.enveloped->enc_data->algorithm;
105                 evp_cipher=p7->d.enveloped->enc_data->cipher;
106                 if (evp_cipher == NULL)
107                         {
108                         PKCS7err(PKCS7_F_PKCS7_DATAINIT,
109                                                 PKCS7_R_CIPHER_NOT_INITIALIZED);
110                         goto err;
111                         }
112                 break;
113         default:
114                 PKCS7err(PKCS7_F_PKCS7_DATAINIT,PKCS7_R_UNSUPPORTED_CONTENT_TYPE);
115                 goto err;
116                 }
117
118         if (md_sk != NULL)
119                 {
120                 for (i=0; i<sk_X509_ALGOR_num(md_sk); i++)
121                         {
122                         xa=sk_X509_ALGOR_value(md_sk,i);
123                         if ((btmp=BIO_new(BIO_f_md())) == NULL)
124                                 {
125                                 PKCS7err(PKCS7_F_PKCS7_DATAINIT,ERR_R_BIO_LIB);
126                                 goto err;
127                                 }
128
129                         j=OBJ_obj2nid(xa->algorithm);
130                         evp_md=EVP_get_digestbyname(OBJ_nid2sn(j));
131                         if (evp_md == NULL)
132                                 {
133                                 PKCS7err(PKCS7_F_PKCS7_DATAINIT,PKCS7_R_UNKNOWN_DIGEST_TYPE);
134                                 goto err;
135                                 }
136
137                         BIO_set_md(btmp,evp_md);
138                         if (out == NULL)
139                                 out=btmp;
140                         else
141                                 BIO_push(out,btmp);
142                         btmp=NULL;
143                         }
144                 }
145
146         if (evp_cipher != NULL)
147                 {
148                 unsigned char key[EVP_MAX_KEY_LENGTH];
149                 unsigned char iv[EVP_MAX_IV_LENGTH];
150                 int keylen,ivlen;
151                 int jj,max;
152                 unsigned char *tmp;
153                 EVP_CIPHER_CTX *ctx;
154
155                 if ((btmp=BIO_new(BIO_f_cipher())) == NULL)
156                         {
157                         PKCS7err(PKCS7_F_PKCS7_DATAINIT,ERR_R_BIO_LIB);
158                         goto err;
159                         }
160                 BIO_get_cipher_ctx(btmp, &ctx);
161                 keylen=EVP_CIPHER_key_length(evp_cipher);
162                 ivlen=EVP_CIPHER_iv_length(evp_cipher);
163                 RAND_bytes(key,keylen);
164                 xalg->algorithm = OBJ_nid2obj(EVP_CIPHER_type(evp_cipher));
165                 if (ivlen > 0) RAND_bytes(iv,ivlen);
166                 EVP_CipherInit(ctx, evp_cipher, key, iv, 1);
167
168                 if (ivlen > 0) {
169                         if (xalg->parameter == NULL) 
170                                                 xalg->parameter=ASN1_TYPE_new();
171                         if(EVP_CIPHER_param_to_asn1(ctx, xalg->parameter) < 0)
172                                                                        goto err;
173                 }
174
175                 /* Lets do the pub key stuff :-) */
176                 max=0;
177                 for (i=0; i<sk_PKCS7_RECIP_INFO_num(rsk); i++)
178                         {
179                         ri=sk_PKCS7_RECIP_INFO_value(rsk,i);
180                         if (ri->cert == NULL)
181                                 {
182                                 PKCS7err(PKCS7_F_PKCS7_DATAINIT,PKCS7_R_MISSING_CERIPEND_INFO);
183                                 goto err;
184                                 }
185                         pkey=X509_get_pubkey(ri->cert);
186                         jj=EVP_PKEY_size(pkey);
187                         EVP_PKEY_free(pkey);
188                         if (max < jj) max=jj;
189                         }
190                 if ((tmp=(unsigned char *)Malloc(max)) == NULL)
191                         {
192                         PKCS7err(PKCS7_F_PKCS7_DATAINIT,ERR_R_MALLOC_FAILURE);
193                         goto err;
194                         }
195                 for (i=0; i<sk_PKCS7_RECIP_INFO_num(rsk); i++)
196                         {
197                         ri=sk_PKCS7_RECIP_INFO_value(rsk,i);
198                         pkey=X509_get_pubkey(ri->cert);
199                         jj=EVP_PKEY_encrypt(tmp,key,keylen,pkey);
200                         EVP_PKEY_free(pkey);
201                         if (jj <= 0)
202                                 {
203                                 PKCS7err(PKCS7_F_PKCS7_DATAINIT,ERR_R_EVP_LIB);
204                                 Free(tmp);
205                                 goto err;
206                                 }
207                         ASN1_OCTET_STRING_set(ri->enc_key,tmp,jj);
208                         }
209                 Free(tmp);
210                 memset(key, 0, keylen);
211
212                 if (out == NULL)
213                         out=btmp;
214                 else
215                         BIO_push(out,btmp);
216                 btmp=NULL;
217                 }
218
219         if (bio == NULL) {
220                 if (p7->detached)
221                         bio=BIO_new(BIO_s_null());
222                 else {
223                         if (PKCS7_type_is_signed(p7) &&
224                                 PKCS7_type_is_data(p7->d.sign->contents)) {
225                                 ASN1_OCTET_STRING *os;
226                                 os=p7->d.sign->contents->d.data;
227                                 if (os->length > 0) bio = 
228                                         BIO_new_mem_buf(os->data, os->length);
229                         } else {
230                                 bio=BIO_new(BIO_s_mem());
231                                 BIO_set_mem_eof_return(bio,0);
232                         }
233                 }
234         }
235         BIO_push(out,bio);
236         bio=NULL;
237         if (0)
238                 {
239 err:
240                 if (out != NULL)
241                         BIO_free_all(out);
242                 if (btmp != NULL)
243                         BIO_free_all(btmp);
244                 out=NULL;
245                 }
246         return(out);
247         }
248
249 /* int */
250 BIO *PKCS7_dataDecode(PKCS7 *p7, EVP_PKEY *pkey, BIO *in_bio, X509 *pcert)
251         {
252         int i,j;
253         BIO *out=NULL,*btmp=NULL,*etmp=NULL,*bio=NULL;
254         char *tmp=NULL;
255         X509_ALGOR *xa;
256         ASN1_OCTET_STRING *data_body=NULL;
257         const EVP_MD *evp_md;
258         const EVP_CIPHER *evp_cipher=NULL;
259         EVP_CIPHER_CTX *evp_ctx=NULL;
260         X509_ALGOR *enc_alg=NULL;
261         STACK_OF(X509_ALGOR) *md_sk=NULL;
262         STACK_OF(PKCS7_RECIP_INFO) *rsk=NULL;
263         X509_ALGOR *xalg=NULL;
264         PKCS7_RECIP_INFO *ri=NULL;
265 /*      EVP_PKEY *pkey; */
266 #if 0
267         X509_STORE_CTX s_ctx;
268 #endif
269
270         i=OBJ_obj2nid(p7->type);
271         p7->state=PKCS7_S_HEADER;
272
273         switch (i)
274                 {
275         case NID_pkcs7_signed:
276                 data_body=p7->d.sign->contents->d.data;
277                 md_sk=p7->d.sign->md_algs;
278                 break;
279         case NID_pkcs7_signedAndEnveloped:
280                 rsk=p7->d.signed_and_enveloped->recipientinfo;
281                 md_sk=p7->d.signed_and_enveloped->md_algs;
282                 data_body=p7->d.signed_and_enveloped->enc_data->enc_data;
283                 enc_alg=p7->d.signed_and_enveloped->enc_data->algorithm;
284                 evp_cipher=EVP_get_cipherbyname(OBJ_nid2sn(OBJ_obj2nid(enc_alg->algorithm)));
285                 if (evp_cipher == NULL)
286                         {
287                         PKCS7err(PKCS7_F_PKCS7_DATADECODE,PKCS7_R_UNSUPPORTED_CIPHER_TYPE);
288                         goto err;
289                         }
290                 xalg=p7->d.signed_and_enveloped->enc_data->algorithm;
291                 break;
292         case NID_pkcs7_enveloped:
293                 rsk=p7->d.enveloped->recipientinfo;
294                 enc_alg=p7->d.enveloped->enc_data->algorithm;
295                 data_body=p7->d.enveloped->enc_data->enc_data;
296                 evp_cipher=EVP_get_cipherbyname(OBJ_nid2sn(OBJ_obj2nid(enc_alg->algorithm)));
297                 if (evp_cipher == NULL)
298                         {
299                         PKCS7err(PKCS7_F_PKCS7_DATADECODE,PKCS7_R_UNSUPPORTED_CIPHER_TYPE);
300                         goto err;
301                         }
302                 xalg=p7->d.enveloped->enc_data->algorithm;
303                 break;
304         default:
305                 PKCS7err(PKCS7_F_PKCS7_DATADECODE,PKCS7_R_UNSUPPORTED_CONTENT_TYPE);
306                 goto err;
307                 }
308
309         /* We will be checking the signature */
310         if (md_sk != NULL)
311                 {
312                 for (i=0; i<sk_X509_ALGOR_num(md_sk); i++)
313                         {
314                         xa=sk_X509_ALGOR_value(md_sk,i);
315                         if ((btmp=BIO_new(BIO_f_md())) == NULL)
316                                 {
317                                 PKCS7err(PKCS7_F_PKCS7_DATADECODE,ERR_R_BIO_LIB);
318                                 goto err;
319                                 }
320
321                         j=OBJ_obj2nid(xa->algorithm);
322                         evp_md=EVP_get_digestbyname(OBJ_nid2sn(j));
323                         if (evp_md == NULL)
324                                 {
325                                 PKCS7err(PKCS7_F_PKCS7_DATADECODE,PKCS7_R_UNKNOWN_DIGEST_TYPE);
326                                 goto err;
327                                 }
328
329                         BIO_set_md(btmp,evp_md);
330                         if (out == NULL)
331                                 out=btmp;
332                         else
333                                 BIO_push(out,btmp);
334                         btmp=NULL;
335                         }
336                 }
337
338         if (evp_cipher != NULL)
339                 {
340 #if 0
341                 unsigned char key[EVP_MAX_KEY_LENGTH];
342                 unsigned char iv[EVP_MAX_IV_LENGTH];
343                 unsigned char *p;
344                 int keylen,ivlen;
345                 int max;
346                 X509_OBJECT ret;
347 #endif
348                 int jj;
349
350                 if ((etmp=BIO_new(BIO_f_cipher())) == NULL)
351                         {
352                         PKCS7err(PKCS7_F_PKCS7_DATADECODE,ERR_R_BIO_LIB);
353                         goto err;
354                         }
355
356                 /* It was encrypted, we need to decrypt the secret key
357                  * with the private key */
358
359                 /* Find the recipientInfo which matches the passed certificate
360                  * (if any)
361                  */
362
363                 for (i=0; i<sk_PKCS7_RECIP_INFO_num(rsk); i++) {
364                         ri=sk_PKCS7_RECIP_INFO_value(rsk,i);
365                         if(!X509_NAME_cmp(ri->issuer_and_serial->issuer,
366                                         pcert->cert_info->issuer) &&
367                              !ASN1_INTEGER_cmp(pcert->cert_info->serialNumber,
368                                         ri->issuer_and_serial->serial)) break;
369                         ri=NULL;
370                 }
371                 if (ri == NULL) {
372                         PKCS7err(PKCS7_F_PKCS7_DATADECODE,
373                                  PKCS7_R_NO_RECIPIENT_MATCHES_CERTIFICATE);
374                         return(NULL);
375                 }
376
377                 jj=EVP_PKEY_size(pkey);
378                 tmp=Malloc(jj+10);
379                 if (tmp == NULL)
380                         {
381                         PKCS7err(PKCS7_F_PKCS7_DATADECODE,ERR_R_MALLOC_FAILURE);
382                         goto err;
383                         }
384
385                 jj=EVP_PKEY_decrypt((unsigned char *)tmp,
386                         ASN1_STRING_data(ri->enc_key),
387                         ASN1_STRING_length(ri->enc_key),
388                         pkey);
389                 if (jj <= 0)
390                         {
391                         PKCS7err(PKCS7_F_PKCS7_DATADECODE,ERR_R_EVP_LIB);
392                         goto err;
393                         }
394
395                 evp_ctx=NULL;
396                 BIO_get_cipher_ctx(etmp,&evp_ctx);
397                 EVP_CipherInit(evp_ctx,evp_cipher,NULL,NULL,0);
398                 if (EVP_CIPHER_asn1_to_param(evp_ctx,enc_alg->parameter) < 0)
399                         return(NULL);
400
401                 if (jj != EVP_CIPHER_CTX_key_length(evp_ctx))
402                         {
403                         PKCS7err(PKCS7_F_PKCS7_DATADECODE,
404                                         PKCS7_R_DECRYPTED_KEY_IS_WRONG_LENGTH);
405                         goto err;
406                         }
407                 EVP_CipherInit(evp_ctx,NULL,(unsigned char *)tmp,NULL,0);
408
409                 memset(tmp,0,jj);
410
411                 if (out == NULL)
412                         out=etmp;
413                 else
414                         BIO_push(out,etmp);
415                 etmp=NULL;
416                 }
417
418 #if 1
419         if (p7->detached || (in_bio != NULL))
420                 {
421                 bio=in_bio;
422                 }
423         else 
424                 {
425 #if 0
426                 bio=BIO_new(BIO_s_mem());
427                 /* We need to set this so that when we have read all
428                  * the data, the encrypt BIO, if present, will read
429                  * EOF and encode the last few bytes */
430                 BIO_set_mem_eof_return(bio,0);
431
432                 if (data_body->length > 0)
433                         BIO_write(bio,(char *)data_body->data,data_body->length);
434 #else
435                 if (data_body->length > 0)
436                       bio = BIO_new_mem_buf(data_body->data,data_body->length);
437                 else {
438                         bio=BIO_new(BIO_s_mem());
439                         BIO_set_mem_eof_return(bio,0);
440                 }
441 #endif
442                 }
443         BIO_push(out,bio);
444         bio=NULL;
445 #endif
446         if (0)
447                 {
448 err:
449                 if (out != NULL) BIO_free_all(out);
450                 if (btmp != NULL) BIO_free_all(btmp);
451                 if (etmp != NULL) BIO_free_all(etmp);
452                 if (bio != NULL) BIO_free_all(bio);
453                 out=NULL;
454                 }
455         if (tmp != NULL)
456                 Free(tmp);
457         return(out);
458         }
459
460 int PKCS7_dataFinal(PKCS7 *p7, BIO *bio)
461         {
462         int ret=0;
463         int i,j;
464         BIO *btmp;
465         BUF_MEM *buf_mem=NULL;
466         BUF_MEM *buf=NULL;
467         PKCS7_SIGNER_INFO *si;
468         EVP_MD_CTX *mdc,ctx_tmp;
469         STACK_OF(X509_ATTRIBUTE) *sk;
470         STACK_OF(PKCS7_SIGNER_INFO) *si_sk=NULL;
471         unsigned char *p,*pp=NULL;
472         int x;
473         ASN1_OCTET_STRING *os=NULL;
474
475         i=OBJ_obj2nid(p7->type);
476         p7->state=PKCS7_S_HEADER;
477
478         switch (i)
479                 {
480         case NID_pkcs7_signedAndEnveloped:
481                 /* XXXXXXXXXXXXXXXX */
482                 si_sk=p7->d.signed_and_enveloped->signer_info;
483                 os=ASN1_OCTET_STRING_new();
484                 p7->d.signed_and_enveloped->enc_data->enc_data=os;
485                 break;
486         case NID_pkcs7_enveloped:
487                 /* XXXXXXXXXXXXXXXX */
488                 os=ASN1_OCTET_STRING_new();
489                 p7->d.enveloped->enc_data->enc_data=os;
490                 break;
491         case NID_pkcs7_signed:
492                 si_sk=p7->d.sign->signer_info;
493                 os=p7->d.sign->contents->d.data;
494                 /* If detached data then the content is excluded */
495                 if(p7->detached) {
496                         ASN1_OCTET_STRING_free(os);
497                         p7->d.sign->contents->d.data = NULL;
498                 }
499                 break;
500                 }
501
502         if (si_sk != NULL)
503                 {
504                 if ((buf=BUF_MEM_new()) == NULL)
505                         {
506                         PKCS7err(PKCS7_F_PKCS7_DATASIGN,ERR_R_BIO_LIB);
507                         goto err;
508                         }
509                 for (i=0; i<sk_PKCS7_SIGNER_INFO_num(si_sk); i++)
510                         {
511                         si=sk_PKCS7_SIGNER_INFO_value(si_sk,i);
512                         if (si->pkey == NULL) continue;
513
514                         j=OBJ_obj2nid(si->digest_alg->algorithm);
515
516                         btmp=bio;
517                         for (;;)
518                                 {
519                                 if ((btmp=BIO_find_type(btmp,BIO_TYPE_MD)) 
520                                         == NULL)
521                                         {
522                                         PKCS7err(PKCS7_F_PKCS7_DATASIGN,PKCS7_R_UNABLE_TO_FIND_MESSAGE_DIGEST);
523                                         goto err;
524                                         }
525                                 BIO_get_md_ctx(btmp,&mdc);
526                                 if (mdc == NULL)
527                                         {
528                                         PKCS7err(PKCS7_F_PKCS7_DATASIGN,PKCS7_R_INTERNAL_ERROR);
529                                         goto err;
530                                         }
531                                 if (EVP_MD_type(EVP_MD_CTX_type(mdc)) == j)
532                                         break;
533                                 else
534                                         btmp=btmp->next_bio;
535                                 }
536                         
537                         /* We now have the EVP_MD_CTX, lets do the
538                          * signing. */
539                         memcpy(&ctx_tmp,mdc,sizeof(ctx_tmp));
540                         if (!BUF_MEM_grow(buf,EVP_PKEY_size(si->pkey)))
541                                 {
542                                 PKCS7err(PKCS7_F_PKCS7_DATASIGN,ERR_R_BIO_LIB);
543                                 goto err;
544                                 }
545
546                         sk=si->auth_attr;
547
548                         /* If there are attributes, we add the digest
549                          * attribute and only sign the attributes */
550                         if ((sk != NULL) && (sk_X509_ATTRIBUTE_num(sk) != 0))
551                                 {
552                                 unsigned char md_data[EVP_MAX_MD_SIZE];
553                                 unsigned int md_len;
554                                 ASN1_OCTET_STRING *digest;
555                                 ASN1_UTCTIME *sign_time;
556                                 const EVP_MD *md_tmp;
557
558                                 /* Add signing time */
559                                 sign_time=X509_gmtime_adj(NULL,0);
560                                 PKCS7_add_signed_attribute(si,
561                                         NID_pkcs9_signingTime,
562                                         V_ASN1_UTCTIME,sign_time);
563
564                                 /* Add digest */
565                                 md_tmp=EVP_MD_CTX_type(&ctx_tmp);
566                                 EVP_DigestFinal(&ctx_tmp,md_data,&md_len);
567                                 digest=ASN1_OCTET_STRING_new();
568                                 ASN1_OCTET_STRING_set(digest,md_data,md_len);
569                                 PKCS7_add_signed_attribute(si,
570                                         NID_pkcs9_messageDigest,
571                                         V_ASN1_OCTET_STRING,digest);
572
573                                 /* Now sign the mess */
574                                 EVP_SignInit(&ctx_tmp,md_tmp);
575                                 x=i2d_ASN1_SET_OF_X509_ATTRIBUTE(sk,NULL,
576                                            i2d_X509_ATTRIBUTE,
577                                            V_ASN1_SET,V_ASN1_UNIVERSAL,IS_SET);
578                                 pp=(unsigned char *)Malloc(x);
579                                 p=pp;
580                                 i2d_ASN1_SET_OF_X509_ATTRIBUTE(sk,&p,
581                                            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                 /* Mark the BIO read only then we can use its copy of the data
616                  * instead of making an extra copy.
617                  */
618                 BIO_set_flags(btmp, BIO_FLAGS_MEM_RDONLY);
619                 BIO_set_mem_eof_return(btmp, 0);
620                 os->data = (unsigned char *)buf_mem->data;
621                 os->length = buf_mem->length;
622 #if 0
623                 ASN1_OCTET_STRING_set(os,
624                         (unsigned char *)buf_mem->data,buf_mem->length);
625 #endif
626                 }
627         if (pp != NULL) Free(pp);
628         pp=NULL;
629
630         ret=1;
631 err:
632         if (buf != NULL) BUF_MEM_free(buf);
633         return(ret);
634         }
635
636 int PKCS7_dataVerify(X509_STORE *cert_store, X509_STORE_CTX *ctx, BIO *bio,
637              PKCS7 *p7, PKCS7_SIGNER_INFO *si)
638         {
639         PKCS7_ISSUER_AND_SERIAL *ias;
640         int ret=0,i;
641         STACK_OF(X509) *cert;
642         X509 *x509;
643
644         if (PKCS7_type_is_signed(p7))
645                 {
646                 cert=p7->d.sign->cert;
647                 }
648         else if (PKCS7_type_is_signedAndEnveloped(p7))
649                 {
650                 cert=p7->d.signed_and_enveloped->cert;
651                 }
652         else
653                 {
654                 PKCS7err(PKCS7_F_PKCS7_DATAVERIFY,PKCS7_R_WRONG_PKCS7_TYPE);
655                 goto err;
656                 }
657         /* XXXXXXXXXXXXXXXXXXXXXXX */
658         ias=si->issuer_and_serial;
659
660         x509=X509_find_by_issuer_and_serial(cert,ias->issuer,ias->serial);
661
662         /* were we able to find the cert in passed to us */
663         if (x509 == NULL)
664                 {
665                 PKCS7err(PKCS7_F_PKCS7_DATAVERIFY,PKCS7_R_UNABLE_TO_FIND_CERTIFICATE);
666                 goto err;
667                 }
668
669         /* Lets verify */
670         X509_STORE_CTX_init(ctx,cert_store,x509,cert);
671         i=X509_verify_cert(ctx);
672         if (i <= 0) 
673                 {
674                 PKCS7err(PKCS7_F_PKCS7_DATAVERIFY,ERR_R_X509_LIB);
675                 goto err;
676                 }
677         X509_STORE_CTX_cleanup(ctx);
678
679         return PKCS7_signatureVerify(bio, p7, si, x509);
680         err:
681         return ret;
682         }
683
684 int PKCS7_signatureVerify(BIO *bio, PKCS7 *p7, PKCS7_SIGNER_INFO *si,
685                                                                 X509 *x509)
686         {
687         ASN1_OCTET_STRING *os;
688         EVP_MD_CTX mdc_tmp,*mdc;
689         unsigned char *pp,*p;
690         int ret=0,i;
691         int md_type;
692         STACK_OF(X509_ATTRIBUTE) *sk;
693         BIO *btmp;
694         EVP_PKEY *pkey;
695
696         if (!PKCS7_type_is_signed(p7) && 
697                                 !PKCS7_type_is_signedAndEnveloped(p7)) {
698                 PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY,
699                                                 PKCS7_R_WRONG_PKCS7_TYPE);
700                 goto err;
701         }
702
703         md_type=OBJ_obj2nid(si->digest_alg->algorithm);
704
705         btmp=bio;
706         for (;;)
707                 {
708                 if ((btmp == NULL) ||
709                         ((btmp=BIO_find_type(btmp,BIO_TYPE_MD)) == NULL))
710                         {
711                         PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY,
712                                         PKCS7_R_UNABLE_TO_FIND_MESSAGE_DIGEST);
713                         goto err;
714                         }
715                 BIO_get_md_ctx(btmp,&mdc);
716                 if (mdc == NULL)
717                         {
718                         PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY,
719                                                         PKCS7_R_INTERNAL_ERROR);
720                         goto err;
721                         }
722                 if (EVP_MD_type(EVP_MD_CTX_type(mdc)) == md_type)
723                         break;
724                 btmp=btmp->next_bio;    
725                 }
726
727         /* mdc is the digest ctx that we want, unless there are attributes,
728          * in which case the digest is the signed attributes */
729         memcpy(&mdc_tmp,mdc,sizeof(mdc_tmp));
730
731         sk=si->auth_attr;
732         if ((sk != NULL) && (sk_X509_ATTRIBUTE_num(sk) != 0))
733                 {
734                 unsigned char md_dat[EVP_MAX_MD_SIZE];
735                 unsigned int md_len;
736                 ASN1_OCTET_STRING *message_digest;
737
738                 EVP_DigestFinal(&mdc_tmp,md_dat,&md_len);
739                 message_digest=PKCS7_digest_from_attributes(sk);
740                 if (!message_digest)
741                         {
742                         PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY,
743                                         PKCS7_R_UNABLE_TO_FIND_MESSAGE_DIGEST);
744                         goto err;
745                         }
746                 if ((message_digest->length != (int)md_len) ||
747                         (memcmp(message_digest->data,md_dat,md_len)))
748                         {
749 #if 0
750 {
751 int ii;
752 for (ii=0; ii<message_digest->length; ii++)
753         printf("%02X",message_digest->data[ii]); printf(" sent\n");
754 for (ii=0; ii<md_len; ii++) printf("%02X",md_dat[ii]); printf(" calc\n");
755 }
756 #endif
757                         PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY,
758                                                         PKCS7_R_DIGEST_FAILURE);
759                         ret= -1;
760                         goto err;
761                         }
762
763                 EVP_VerifyInit(&mdc_tmp,EVP_get_digestbynid(md_type));
764                 /* Note: when forming the encoding of the attributes we
765                  * shouldn't reorder them or this will break the signature.
766                  * This is done by using the IS_SEQUENCE flag.
767                  */
768                 i=i2d_ASN1_SET_OF_X509_ATTRIBUTE(sk,NULL,i2d_X509_ATTRIBUTE,
769                         V_ASN1_SET,V_ASN1_UNIVERSAL, IS_SEQUENCE);
770                 pp=Malloc(i);
771                 p=pp;
772                 i2d_ASN1_SET_OF_X509_ATTRIBUTE(sk,&p,i2d_X509_ATTRIBUTE,
773                         V_ASN1_SET,V_ASN1_UNIVERSAL, IS_SEQUENCE);
774                 EVP_VerifyUpdate(&mdc_tmp,pp,i);
775
776                 Free(pp);
777                 }
778
779         os=si->enc_digest;
780         pkey = X509_get_pubkey(x509);
781         if(pkey->type == EVP_PKEY_DSA) mdc_tmp.digest=EVP_dss1();
782
783         i=EVP_VerifyFinal(&mdc_tmp,os->data,os->length, pkey);
784         EVP_PKEY_free(pkey);
785         if (i <= 0)
786                 {
787                 PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY,
788                                                 PKCS7_R_SIGNATURE_FAILURE);
789                 ret= -1;
790                 goto err;
791                 }
792         else
793                 ret=1;
794 err:
795         return(ret);
796         }
797
798 PKCS7_ISSUER_AND_SERIAL *PKCS7_get_issuer_and_serial(PKCS7 *p7, int idx)
799         {
800         STACK_OF(PKCS7_RECIP_INFO) *rsk;
801         PKCS7_RECIP_INFO *ri;
802         int i;
803
804         i=OBJ_obj2nid(p7->type);
805         if (i != NID_pkcs7_signedAndEnveloped) return(NULL);
806         rsk=p7->d.signed_and_enveloped->recipientinfo;
807         ri=sk_PKCS7_RECIP_INFO_value(rsk,0);
808         if (sk_PKCS7_RECIP_INFO_num(rsk) <= idx) return(NULL);
809         ri=sk_PKCS7_RECIP_INFO_value(rsk,idx);
810         return(ri->issuer_and_serial);
811         }
812
813 ASN1_TYPE *PKCS7_get_signed_attribute(PKCS7_SIGNER_INFO *si, int nid)
814         {
815         return(get_attribute(si->auth_attr,nid));
816         }
817
818 ASN1_TYPE *PKCS7_get_attribute(PKCS7_SIGNER_INFO *si, int nid)
819         {
820         return(get_attribute(si->unauth_attr,nid));
821         }
822
823 static ASN1_TYPE *get_attribute(STACK_OF(X509_ATTRIBUTE) *sk, int nid)
824         {
825         int i;
826         X509_ATTRIBUTE *xa;
827         ASN1_OBJECT *o;
828
829         o=OBJ_nid2obj(nid);
830         if (!o || !sk) return(NULL);
831         for (i=0; i<sk_X509_ATTRIBUTE_num(sk); i++)
832                 {
833                 xa=sk_X509_ATTRIBUTE_value(sk,i);
834                 if (OBJ_cmp(xa->object,o) == 0)
835                         {
836                         if (xa->set && sk_ASN1_TYPE_num(xa->value.set))
837                                 return(sk_ASN1_TYPE_value(xa->value.set,0));
838                         else
839                                 return(NULL);
840                         }
841                 }
842         return(NULL);
843         }
844
845 ASN1_OCTET_STRING *PKCS7_digest_from_attributes(STACK_OF(X509_ATTRIBUTE) *sk)
846 {
847         ASN1_TYPE *astype;
848         if(!(astype = get_attribute(sk, NID_pkcs9_messageDigest))) return NULL;
849         return astype->value.octet_string;
850 }
851
852 int PKCS7_set_signed_attributes(PKCS7_SIGNER_INFO *p7si,
853                                 STACK_OF(X509_ATTRIBUTE) *sk)
854         {
855         int i;
856
857         if (p7si->auth_attr != NULL)
858                 sk_X509_ATTRIBUTE_pop_free(p7si->auth_attr,X509_ATTRIBUTE_free);
859         p7si->auth_attr=sk_X509_ATTRIBUTE_dup(sk);
860         for (i=0; i<sk_X509_ATTRIBUTE_num(sk); i++)
861                 {
862                 if ((sk_X509_ATTRIBUTE_set(p7si->auth_attr,i,
863                         X509_ATTRIBUTE_dup(sk_X509_ATTRIBUTE_value(sk,i))))
864                     == NULL)
865                         return(0);
866                 }
867         return(1);
868         }
869
870 int PKCS7_set_attributes(PKCS7_SIGNER_INFO *p7si, STACK_OF(X509_ATTRIBUTE) *sk)
871         {
872         int i;
873
874         if (p7si->unauth_attr != NULL)
875                 sk_X509_ATTRIBUTE_pop_free(p7si->unauth_attr,
876                                            X509_ATTRIBUTE_free);
877         p7si->unauth_attr=sk_X509_ATTRIBUTE_dup(sk);
878         for (i=0; i<sk_X509_ATTRIBUTE_num(sk); i++)
879                 {
880                 if ((sk_X509_ATTRIBUTE_set(p7si->unauth_attr,i,
881                         X509_ATTRIBUTE_dup(sk_X509_ATTRIBUTE_value(sk,i))))
882                     == NULL)
883                         return(0);
884                 }
885         return(1);
886         }
887
888 int PKCS7_add_signed_attribute(PKCS7_SIGNER_INFO *p7si, int nid, int atrtype,
889              void *value)
890         {
891         return(add_attribute(&(p7si->auth_attr),nid,atrtype,value));
892         }
893
894 int PKCS7_add_attribute(PKCS7_SIGNER_INFO *p7si, int nid, int atrtype,
895              void *value)
896         {
897         return(add_attribute(&(p7si->unauth_attr),nid,atrtype,value));
898         }
899
900 static int add_attribute(STACK_OF(X509_ATTRIBUTE) **sk, int nid, int atrtype,
901                          void *value)
902         {
903         X509_ATTRIBUTE *attr=NULL;
904
905         if (*sk == NULL)
906                 {
907                 *sk = sk_X509_ATTRIBUTE_new(NULL);
908 new_attrib:
909                 attr=X509_ATTRIBUTE_create(nid,atrtype,value);
910                 sk_X509_ATTRIBUTE_push(*sk,attr);
911                 }
912         else
913                 {
914                 int i;
915
916                 for (i=0; i<sk_X509_ATTRIBUTE_num(*sk); i++)
917                         {
918                         attr=sk_X509_ATTRIBUTE_value(*sk,i);
919                         if (OBJ_obj2nid(attr->object) == nid)
920                                 {
921                                 X509_ATTRIBUTE_free(attr);
922                                 attr=X509_ATTRIBUTE_create(nid,atrtype,value);
923                                 sk_X509_ATTRIBUTE_set(*sk,i,attr);
924                                 goto end;
925                                 }
926                         }
927                 goto new_attrib;
928                 }
929 end:
930         return(1);
931         }
932