Because Rijndael is more known as AES, use crypto/aes instead of
[openssl.git] / crypto / evp / bio_ok.c
1 /* crypto/evp/bio_ok.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 /*
60         From: Arne Ansper <arne@cyber.ee>
61
62         Why BIO_f_reliable?
63
64         I wrote function which took BIO* as argument, read data from it
65         and processed it. Then I wanted to store the input file in 
66         encrypted form. OK I pushed BIO_f_cipher to the BIO stack
67         and everything was OK. BUT if user types wrong password 
68         BIO_f_cipher outputs only garbage and my function crashes. Yes
69         I can and I should fix my function, but BIO_f_cipher is 
70         easy way to add encryption support to many existing applications
71         and it's hard to debug and fix them all. 
72
73         So I wanted another BIO which would catch the incorrect passwords and
74         file damages which cause garbage on BIO_f_cipher's output. 
75
76         The easy way is to push the BIO_f_md and save the checksum at 
77         the end of the file. However there are several problems with this
78         approach:
79
80         1) you must somehow separate checksum from actual data. 
81         2) you need lot's of memory when reading the file, because you 
82         must read to the end of the file and verify the checksum before
83         letting the application to read the data. 
84         
85         BIO_f_reliable tries to solve both problems, so that you can 
86         read and write arbitrary long streams using only fixed amount
87         of memory.
88
89         BIO_f_reliable splits data stream into blocks. Each block is prefixed
90         with it's length and suffixed with it's digest. So you need only 
91         several Kbytes of memory to buffer single block before verifying 
92         it's digest. 
93
94         BIO_f_reliable goes further and adds several important capabilities:
95
96         1) the digest of the block is computed over the whole stream 
97         -- so nobody can rearrange the blocks or remove or replace them.
98
99         2) to detect invalid passwords right at the start BIO_f_reliable 
100         adds special prefix to the stream. In order to avoid known plain-text
101         attacks this prefix is generated as follows:
102
103                 *) digest is initialized with random seed instead of 
104                 standardized one.
105                 *) same seed is written to ouput
106                 *) well-known text is then hashed and the output 
107                 of the digest is also written to output.
108
109         reader can now read the seed from stream, hash the same string
110         and then compare the digest output.
111
112         Bad things: BIO_f_reliable knows what's going on in EVP_Digest. I 
113         initially wrote and tested this code on x86 machine and wrote the
114         digests out in machine-dependent order :( There are people using
115         this code and I cannot change this easily without making existing
116         data files unreadable.
117
118 */
119
120 #include <stdio.h>
121 #include <errno.h>
122 #include "cryptlib.h"
123 #include <openssl/buffer.h>
124 #include <openssl/bio.h>
125 #include <openssl/evp.h>
126 #include <openssl/rand.h>
127
128 static int ok_write(BIO *h, const char *buf, int num);
129 static int ok_read(BIO *h, char *buf, int size);
130 static long ok_ctrl(BIO *h, int cmd, long arg1, void *arg2);
131 static int ok_new(BIO *h);
132 static int ok_free(BIO *data);
133 static long ok_callback_ctrl(BIO *h, int cmd, bio_info_cb *fp);
134
135 static void sig_out(BIO* b);
136 static void sig_in(BIO* b);
137 static void block_out(BIO* b);
138 static void block_in(BIO* b);
139 #define OK_BLOCK_SIZE   (1024*4)
140 #define OK_BLOCK_BLOCK  4
141 #define IOBS            (OK_BLOCK_SIZE+ OK_BLOCK_BLOCK+ 3*EVP_MAX_MD_SIZE)
142 #define WELLKNOWN "The quick brown fox jumped over the lazy dog's back."
143
144 #ifndef L_ENDIAN
145 #define swapem(x) \
146         ((unsigned long int)((((unsigned long int)(x) & 0x000000ffU) << 24) | \
147                              (((unsigned long int)(x) & 0x0000ff00U) <<  8) | \
148                              (((unsigned long int)(x) & 0x00ff0000U) >>  8) | \
149                              (((unsigned long int)(x) & 0xff000000U) >> 24)))
150 #else
151 #define swapem(x) (x)
152 #endif
153
154 typedef struct ok_struct
155         {
156         int buf_len;
157         int buf_off;
158         int buf_len_save;
159         int buf_off_save;
160         int cont;               /* <= 0 when finished */
161         int finished;
162         EVP_MD_CTX md;
163         int blockout;           /* output block is ready */ 
164         int sigio;              /* must process signature */
165         unsigned char buf[IOBS];
166         } BIO_OK_CTX;
167
168 static BIO_METHOD methods_ok=
169         {
170         BIO_TYPE_CIPHER,"reliable",
171         ok_write,
172         ok_read,
173         NULL, /* ok_puts, */
174         NULL, /* ok_gets, */
175         ok_ctrl,
176         ok_new,
177         ok_free,
178         ok_callback_ctrl,
179         };
180
181 BIO_METHOD *BIO_f_reliable(void)
182         {
183         return(&methods_ok);
184         }
185
186 static int ok_new(BIO *bi)
187         {
188         BIO_OK_CTX *ctx;
189
190         ctx=(BIO_OK_CTX *)OPENSSL_malloc(sizeof(BIO_OK_CTX));
191         if (ctx == NULL) return(0);
192
193         ctx->buf_len=0;
194         ctx->buf_off=0;
195         ctx->buf_len_save=0;
196         ctx->buf_off_save=0;
197         ctx->cont=1;
198         ctx->finished=0;
199         ctx->blockout= 0;
200         ctx->sigio=1;
201
202         EVP_MD_CTX_init(&ctx->md);
203
204         bi->init=0;
205         bi->ptr=(char *)ctx;
206         bi->flags=0;
207         return(1);
208         }
209
210 static int ok_free(BIO *a)
211         {
212         if (a == NULL) return(0);
213         EVP_MD_CTX_cleanup(&((BIO_OK_CTX *)a->ptr)->md);
214         memset(a->ptr,0,sizeof(BIO_OK_CTX));
215         OPENSSL_free(a->ptr);
216         a->ptr=NULL;
217         a->init=0;
218         a->flags=0;
219         return(1);
220         }
221         
222 static int ok_read(BIO *b, char *out, int outl)
223         {
224         int ret=0,i,n;
225         BIO_OK_CTX *ctx;
226
227         if (out == NULL) return(0);
228         ctx=(BIO_OK_CTX *)b->ptr;
229
230         if ((ctx == NULL) || (b->next_bio == NULL) || (b->init == 0)) return(0);
231
232         while(outl > 0)
233                 {
234
235                 /* copy clean bytes to output buffer */
236                 if (ctx->blockout)
237                         {
238                         i=ctx->buf_len-ctx->buf_off;
239                         if (i > outl) i=outl;
240                         memcpy(out,&(ctx->buf[ctx->buf_off]),i);
241                         ret+=i;
242                         out+=i;
243                         outl-=i;
244                         ctx->buf_off+=i;
245
246                         /* all clean bytes are out */
247                         if (ctx->buf_len == ctx->buf_off)
248                                 {
249                                 ctx->buf_off=0;
250
251                                 /* copy start of the next block into proper place */
252                                 if(ctx->buf_len_save- ctx->buf_off_save > 0)
253                                         {
254                                         ctx->buf_len= ctx->buf_len_save- ctx->buf_off_save;
255                                         memmove(ctx->buf, &(ctx->buf[ctx->buf_off_save]),
256                                                         ctx->buf_len);
257                                         }
258                                 else
259                                         {
260                                         ctx->buf_len=0;
261                                         }
262                                 ctx->blockout= 0;
263                                 }
264                         }
265         
266                 /* output buffer full -- cancel */
267                 if (outl == 0) break;
268
269                 /* no clean bytes in buffer -- fill it */
270                 n=IOBS- ctx->buf_len;
271                 i=BIO_read(b->next_bio,&(ctx->buf[ctx->buf_len]),n);
272
273                 if (i <= 0) break;      /* nothing new */
274
275                 ctx->buf_len+= i;
276
277                 /* no signature yet -- check if we got one */
278                 if (ctx->sigio == 1) sig_in(b);
279
280                 /* signature ok -- check if we got block */
281                 if (ctx->sigio == 0) block_in(b);
282
283                 /* invalid block -- cancel */
284                 if (ctx->cont <= 0) break;
285
286                 }
287
288         BIO_clear_retry_flags(b);
289         BIO_copy_next_retry(b);
290         return(ret);
291         }
292
293 static int ok_write(BIO *b, const char *in, int inl)
294         {
295         int ret=0,n,i;
296         BIO_OK_CTX *ctx;
297
298         ctx=(BIO_OK_CTX *)b->ptr;
299         ret=inl;
300
301         if ((ctx == NULL) || (b->next_bio == NULL) || (b->init == 0)) return(0);
302
303         if(ctx->sigio) sig_out(b);
304
305         do{
306                 BIO_clear_retry_flags(b);
307                 n=ctx->buf_len-ctx->buf_off;
308                 while (ctx->blockout && n > 0)
309                         {
310                         i=BIO_write(b->next_bio,&(ctx->buf[ctx->buf_off]),n);
311                         if (i <= 0)
312                                 {
313                                 BIO_copy_next_retry(b);
314                                 if(!BIO_should_retry(b))
315                                         ctx->cont= 0;
316                                 return(i);
317                                 }
318                         ctx->buf_off+=i;
319                         n-=i;
320                         }
321
322                 /* at this point all pending data has been written */
323                 ctx->blockout= 0;
324                 if (ctx->buf_len == ctx->buf_off)
325                         {
326                         ctx->buf_len=OK_BLOCK_BLOCK;
327                         ctx->buf_off=0;
328                         }
329         
330                 if ((in == NULL) || (inl <= 0)) return(0);
331
332                 n= (inl+ ctx->buf_len > OK_BLOCK_SIZE+ OK_BLOCK_BLOCK) ? 
333                                 OK_BLOCK_SIZE+ OK_BLOCK_BLOCK- ctx->buf_len : inl;
334
335                 memcpy((unsigned char *)(&(ctx->buf[ctx->buf_len])),(unsigned char *)in,n);
336                 ctx->buf_len+= n;
337                 inl-=n;
338                 in+=n;
339
340                 if(ctx->buf_len >= OK_BLOCK_SIZE+ OK_BLOCK_BLOCK)
341                         {
342                         block_out(b);
343                         }
344         }while(inl > 0);
345
346         BIO_clear_retry_flags(b);
347         BIO_copy_next_retry(b);
348         return(ret);
349         }
350
351 static long ok_ctrl(BIO *b, int cmd, long num, void *ptr)
352         {
353         BIO_OK_CTX *ctx;
354         EVP_MD *md;
355         const EVP_MD **ppmd;
356         long ret=1;
357         int i;
358
359         ctx=b->ptr;
360
361         switch (cmd)
362                 {
363         case BIO_CTRL_RESET:
364                 ctx->buf_len=0;
365                 ctx->buf_off=0;
366                 ctx->buf_len_save=0;
367                 ctx->buf_off_save=0;
368                 ctx->cont=1;
369                 ctx->finished=0;
370                 ctx->blockout= 0;
371                 ctx->sigio=1;
372                 ret=BIO_ctrl(b->next_bio,cmd,num,ptr);
373                 break;
374         case BIO_CTRL_EOF:      /* More to read */
375                 if (ctx->cont <= 0)
376                         ret=1;
377                 else
378                         ret=BIO_ctrl(b->next_bio,cmd,num,ptr);
379                 break;
380         case BIO_CTRL_PENDING: /* More to read in buffer */
381         case BIO_CTRL_WPENDING: /* More to read in buffer */
382                 ret=ctx->blockout ? ctx->buf_len-ctx->buf_off : 0;
383                 if (ret <= 0)
384                         ret=BIO_ctrl(b->next_bio,cmd,num,ptr);
385                 break;
386         case BIO_CTRL_FLUSH:
387                 /* do a final write */
388                 if(ctx->blockout == 0)
389                         block_out(b);
390
391                 while (ctx->blockout)
392                         {
393                         i=ok_write(b,NULL,0);
394                         if (i < 0)
395                                 {
396                                 ret=i;
397                                 break;
398                                 }
399                         }
400
401                 ctx->finished=1;
402                 ctx->buf_off=ctx->buf_len=0;
403                 ctx->cont=(int)ret;
404                 
405                 /* Finally flush the underlying BIO */
406                 ret=BIO_ctrl(b->next_bio,cmd,num,ptr);
407                 break;
408         case BIO_C_DO_STATE_MACHINE:
409                 BIO_clear_retry_flags(b);
410                 ret=BIO_ctrl(b->next_bio,cmd,num,ptr);
411                 BIO_copy_next_retry(b);
412                 break;
413         case BIO_CTRL_INFO:
414                 ret=(long)ctx->cont;
415                 break;
416         case BIO_C_SET_MD:
417                 md=ptr;
418                 EVP_DigestInit_ex(&ctx->md, md, NULL);
419                 b->init=1;
420                 break;
421         case BIO_C_GET_MD:
422                 if (b->init)
423                         {
424                         ppmd=ptr;
425                         *ppmd=ctx->md.digest;
426                         }
427                 else
428                         ret=0;
429                 break;
430         default:
431                 ret=BIO_ctrl(b->next_bio,cmd,num,ptr);
432                 break;
433                 }
434         return(ret);
435         }
436
437 static long ok_callback_ctrl(BIO *b, int cmd, bio_info_cb *fp)
438         {
439         long ret=1;
440
441         if (b->next_bio == NULL) return(0);
442         switch (cmd)
443                 {
444         default:
445                 ret=BIO_callback_ctrl(b->next_bio,cmd,fp);
446                 break;
447                 }
448         return(ret);
449         }
450
451 static void longswap(void *_ptr, int len)
452 {
453 #ifndef L_ENDIAN
454         int i;
455         char *ptr=_ptr;
456
457         for(i= 0;i < len;i+= 4){
458                 *((unsigned long *)&(ptr[i]))= swapem(*((unsigned long *)&(ptr[i])));
459         }
460 #endif
461 }
462
463 static void sig_out(BIO* b)
464         {
465         BIO_OK_CTX *ctx;
466         EVP_MD_CTX *md;
467
468         ctx=b->ptr;
469         md=&ctx->md;
470
471         if(ctx->buf_len+ 2* md->digest->md_size > OK_BLOCK_SIZE) return;
472
473         EVP_DigestInit_ex(md, md->digest, NULL);
474         /* FIXME: there's absolutely no guarantee this makes any sense at all,
475          * particularly now EVP_MD_CTX has been restructured.
476          */
477         RAND_pseudo_bytes(md->md_data, md->digest->md_size);
478         memcpy(&(ctx->buf[ctx->buf_len]), md->md_data, md->digest->md_size);
479         longswap(&(ctx->buf[ctx->buf_len]), md->digest->md_size);
480         ctx->buf_len+= md->digest->md_size;
481
482         EVP_DigestUpdate(md, WELLKNOWN, strlen(WELLKNOWN));
483         EVP_DigestFinal_ex(md, &(ctx->buf[ctx->buf_len]), NULL);
484         ctx->buf_len+= md->digest->md_size;
485         ctx->blockout= 1;
486         ctx->sigio= 0;
487         }
488
489 static void sig_in(BIO* b)
490         {
491         BIO_OK_CTX *ctx;
492         EVP_MD_CTX *md;
493         unsigned char tmp[EVP_MAX_MD_SIZE];
494         int ret= 0;
495
496         ctx=b->ptr;
497         md=&ctx->md;
498
499         if(ctx->buf_len- ctx->buf_off < 2* md->digest->md_size) return;
500
501         EVP_DigestInit_ex(md, md->digest, NULL);
502         memcpy(md->md_data, &(ctx->buf[ctx->buf_off]), md->digest->md_size);
503         longswap(md->md_data, md->digest->md_size);
504         ctx->buf_off+= md->digest->md_size;
505
506         EVP_DigestUpdate(md, WELLKNOWN, strlen(WELLKNOWN));
507         EVP_DigestFinal_ex(md, tmp, NULL);
508         ret= memcmp(&(ctx->buf[ctx->buf_off]), tmp, md->digest->md_size) == 0;
509         ctx->buf_off+= md->digest->md_size;
510         if(ret == 1)
511                 {
512                 ctx->sigio= 0;
513                 if(ctx->buf_len != ctx->buf_off)
514                         {
515                         memmove(ctx->buf, &(ctx->buf[ctx->buf_off]), ctx->buf_len- ctx->buf_off);
516                         }
517                 ctx->buf_len-= ctx->buf_off;
518                 ctx->buf_off= 0;
519                 }
520         else
521                 {
522                 ctx->cont= 0;
523                 }
524         }
525
526 static void block_out(BIO* b)
527         {
528         BIO_OK_CTX *ctx;
529         EVP_MD_CTX *md;
530         unsigned long tl;
531
532         ctx=b->ptr;
533         md=&ctx->md;
534
535         tl= ctx->buf_len- OK_BLOCK_BLOCK;
536         tl= swapem(tl);
537         memcpy(ctx->buf, &tl, OK_BLOCK_BLOCK);
538         tl= swapem(tl);
539         EVP_DigestUpdate(md, (unsigned char*) &(ctx->buf[OK_BLOCK_BLOCK]), tl);
540         EVP_DigestFinal_ex(md, &(ctx->buf[ctx->buf_len]), NULL);
541         ctx->buf_len+= md->digest->md_size;
542         ctx->blockout= 1;
543         }
544
545 static void block_in(BIO* b)
546         {
547         BIO_OK_CTX *ctx;
548         EVP_MD_CTX *md;
549         long tl= 0;
550         unsigned char tmp[EVP_MAX_MD_SIZE];
551
552         ctx=b->ptr;
553         md=&ctx->md;
554
555         memcpy(&tl, ctx->buf, OK_BLOCK_BLOCK);
556         tl= swapem(tl);
557         if (ctx->buf_len < tl+ OK_BLOCK_BLOCK+ md->digest->md_size) return;
558  
559         EVP_DigestUpdate(md, (unsigned char*) &(ctx->buf[OK_BLOCK_BLOCK]), tl);
560         EVP_DigestFinal_ex(md, tmp, NULL);
561         if(memcmp(&(ctx->buf[tl+ OK_BLOCK_BLOCK]), tmp, md->digest->md_size) == 0)
562                 {
563                 /* there might be parts from next block lurking around ! */
564                 ctx->buf_off_save= tl+ OK_BLOCK_BLOCK+ md->digest->md_size;
565                 ctx->buf_len_save= ctx->buf_len;
566                 ctx->buf_off= OK_BLOCK_BLOCK;
567                 ctx->buf_len= tl+ OK_BLOCK_BLOCK;
568                 ctx->blockout= 1;
569                 }
570         else
571                 {
572                 ctx->cont= 0;
573                 }
574         }
575