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