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