Always use session_ctx when removing a session
[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             wb->buf = OPENSSL_malloc(packlen);
427             if (wb->buf == NULL) {
428                 SSLerr(SSL_F_SSL3_WRITE_BYTES, ERR_R_MALLOC_FAILURE);
429                 return -1;
430             }
431             wb->len = packlen;
432         } else if (tot == len) { /* done? */
433             OPENSSL_free(wb->buf); /* free jumbo buffer */
434             wb->buf = NULL;
435             return tot;
436         }
437
438         n = (len - tot);
439         for (;;) {
440             if (n < 4 * max_send_fragment) {
441                 OPENSSL_free(wb->buf); /* free jumbo buffer */
442                 wb->buf = NULL;
443                 break;
444             }
445
446             if (s->s3->alert_dispatch) {
447                 i = s->method->ssl_dispatch_alert(s);
448                 if (i <= 0) {
449                     s->rlayer.wnum = tot;
450                     return i;
451                 }
452             }
453
454             if (n >= 8 * max_send_fragment)
455                 nw = max_send_fragment * (mb_param.interleave = 8);
456             else
457                 nw = max_send_fragment * (mb_param.interleave = 4);
458
459             memcpy(aad, s->rlayer.write_sequence, 8);
460             aad[8] = type;
461             aad[9] = (unsigned char)(s->version >> 8);
462             aad[10] = (unsigned char)(s->version);
463             aad[11] = 0;
464             aad[12] = 0;
465             mb_param.out = NULL;
466             mb_param.inp = aad;
467             mb_param.len = nw;
468
469             packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
470                                           EVP_CTRL_TLS1_1_MULTIBLOCK_AAD,
471                                           sizeof(mb_param), &mb_param);
472
473             if (packlen <= 0 || packlen > (int)wb->len) { /* never happens */
474                 OPENSSL_free(wb->buf); /* free jumbo buffer */
475                 wb->buf = NULL;
476                 break;
477             }
478
479             mb_param.out = wb->buf;
480             mb_param.inp = &buf[tot];
481             mb_param.len = nw;
482
483             if (EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
484                                     EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT,
485                                     sizeof(mb_param), &mb_param) <= 0)
486                 return -1;
487
488             s->rlayer.write_sequence[7] += mb_param.interleave;
489             if (s->rlayer.write_sequence[7] < mb_param.interleave) {
490                 int j = 6;
491                 while (j >= 0 && (++s->rlayer.write_sequence[j--]) == 0) ;
492             }
493
494             wb->offset = 0;
495             wb->left = packlen;
496
497             s->rlayer.wpend_tot = nw;
498             s->rlayer.wpend_buf = &buf[tot];
499             s->rlayer.wpend_type = type;
500             s->rlayer.wpend_ret = nw;
501
502             i = ssl3_write_pending(s, type, &buf[tot], nw);
503             if (i <= 0) {
504                 if (i < 0 && (!s->wbio || !BIO_should_retry(s->wbio))) {
505                     OPENSSL_free(wb->buf);
506                     wb->buf = NULL;
507                 }
508                 s->rlayer.wnum = tot;
509                 return i;
510             }
511             if (i == (int)n) {
512                 OPENSSL_free(wb->buf); /* free jumbo buffer */
513                 wb->buf = NULL;
514                 return tot + i;
515             }
516             n -= i;
517             tot += i;
518         }
519     } else
520 #endif
521     if (tot == len) {           /* done? */
522         if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s))
523             ssl3_release_write_buffer(s);
524
525         return tot;
526     }
527
528     n = (len - tot);
529
530     split_send_fragment = s->split_send_fragment;
531     /*
532      * If max_pipelines is 0 then this means "undefined" and we default to
533      * 1 pipeline. Similarly if the cipher does not support pipelined
534      * processing then we also only use 1 pipeline, or if we're not using
535      * explicit IVs
536      */
537     maxpipes = s->max_pipelines;
538     if (maxpipes > SSL_MAX_PIPELINES) {
539         /*
540          * We should have prevented this when we set max_pipelines so we
541          * shouldn't get here
542         */
543         SSLerr(SSL_F_SSL3_WRITE_BYTES, ERR_R_INTERNAL_ERROR);
544         return -1;
545     }
546     if (maxpipes == 0
547             || s->enc_write_ctx == NULL
548             || !(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_write_ctx))
549                  & EVP_CIPH_FLAG_PIPELINE)
550             || !SSL_USE_EXPLICIT_IV(s))
551         maxpipes = 1;
552     if (s->max_send_fragment == 0 || split_send_fragment > s->max_send_fragment
553             || split_send_fragment == 0) {
554         /*
555          * We should have prevented this when we set the split and max send
556          * fragments so we shouldn't get here
557         */
558         SSLerr(SSL_F_SSL3_WRITE_BYTES, ERR_R_INTERNAL_ERROR);
559         return -1;
560     }
561
562     for (;;) {
563         unsigned int pipelens[SSL_MAX_PIPELINES], tmppipelen, remain;
564         unsigned int numpipes, j;
565
566         if (n == 0)
567             numpipes = 1;
568         else
569             numpipes = ((n - 1) / split_send_fragment) + 1;
570         if (numpipes > maxpipes)
571             numpipes = maxpipes;
572
573         if (n / numpipes >= s->max_send_fragment) {
574             /*
575              * We have enough data to completely fill all available
576              * pipelines
577              */
578             for (j = 0; j < numpipes; j++) {
579                 pipelens[j] = s->max_send_fragment;
580             }
581         } else {
582             /* We can partially fill all available pipelines */
583             tmppipelen = n / numpipes;
584             remain = n % numpipes;
585             for (j = 0; j < numpipes; j++) {
586                 pipelens[j] = tmppipelen;
587                 if (j < remain)
588                     pipelens[j]++;
589             }
590         }
591
592         i = do_ssl3_write(s, type, &(buf[tot]), pipelens, numpipes, 0);
593         if (i <= 0) {
594             /* XXX should we ssl3_release_write_buffer if i<0? */
595             s->rlayer.wnum = tot;
596             return i;
597         }
598
599         if ((i == (int)n) ||
600             (type == SSL3_RT_APPLICATION_DATA &&
601              (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
602             /*
603              * next chunk of data should get another prepended empty fragment
604              * in ciphersuites with known-IV weakness:
605              */
606             s->s3->empty_fragment_done = 0;
607
608             if ((i == (int)n) && s->mode & SSL_MODE_RELEASE_BUFFERS &&
609                 !SSL_IS_DTLS(s))
610                 ssl3_release_write_buffer(s);
611
612             return tot + i;
613         }
614
615         n -= i;
616         tot += i;
617     }
618 }
619
620 int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
621                   unsigned int *pipelens, unsigned int numpipes,
622                   int create_empty_fragment)
623 {
624     unsigned char *outbuf[SSL_MAX_PIPELINES], *plen[SSL_MAX_PIPELINES];
625     SSL3_RECORD wr[SSL_MAX_PIPELINES];
626     int i, mac_size, clear = 0;
627     int prefix_len = 0;
628     int eivlen;
629     size_t align = 0;
630     SSL3_BUFFER *wb;
631     SSL_SESSION *sess;
632     unsigned int totlen = 0;
633     unsigned int j;
634
635     for (j = 0; j < numpipes; j++)
636         totlen += pipelens[j];
637     /*
638      * first check if there is a SSL3_BUFFER still being written out.  This
639      * will happen with non blocking IO
640      */
641     if (RECORD_LAYER_write_pending(&s->rlayer))
642         return (ssl3_write_pending(s, type, buf, totlen));
643
644     /* If we have an alert to send, lets send it */
645     if (s->s3->alert_dispatch) {
646         i = s->method->ssl_dispatch_alert(s);
647         if (i <= 0)
648             return (i);
649         /* if it went, fall through and send more stuff */
650     }
651
652     if (s->rlayer.numwpipes < numpipes)
653         if (!ssl3_setup_write_buffer(s, numpipes))
654             return -1;
655
656     if (totlen == 0 && !create_empty_fragment)
657         return 0;
658
659     sess = s->session;
660
661     if ((sess == NULL) ||
662         (s->enc_write_ctx == NULL) ||
663         (EVP_MD_CTX_md(s->write_hash) == NULL)) {
664         clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */
665         mac_size = 0;
666     } else {
667         mac_size = EVP_MD_CTX_size(s->write_hash);
668         if (mac_size < 0)
669             goto err;
670     }
671
672     /*
673      * 'create_empty_fragment' is true only when this function calls itself
674      */
675     if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done) {
676         /*
677          * countermeasure against known-IV weakness in CBC ciphersuites (see
678          * http://www.openssl.org/~bodo/tls-cbc.txt)
679          */
680
681         if (s->s3->need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) {
682             /*
683              * recursive function call with 'create_empty_fragment' set; this
684              * prepares and buffers the data for an empty fragment (these
685              * 'prefix_len' bytes are sent out later together with the actual
686              * payload)
687              */
688             unsigned int tmppipelen = 0;
689
690             prefix_len = do_ssl3_write(s, type, buf, &tmppipelen, 1, 1);
691             if (prefix_len <= 0)
692                 goto err;
693
694             if (prefix_len >
695                 (SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD))
696             {
697                 /* insufficient space */
698                 SSLerr(SSL_F_DO_SSL3_WRITE, ERR_R_INTERNAL_ERROR);
699                 goto err;
700             }
701         }
702
703         s->s3->empty_fragment_done = 1;
704     }
705
706     if (create_empty_fragment) {
707         wb = &s->rlayer.wbuf[0];
708 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
709         /*
710          * extra fragment would be couple of cipher blocks, which would be
711          * multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real
712          * payload, then we can just pretend we simply have two headers.
713          */
714         align = (size_t)SSL3_BUFFER_get_buf(wb) + 2 * SSL3_RT_HEADER_LENGTH;
715         align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
716 #endif
717         outbuf[0] = SSL3_BUFFER_get_buf(wb) + align;
718         SSL3_BUFFER_set_offset(wb, align);
719     } else if (prefix_len) {
720         wb = &s->rlayer.wbuf[0];
721         outbuf[0] = SSL3_BUFFER_get_buf(wb) + SSL3_BUFFER_get_offset(wb)
722                     + prefix_len;
723     } else {
724         for (j=0; j < numpipes; j++) {
725             wb = &s->rlayer.wbuf[j];
726 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
727             align = (size_t)SSL3_BUFFER_get_buf(wb) + SSL3_RT_HEADER_LENGTH;
728             align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
729 #endif
730             outbuf[j] = SSL3_BUFFER_get_buf(wb) + align;
731             SSL3_BUFFER_set_offset(wb, align);
732         }
733     }
734
735     /* Explicit IV length, block ciphers appropriate version flag */
736     if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s)) {
737         int mode = EVP_CIPHER_CTX_mode(s->enc_write_ctx);
738         if (mode == EVP_CIPH_CBC_MODE) {
739             eivlen = EVP_CIPHER_CTX_iv_length(s->enc_write_ctx);
740             if (eivlen <= 1)
741                 eivlen = 0;
742         }
743         /* Need explicit part of IV for GCM mode */
744         else if (mode == EVP_CIPH_GCM_MODE)
745             eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
746         else if (mode == EVP_CIPH_CCM_MODE)
747             eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;
748         else
749             eivlen = 0;
750     } else
751         eivlen = 0;
752
753
754     totlen = 0;
755     /* Clear our SSL3_RECORD structures */
756     memset(wr, 0, sizeof wr);
757     for (j=0; j < numpipes; j++) {
758         /* write the header */
759         *(outbuf[j]++) = type & 0xff;
760         SSL3_RECORD_set_type(&wr[j], type);
761
762         *(outbuf[j]++) = (s->version >> 8);
763         /*
764          * Some servers hang if initial client hello is larger than 256 bytes
765          * and record version number > TLS 1.0
766          */
767         if (SSL_get_state(s) == TLS_ST_CW_CLNT_HELLO
768             && !s->renegotiate && TLS1_get_version(s) > TLS1_VERSION)
769             *(outbuf[j]++) = 0x1;
770         else
771             *(outbuf[j]++) = s->version & 0xff;
772
773         /* field where we are to write out packet length */
774         plen[j] = outbuf[j];
775         outbuf[j] += 2;
776
777         /* lets setup the record stuff. */
778         SSL3_RECORD_set_data(&wr[j], outbuf[j] + eivlen);
779         SSL3_RECORD_set_length(&wr[j], (int)pipelens[j]);
780         SSL3_RECORD_set_input(&wr[j], (unsigned char *)&buf[totlen]);
781         totlen += pipelens[j];
782
783         /*
784          * we now 'read' from wr->input, wr->length bytes into wr->data
785          */
786
787         /* first we compress */
788         if (s->compress != NULL) {
789             if (!ssl3_do_compress(s, &wr[j])) {
790                 SSLerr(SSL_F_DO_SSL3_WRITE, SSL_R_COMPRESSION_FAILURE);
791                 goto err;
792             }
793         } else {
794             memcpy(wr[j].data, wr[j].input, wr[j].length);
795             SSL3_RECORD_reset_input(&wr[j]);
796         }
797
798         /*
799          * we should still have the output to wr->data and the input from
800          * wr->input.  Length should be wr->length. wr->data still points in the
801          * wb->buf
802          */
803
804         if (!SSL_USE_ETM(s) && mac_size != 0) {
805             if (s->method->ssl3_enc->mac(s, &wr[j],
806                     &(outbuf[j][wr[j].length + eivlen]), 1) < 0)
807                 goto err;
808             SSL3_RECORD_add_length(&wr[j], mac_size);
809         }
810
811
812         SSL3_RECORD_set_data(&wr[j], outbuf[j]);
813         SSL3_RECORD_reset_input(&wr[j]);
814
815         if (eivlen) {
816             /*
817              * if (RAND_pseudo_bytes(p, eivlen) <= 0) goto err;
818              */
819             SSL3_RECORD_add_length(&wr[j], eivlen);
820         }
821     }
822
823     if (s->method->ssl3_enc->enc(s, wr, numpipes, 1) < 1)
824         goto err;
825
826     for (j=0; j < numpipes; j++) {
827         if (SSL_USE_ETM(s) && mac_size != 0) {
828             if (s->method->ssl3_enc->mac(s, &wr[j],
829                                          outbuf[j] + wr[j].length, 1) < 0)
830                 goto err;
831             SSL3_RECORD_add_length(&wr[j], mac_size);
832         }
833
834         /* record length after mac and block padding */
835         s2n(SSL3_RECORD_get_length(&wr[j]), plen[j]);
836
837         if (s->msg_callback)
838             s->msg_callback(1, 0, SSL3_RT_HEADER, plen[j] - 5, 5, s,
839                             s->msg_callback_arg);
840
841         /*
842          * we should now have wr->data pointing to the encrypted data, which is
843          * wr->length long
844          */
845         SSL3_RECORD_set_type(&wr[j], type);  /* not needed but helps for debugging */
846         SSL3_RECORD_add_length(&wr[j], SSL3_RT_HEADER_LENGTH);
847
848         if (create_empty_fragment) {
849             /*
850              * we are in a recursive call; just return the length, don't write
851              * out anything here
852              */
853             if (j > 0) {
854                 /* We should never be pipelining an empty fragment!! */
855                 SSLerr(SSL_F_DO_SSL3_WRITE, ERR_R_INTERNAL_ERROR);
856                 goto err;
857             }
858             return SSL3_RECORD_get_length(wr);
859         }
860
861         /* now let's set up wb */
862         SSL3_BUFFER_set_left(&s->rlayer.wbuf[j],
863             prefix_len + SSL3_RECORD_get_length(&wr[j]));
864     }
865
866
867
868     /*
869      * memorize arguments so that ssl3_write_pending can detect bad write
870      * retries later
871      */
872     s->rlayer.wpend_tot = totlen;
873     s->rlayer.wpend_buf = buf;
874     s->rlayer.wpend_type = type;
875     s->rlayer.wpend_ret = totlen;
876
877     /* we now just need to write the buffer */
878     return ssl3_write_pending(s, type, buf, totlen);
879  err:
880     return -1;
881 }
882
883 /* if s->s3->wbuf.left != 0, we need to call this */
884 int ssl3_write_pending(SSL *s, int type, const unsigned char *buf,
885                        unsigned int len)
886 {
887     int i;
888     SSL3_BUFFER *wb = s->rlayer.wbuf;
889     unsigned int currbuf = 0;
890
891 /* XXXX */
892     if ((s->rlayer.wpend_tot > (int)len)
893         || ((s->rlayer.wpend_buf != buf) &&
894             !(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER))
895         || (s->rlayer.wpend_type != type)) {
896         SSLerr(SSL_F_SSL3_WRITE_PENDING, SSL_R_BAD_WRITE_RETRY);
897         return (-1);
898     }
899
900     for (;;) {
901         /* Loop until we find a buffer we haven't written out yet */
902         if (SSL3_BUFFER_get_left(&wb[currbuf]) == 0
903                 && currbuf < s->rlayer.numwpipes - 1) {
904             currbuf++;
905             continue;
906         }
907         clear_sys_error();
908         if (s->wbio != NULL) {
909             s->rwstate = SSL_WRITING;
910             i = BIO_write(s->wbio,
911                 (char *)&(SSL3_BUFFER_get_buf(&wb[currbuf])[
912                                 SSL3_BUFFER_get_offset(&wb[currbuf])]),
913                 (unsigned int)SSL3_BUFFER_get_left(&wb[currbuf]));
914         } else {
915             SSLerr(SSL_F_SSL3_WRITE_PENDING, SSL_R_BIO_NOT_SET);
916             i = -1;
917         }
918         if (i == SSL3_BUFFER_get_left(&wb[currbuf])) {
919             SSL3_BUFFER_set_left(&wb[currbuf], 0);
920             SSL3_BUFFER_add_offset(&wb[currbuf], i);
921             if (currbuf + 1 < s->rlayer.numwpipes)
922                 continue;
923             s->rwstate = SSL_NOTHING;
924             return (s->rlayer.wpend_ret);
925         } else if (i <= 0) {
926             if (SSL_IS_DTLS(s)) {
927                 /*
928                  * For DTLS, just drop it. That's kind of the whole point in
929                  * using a datagram service
930                  */
931                 SSL3_BUFFER_set_left(&wb[currbuf], 0);
932             }
933             return (i);
934         }
935         SSL3_BUFFER_add_offset(&wb[currbuf], i);
936         SSL3_BUFFER_add_left(&wb[currbuf], -i);
937     }
938 }
939
940 /*-
941  * Return up to 'len' payload bytes received in 'type' records.
942  * 'type' is one of the following:
943  *
944  *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
945  *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
946  *   -  0 (during a shutdown, no data has to be returned)
947  *
948  * If we don't have stored data to work from, read a SSL/TLS record first
949  * (possibly multiple records if we still don't have anything to return).
950  *
951  * This function must handle any surprises the peer may have for us, such as
952  * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
953  * messages are treated as if they were handshake messages *if* the |recd_type|
954  * argument is non NULL.
955  * Also if record payloads contain fragments too small to process, we store
956  * them until there is enough for the respective protocol (the record protocol
957  * may use arbitrary fragmentation and even interleaving):
958  *     Change cipher spec protocol
959  *             just 1 byte needed, no need for keeping anything stored
960  *     Alert protocol
961  *             2 bytes needed (AlertLevel, AlertDescription)
962  *     Handshake protocol
963  *             4 bytes needed (HandshakeType, uint24 length) -- we just have
964  *             to detect unexpected Client Hello and Hello Request messages
965  *             here, anything else is handled by higher layers
966  *     Application data protocol
967  *             none of our business
968  */
969 int ssl3_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
970                     int len, int peek)
971 {
972     int al, i, j, ret;
973     unsigned int n, curr_rec, num_recs, read_bytes;
974     SSL3_RECORD *rr;
975     SSL3_BUFFER *rbuf;
976     void (*cb) (const SSL *ssl, int type2, int val) = NULL;
977
978     rbuf = &s->rlayer.rbuf;
979
980     if (!SSL3_BUFFER_is_initialised(rbuf)) {
981         /* Not initialized yet */
982         if (!ssl3_setup_read_buffer(s))
983             return (-1);
984     }
985
986     if ((type && (type != SSL3_RT_APPLICATION_DATA)
987          && (type != SSL3_RT_HANDSHAKE)) || (peek
988                                              && (type !=
989                                                  SSL3_RT_APPLICATION_DATA))) {
990         SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
991         return -1;
992     }
993
994     if ((type == SSL3_RT_HANDSHAKE) && (s->rlayer.handshake_fragment_len > 0))
995         /* (partially) satisfy request from storage */
996     {
997         unsigned char *src = s->rlayer.handshake_fragment;
998         unsigned char *dst = buf;
999         unsigned int k;
1000
1001         /* peek == 0 */
1002         n = 0;
1003         while ((len > 0) && (s->rlayer.handshake_fragment_len > 0)) {
1004             *dst++ = *src++;
1005             len--;
1006             s->rlayer.handshake_fragment_len--;
1007             n++;
1008         }
1009         /* move any remaining fragment bytes: */
1010         for (k = 0; k < s->rlayer.handshake_fragment_len; k++)
1011             s->rlayer.handshake_fragment[k] = *src++;
1012
1013         if (recvd_type != NULL)
1014             *recvd_type = SSL3_RT_HANDSHAKE;
1015
1016         return n;
1017     }
1018
1019     /*
1020      * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
1021      */
1022
1023     if (!ossl_statem_get_in_handshake(s) && SSL_in_init(s)) {
1024         /* type == SSL3_RT_APPLICATION_DATA */
1025         i = s->handshake_func(s);
1026         if (i < 0)
1027             return (i);
1028         if (i == 0) {
1029             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
1030             return (-1);
1031         }
1032     }
1033  start:
1034     s->rwstate = SSL_NOTHING;
1035
1036     /*-
1037      * For each record 'i' up to |num_recs]
1038      * rr[i].type     - is the type of record
1039      * rr[i].data,    - data
1040      * rr[i].off,     - offset into 'data' for next read
1041      * rr[i].length,  - number of bytes.
1042      */
1043     rr = s->rlayer.rrec;
1044     num_recs = RECORD_LAYER_get_numrpipes(&s->rlayer);
1045
1046     do {
1047         /* get new records if necessary */
1048         if (num_recs == 0) {
1049             ret = ssl3_get_record(s);
1050             if (ret <= 0)
1051                 return (ret);
1052             num_recs = RECORD_LAYER_get_numrpipes(&s->rlayer);
1053             if (num_recs == 0) {
1054                 /* Shouldn't happen */
1055                 al = SSL_AD_INTERNAL_ERROR;
1056                 SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
1057                 goto f_err;
1058             }
1059         }
1060         /* Skip over any records we have already read */
1061         for (curr_rec = 0;
1062              curr_rec < num_recs && SSL3_RECORD_is_read(&rr[curr_rec]);
1063              curr_rec++);
1064         if (curr_rec == num_recs) {
1065             RECORD_LAYER_set_numrpipes(&s->rlayer, 0);
1066             num_recs = 0;
1067             curr_rec = 0;
1068         }
1069     } while (num_recs == 0);
1070     rr = &rr[curr_rec];
1071
1072     /* we now have a packet which can be read and processed */
1073
1074     if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
1075                                    * reset by ssl3_get_finished */
1076         && (SSL3_RECORD_get_type(rr) != SSL3_RT_HANDSHAKE)) {
1077         al = SSL_AD_UNEXPECTED_MESSAGE;
1078         SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
1079         goto f_err;
1080     }
1081
1082     /*
1083      * If the other end has shut down, throw anything we read away (even in
1084      * 'peek' mode)
1085      */
1086     if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1087         SSL3_RECORD_set_length(rr, 0);
1088         s->rwstate = SSL_NOTHING;
1089         return (0);
1090     }
1091
1092     if (type == SSL3_RECORD_get_type(rr)
1093             || (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC
1094                 && type == SSL3_RT_HANDSHAKE && recvd_type != NULL)) {
1095         /*
1096          * SSL3_RT_APPLICATION_DATA or
1097          * SSL3_RT_HANDSHAKE or
1098          * SSL3_RT_CHANGE_CIPHER_SPEC
1099          */
1100         /*
1101          * make sure that we are not getting application data when we are
1102          * doing a handshake for the first time
1103          */
1104         if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
1105             (s->enc_read_ctx == NULL)) {
1106             al = SSL_AD_UNEXPECTED_MESSAGE;
1107             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_APP_DATA_IN_HANDSHAKE);
1108             goto f_err;
1109         }
1110
1111         if (type == SSL3_RT_HANDSHAKE
1112                 && SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC
1113                 && s->rlayer.handshake_fragment_len > 0) {
1114             al = SSL_AD_UNEXPECTED_MESSAGE;
1115             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_CCS_RECEIVED_EARLY);
1116             goto f_err;
1117         }
1118
1119         if (recvd_type != NULL)
1120             *recvd_type = SSL3_RECORD_get_type(rr);
1121
1122         if (len <= 0)
1123             return (len);
1124
1125         read_bytes = 0;
1126         do {
1127             if ((unsigned int)len - read_bytes > SSL3_RECORD_get_length(rr))
1128                 n = SSL3_RECORD_get_length(rr);
1129             else
1130                 n = (unsigned int)len - read_bytes;
1131
1132             memcpy(buf, &(rr->data[rr->off]), n);
1133             buf += n;
1134             if (!peek) {
1135                 SSL3_RECORD_sub_length(rr, n);
1136                 SSL3_RECORD_add_off(rr, n);
1137                 if (SSL3_RECORD_get_length(rr) == 0) {
1138                     s->rlayer.rstate = SSL_ST_READ_HEADER;
1139                     SSL3_RECORD_set_off(rr, 0);
1140                     SSL3_RECORD_set_read(rr);
1141                 }
1142             }
1143             if (SSL3_RECORD_get_length(rr) == 0
1144                 || (peek && n == SSL3_RECORD_get_length(rr))) {
1145                 curr_rec++;
1146                 rr++;
1147             }
1148             read_bytes += n;
1149         } while (type == SSL3_RT_APPLICATION_DATA && curr_rec < num_recs
1150                  && read_bytes < (unsigned int)len);
1151         if (read_bytes == 0) {
1152             /* We must have read empty records. Get more data */
1153             goto start;
1154         }
1155         if (!peek && curr_rec == num_recs
1156                 && (s->mode & SSL_MODE_RELEASE_BUFFERS)
1157                 && SSL3_BUFFER_get_left(rbuf) == 0)
1158             ssl3_release_read_buffer(s);
1159         return read_bytes;
1160     }
1161
1162     /*
1163      * If we get here, then type != rr->type; if we have a handshake message,
1164      * then it was unexpected (Hello Request or Client Hello) or invalid (we
1165      * were actually expecting a CCS).
1166      */
1167
1168     if (rr->type == SSL3_RT_HANDSHAKE && type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1169         al = SSL_AD_UNEXPECTED_MESSAGE;
1170         SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_MESSAGE);
1171         goto f_err;
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                 goto start;     /* fragment was too small */
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_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
1320         goto start;
1321     }
1322     if (s->rlayer.alert_fragment_len >= 2) {
1323         int alert_level = s->rlayer.alert_fragment[0];
1324         int alert_descr = s->rlayer.alert_fragment[1];
1325
1326         s->rlayer.alert_fragment_len = 0;
1327
1328         if (s->msg_callback)
1329             s->msg_callback(0, s->version, SSL3_RT_ALERT,
1330                             s->rlayer.alert_fragment, 2, s,
1331                             s->msg_callback_arg);
1332
1333         if (s->info_callback != NULL)
1334             cb = s->info_callback;
1335         else if (s->ctx->info_callback != NULL)
1336             cb = s->ctx->info_callback;
1337
1338         if (cb != NULL) {
1339             j = (alert_level << 8) | alert_descr;
1340             cb(s, SSL_CB_READ_ALERT, j);
1341         }
1342
1343         if (alert_level == SSL3_AL_WARNING) {
1344             s->s3->warn_alert = alert_descr;
1345             if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
1346                 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1347                 return (0);
1348             }
1349             /*
1350              * This is a warning but we receive it if we requested
1351              * renegotiation and the peer denied it. Terminate with a fatal
1352              * alert because if application tried to renegotiate it
1353              * presumably had a good reason and expects it to succeed. In
1354              * future we might have a renegotiation where we don't care if
1355              * the peer refused it where we carry on.
1356              */
1357             else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
1358                 al = SSL_AD_HANDSHAKE_FAILURE;
1359                 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_NO_RENEGOTIATION);
1360                 goto f_err;
1361             }
1362 #ifdef SSL_AD_MISSING_SRP_USERNAME
1363             else if (alert_descr == SSL_AD_MISSING_SRP_USERNAME)
1364                 return (0);
1365 #endif
1366         } else if (alert_level == SSL3_AL_FATAL) {
1367             char tmp[16];
1368
1369             s->rwstate = SSL_NOTHING;
1370             s->s3->fatal_alert = alert_descr;
1371             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr);
1372             BIO_snprintf(tmp, sizeof tmp, "%d", alert_descr);
1373             ERR_add_error_data(2, "SSL alert number ", tmp);
1374             s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1375             SSL_CTX_remove_session(s->session_ctx, s->session);
1376             return (0);
1377         } else {
1378             al = SSL_AD_ILLEGAL_PARAMETER;
1379             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNKNOWN_ALERT_TYPE);
1380             goto f_err;
1381         }
1382
1383         goto start;
1384     }
1385
1386     if (s->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a
1387                                             * shutdown */
1388         s->rwstate = SSL_NOTHING;
1389         SSL3_RECORD_set_length(rr, 0);
1390         return (0);
1391     }
1392
1393     if (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC) {
1394         al = SSL_AD_UNEXPECTED_MESSAGE;
1395         SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_CCS_RECEIVED_EARLY);
1396         goto f_err;
1397     }
1398
1399     /*
1400      * Unexpected handshake message (Client Hello, or protocol violation)
1401      */
1402     if ((s->rlayer.handshake_fragment_len >= 4)
1403             && !ossl_statem_get_in_handshake(s)) {
1404         if (SSL_is_init_finished(s) &&
1405             !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) {
1406             ossl_statem_set_in_init(s, 1);
1407             s->renegotiate = 1;
1408             s->new_session = 1;
1409         }
1410         i = s->handshake_func(s);
1411         if (i < 0)
1412             return (i);
1413         if (i == 0) {
1414             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
1415             return (-1);
1416         }
1417
1418         if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1419             if (SSL3_BUFFER_get_left(rbuf) == 0) {
1420                 /* no read-ahead left? */
1421                 BIO *bio;
1422                 /*
1423                  * In the case where we try to read application data, but we
1424                  * trigger an SSL handshake, we return -1 with the retry
1425                  * option set.  Otherwise renegotiation may cause nasty
1426                  * problems in the blocking world
1427                  */
1428                 s->rwstate = SSL_READING;
1429                 bio = SSL_get_rbio(s);
1430                 BIO_clear_retry_flags(bio);
1431                 BIO_set_retry_read(bio);
1432                 return (-1);
1433             }
1434         }
1435         goto start;
1436     }
1437
1438     switch (SSL3_RECORD_get_type(rr)) {
1439     default:
1440         /*
1441          * TLS up to v1.1 just ignores unknown message types: TLS v1.2 give
1442          * an unexpected message alert.
1443          */
1444         if (s->version >= TLS1_VERSION && s->version <= TLS1_1_VERSION) {
1445             SSL3_RECORD_set_length(rr, 0);
1446             goto start;
1447         }
1448         al = SSL_AD_UNEXPECTED_MESSAGE;
1449         SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
1450         goto f_err;
1451     case SSL3_RT_CHANGE_CIPHER_SPEC:
1452     case SSL3_RT_ALERT:
1453     case SSL3_RT_HANDSHAKE:
1454         /*
1455          * we already handled all of these, with the possible exception of
1456          * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
1457          * that should not happen when type != rr->type
1458          */
1459         al = SSL_AD_UNEXPECTED_MESSAGE;
1460         SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
1461         goto f_err;
1462     case SSL3_RT_APPLICATION_DATA:
1463         /*
1464          * At this point, we were expecting handshake data, but have
1465          * application data.  If the library was running inside ssl3_read()
1466          * (i.e. in_read_app_data is set) and it makes sense to read
1467          * application data at this point (session renegotiation not yet
1468          * started), we will indulge it.
1469          */
1470         if (ossl_statem_app_data_allowed(s)) {
1471             s->s3->in_read_app_data = 2;
1472             return (-1);
1473         } else {
1474             al = SSL_AD_UNEXPECTED_MESSAGE;
1475             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
1476             goto f_err;
1477         }
1478     }
1479     /* not reached */
1480
1481  f_err:
1482     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1483     return (-1);
1484 }
1485
1486 void ssl3_record_sequence_update(unsigned char *seq)
1487 {
1488     int i;
1489
1490     for (i = 7; i >= 0; i--) {
1491         ++seq[i];
1492         if (seq[i] != 0)
1493             break;
1494     }
1495 }
1496
1497 /*
1498  * Returns true if the current rrec was sent in SSLv2 backwards compatible
1499  * format and false otherwise.
1500  */
1501 int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl)
1502 {
1503     return SSL3_RECORD_is_sslv2_record(&rl->rrec[0]);
1504 }
1505
1506 /*
1507  * Returns the length in bytes of the current rrec
1508  */
1509 unsigned int RECORD_LAYER_get_rrec_length(RECORD_LAYER *rl)
1510 {
1511     return SSL3_RECORD_get_length(&rl->rrec[0]);
1512 }