6d2f250b7b07979ac4395cde46990bb8896333ab
[openssl.git] / ssl / record / rec_layer_s3.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  * Copyright (c) 1998-2002 The OpenSSL Project.  All rights reserved.
59  *
60  * Redistribution and use in source and binary forms, with or without
61  * modification, are permitted provided that the following conditions
62  * are met:
63  *
64  * 1. Redistributions of source code must retain the above copyright
65  *    notice, this list of conditions and the following disclaimer.
66  *
67  * 2. Redistributions in binary form must reproduce the above copyright
68  *    notice, this list of conditions and the following disclaimer in
69  *    the documentation and/or other materials provided with the
70  *    distribution.
71  *
72  * 3. All advertising materials mentioning features or use of this
73  *    software must display the following acknowledgment:
74  *    "This product includes software developed by the OpenSSL Project
75  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
76  *
77  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78  *    endorse or promote products derived from this software without
79  *    prior written permission. For written permission, please contact
80  *    openssl-core@openssl.org.
81  *
82  * 5. Products derived from this software may not be called "OpenSSL"
83  *    nor may "OpenSSL" appear in their names without prior written
84  *    permission of the OpenSSL Project.
85  *
86  * 6. Redistributions of any form whatsoever must retain the following
87  *    acknowledgment:
88  *    "This product includes software developed by the OpenSSL Project
89  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90  *
91  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
95  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102  * OF THE POSSIBILITY OF SUCH DAMAGE.
103  * ====================================================================
104  *
105  * This product includes cryptographic software written by Eric Young
106  * (eay@cryptsoft.com).  This product includes software written by Tim
107  * Hudson (tjh@cryptsoft.com).
108  *
109  */
110
111 #include <stdio.h>
112 #include <limits.h>
113 #include <errno.h>
114 #define USE_SOCKETS
115 #include "../ssl_locl.h"
116 #include <openssl/evp.h>
117 #include <openssl/buffer.h>
118 #include <openssl/rand.h>
119 #include "record_locl.h"
120
121 #ifndef  EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
122 # define EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK 0
123 #endif
124
125 #if     defined(OPENSSL_SMALL_FOOTPRINT) || \
126         !(      defined(AES_ASM) &&     ( \
127                 defined(__x86_64)       || defined(__x86_64__)  || \
128                 defined(_M_AMD64)       || defined(_M_X64)      || \
129                 defined(__INTEL__)      ) \
130         )
131 # undef EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
132 # define EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK 0
133 #endif
134
135 void RECORD_LAYER_init(RECORD_LAYER *rl, SSL *s)
136 {
137     rl->s = s;
138     SSL3_RECORD_clear(rl->rrec, SSL_MAX_PIPELINES);
139 }
140
141 void RECORD_LAYER_clear(RECORD_LAYER *rl)
142 {
143     unsigned int pipes;
144
145     rl->rstate = SSL_ST_READ_HEADER;
146
147     /* Do I need to clear read_ahead? As far as I can tell read_ahead did not
148      * previously get reset by SSL_clear...so I'll keep it that way..but is
149      * that right?
150      */
151
152     rl->packet = NULL;
153     rl->packet_length = 0;
154     rl->wnum = 0;
155     memset(rl->alert_fragment, 0, sizeof(rl->alert_fragment));
156     rl->alert_fragment_len = 0;
157     memset(rl->handshake_fragment, 0, sizeof(rl->handshake_fragment));
158     rl->handshake_fragment_len = 0;
159     rl->wpend_tot = 0;
160     rl->wpend_type = 0;
161     rl->wpend_ret = 0;
162     rl->wpend_buf = NULL;
163
164     SSL3_BUFFER_clear(&rl->rbuf);
165     for(pipes = 0; pipes < rl->numwpipes; pipes++)
166         SSL3_BUFFER_clear(&rl->wbuf[pipes]);
167     rl->numwpipes = 0;
168     SSL3_RECORD_clear(rl->rrec, SSL_MAX_PIPELINES);
169
170     RECORD_LAYER_reset_read_sequence(rl);
171     RECORD_LAYER_reset_write_sequence(rl);
172     
173     if (rl->d)
174         DTLS_RECORD_LAYER_clear(rl);
175 }
176
177 void RECORD_LAYER_release(RECORD_LAYER *rl)
178 {
179     if (SSL3_BUFFER_is_initialised(&rl->rbuf))
180         ssl3_release_read_buffer(rl->s);
181     if (rl->numwpipes > 0)
182         ssl3_release_write_buffer(rl->s);
183     SSL3_RECORD_release(rl->rrec, SSL_MAX_PIPELINES);
184 }
185
186 int RECORD_LAYER_read_pending(const RECORD_LAYER *rl)
187 {
188     return SSL3_BUFFER_get_left(&rl->rbuf) != 0;
189 }
190
191 int RECORD_LAYER_write_pending(const RECORD_LAYER *rl)
192 {
193     return (rl->numwpipes > 0)
194             && SSL3_BUFFER_get_left(&rl->wbuf[rl->numwpipes-1]) != 0;
195 }
196
197 int RECORD_LAYER_set_data(RECORD_LAYER *rl, const unsigned char *buf, int len)
198 {
199     rl->packet_length = len;
200     if (len != 0) {
201         rl->rstate = SSL_ST_READ_HEADER;
202         if (!SSL3_BUFFER_is_initialised(&rl->rbuf))
203             if (!ssl3_setup_read_buffer(rl->s))
204                 return 0;
205     }
206
207     rl->packet = SSL3_BUFFER_get_buf(&rl->rbuf);
208     SSL3_BUFFER_set_data(&rl->rbuf, buf, len);
209
210     return 1;
211 }
212
213 void RECORD_LAYER_reset_read_sequence(RECORD_LAYER *rl)
214 {
215     memset(rl->read_sequence, 0, sizeof(rl->read_sequence));
216 }
217
218 void RECORD_LAYER_reset_write_sequence(RECORD_LAYER *rl)
219 {
220     memset(rl->write_sequence, 0, sizeof(rl->write_sequence));
221 }
222
223 int ssl3_pending(const SSL *s)
224 {
225     unsigned int i;
226     int num = 0;
227
228     if (s->rlayer.rstate == SSL_ST_READ_BODY)
229         return 0;
230
231     for (i = 0; i < RECORD_LAYER_get_numrpipes(&s->rlayer); i++) {
232         if (SSL3_RECORD_get_type(&s->rlayer.rrec[i])
233                 != SSL3_RT_APPLICATION_DATA)
234             return 0;
235         num += SSL3_RECORD_get_length(&s->rlayer.rrec[i]);
236     }
237
238     return num;
239 }
240
241 void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len)
242 {
243     ctx->default_read_buf_len = len;
244 }
245
246 void SSL_set_default_read_buffer_len(SSL *s, size_t len)
247 {
248     SSL3_BUFFER_set_default_len(RECORD_LAYER_get_rbuf(&s->rlayer), len);
249 }
250
251 const char *SSL_rstate_string_long(const SSL *s)
252 {
253     const char *str;
254
255     switch (s->rlayer.rstate) {
256     case SSL_ST_READ_HEADER:
257         str = "read header";
258         break;
259     case SSL_ST_READ_BODY:
260         str = "read body";
261         break;
262     case SSL_ST_READ_DONE:
263         str = "read done";
264         break;
265     default:
266         str = "unknown";
267         break;
268     }
269     return (str);
270 }
271
272 const char *SSL_rstate_string(const SSL *s)
273 {
274     const char *str;
275
276     switch (s->rlayer.rstate) {
277     case SSL_ST_READ_HEADER:
278         str = "RH";
279         break;
280     case SSL_ST_READ_BODY:
281         str = "RB";
282         break;
283     case SSL_ST_READ_DONE:
284         str = "RD";
285         break;
286     default:
287         str = "unknown";
288         break;
289     }
290     return (str);
291 }
292
293 int ssl3_read_n(SSL *s, int n, int max, int extend, int clearold)
294 {
295     /*
296      * If extend == 0, obtain new n-byte packet; if extend == 1, increase
297      * packet by another n bytes. The packet will be in the sub-array of
298      * s->s3->rbuf.buf specified by s->packet and s->packet_length. (If
299      * s->rlayer.read_ahead is set, 'max' bytes may be stored in rbuf [plus
300      * s->packet_length bytes if extend == 1].)
301      * if clearold == 1, move the packet to the start of the buffer; if
302      * clearold == 0 then leave any old packets where they were
303      */
304     int i, len, left;
305     size_t align = 0;
306     unsigned char *pkt;
307     SSL3_BUFFER *rb;
308
309     if (n <= 0)
310         return n;
311
312     rb = &s->rlayer.rbuf;
313     if (rb->buf == NULL)
314         if (!ssl3_setup_read_buffer(s))
315             return -1;
316
317     left = rb->left;
318 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
319     align = (size_t)rb->buf + SSL3_RT_HEADER_LENGTH;
320     align = (0-align) & (SSL3_ALIGN_PAYLOAD - 1);
321 #endif
322
323     if (!extend) {
324         /* start with empty packet ... */
325         if (left == 0)
326             rb->offset = align;
327         else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH) {
328             /*
329              * check if next packet length is large enough to justify payload
330              * alignment...
331              */
332             pkt = rb->buf + rb->offset;
333             if (pkt[0] == SSL3_RT_APPLICATION_DATA
334                 && (pkt[3] << 8 | pkt[4]) >= 128) {
335                 /*
336                  * Note that even if packet is corrupted and its length field
337                  * is insane, we can only be led to wrong decision about
338                  * whether memmove will occur or not. Header values has no
339                  * effect on memmove arguments and therefore no buffer
340                  * overrun can be triggered.
341                  */
342                 memmove(rb->buf + align, pkt, left);
343                 rb->offset = align;
344             }
345         }
346         s->rlayer.packet = rb->buf + rb->offset;
347         s->rlayer.packet_length = 0;
348         /* ... now we can act as if 'extend' was set */
349     }
350
351     /*
352      * For DTLS/UDP reads should not span multiple packets because the read
353      * operation returns the whole packet at once (as long as it fits into
354      * the buffer).
355      */
356     if (SSL_IS_DTLS(s)) {
357         if (left == 0 && extend)
358             return 0;
359         if (left > 0 && n > left)
360             n = left;
361     }
362
363     /* if there is enough in the buffer from a previous read, take some */
364     if (left >= n) {
365         s->rlayer.packet_length += n;
366         rb->left = left - n;
367         rb->offset += n;
368         return (n);
369     }
370
371     /* else we need to read more data */
372
373     len = s->rlayer.packet_length;
374     pkt = rb->buf + align;
375     /*
376      * Move any available bytes to front of buffer: 'len' bytes already
377      * pointed to by 'packet', 'left' extra ones at the end
378      */
379     if (s->rlayer.packet != pkt && clearold == 1) {     /* len > 0 */
380         memmove(pkt, s->rlayer.packet, len + left);
381         s->rlayer.packet = pkt;
382         rb->offset = len + align;
383     }
384
385     if (n > (int)(rb->len - rb->offset)) { /* does not happen */
386         SSLerr(SSL_F_SSL3_READ_N, ERR_R_INTERNAL_ERROR);
387         return -1;
388     }
389
390     /* We always act like read_ahead is set for DTLS */
391     if (!s->rlayer.read_ahead && !SSL_IS_DTLS(s))
392         /* ignore max parameter */
393         max = n;
394     else {
395         if (max < n)
396             max = n;
397         if (max > (int)(rb->len - rb->offset))
398             max = rb->len - rb->offset;
399     }
400
401     while (left < n) {
402         /*
403          * Now we have len+left bytes at the front of s->s3->rbuf.buf and
404          * need to read in more until we have len+n (up to len+max if
405          * possible)
406          */
407
408         clear_sys_error();
409         if (s->rbio != NULL) {
410             s->rwstate = SSL_READING;
411             i = BIO_read(s->rbio, pkt + len + left, max - left);
412         } else {
413             SSLerr(SSL_F_SSL3_READ_N, SSL_R_READ_BIO_NOT_SET);
414             i = -1;
415         }
416
417         if (i <= 0) {
418             rb->left = left;
419             if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s))
420                 if (len + left == 0)
421                     ssl3_release_read_buffer(s);
422             return (i);
423         }
424         left += i;
425         /*
426          * reads should *never* span multiple packets for DTLS because the
427          * underlying transport protocol is message oriented as opposed to
428          * byte oriented as in the TLS case.
429          */
430         if (SSL_IS_DTLS(s)) {
431             if (n > left)
432                 n = left;       /* makes the while condition false */
433         }
434     }
435
436     /* done reading, now the book-keeping */
437     rb->offset += n;
438     rb->left = left - n;
439     s->rlayer.packet_length += n;
440     s->rwstate = SSL_NOTHING;
441     return (n);
442 }
443
444
445 /*
446  * Call this to write data in records of type 'type' It will return <= 0 if
447  * not all data has been sent or non-blocking IO.
448  */
449 int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
450 {
451     const unsigned char *buf = buf_;
452     int tot;
453     unsigned int n, split_send_fragment, maxpipes;
454 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
455     unsigned int max_send_fragment, nw;
456     unsigned int u_len = (unsigned int)len;
457 #endif
458     SSL3_BUFFER *wb = &s->rlayer.wbuf[0];
459     int i;
460
461     if (len < 0) {
462         SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_SSL_NEGATIVE_LENGTH);
463         return -1;
464     }
465
466     s->rwstate = SSL_NOTHING;
467     tot = s->rlayer.wnum;
468     /*
469      * ensure that if we end up with a smaller value of data to write out
470      * than the the original len from a write which didn't complete for
471      * non-blocking I/O and also somehow ended up avoiding the check for
472      * this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be
473      * possible to end up with (len-tot) as a large number that will then
474      * promptly send beyond the end of the users buffer ... so we trap and
475      * report the error in a way the user will notice
476      */
477     if ((unsigned int)len < s->rlayer.wnum) {
478         SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_BAD_LENGTH);
479         return -1;
480     }
481
482
483     s->rlayer.wnum = 0;
484
485     if (SSL_in_init(s) && !ossl_statem_get_in_handshake(s)) {
486         i = s->handshake_func(s);
487         if (i < 0)
488             return (i);
489         if (i == 0) {
490             SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
491             return -1;
492         }
493     }
494
495     /*
496      * first check if there is a SSL3_BUFFER still being written out.  This
497      * will happen with non blocking IO
498      */
499     if (wb->left != 0) {
500         i = ssl3_write_pending(s, type, &buf[tot], s->rlayer.wpend_tot);
501         if (i <= 0) {
502             /* XXX should we ssl3_release_write_buffer if i<0? */
503             s->rlayer.wnum = tot;
504             return i;
505         }
506         tot += i;               /* this might be last fragment */
507     }
508 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
509     /*
510      * Depending on platform multi-block can deliver several *times*
511      * better performance. Downside is that it has to allocate
512      * jumbo buffer to accomodate up to 8 records, but the
513      * compromise is considered worthy.
514      */
515     if (type == SSL3_RT_APPLICATION_DATA &&
516         u_len >= 4 * (max_send_fragment = s->max_send_fragment) &&
517         s->compress == NULL && s->msg_callback == NULL &&
518         !SSL_USE_ETM(s) && SSL_USE_EXPLICIT_IV(s) &&
519         EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_write_ctx)) &
520         EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK) {
521         unsigned char aad[13];
522         EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param;
523         int packlen;
524
525         /* minimize address aliasing conflicts */
526         if ((max_send_fragment & 0xfff) == 0)
527             max_send_fragment -= 512;
528
529         if (tot == 0 || wb->buf == NULL) { /* allocate jumbo buffer */
530             ssl3_release_write_buffer(s);
531
532             packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
533                                           EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE,
534                                           max_send_fragment, NULL);
535
536             if (u_len >= 8 * max_send_fragment)
537                 packlen *= 8;
538             else
539                 packlen *= 4;
540
541             wb->buf = OPENSSL_malloc(packlen);
542             if (wb->buf == NULL) {
543                 SSLerr(SSL_F_SSL3_WRITE_BYTES, ERR_R_MALLOC_FAILURE);
544                 return -1;
545             }
546             wb->len = packlen;
547         } else if (tot == len) { /* done? */
548             OPENSSL_free(wb->buf); /* free jumbo buffer */
549             wb->buf = NULL;
550             return tot;
551         }
552
553         n = (len - tot);
554         for (;;) {
555             if (n < 4 * max_send_fragment) {
556                 OPENSSL_free(wb->buf); /* free jumbo buffer */
557                 wb->buf = NULL;
558                 break;
559             }
560
561             if (s->s3->alert_dispatch) {
562                 i = s->method->ssl_dispatch_alert(s);
563                 if (i <= 0) {
564                     s->rlayer.wnum = tot;
565                     return i;
566                 }
567             }
568
569             if (n >= 8 * max_send_fragment)
570                 nw = max_send_fragment * (mb_param.interleave = 8);
571             else
572                 nw = max_send_fragment * (mb_param.interleave = 4);
573
574             memcpy(aad, s->rlayer.write_sequence, 8);
575             aad[8] = type;
576             aad[9] = (unsigned char)(s->version >> 8);
577             aad[10] = (unsigned char)(s->version);
578             aad[11] = 0;
579             aad[12] = 0;
580             mb_param.out = NULL;
581             mb_param.inp = aad;
582             mb_param.len = nw;
583
584             packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
585                                           EVP_CTRL_TLS1_1_MULTIBLOCK_AAD,
586                                           sizeof(mb_param), &mb_param);
587
588             if (packlen <= 0 || packlen > (int)wb->len) { /* never happens */
589                 OPENSSL_free(wb->buf); /* free jumbo buffer */
590                 wb->buf = NULL;
591                 break;
592             }
593
594             mb_param.out = wb->buf;
595             mb_param.inp = &buf[tot];
596             mb_param.len = nw;
597
598             if (EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
599                                     EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT,
600                                     sizeof(mb_param), &mb_param) <= 0)
601                 return -1;
602
603             s->rlayer.write_sequence[7] += mb_param.interleave;
604             if (s->rlayer.write_sequence[7] < mb_param.interleave) {
605                 int j = 6;
606                 while (j >= 0 && (++s->rlayer.write_sequence[j--]) == 0) ;
607             }
608
609             wb->offset = 0;
610             wb->left = packlen;
611
612             s->rlayer.wpend_tot = nw;
613             s->rlayer.wpend_buf = &buf[tot];
614             s->rlayer.wpend_type = type;
615             s->rlayer.wpend_ret = nw;
616
617             i = ssl3_write_pending(s, type, &buf[tot], nw);
618             if (i <= 0) {
619                 if (i < 0 && (!s->wbio || !BIO_should_retry(s->wbio))) {
620                     OPENSSL_free(wb->buf);
621                     wb->buf = NULL;
622                 }
623                 s->rlayer.wnum = tot;
624                 return i;
625             }
626             if (i == (int)n) {
627                 OPENSSL_free(wb->buf); /* free jumbo buffer */
628                 wb->buf = NULL;
629                 return tot + i;
630             }
631             n -= i;
632             tot += i;
633         }
634     } else
635 #endif
636     if (tot == len) {           /* done? */
637         if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s))
638             ssl3_release_write_buffer(s);
639
640         return tot;
641     }
642
643     n = (len - tot);
644
645     split_send_fragment = s->split_send_fragment;
646     /*
647      * If max_pipelines is 0 then this means "undefined" and we default to
648      * 1 pipeline. Similaraly if the cipher does not support pipelined
649      * processing then we also only use 1 pipeline, or if we're not using
650      * explicit IVs
651      */
652     maxpipes = s->max_pipelines;
653     if (maxpipes > SSL_MAX_PIPELINES) {
654         /*
655          * We should have prevented this when we set max_pipelines so we
656          * shouldn't get here
657         */
658         SSLerr(SSL_F_SSL3_WRITE_BYTES, ERR_R_INTERNAL_ERROR);
659         return -1;
660     }
661     if (maxpipes == 0
662             || s->enc_write_ctx == NULL
663             || !(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_write_ctx))
664                  & EVP_CIPH_FLAG_PIPELINE)
665             || !SSL_USE_EXPLICIT_IV(s))
666         maxpipes = 1;
667     if (s->max_send_fragment == 0 || split_send_fragment > s->max_send_fragment
668             || split_send_fragment == 0) {
669         /*
670          * We should have prevented this when we set the split and max send
671          * fragments so we shouldn't get here
672         */
673         SSLerr(SSL_F_SSL3_WRITE_BYTES, ERR_R_INTERNAL_ERROR);
674         return -1;
675     }
676
677     for (;;) {
678         unsigned int pipelens[SSL_MAX_PIPELINES], tmppipelen, remain;
679         unsigned int numpipes, j;
680
681         if (n == 0)
682             numpipes = 1;
683         else
684             numpipes = ((n - 1) / split_send_fragment) + 1;
685         if (numpipes > maxpipes)
686             numpipes = maxpipes;
687
688         if (n / numpipes >= s->max_send_fragment) {
689             /*
690              * We have enough data to completely fill all available
691              * pipelines
692              */
693             for (j = 0; j < numpipes; j++) {
694                 pipelens[j] = s->max_send_fragment;
695             }
696         } else {
697             /* We can partially fill all available pipelines */
698             tmppipelen = n / numpipes;
699             remain = n % numpipes;
700             for (j = 0; j < numpipes; j++) {
701                 pipelens[j] = tmppipelen;
702                 if (j < remain)
703                     pipelens[j]++;
704             }
705         }
706
707         i = do_ssl3_write(s, type, &(buf[tot]), pipelens, numpipes, 0);
708         if (i <= 0) {
709             /* XXX should we ssl3_release_write_buffer if i<0? */
710             s->rlayer.wnum = tot;
711             return i;
712         }
713
714         if ((i == (int)n) ||
715             (type == SSL3_RT_APPLICATION_DATA &&
716              (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
717             /*
718              * next chunk of data should get another prepended empty fragment
719              * in ciphersuites with known-IV weakness:
720              */
721             s->s3->empty_fragment_done = 0;
722
723             if ((i == (int)n) && s->mode & SSL_MODE_RELEASE_BUFFERS &&
724                 !SSL_IS_DTLS(s))
725                 ssl3_release_write_buffer(s);
726
727             return tot + i;
728         }
729
730         n -= i;
731         tot += i;
732     }
733 }
734
735 int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
736                   unsigned int *pipelens, unsigned int numpipes,
737                   int create_empty_fragment)
738 {
739     unsigned char *outbuf[SSL_MAX_PIPELINES], *plen[SSL_MAX_PIPELINES];
740     SSL3_RECORD wr[SSL_MAX_PIPELINES];
741     int i, mac_size, clear = 0;
742     int prefix_len = 0;
743     int eivlen;
744     size_t align = 0;
745     SSL3_BUFFER *wb;
746     SSL_SESSION *sess;
747     unsigned int totlen = 0;
748     unsigned int j;
749
750     for (j = 0; j < numpipes; j++)
751         totlen += pipelens[j];
752     /*
753      * first check if there is a SSL3_BUFFER still being written out.  This
754      * will happen with non blocking IO
755      */
756     if (RECORD_LAYER_write_pending(&s->rlayer))
757         return (ssl3_write_pending(s, type, buf, totlen));
758
759     /* If we have an alert to send, lets send it */
760     if (s->s3->alert_dispatch) {
761         i = s->method->ssl_dispatch_alert(s);
762         if (i <= 0)
763             return (i);
764         /* if it went, fall through and send more stuff */
765     }
766
767     if (s->rlayer.numwpipes < numpipes)
768         if (!ssl3_setup_write_buffer(s, numpipes))
769             return -1;
770
771     if (totlen == 0 && !create_empty_fragment)
772         return 0;
773
774     sess = s->session;
775
776     if ((sess == NULL) ||
777         (s->enc_write_ctx == NULL) ||
778         (EVP_MD_CTX_md(s->write_hash) == NULL)) {
779         clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */
780         mac_size = 0;
781     } else {
782         mac_size = EVP_MD_CTX_size(s->write_hash);
783         if (mac_size < 0)
784             goto err;
785     }
786
787     /*
788      * 'create_empty_fragment' is true only when this function calls itself
789      */
790     if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done) {
791         /*
792          * countermeasure against known-IV weakness in CBC ciphersuites (see
793          * http://www.openssl.org/~bodo/tls-cbc.txt)
794          */
795
796         if (s->s3->need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) {
797             /*
798              * recursive function call with 'create_empty_fragment' set; this
799              * prepares and buffers the data for an empty fragment (these
800              * 'prefix_len' bytes are sent out later together with the actual
801              * payload)
802              */
803             unsigned int tmppipelen = 0;
804
805             prefix_len = do_ssl3_write(s, type, buf, &tmppipelen, 1, 1);
806             if (prefix_len <= 0)
807                 goto err;
808
809             if (prefix_len >
810                 (SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD))
811             {
812                 /* insufficient space */
813                 SSLerr(SSL_F_DO_SSL3_WRITE, ERR_R_INTERNAL_ERROR);
814                 goto err;
815             }
816         }
817
818         s->s3->empty_fragment_done = 1;
819     }
820
821     if (create_empty_fragment) {
822         wb = &s->rlayer.wbuf[0];
823 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
824         /*
825          * extra fragment would be couple of cipher blocks, which would be
826          * multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real
827          * payload, then we can just pretent we simply have two headers.
828          */
829         align = (size_t)SSL3_BUFFER_get_buf(wb) + 2 * SSL3_RT_HEADER_LENGTH;
830         align = (0-align) & (SSL3_ALIGN_PAYLOAD - 1);
831 #endif
832         outbuf[0] = SSL3_BUFFER_get_buf(wb) + align;
833         SSL3_BUFFER_set_offset(wb, align);
834     } else if (prefix_len) {
835         wb = &s->rlayer.wbuf[0];
836         outbuf[0] = SSL3_BUFFER_get_buf(wb) + SSL3_BUFFER_get_offset(wb)
837                     + prefix_len;
838     } else {
839         for (j=0; j < numpipes; j++) {
840             wb = &s->rlayer.wbuf[j];
841 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
842             align = (size_t)SSL3_BUFFER_get_buf(wb) + SSL3_RT_HEADER_LENGTH;
843             align = (-align) & (SSL3_ALIGN_PAYLOAD - 1);
844 #endif
845             outbuf[j] = SSL3_BUFFER_get_buf(wb) + align;
846             SSL3_BUFFER_set_offset(wb, align);
847         }
848     }
849
850     /* Explicit IV length, block ciphers appropriate version flag */
851     if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s)) {
852         int mode = EVP_CIPHER_CTX_mode(s->enc_write_ctx);
853         if (mode == EVP_CIPH_CBC_MODE) {
854             eivlen = EVP_CIPHER_CTX_iv_length(s->enc_write_ctx);
855             if (eivlen <= 1)
856                 eivlen = 0;
857         }
858         /* Need explicit part of IV for GCM mode */
859         else if (mode == EVP_CIPH_GCM_MODE)
860             eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
861         else if (mode == EVP_CIPH_CCM_MODE)
862             eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;
863         else
864             eivlen = 0;
865     } else
866         eivlen = 0;
867
868
869     totlen = 0;
870     /* Clear our SSL3_RECORD structures */
871     memset(wr, 0, sizeof wr);
872     for (j=0; j < numpipes; j++) {
873         /* write the header */
874         *(outbuf[j]++) = type & 0xff;
875         SSL3_RECORD_set_type(&wr[j], type);
876
877         *(outbuf[j]++) = (s->version >> 8);
878         /*
879          * Some servers hang if iniatial client hello is larger than 256 bytes
880          * and record version number > TLS 1.0
881          */
882         if (SSL_get_state(s) == TLS_ST_CW_CLNT_HELLO
883             && !s->renegotiate && TLS1_get_version(s) > TLS1_VERSION)
884             *(outbuf[j]++) = 0x1;
885         else
886             *(outbuf[j]++) = s->version & 0xff;
887
888         /* field where we are to write out packet length */
889         plen[j] = outbuf[j];
890         outbuf[j] += 2;
891
892         /* lets setup the record stuff. */
893         SSL3_RECORD_set_data(&wr[j], outbuf[j] + eivlen);
894         SSL3_RECORD_set_length(&wr[j], (int)pipelens[j]);
895         SSL3_RECORD_set_input(&wr[j], (unsigned char *)&buf[totlen]);
896         totlen += pipelens[j];
897
898         /*
899          * we now 'read' from wr->input, wr->length bytes into wr->data
900          */
901
902         /* first we compress */
903         if (s->compress != NULL) {
904             if (!ssl3_do_compress(s, &wr[j])) {
905                 SSLerr(SSL_F_DO_SSL3_WRITE, SSL_R_COMPRESSION_FAILURE);
906                 goto err;
907             }
908         } else {
909             memcpy(wr[j].data, wr[j].input, wr[j].length);
910             SSL3_RECORD_reset_input(&wr[j]);
911         }
912
913         /*
914          * we should still have the output to wr->data and the input from
915          * wr->input.  Length should be wr->length. wr->data still points in the
916          * wb->buf
917          */
918
919         if (!SSL_USE_ETM(s) && mac_size != 0) {
920             if (s->method->ssl3_enc->mac(s, &wr[j],
921                     &(outbuf[j][wr[j].length + eivlen]), 1) < 0)
922                 goto err;
923             SSL3_RECORD_add_length(&wr[j], mac_size);
924         }
925
926
927         SSL3_RECORD_set_data(&wr[j], outbuf[j]);
928         SSL3_RECORD_reset_input(&wr[j]);
929
930         if (eivlen) {
931             /*
932              * if (RAND_pseudo_bytes(p, eivlen) <= 0) goto err;
933              */
934             SSL3_RECORD_add_length(&wr[j], eivlen);
935         }
936     }
937
938     if (s->method->ssl3_enc->enc(s, wr, numpipes, 1) < 1)
939         goto err;
940
941     for (j=0; j < numpipes; j++) {
942         if (SSL_USE_ETM(s) && mac_size != 0) {
943             if (s->method->ssl3_enc->mac(s, &wr[j],
944                                          outbuf[j] + wr[j].length, 1) < 0)
945                 goto err;
946             SSL3_RECORD_add_length(&wr[j], mac_size);
947         }
948
949         /* record length after mac and block padding */
950         s2n(SSL3_RECORD_get_length(&wr[j]), plen[j]);
951
952         if (s->msg_callback)
953             s->msg_callback(1, 0, SSL3_RT_HEADER, plen[j] - 5, 5, s,
954                             s->msg_callback_arg);
955
956         /*
957          * we should now have wr->data pointing to the encrypted data, which is
958          * wr->length long
959          */
960         SSL3_RECORD_set_type(&wr[j], type);  /* not needed but helps for debugging */
961         SSL3_RECORD_add_length(&wr[j], SSL3_RT_HEADER_LENGTH);
962
963         if (create_empty_fragment) {
964             /*
965              * we are in a recursive call; just return the length, don't write
966              * out anything here
967              */
968             if (j > 0) {
969                 /* We should never be pipelining an empty fragment!! */
970                 SSLerr(SSL_F_DO_SSL3_WRITE, ERR_R_INTERNAL_ERROR);
971                 goto err;
972             }
973             return SSL3_RECORD_get_length(wr);
974         }
975
976         /* now let's set up wb */
977         SSL3_BUFFER_set_left(&s->rlayer.wbuf[j],
978             prefix_len + SSL3_RECORD_get_length(&wr[j]));
979     }
980
981
982
983     /*
984      * memorize arguments so that ssl3_write_pending can detect bad write
985      * retries later
986      */
987     s->rlayer.wpend_tot = totlen;
988     s->rlayer.wpend_buf = buf;
989     s->rlayer.wpend_type = type;
990     s->rlayer.wpend_ret = totlen;
991
992     /* we now just need to write the buffer */
993     return ssl3_write_pending(s, type, buf, totlen);
994  err:
995     return -1;
996 }
997
998 /* if s->s3->wbuf.left != 0, we need to call this */
999 int ssl3_write_pending(SSL *s, int type, const unsigned char *buf,
1000                        unsigned int len)
1001 {
1002     int i;
1003     SSL3_BUFFER *wb = s->rlayer.wbuf;
1004     unsigned int currbuf = 0;
1005
1006 /* XXXX */
1007     if ((s->rlayer.wpend_tot > (int)len)
1008         || ((s->rlayer.wpend_buf != buf) &&
1009             !(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER))
1010         || (s->rlayer.wpend_type != type)) {
1011         SSLerr(SSL_F_SSL3_WRITE_PENDING, SSL_R_BAD_WRITE_RETRY);
1012         return (-1);
1013     }
1014
1015     for (;;) {
1016         /* Loop until we find a buffer we haven't written out yet */
1017         if (SSL3_BUFFER_get_left(&wb[currbuf]) == 0
1018                 && currbuf < s->rlayer.numwpipes - 1) {
1019             currbuf++;
1020             continue;
1021         }
1022         clear_sys_error();
1023         if (s->wbio != NULL) {
1024             s->rwstate = SSL_WRITING;
1025             i = BIO_write(s->wbio,
1026                 (char *)&(SSL3_BUFFER_get_buf(&wb[currbuf])[
1027                                 SSL3_BUFFER_get_offset(&wb[currbuf])]),
1028                 (unsigned int)SSL3_BUFFER_get_left(&wb[currbuf]));
1029         } else {
1030             SSLerr(SSL_F_SSL3_WRITE_PENDING, SSL_R_BIO_NOT_SET);
1031             i = -1;
1032         }
1033         if (i == SSL3_BUFFER_get_left(&wb[currbuf])) {
1034             SSL3_BUFFER_set_left(&wb[currbuf], 0);
1035             SSL3_BUFFER_add_offset(&wb[currbuf], i);
1036             if (currbuf + 1 < s->rlayer.numwpipes)
1037                 continue;
1038             s->rwstate = SSL_NOTHING;
1039             return (s->rlayer.wpend_ret);
1040         } else if (i <= 0) {
1041             if (SSL_IS_DTLS(s)) {
1042                 /*
1043                  * For DTLS, just drop it. That's kind of the whole point in
1044                  * using a datagram service
1045                  */
1046                 SSL3_BUFFER_set_left(&wb[currbuf], 0);
1047             }
1048             return (i);
1049         }
1050         SSL3_BUFFER_add_offset(&wb[currbuf], i);
1051         SSL3_BUFFER_add_left(&wb[currbuf], -i);
1052     }
1053 }
1054
1055 /*-
1056  * Return up to 'len' payload bytes received in 'type' records.
1057  * 'type' is one of the following:
1058  *
1059  *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
1060  *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
1061  *   -  0 (during a shutdown, no data has to be returned)
1062  *
1063  * If we don't have stored data to work from, read a SSL/TLS record first
1064  * (possibly multiple records if we still don't have anything to return).
1065  *
1066  * This function must handle any surprises the peer may have for us, such as
1067  * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
1068  * messages are treated as if they were handshake messages *if* the |recd_type|
1069  * argument is non NULL.
1070  * Also if record payloads contain fragments too small to process, we store
1071  * them until there is enough for the respective protocol (the record protocol
1072  * may use arbitrary fragmentation and even interleaving):
1073  *     Change cipher spec protocol
1074  *             just 1 byte needed, no need for keeping anything stored
1075  *     Alert protocol
1076  *             2 bytes needed (AlertLevel, AlertDescription)
1077  *     Handshake protocol
1078  *             4 bytes needed (HandshakeType, uint24 length) -- we just have
1079  *             to detect unexpected Client Hello and Hello Request messages
1080  *             here, anything else is handled by higher layers
1081  *     Application data protocol
1082  *             none of our business
1083  */
1084 int ssl3_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
1085                     int len, int peek)
1086 {
1087     int al, i, j, ret;
1088     unsigned int n, curr_rec, num_recs, read_bytes;
1089     SSL3_RECORD *rr;
1090     SSL3_BUFFER *rbuf;
1091     void (*cb) (const SSL *ssl, int type2, int val) = NULL;
1092
1093     rbuf = &s->rlayer.rbuf;
1094
1095     if (!SSL3_BUFFER_is_initialised(rbuf)) {
1096         /* Not initialized yet */
1097         if (!ssl3_setup_read_buffer(s))
1098             return (-1);
1099     }
1100
1101     if ((type && (type != SSL3_RT_APPLICATION_DATA)
1102          && (type != SSL3_RT_HANDSHAKE)) || (peek
1103                                              && (type !=
1104                                                  SSL3_RT_APPLICATION_DATA))) {
1105         SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
1106         return -1;
1107     }
1108
1109     if ((type == SSL3_RT_HANDSHAKE) && (s->rlayer.handshake_fragment_len > 0))
1110         /* (partially) satisfy request from storage */
1111     {
1112         unsigned char *src = s->rlayer.handshake_fragment;
1113         unsigned char *dst = buf;
1114         unsigned int k;
1115
1116         /* peek == 0 */
1117         n = 0;
1118         while ((len > 0) && (s->rlayer.handshake_fragment_len > 0)) {
1119             *dst++ = *src++;
1120             len--;
1121             s->rlayer.handshake_fragment_len--;
1122             n++;
1123         }
1124         /* move any remaining fragment bytes: */
1125         for (k = 0; k < s->rlayer.handshake_fragment_len; k++)
1126             s->rlayer.handshake_fragment[k] = *src++;
1127
1128         if (recvd_type != NULL)
1129             *recvd_type = SSL3_RT_HANDSHAKE;
1130
1131         return n;
1132     }
1133
1134     /*
1135      * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
1136      */
1137
1138     if (!ossl_statem_get_in_handshake(s) && SSL_in_init(s)) {
1139         /* type == SSL3_RT_APPLICATION_DATA */
1140         i = s->handshake_func(s);
1141         if (i < 0)
1142             return (i);
1143         if (i == 0) {
1144             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
1145             return (-1);
1146         }
1147     }
1148  start:
1149     s->rwstate = SSL_NOTHING;
1150
1151     /*-
1152      * For each record 'i' up to |num_recs]
1153      * rr[i].type     - is the type of record
1154      * rr[i].data,    - data
1155      * rr[i].off,     - offset into 'data' for next read
1156      * rr[i].length,  - number of bytes.
1157      */
1158     rr = s->rlayer.rrec;
1159     num_recs = RECORD_LAYER_get_numrpipes(&s->rlayer);
1160
1161     do {
1162         /* get new records if necessary */
1163         if (num_recs == 0) {
1164             ret = ssl3_get_record(s);
1165             if (ret <= 0)
1166                 return (ret);
1167             num_recs = RECORD_LAYER_get_numrpipes(&s->rlayer);
1168             if (num_recs == 0) {
1169                 /* Shouldn't happen */
1170                 al = SSL_AD_INTERNAL_ERROR;
1171                 SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
1172                 goto f_err;
1173             }
1174         }
1175         /* Skip over any records we have already used or are zero in length */
1176         for (curr_rec = 0;
1177              curr_rec < num_recs && SSL3_RECORD_get_length(&rr[curr_rec]) == 0;
1178              curr_rec++);
1179         if (curr_rec == num_recs) {
1180             RECORD_LAYER_set_numrpipes(&s->rlayer, 0);
1181             num_recs = 0;
1182             curr_rec = 0;
1183         }
1184     } while (num_recs == 0);
1185     rr = &rr[curr_rec];
1186
1187     /* we now have a packet which can be read and processed */
1188
1189     if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
1190                                    * reset by ssl3_get_finished */
1191         && (SSL3_RECORD_get_type(rr) != SSL3_RT_HANDSHAKE)) {
1192         al = SSL_AD_UNEXPECTED_MESSAGE;
1193         SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
1194         goto f_err;
1195     }
1196
1197     /*
1198      * If the other end has shut down, throw anything we read away (even in
1199      * 'peek' mode)
1200      */
1201     if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1202         SSL3_RECORD_set_length(rr, 0);
1203         s->rwstate = SSL_NOTHING;
1204         return (0);
1205     }
1206
1207     if (type == SSL3_RECORD_get_type(rr)
1208             || (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC
1209                 && type == SSL3_RT_HANDSHAKE && recvd_type != NULL)) {
1210         /*
1211          * SSL3_RT_APPLICATION_DATA or
1212          * SSL3_RT_HANDSHAKE or
1213          * SSL3_RT_CHANGE_CIPHER_SPEC
1214          */
1215         /*
1216          * make sure that we are not getting application data when we are
1217          * doing a handshake for the first time
1218          */
1219         if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
1220             (s->enc_read_ctx == NULL)) {
1221             al = SSL_AD_UNEXPECTED_MESSAGE;
1222             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_APP_DATA_IN_HANDSHAKE);
1223             goto f_err;
1224         }
1225
1226         if (type == SSL3_RT_HANDSHAKE
1227                 && SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC
1228                 && s->rlayer.handshake_fragment_len > 0) {
1229             al = SSL_AD_UNEXPECTED_MESSAGE;
1230             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_CCS_RECEIVED_EARLY);
1231             goto f_err;
1232         }
1233
1234         if (recvd_type != NULL)
1235             *recvd_type = SSL3_RECORD_get_type(rr);
1236
1237         if (len <= 0)
1238             return (len);
1239
1240         read_bytes = 0;
1241         do {
1242             if ((unsigned int)len - read_bytes > SSL3_RECORD_get_length(rr))
1243                 n = SSL3_RECORD_get_length(rr);
1244             else
1245                 n = (unsigned int)len - read_bytes;
1246
1247             memcpy(buf, &(rr->data[rr->off]), n);
1248             buf += n;
1249             if (!peek) {
1250                 SSL3_RECORD_add_length(rr, -n);
1251                 SSL3_RECORD_add_off(rr, n);
1252                 if (SSL3_RECORD_get_length(rr) == 0) {
1253                     s->rlayer.rstate = SSL_ST_READ_HEADER;
1254                     SSL3_RECORD_set_off(rr, 0);
1255                 }
1256             }
1257             if (SSL3_RECORD_get_length(rr) == 0
1258                 || (peek && n == SSL3_RECORD_get_length(rr))) {
1259                 curr_rec++;
1260                 rr++;
1261             }
1262             read_bytes += n;
1263         } while (type == SSL3_RT_APPLICATION_DATA && curr_rec < num_recs
1264                  && read_bytes < (unsigned int)len);
1265         if (!peek && curr_rec == num_recs
1266                 && (s->mode & SSL_MODE_RELEASE_BUFFERS)
1267                 && SSL3_BUFFER_get_left(rbuf) == 0)
1268             ssl3_release_read_buffer(s);
1269         return read_bytes;
1270     }
1271
1272     /*
1273      * If we get here, then type != rr->type; if we have a handshake message,
1274      * then it was unexpected (Hello Request or Client Hello) or invalid (we
1275      * were actually expecting a CCS).
1276      */
1277
1278     if (rr->type == SSL3_RT_HANDSHAKE && type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1279         al = SSL_AD_UNEXPECTED_MESSAGE;
1280         SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_MESSAGE);
1281         goto f_err;
1282     }
1283
1284     /*
1285      * Lets just double check that we've not got an SSLv2 record
1286      */
1287     if (rr->rec_version == SSL2_VERSION) {
1288         /*
1289          * Should never happen. ssl3_get_record() should only give us an SSLv2
1290          * record back if this is the first packet and we are looking for an
1291          * initial ClientHello. Therefore |type| should always be equal to
1292          * |rr->type|. If not then something has gone horribly wrong
1293          */
1294         al = SSL_AD_INTERNAL_ERROR;
1295         SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
1296         goto f_err;
1297     }
1298
1299     if(s->method->version == TLS_ANY_VERSION
1300             && (s->server || rr->type != SSL3_RT_ALERT)) {
1301         /*
1302          * If we've got this far and still haven't decided on what version
1303          * we're using then this must be a client side alert we're dealing with
1304          * (we don't allow heartbeats yet). We shouldn't be receiving anything
1305          * other than a ClientHello if we are a server.
1306          */
1307         s->version = rr->rec_version;
1308         al = SSL_AD_UNEXPECTED_MESSAGE;
1309         SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_MESSAGE);
1310         goto f_err;
1311     }
1312
1313     /*
1314      * In case of record types for which we have 'fragment' storage, fill
1315      * that so that we can process the data at a fixed place.
1316      */
1317     {
1318         unsigned int dest_maxlen = 0;
1319         unsigned char *dest = NULL;
1320         unsigned int *dest_len = NULL;
1321
1322         if (SSL3_RECORD_get_type(rr) == SSL3_RT_HANDSHAKE) {
1323             dest_maxlen = sizeof s->rlayer.handshake_fragment;
1324             dest = s->rlayer.handshake_fragment;
1325             dest_len = &s->rlayer.handshake_fragment_len;
1326         } else if (SSL3_RECORD_get_type(rr) == SSL3_RT_ALERT) {
1327             dest_maxlen = sizeof s->rlayer.alert_fragment;
1328             dest = s->rlayer.alert_fragment;
1329             dest_len = &s->rlayer.alert_fragment_len;
1330         }
1331
1332         if (dest_maxlen > 0) {
1333             n = dest_maxlen - *dest_len; /* available space in 'dest' */
1334             if (SSL3_RECORD_get_length(rr) < n)
1335                 n = SSL3_RECORD_get_length(rr); /* available bytes */
1336
1337             /* now move 'n' bytes: */
1338             while (n-- > 0) {
1339                 dest[(*dest_len)++] =
1340                     SSL3_RECORD_get_data(rr)[SSL3_RECORD_get_off(rr)];
1341                 SSL3_RECORD_add_off(rr, 1);
1342                 SSL3_RECORD_add_length(rr, -1);
1343             }
1344
1345             if (*dest_len < dest_maxlen)
1346                 goto start;     /* fragment was too small */
1347         }
1348     }
1349
1350     /*-
1351      * s->rlayer.handshake_fragment_len == 4  iff  rr->type == SSL3_RT_HANDSHAKE;
1352      * s->rlayer.alert_fragment_len == 2      iff  rr->type == SSL3_RT_ALERT.
1353      * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
1354      */
1355
1356     /* If we are a client, check for an incoming 'Hello Request': */
1357     if ((!s->server) &&
1358         (s->rlayer.handshake_fragment_len >= 4) &&
1359         (s->rlayer.handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
1360         (s->session != NULL) && (s->session->cipher != NULL)) {
1361         s->rlayer.handshake_fragment_len = 0;
1362
1363         if ((s->rlayer.handshake_fragment[1] != 0) ||
1364             (s->rlayer.handshake_fragment[2] != 0) ||
1365             (s->rlayer.handshake_fragment[3] != 0)) {
1366             al = SSL_AD_DECODE_ERROR;
1367             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_BAD_HELLO_REQUEST);
1368             goto f_err;
1369         }
1370
1371         if (s->msg_callback)
1372             s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1373                             s->rlayer.handshake_fragment, 4, s,
1374                             s->msg_callback_arg);
1375
1376         if (SSL_is_init_finished(s) &&
1377             !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
1378             !s->s3->renegotiate) {
1379             ssl3_renegotiate(s);
1380             if (ssl3_renegotiate_check(s)) {
1381                 i = s->handshake_func(s);
1382                 if (i < 0)
1383                     return (i);
1384                 if (i == 0) {
1385                     SSLerr(SSL_F_SSL3_READ_BYTES,
1386                            SSL_R_SSL_HANDSHAKE_FAILURE);
1387                     return (-1);
1388                 }
1389
1390                 if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1391                     if (SSL3_BUFFER_get_left(rbuf) == 0) {
1392                         /* no read-ahead left? */
1393                         BIO *bio;
1394                         /*
1395                          * In the case where we try to read application data,
1396                          * but we trigger an SSL handshake, we return -1 with
1397                          * the retry option set.  Otherwise renegotiation may
1398                          * cause nasty problems in the blocking world
1399                          */
1400                         s->rwstate = SSL_READING;
1401                         bio = SSL_get_rbio(s);
1402                         BIO_clear_retry_flags(bio);
1403                         BIO_set_retry_read(bio);
1404                         return (-1);
1405                     }
1406                 }
1407             }
1408         }
1409         /*
1410          * we either finished a handshake or ignored the request, now try
1411          * again to obtain the (application) data we were asked for
1412          */
1413         goto start;
1414     }
1415     /*
1416      * If we are a server and get a client hello when renegotiation isn't
1417      * allowed send back a no renegotiation alert and carry on. WARNING:
1418      * experimental code, needs reviewing (steve)
1419      */
1420     if (s->server &&
1421         SSL_is_init_finished(s) &&
1422         !s->s3->send_connection_binding &&
1423         (s->version > SSL3_VERSION) &&
1424         (s->rlayer.handshake_fragment_len >= 4) &&
1425         (s->rlayer.handshake_fragment[0] == SSL3_MT_CLIENT_HELLO) &&
1426         (s->session != NULL) && (s->session->cipher != NULL) &&
1427         !(s->ctx->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
1428         SSL3_RECORD_set_length(rr, 0);
1429         ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
1430         goto start;
1431     }
1432     if (s->rlayer.alert_fragment_len >= 2) {
1433         int alert_level = s->rlayer.alert_fragment[0];
1434         int alert_descr = s->rlayer.alert_fragment[1];
1435
1436         s->rlayer.alert_fragment_len = 0;
1437
1438         if (s->msg_callback)
1439             s->msg_callback(0, s->version, SSL3_RT_ALERT,
1440                             s->rlayer.alert_fragment, 2, s,
1441                             s->msg_callback_arg);
1442
1443         if (s->info_callback != NULL)
1444             cb = s->info_callback;
1445         else if (s->ctx->info_callback != NULL)
1446             cb = s->ctx->info_callback;
1447
1448         if (cb != NULL) {
1449             j = (alert_level << 8) | alert_descr;
1450             cb(s, SSL_CB_READ_ALERT, j);
1451         }
1452
1453         if (alert_level == SSL3_AL_WARNING) {
1454             s->s3->warn_alert = alert_descr;
1455             if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
1456                 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1457                 return (0);
1458             }
1459             /*
1460              * This is a warning but we receive it if we requested
1461              * renegotiation and the peer denied it. Terminate with a fatal
1462              * alert because if application tried to renegotiatie it
1463              * presumably had a good reason and expects it to succeed. In
1464              * future we might have a renegotiation where we don't care if
1465              * the peer refused it where we carry on.
1466              */
1467             else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
1468                 al = SSL_AD_HANDSHAKE_FAILURE;
1469                 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_NO_RENEGOTIATION);
1470                 goto f_err;
1471             }
1472 #ifdef SSL_AD_MISSING_SRP_USERNAME
1473             else if (alert_descr == SSL_AD_MISSING_SRP_USERNAME)
1474                 return (0);
1475 #endif
1476         } else if (alert_level == SSL3_AL_FATAL) {
1477             char tmp[16];
1478
1479             s->rwstate = SSL_NOTHING;
1480             s->s3->fatal_alert = alert_descr;
1481             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr);
1482             BIO_snprintf(tmp, sizeof tmp, "%d", alert_descr);
1483             ERR_add_error_data(2, "SSL alert number ", tmp);
1484             s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1485             SSL_CTX_remove_session(s->ctx, s->session);
1486             return (0);
1487         } else {
1488             al = SSL_AD_ILLEGAL_PARAMETER;
1489             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNKNOWN_ALERT_TYPE);
1490             goto f_err;
1491         }
1492
1493         goto start;
1494     }
1495
1496     if (s->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a
1497                                             * shutdown */
1498         s->rwstate = SSL_NOTHING;
1499         SSL3_RECORD_set_length(rr, 0);
1500         return (0);
1501     }
1502
1503     if (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC) {
1504         al = SSL_AD_UNEXPECTED_MESSAGE;
1505         SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_CCS_RECEIVED_EARLY);
1506         goto f_err;
1507     }
1508
1509     /*
1510      * Unexpected handshake message (Client Hello, or protocol violation)
1511      */
1512     if ((s->rlayer.handshake_fragment_len >= 4)
1513             && !ossl_statem_get_in_handshake(s)) {
1514         if (SSL_is_init_finished(s) &&
1515             !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) {
1516             ossl_statem_set_in_init(s, 1);
1517             s->renegotiate = 1;
1518             s->new_session = 1;
1519         }
1520         i = s->handshake_func(s);
1521         if (i < 0)
1522             return (i);
1523         if (i == 0) {
1524             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
1525             return (-1);
1526         }
1527
1528         if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1529             if (SSL3_BUFFER_get_left(rbuf) == 0) {
1530                 /* no read-ahead left? */
1531                 BIO *bio;
1532                 /*
1533                  * In the case where we try to read application data, but we
1534                  * trigger an SSL handshake, we return -1 with the retry
1535                  * option set.  Otherwise renegotiation may cause nasty
1536                  * problems in the blocking world
1537                  */
1538                 s->rwstate = SSL_READING;
1539                 bio = SSL_get_rbio(s);
1540                 BIO_clear_retry_flags(bio);
1541                 BIO_set_retry_read(bio);
1542                 return (-1);
1543             }
1544         }
1545         goto start;
1546     }
1547
1548     switch (SSL3_RECORD_get_type(rr)) {
1549     default:
1550         /*
1551          * TLS up to v1.1 just ignores unknown message types: TLS v1.2 give
1552          * an unexpected message alert.
1553          */
1554         if (s->version >= TLS1_VERSION && s->version <= TLS1_1_VERSION) {
1555             SSL3_RECORD_set_length(rr, 0);
1556             goto start;
1557         }
1558         al = SSL_AD_UNEXPECTED_MESSAGE;
1559         SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
1560         goto f_err;
1561     case SSL3_RT_CHANGE_CIPHER_SPEC:
1562     case SSL3_RT_ALERT:
1563     case SSL3_RT_HANDSHAKE:
1564         /*
1565          * we already handled all of these, with the possible exception of
1566          * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
1567          * that should not happen when type != rr->type
1568          */
1569         al = SSL_AD_UNEXPECTED_MESSAGE;
1570         SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
1571         goto f_err;
1572     case SSL3_RT_APPLICATION_DATA:
1573         /*
1574          * At this point, we were expecting handshake data, but have
1575          * application data.  If the library was running inside ssl3_read()
1576          * (i.e. in_read_app_data is set) and it makes sense to read
1577          * application data at this point (session renegotiation not yet
1578          * started), we will indulge it.
1579          */
1580         if (ossl_statem_app_data_allowed(s)) {
1581             s->s3->in_read_app_data = 2;
1582             return (-1);
1583         } else {
1584             al = SSL_AD_UNEXPECTED_MESSAGE;
1585             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
1586             goto f_err;
1587         }
1588     }
1589     /* not reached */
1590
1591  f_err:
1592     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1593     return (-1);
1594 }
1595
1596 void ssl3_record_sequence_update(unsigned char *seq)
1597 {
1598     int i;
1599
1600     for (i = 7; i >= 0; i--) {
1601         ++seq[i];
1602         if (seq[i] != 0)
1603             break;
1604     }
1605 }
1606
1607 /*
1608  * Returns true if the current rrec was sent in SSLv2 backwards compatible
1609  * format and false otherwise.
1610  */
1611 int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl)
1612 {
1613     return SSL3_RECORD_is_sslv2_record(&rl->rrec[0]);
1614 }
1615
1616 /*
1617  * Returns the length in bytes of the current rrec
1618  */
1619 unsigned int RECORD_LAYER_get_rrec_length(RECORD_LAYER *rl)
1620 {
1621     return SSL3_RECORD_get_length(&rl->rrec[0]);
1622 }