Add inclusion of internal/evp_int.h to all crypto/ files that need it
[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 output
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 <assert.h>
123 #include "internal/cryptlib.h"
124 #include <openssl/buffer.h>
125 #include <openssl/bio.h>
126 #include <openssl/evp.h>
127 #include <openssl/rand.h>
128 #include "internal/evp_int.h"
129
130 static int ok_write(BIO *h, const char *buf, int num);
131 static int ok_read(BIO *h, char *buf, int size);
132 static long ok_ctrl(BIO *h, int cmd, long arg1, void *arg2);
133 static int ok_new(BIO *h);
134 static int ok_free(BIO *data);
135 static long ok_callback_ctrl(BIO *h, int cmd, bio_info_cb *fp);
136
137 static __owur int sig_out(BIO *b);
138 static __owur int sig_in(BIO *b);
139 static __owur int block_out(BIO *b);
140 static __owur int block_in(BIO *b);
141 #define OK_BLOCK_SIZE   (1024*4)
142 #define OK_BLOCK_BLOCK  4
143 #define IOBS            (OK_BLOCK_SIZE+ OK_BLOCK_BLOCK+ 3*EVP_MAX_MD_SIZE)
144 #define WELLKNOWN "The quick brown fox jumped over the lazy dog's back."
145
146 typedef struct ok_struct {
147     size_t buf_len;
148     size_t buf_off;
149     size_t buf_len_save;
150     size_t buf_off_save;
151     int cont;                   /* <= 0 when finished */
152     int finished;
153     EVP_MD_CTX *md;
154     int blockout;               /* output block is ready */
155     int sigio;                  /* must process signature */
156     unsigned char buf[IOBS];
157 } BIO_OK_CTX;
158
159 static BIO_METHOD methods_ok = {
160     BIO_TYPE_CIPHER, "reliable",
161     ok_write,
162     ok_read,
163     NULL,                       /* ok_puts, */
164     NULL,                       /* ok_gets, */
165     ok_ctrl,
166     ok_new,
167     ok_free,
168     ok_callback_ctrl,
169 };
170
171 BIO_METHOD *BIO_f_reliable(void)
172 {
173     return (&methods_ok);
174 }
175
176 static int ok_new(BIO *bi)
177 {
178     BIO_OK_CTX *ctx;
179
180     ctx = OPENSSL_zalloc(sizeof(*ctx));
181     if (ctx == NULL)
182         return (0);
183
184     ctx->cont = 1;
185     ctx->sigio = 1;
186     ctx->md = EVP_MD_CTX_create();
187     bi->init = 0;
188     bi->ptr = (char *)ctx;
189     bi->flags = 0;
190     return (1);
191 }
192
193 static int ok_free(BIO *a)
194 {
195     if (a == NULL)
196         return (0);
197     EVP_MD_CTX_destroy(((BIO_OK_CTX *)a->ptr)->md);
198     OPENSSL_clear_free(a->ptr, sizeof(BIO_OK_CTX));
199     a->ptr = NULL;
200     a->init = 0;
201     a->flags = 0;
202     return (1);
203 }
204
205 static int ok_read(BIO *b, char *out, int outl)
206 {
207     int ret = 0, i, n;
208     BIO_OK_CTX *ctx;
209
210     if (out == NULL)
211         return (0);
212     ctx = (BIO_OK_CTX *)b->ptr;
213
214     if ((ctx == NULL) || (b->next_bio == NULL) || (b->init == 0))
215         return (0);
216
217     while (outl > 0) {
218
219         /* copy clean bytes to output buffer */
220         if (ctx->blockout) {
221             i = ctx->buf_len - ctx->buf_off;
222             if (i > outl)
223                 i = outl;
224             memcpy(out, &(ctx->buf[ctx->buf_off]), i);
225             ret += i;
226             out += i;
227             outl -= i;
228             ctx->buf_off += i;
229
230             /* all clean bytes are out */
231             if (ctx->buf_len == ctx->buf_off) {
232                 ctx->buf_off = 0;
233
234                 /*
235                  * copy start of the next block into proper place
236                  */
237                 if (ctx->buf_len_save - ctx->buf_off_save > 0) {
238                     ctx->buf_len = ctx->buf_len_save - ctx->buf_off_save;
239                     memmove(ctx->buf, &(ctx->buf[ctx->buf_off_save]),
240                             ctx->buf_len);
241                 } else {
242                     ctx->buf_len = 0;
243                 }
244                 ctx->blockout = 0;
245             }
246         }
247
248         /* output buffer full -- cancel */
249         if (outl == 0)
250             break;
251
252         /* no clean bytes in buffer -- fill it */
253         n = IOBS - ctx->buf_len;
254         i = BIO_read(b->next_bio, &(ctx->buf[ctx->buf_len]), n);
255
256         if (i <= 0)
257             break;              /* nothing new */
258
259         ctx->buf_len += i;
260
261         /* no signature yet -- check if we got one */
262         if (ctx->sigio == 1) {
263             if (!sig_in(b)) {
264                 BIO_clear_retry_flags(b);
265                 return 0;
266             }
267         }
268
269         /* signature ok -- check if we got block */
270         if (ctx->sigio == 0) {
271             if (!block_in(b)) {
272                 BIO_clear_retry_flags(b);
273                 return 0;
274             }
275         }
276
277         /* invalid block -- cancel */
278         if (ctx->cont <= 0)
279             break;
280
281     }
282
283     BIO_clear_retry_flags(b);
284     BIO_copy_next_retry(b);
285     return (ret);
286 }
287
288 static int ok_write(BIO *b, const char *in, int inl)
289 {
290     int ret = 0, n, i;
291     BIO_OK_CTX *ctx;
292
293     if (inl <= 0)
294         return inl;
295
296     ctx = (BIO_OK_CTX *)b->ptr;
297     ret = inl;
298
299     if ((ctx == NULL) || (b->next_bio == NULL) || (b->init == 0))
300         return (0);
301
302     if (ctx->sigio && !sig_out(b))
303         return 0;
304
305     do {
306         BIO_clear_retry_flags(b);
307         n = ctx->buf_len - ctx->buf_off;
308         while (ctx->blockout && n > 0) {
309             i = BIO_write(b->next_bio, &(ctx->buf[ctx->buf_off]), n);
310             if (i <= 0) {
311                 BIO_copy_next_retry(b);
312                 if (!BIO_should_retry(b))
313                     ctx->cont = 0;
314                 return (i);
315             }
316             ctx->buf_off += i;
317             n -= i;
318         }
319
320         /* at this point all pending data has been written */
321         ctx->blockout = 0;
322         if (ctx->buf_len == ctx->buf_off) {
323             ctx->buf_len = OK_BLOCK_BLOCK;
324             ctx->buf_off = 0;
325         }
326
327         if ((in == NULL) || (inl <= 0))
328             return (0);
329
330         n = (inl + ctx->buf_len > OK_BLOCK_SIZE + OK_BLOCK_BLOCK) ?
331             (int)(OK_BLOCK_SIZE + OK_BLOCK_BLOCK - ctx->buf_len) : inl;
332
333         memcpy(&ctx->buf[ctx->buf_len], in, n);
334         ctx->buf_len += n;
335         inl -= n;
336         in += n;
337
338         if (ctx->buf_len >= OK_BLOCK_SIZE + OK_BLOCK_BLOCK) {
339             if (!block_out(b)) {
340                 BIO_clear_retry_flags(b);
341                 return 0;
342             }
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     case BIO_CTRL_RESET:
363         ctx->buf_len = 0;
364         ctx->buf_off = 0;
365         ctx->buf_len_save = 0;
366         ctx->buf_off_save = 0;
367         ctx->cont = 1;
368         ctx->finished = 0;
369         ctx->blockout = 0;
370         ctx->sigio = 1;
371         ret = BIO_ctrl(b->next_bio, cmd, num, ptr);
372         break;
373     case BIO_CTRL_EOF:         /* More to read */
374         if (ctx->cont <= 0)
375             ret = 1;
376         else
377             ret = BIO_ctrl(b->next_bio, cmd, num, ptr);
378         break;
379     case BIO_CTRL_PENDING:     /* More to read in buffer */
380     case BIO_CTRL_WPENDING:    /* More to read in buffer */
381         ret = ctx->blockout ? ctx->buf_len - ctx->buf_off : 0;
382         if (ret <= 0)
383             ret = BIO_ctrl(b->next_bio, cmd, num, ptr);
384         break;
385     case BIO_CTRL_FLUSH:
386         /* do a final write */
387         if (ctx->blockout == 0)
388             if (!block_out(b))
389                 return 0;
390
391         while (ctx->blockout) {
392             i = ok_write(b, NULL, 0);
393             if (i < 0) {
394                 ret = i;
395                 break;
396             }
397         }
398
399         ctx->finished = 1;
400         ctx->buf_off = ctx->buf_len = 0;
401         ctx->cont = (int)ret;
402
403         /* Finally flush the underlying BIO */
404         ret = BIO_ctrl(b->next_bio, cmd, num, ptr);
405         break;
406     case BIO_C_DO_STATE_MACHINE:
407         BIO_clear_retry_flags(b);
408         ret = BIO_ctrl(b->next_bio, cmd, num, ptr);
409         BIO_copy_next_retry(b);
410         break;
411     case BIO_CTRL_INFO:
412         ret = (long)ctx->cont;
413         break;
414     case BIO_C_SET_MD:
415         md = ptr;
416         if (!EVP_DigestInit_ex(ctx->md, md, NULL))
417             return 0;
418         b->init = 1;
419         break;
420     case BIO_C_GET_MD:
421         if (b->init) {
422             ppmd = ptr;
423             *ppmd = EVP_MD_CTX_md(ctx->md);
424         } else
425             ret = 0;
426         break;
427     default:
428         ret = BIO_ctrl(b->next_bio, cmd, num, ptr);
429         break;
430     }
431     return (ret);
432 }
433
434 static long ok_callback_ctrl(BIO *b, int cmd, bio_info_cb *fp)
435 {
436     long ret = 1;
437
438     if (b->next_bio == NULL)
439         return (0);
440     switch (cmd) {
441     default:
442         ret = BIO_callback_ctrl(b->next_bio, cmd, fp);
443         break;
444     }
445     return (ret);
446 }
447
448 static void longswap(void *_ptr, size_t len)
449 {
450     const union {
451         long one;
452         char little;
453     } is_endian = {
454         1
455     };
456
457     if (is_endian.little) {
458         size_t i;
459         unsigned char *p = _ptr, c;
460
461         for (i = 0; i < len; i += 4) {
462             c = p[0], p[0] = p[3], p[3] = c;
463             c = p[1], p[1] = p[2], p[2] = c;
464         }
465     }
466 }
467
468 static int sig_out(BIO *b)
469 {
470     BIO_OK_CTX *ctx;
471     EVP_MD_CTX *md;
472     const EVP_MD *digest;
473     int md_size;
474     void *md_data;
475
476     ctx = b->ptr;
477     md = ctx->md;
478     digest = EVP_MD_CTX_md(md);
479     md_size = EVP_MD_size(digest);
480     md_data = EVP_MD_CTX_md_data(md);
481
482     if (ctx->buf_len + 2 * md_size > OK_BLOCK_SIZE)
483         return 1;
484
485     if (!EVP_DigestInit_ex(md, digest, NULL))
486         goto berr;
487     /*
488      * FIXME: there's absolutely no guarantee this makes any sense at all,
489      * particularly now EVP_MD_CTX has been restructured.
490      */
491     if (RAND_bytes(md_data, md_size) <= 0)
492         goto berr;
493     memcpy(&(ctx->buf[ctx->buf_len]), md_data, md_size);
494     longswap(&(ctx->buf[ctx->buf_len]), md_size);
495     ctx->buf_len += md_size;
496
497     if (!EVP_DigestUpdate(md, WELLKNOWN, strlen(WELLKNOWN)))
498         goto berr;
499     if (!EVP_DigestFinal_ex(md, &(ctx->buf[ctx->buf_len]), NULL))
500         goto berr;
501     ctx->buf_len += md_size;
502     ctx->blockout = 1;
503     ctx->sigio = 0;
504     return 1;
505  berr:
506     BIO_clear_retry_flags(b);
507     return 0;
508 }
509
510 static int sig_in(BIO *b)
511 {
512     BIO_OK_CTX *ctx;
513     EVP_MD_CTX *md;
514     unsigned char tmp[EVP_MAX_MD_SIZE];
515     int ret = 0;
516     const EVP_MD *digest;
517     int md_size;
518     void *md_data;
519
520     ctx = b->ptr;
521     md = ctx->md;
522     digest = EVP_MD_CTX_md(md);
523     md_size = EVP_MD_size(digest);
524     md_data = EVP_MD_CTX_md_data(md);
525
526     if ((int)(ctx->buf_len - ctx->buf_off) < 2 * md_size)
527         return 1;
528
529     if (!EVP_DigestInit_ex(md, digest, NULL))
530         goto berr;
531     memcpy(md_data, &(ctx->buf[ctx->buf_off]), md_size);
532     longswap(md_data, md_size);
533     ctx->buf_off += md_size;
534
535     if (!EVP_DigestUpdate(md, WELLKNOWN, strlen(WELLKNOWN)))
536         goto berr;
537     if (!EVP_DigestFinal_ex(md, tmp, NULL))
538         goto berr;
539     ret = memcmp(&(ctx->buf[ctx->buf_off]), tmp, md_size) == 0;
540     ctx->buf_off += md_size;
541     if (ret == 1) {
542         ctx->sigio = 0;
543         if (ctx->buf_len != ctx->buf_off) {
544             memmove(ctx->buf, &(ctx->buf[ctx->buf_off]),
545                     ctx->buf_len - ctx->buf_off);
546         }
547         ctx->buf_len -= ctx->buf_off;
548         ctx->buf_off = 0;
549     } else {
550         ctx->cont = 0;
551     }
552     return 1;
553  berr:
554     BIO_clear_retry_flags(b);
555     return 0;
556 }
557
558 static int block_out(BIO *b)
559 {
560     BIO_OK_CTX *ctx;
561     EVP_MD_CTX *md;
562     unsigned long tl;
563     const EVP_MD *digest;
564     int md_size;
565
566     ctx = b->ptr;
567     md = ctx->md;
568     digest = EVP_MD_CTX_md(md);
569     md_size = EVP_MD_size(digest);
570
571     tl = ctx->buf_len - OK_BLOCK_BLOCK;
572     ctx->buf[0] = (unsigned char)(tl >> 24);
573     ctx->buf[1] = (unsigned char)(tl >> 16);
574     ctx->buf[2] = (unsigned char)(tl >> 8);
575     ctx->buf[3] = (unsigned char)(tl);
576     if (!EVP_DigestUpdate(md,
577                           (unsigned char *)&(ctx->buf[OK_BLOCK_BLOCK]), tl))
578         goto berr;
579     if (!EVP_DigestFinal_ex(md, &(ctx->buf[ctx->buf_len]), NULL))
580         goto berr;
581     ctx->buf_len += md_size;
582     ctx->blockout = 1;
583     return 1;
584  berr:
585     BIO_clear_retry_flags(b);
586     return 0;
587 }
588
589 static int block_in(BIO *b)
590 {
591     BIO_OK_CTX *ctx;
592     EVP_MD_CTX *md;
593     unsigned long tl = 0;
594     unsigned char tmp[EVP_MAX_MD_SIZE];
595     int md_size;
596
597     ctx = b->ptr;
598     md = ctx->md;
599     md_size = EVP_MD_size(EVP_MD_CTX_md(md));
600
601     assert(sizeof(tl) >= OK_BLOCK_BLOCK); /* always true */
602     tl = ctx->buf[0];
603     tl <<= 8;
604     tl |= ctx->buf[1];
605     tl <<= 8;
606     tl |= ctx->buf[2];
607     tl <<= 8;
608     tl |= ctx->buf[3];
609
610     if (ctx->buf_len < tl + OK_BLOCK_BLOCK + md_size)
611         return 1;
612
613     if (!EVP_DigestUpdate(md,
614                           (unsigned char *)&(ctx->buf[OK_BLOCK_BLOCK]), tl))
615         goto berr;
616     if (!EVP_DigestFinal_ex(md, tmp, NULL))
617         goto berr;
618     if (memcmp(&(ctx->buf[tl + OK_BLOCK_BLOCK]), tmp, md_size) == 0) {
619         /* there might be parts from next block lurking around ! */
620         ctx->buf_off_save = tl + OK_BLOCK_BLOCK + md_size;
621         ctx->buf_len_save = ctx->buf_len;
622         ctx->buf_off = OK_BLOCK_BLOCK;
623         ctx->buf_len = tl + OK_BLOCK_BLOCK;
624         ctx->blockout = 1;
625     } else {
626         ctx->cont = 0;
627     }
628     return 1;
629  berr:
630     BIO_clear_retry_flags(b);
631     return 0;
632 }