crypto/ppccap.c: permit build with no-chacha and no-poly1305.
[openssl.git] / crypto / evp / bio_ok.c
1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.]
56  */
57
58 /*-
59         From: Arne Ansper <arne@cyber.ee>
60
61         Why BIO_f_reliable?
62
63         I wrote function which took BIO* as argument, read data from it
64         and processed it. Then I wanted to store the input file in
65         encrypted form. OK I pushed BIO_f_cipher to the BIO stack
66         and everything was OK. BUT if user types wrong password
67         BIO_f_cipher outputs only garbage and my function crashes. Yes
68         I can and I should fix my function, but BIO_f_cipher is
69         easy way to add encryption support to many existing applications
70         and it's hard to debug and fix them all.
71
72         So I wanted another BIO which would catch the incorrect passwords and
73         file damages which cause garbage on BIO_f_cipher's output.
74
75         The easy way is to push the BIO_f_md and save the checksum at
76         the end of the file. However there are several problems with this
77         approach:
78
79         1) you must somehow separate checksum from actual data.
80         2) you need lot's of memory when reading the file, because you
81         must read to the end of the file and verify the checksum before
82         letting the application to read the data.
83
84         BIO_f_reliable tries to solve both problems, so that you can
85         read and write arbitrary long streams using only fixed amount
86         of memory.
87
88         BIO_f_reliable splits data stream into blocks. Each block is prefixed
89         with it's length and suffixed with it's digest. So you need only
90         several Kbytes of memory to buffer single block before verifying
91         it's digest.
92
93         BIO_f_reliable goes further and adds several important capabilities:
94
95         1) the digest of the block is computed over the whole stream
96         -- so nobody can rearrange the blocks or remove or replace them.
97
98         2) to detect invalid passwords right at the start BIO_f_reliable
99         adds special prefix to the stream. In order to avoid known plain-text
100         attacks this prefix is generated as follows:
101
102                 *) digest is initialized with random seed instead of
103                 standardized one.
104                 *) same seed is written to output
105                 *) well-known text is then hashed and the output
106                 of the digest is also written to output.
107
108         reader can now read the seed from stream, hash the same string
109         and then compare the digest output.
110
111         Bad things: BIO_f_reliable knows what's going on in EVP_Digest. I
112         initially wrote and tested this code on x86 machine and wrote the
113         digests out in machine-dependent order :( There are people using
114         this code and I cannot change this easily without making existing
115         data files unreadable.
116
117 */
118
119 #include <stdio.h>
120 #include <errno.h>
121 #include <assert.h>
122 #include "internal/cryptlib.h"
123 #include <openssl/buffer.h>
124 #include "internal/bio.h"
125 #include <openssl/evp.h>
126 #include <openssl/rand.h>
127 #include "internal/evp_int.h"
128
129 static int ok_write(BIO *h, const char *buf, int num);
130 static int ok_read(BIO *h, char *buf, int size);
131 static long ok_ctrl(BIO *h, int cmd, long arg1, void *arg2);
132 static int ok_new(BIO *h);
133 static int ok_free(BIO *data);
134 static long ok_callback_ctrl(BIO *h, int cmd, bio_info_cb *fp);
135
136 static __owur int sig_out(BIO *b);
137 static __owur int sig_in(BIO *b);
138 static __owur int block_out(BIO *b);
139 static __owur int block_in(BIO *b);
140 #define OK_BLOCK_SIZE   (1024*4)
141 #define OK_BLOCK_BLOCK  4
142 #define IOBS            (OK_BLOCK_SIZE+ OK_BLOCK_BLOCK+ 3*EVP_MAX_MD_SIZE)
143 #define WELLKNOWN "The quick brown fox jumped over the lazy dog's back."
144
145 typedef struct ok_struct {
146     size_t buf_len;
147     size_t buf_off;
148     size_t buf_len_save;
149     size_t buf_off_save;
150     int cont;                   /* <= 0 when finished */
151     int finished;
152     EVP_MD_CTX *md;
153     int blockout;               /* output block is ready */
154     int sigio;                  /* must process signature */
155     unsigned char buf[IOBS];
156 } BIO_OK_CTX;
157
158 static const BIO_METHOD methods_ok = {
159     BIO_TYPE_CIPHER, "reliable",
160     ok_write,
161     ok_read,
162     NULL,                       /* ok_puts, */
163     NULL,                       /* ok_gets, */
164     ok_ctrl,
165     ok_new,
166     ok_free,
167     ok_callback_ctrl,
168 };
169
170 const BIO_METHOD *BIO_f_reliable(void)
171 {
172     return (&methods_ok);
173 }
174
175 static int ok_new(BIO *bi)
176 {
177     BIO_OK_CTX *ctx;
178
179     ctx = OPENSSL_zalloc(sizeof(*ctx));
180     if (ctx == NULL)
181         return 0;
182
183     ctx->cont = 1;
184     ctx->sigio = 1;
185     ctx->md = EVP_MD_CTX_new();
186     BIO_set_init(bi, 0);
187     BIO_set_data(bi, ctx);
188
189     return 1;
190 }
191
192 static int ok_free(BIO *a)
193 {
194     BIO_OK_CTX *ctx;
195
196     if (a == NULL)
197         return 0;
198
199     ctx = BIO_get_data(a);
200
201     EVP_MD_CTX_free(ctx->md);
202     OPENSSL_clear_free(ctx, sizeof(BIO_OK_CTX));
203     BIO_set_data(a, NULL);
204     BIO_set_init(a, 0);
205
206     return 1;
207 }
208
209 static int ok_read(BIO *b, char *out, int outl)
210 {
211     int ret = 0, i, n;
212     BIO_OK_CTX *ctx;
213     BIO *next;
214
215     if (out == NULL)
216         return 0;
217
218     ctx = BIO_get_data(b);
219     next = BIO_next(b);
220
221     if ((ctx == NULL) || (next == NULL) || (BIO_get_init(b) == 0))
222         return 0;
223
224     while (outl > 0) {
225
226         /* copy clean bytes to output buffer */
227         if (ctx->blockout) {
228             i = ctx->buf_len - ctx->buf_off;
229             if (i > outl)
230                 i = outl;
231             memcpy(out, &(ctx->buf[ctx->buf_off]), i);
232             ret += i;
233             out += i;
234             outl -= i;
235             ctx->buf_off += i;
236
237             /* all clean bytes are out */
238             if (ctx->buf_len == ctx->buf_off) {
239                 ctx->buf_off = 0;
240
241                 /*
242                  * copy start of the next block into proper place
243                  */
244                 if (ctx->buf_len_save - ctx->buf_off_save > 0) {
245                     ctx->buf_len = ctx->buf_len_save - ctx->buf_off_save;
246                     memmove(ctx->buf, &(ctx->buf[ctx->buf_off_save]),
247                             ctx->buf_len);
248                 } else {
249                     ctx->buf_len = 0;
250                 }
251                 ctx->blockout = 0;
252             }
253         }
254
255         /* output buffer full -- cancel */
256         if (outl == 0)
257             break;
258
259         /* no clean bytes in buffer -- fill it */
260         n = IOBS - ctx->buf_len;
261         i = BIO_read(next, &(ctx->buf[ctx->buf_len]), n);
262
263         if (i <= 0)
264             break;              /* nothing new */
265
266         ctx->buf_len += i;
267
268         /* no signature yet -- check if we got one */
269         if (ctx->sigio == 1) {
270             if (!sig_in(b)) {
271                 BIO_clear_retry_flags(b);
272                 return 0;
273             }
274         }
275
276         /* signature ok -- check if we got block */
277         if (ctx->sigio == 0) {
278             if (!block_in(b)) {
279                 BIO_clear_retry_flags(b);
280                 return 0;
281             }
282         }
283
284         /* invalid block -- cancel */
285         if (ctx->cont <= 0)
286             break;
287
288     }
289
290     BIO_clear_retry_flags(b);
291     BIO_copy_next_retry(b);
292     return ret;
293 }
294
295 static int ok_write(BIO *b, const char *in, int inl)
296 {
297     int ret = 0, n, i;
298     BIO_OK_CTX *ctx;
299     BIO *next;
300
301     if (inl <= 0)
302         return inl;
303
304     ctx = BIO_get_data(b);
305     next = BIO_next(b);
306     ret = inl;
307
308     if ((ctx == NULL) || (next == NULL) || (BIO_get_init(b) == 0))
309         return (0);
310
311     if (ctx->sigio && !sig_out(b))
312         return 0;
313
314     do {
315         BIO_clear_retry_flags(b);
316         n = ctx->buf_len - ctx->buf_off;
317         while (ctx->blockout && n > 0) {
318             i = BIO_write(next, &(ctx->buf[ctx->buf_off]), n);
319             if (i <= 0) {
320                 BIO_copy_next_retry(b);
321                 if (!BIO_should_retry(b))
322                     ctx->cont = 0;
323                 return (i);
324             }
325             ctx->buf_off += i;
326             n -= i;
327         }
328
329         /* at this point all pending data has been written */
330         ctx->blockout = 0;
331         if (ctx->buf_len == ctx->buf_off) {
332             ctx->buf_len = OK_BLOCK_BLOCK;
333             ctx->buf_off = 0;
334         }
335
336         if ((in == NULL) || (inl <= 0))
337             return (0);
338
339         n = (inl + ctx->buf_len > OK_BLOCK_SIZE + OK_BLOCK_BLOCK) ?
340             (int)(OK_BLOCK_SIZE + OK_BLOCK_BLOCK - ctx->buf_len) : inl;
341
342         memcpy(&ctx->buf[ctx->buf_len], in, n);
343         ctx->buf_len += n;
344         inl -= n;
345         in += n;
346
347         if (ctx->buf_len >= OK_BLOCK_SIZE + OK_BLOCK_BLOCK) {
348             if (!block_out(b)) {
349                 BIO_clear_retry_flags(b);
350                 return 0;
351             }
352         }
353     } while (inl > 0);
354
355     BIO_clear_retry_flags(b);
356     BIO_copy_next_retry(b);
357     return (ret);
358 }
359
360 static long ok_ctrl(BIO *b, int cmd, long num, void *ptr)
361 {
362     BIO_OK_CTX *ctx;
363     EVP_MD *md;
364     const EVP_MD **ppmd;
365     long ret = 1;
366     int i;
367     BIO *next;
368
369     ctx = BIO_get_data(b);
370     next = BIO_next(b);
371
372     switch (cmd) {
373     case BIO_CTRL_RESET:
374         ctx->buf_len = 0;
375         ctx->buf_off = 0;
376         ctx->buf_len_save = 0;
377         ctx->buf_off_save = 0;
378         ctx->cont = 1;
379         ctx->finished = 0;
380         ctx->blockout = 0;
381         ctx->sigio = 1;
382         ret = BIO_ctrl(next, cmd, num, ptr);
383         break;
384     case BIO_CTRL_EOF:         /* More to read */
385         if (ctx->cont <= 0)
386             ret = 1;
387         else
388             ret = BIO_ctrl(next, cmd, num, ptr);
389         break;
390     case BIO_CTRL_PENDING:     /* More to read in buffer */
391     case BIO_CTRL_WPENDING:    /* More to read in buffer */
392         ret = ctx->blockout ? ctx->buf_len - ctx->buf_off : 0;
393         if (ret <= 0)
394             ret = BIO_ctrl(next, cmd, num, ptr);
395         break;
396     case BIO_CTRL_FLUSH:
397         /* do a final write */
398         if (ctx->blockout == 0)
399             if (!block_out(b))
400                 return 0;
401
402         while (ctx->blockout) {
403             i = ok_write(b, NULL, 0);
404             if (i < 0) {
405                 ret = i;
406                 break;
407             }
408         }
409
410         ctx->finished = 1;
411         ctx->buf_off = ctx->buf_len = 0;
412         ctx->cont = (int)ret;
413
414         /* Finally flush the underlying BIO */
415         ret = BIO_ctrl(next, cmd, num, ptr);
416         break;
417     case BIO_C_DO_STATE_MACHINE:
418         BIO_clear_retry_flags(b);
419         ret = BIO_ctrl(next, cmd, num, ptr);
420         BIO_copy_next_retry(b);
421         break;
422     case BIO_CTRL_INFO:
423         ret = (long)ctx->cont;
424         break;
425     case BIO_C_SET_MD:
426         md = ptr;
427         if (!EVP_DigestInit_ex(ctx->md, md, NULL))
428             return 0;
429         BIO_set_init(b, 1);
430         break;
431     case BIO_C_GET_MD:
432         if (BIO_get_init(b)) {
433             ppmd = ptr;
434             *ppmd = EVP_MD_CTX_md(ctx->md);
435         } else
436             ret = 0;
437         break;
438     default:
439         ret = BIO_ctrl(next, cmd, num, ptr);
440         break;
441     }
442     return ret;
443 }
444
445 static long ok_callback_ctrl(BIO *b, int cmd, bio_info_cb *fp)
446 {
447     long ret = 1;
448     BIO *next;
449     
450     next = BIO_next(b);
451
452     if (next == NULL)
453         return 0;
454
455     switch (cmd) {
456     default:
457         ret = BIO_callback_ctrl(next, cmd, fp);
458         break;
459     }
460
461     return ret;
462 }
463
464 static void longswap(void *_ptr, size_t len)
465 {
466     const union {
467         long one;
468         char little;
469     } is_endian = {
470         1
471     };
472
473     if (is_endian.little) {
474         size_t i;
475         unsigned char *p = _ptr, c;
476
477         for (i = 0; i < len; i += 4) {
478             c = p[0], p[0] = p[3], p[3] = c;
479             c = p[1], p[1] = p[2], p[2] = c;
480         }
481     }
482 }
483
484 static int sig_out(BIO *b)
485 {
486     BIO_OK_CTX *ctx;
487     EVP_MD_CTX *md;
488     const EVP_MD *digest;
489     int md_size;
490     void *md_data;
491
492     ctx = BIO_get_data(b);
493     md = ctx->md;
494     digest = EVP_MD_CTX_md(md);
495     md_size = EVP_MD_size(digest);
496     md_data = EVP_MD_CTX_md_data(md);
497
498     if (ctx->buf_len + 2 * md_size > OK_BLOCK_SIZE)
499         return 1;
500
501     if (!EVP_DigestInit_ex(md, digest, NULL))
502         goto berr;
503     /*
504      * FIXME: there's absolutely no guarantee this makes any sense at all,
505      * particularly now EVP_MD_CTX has been restructured.
506      */
507     if (RAND_bytes(md_data, md_size) <= 0)
508         goto berr;
509     memcpy(&(ctx->buf[ctx->buf_len]), md_data, md_size);
510     longswap(&(ctx->buf[ctx->buf_len]), md_size);
511     ctx->buf_len += md_size;
512
513     if (!EVP_DigestUpdate(md, WELLKNOWN, strlen(WELLKNOWN)))
514         goto berr;
515     if (!EVP_DigestFinal_ex(md, &(ctx->buf[ctx->buf_len]), NULL))
516         goto berr;
517     ctx->buf_len += md_size;
518     ctx->blockout = 1;
519     ctx->sigio = 0;
520     return 1;
521  berr:
522     BIO_clear_retry_flags(b);
523     return 0;
524 }
525
526 static int sig_in(BIO *b)
527 {
528     BIO_OK_CTX *ctx;
529     EVP_MD_CTX *md;
530     unsigned char tmp[EVP_MAX_MD_SIZE];
531     int ret = 0;
532     const EVP_MD *digest;
533     int md_size;
534     void *md_data;
535
536     ctx = BIO_get_data(b);
537     md = ctx->md;
538     digest = EVP_MD_CTX_md(md);
539     md_size = EVP_MD_size(digest);
540     md_data = EVP_MD_CTX_md_data(md);
541
542     if ((int)(ctx->buf_len - ctx->buf_off) < 2 * md_size)
543         return 1;
544
545     if (!EVP_DigestInit_ex(md, digest, NULL))
546         goto berr;
547     memcpy(md_data, &(ctx->buf[ctx->buf_off]), md_size);
548     longswap(md_data, md_size);
549     ctx->buf_off += md_size;
550
551     if (!EVP_DigestUpdate(md, WELLKNOWN, strlen(WELLKNOWN)))
552         goto berr;
553     if (!EVP_DigestFinal_ex(md, tmp, NULL))
554         goto berr;
555     ret = memcmp(&(ctx->buf[ctx->buf_off]), tmp, md_size) == 0;
556     ctx->buf_off += md_size;
557     if (ret == 1) {
558         ctx->sigio = 0;
559         if (ctx->buf_len != ctx->buf_off) {
560             memmove(ctx->buf, &(ctx->buf[ctx->buf_off]),
561                     ctx->buf_len - ctx->buf_off);
562         }
563         ctx->buf_len -= ctx->buf_off;
564         ctx->buf_off = 0;
565     } else {
566         ctx->cont = 0;
567     }
568     return 1;
569  berr:
570     BIO_clear_retry_flags(b);
571     return 0;
572 }
573
574 static int block_out(BIO *b)
575 {
576     BIO_OK_CTX *ctx;
577     EVP_MD_CTX *md;
578     unsigned long tl;
579     const EVP_MD *digest;
580     int md_size;
581
582     ctx = BIO_get_data(b);
583     md = ctx->md;
584     digest = EVP_MD_CTX_md(md);
585     md_size = EVP_MD_size(digest);
586
587     tl = ctx->buf_len - OK_BLOCK_BLOCK;
588     ctx->buf[0] = (unsigned char)(tl >> 24);
589     ctx->buf[1] = (unsigned char)(tl >> 16);
590     ctx->buf[2] = (unsigned char)(tl >> 8);
591     ctx->buf[3] = (unsigned char)(tl);
592     if (!EVP_DigestUpdate(md,
593                           (unsigned char *)&(ctx->buf[OK_BLOCK_BLOCK]), tl))
594         goto berr;
595     if (!EVP_DigestFinal_ex(md, &(ctx->buf[ctx->buf_len]), NULL))
596         goto berr;
597     ctx->buf_len += md_size;
598     ctx->blockout = 1;
599     return 1;
600  berr:
601     BIO_clear_retry_flags(b);
602     return 0;
603 }
604
605 static int block_in(BIO *b)
606 {
607     BIO_OK_CTX *ctx;
608     EVP_MD_CTX *md;
609     unsigned long tl = 0;
610     unsigned char tmp[EVP_MAX_MD_SIZE];
611     int md_size;
612
613     ctx = BIO_get_data(b);
614     md = ctx->md;
615     md_size = EVP_MD_size(EVP_MD_CTX_md(md));
616
617     assert(sizeof(tl) >= OK_BLOCK_BLOCK); /* always true */
618     tl = ctx->buf[0];
619     tl <<= 8;
620     tl |= ctx->buf[1];
621     tl <<= 8;
622     tl |= ctx->buf[2];
623     tl <<= 8;
624     tl |= ctx->buf[3];
625
626     if (ctx->buf_len < tl + OK_BLOCK_BLOCK + md_size)
627         return 1;
628
629     if (!EVP_DigestUpdate(md,
630                           (unsigned char *)&(ctx->buf[OK_BLOCK_BLOCK]), tl))
631         goto berr;
632     if (!EVP_DigestFinal_ex(md, tmp, NULL))
633         goto berr;
634     if (memcmp(&(ctx->buf[tl + OK_BLOCK_BLOCK]), tmp, md_size) == 0) {
635         /* there might be parts from next block lurking around ! */
636         ctx->buf_off_save = tl + OK_BLOCK_BLOCK + md_size;
637         ctx->buf_len_save = ctx->buf_len;
638         ctx->buf_off = OK_BLOCK_BLOCK;
639         ctx->buf_len = tl + OK_BLOCK_BLOCK;
640         ctx->blockout = 1;
641     } else {
642         ctx->cont = 0;
643     }
644     return 1;
645  berr:
646     BIO_clear_retry_flags(b);
647     return 0;
648 }