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