Remove some more redundant TODO(RECLAYER) comments
[openssl.git] / ssl / record / rec_layer_s3.c
1 /*
2  * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (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 #include "../ssl_local.h"
14 #include <openssl/evp.h>
15 #include <openssl/buffer.h>
16 #include <openssl/rand.h>
17 #include <openssl/core_names.h>
18 #include "record_local.h"
19 #include "internal/packet.h"
20
21 #if     defined(OPENSSL_SMALL_FOOTPRINT) || \
22         !(      defined(AES_ASM) &&     ( \
23                 defined(__x86_64)       || defined(__x86_64__)  || \
24                 defined(_M_AMD64)       || defined(_M_X64)      ) \
25         )
26 # undef EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
27 # define EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK 0
28 #endif
29
30 void RECORD_LAYER_init(RECORD_LAYER *rl, SSL_CONNECTION *s)
31 {
32     rl->s = s;
33     RECORD_LAYER_set_first_record(&s->rlayer);
34     SSL3_RECORD_clear(rl->rrec, SSL_MAX_PIPELINES);
35 }
36
37 void RECORD_LAYER_clear(RECORD_LAYER *rl)
38 {
39     rl->rstate = SSL_ST_READ_HEADER;
40
41     /*
42      * Do I need to clear read_ahead? As far as I can tell read_ahead did not
43      * previously get reset by SSL_clear...so I'll keep it that way..but is
44      * that right?
45      */
46
47     rl->packet = NULL;
48     rl->packet_length = 0;
49     rl->wnum = 0;
50     memset(rl->handshake_fragment, 0, sizeof(rl->handshake_fragment));
51     rl->handshake_fragment_len = 0;
52     rl->wpend_tot = 0;
53     rl->wpend_type = 0;
54     rl->wpend_ret = 0;
55     rl->wpend_buf = NULL;
56
57     SSL3_BUFFER_clear(&rl->rbuf);
58     ssl3_release_write_buffer(rl->s);
59     rl->numrpipes = 0;
60     SSL3_RECORD_clear(rl->rrec, SSL_MAX_PIPELINES);
61
62     RECORD_LAYER_reset_read_sequence(rl);
63     RECORD_LAYER_reset_write_sequence(rl);
64
65     if (rl->d)
66         DTLS_RECORD_LAYER_clear(rl);
67 }
68
69 void RECORD_LAYER_release(RECORD_LAYER *rl)
70 {
71     if (rl->numwpipes > 0)
72         ssl3_release_write_buffer(rl->s);
73     SSL3_RECORD_release(rl->rrec, SSL_MAX_PIPELINES);
74 }
75
76 /* Checks if we have unprocessed read ahead data pending */
77 int RECORD_LAYER_read_pending(const RECORD_LAYER *rl)
78 {
79     return rl->s->rrlmethod->unprocessed_read_pending(rl->s->rrl);
80 }
81
82 /* Checks if we have decrypted unread record data pending */
83 int RECORD_LAYER_processed_read_pending(const RECORD_LAYER *rl)
84 {
85     return (rl->curr_rec < rl->num_recs)
86            || rl->s->rrlmethod->processed_read_pending(rl->s->rrl);
87 }
88
89 int RECORD_LAYER_write_pending(const RECORD_LAYER *rl)
90 {
91     return (rl->numwpipes > 0)
92         && SSL3_BUFFER_get_left(&rl->wbuf[rl->numwpipes - 1]) != 0;
93 }
94
95 void RECORD_LAYER_reset_read_sequence(RECORD_LAYER *rl)
96 {
97     memset(rl->read_sequence, 0, sizeof(rl->read_sequence));
98 }
99
100 void RECORD_LAYER_reset_write_sequence(RECORD_LAYER *rl)
101 {
102     memset(rl->write_sequence, 0, sizeof(rl->write_sequence));
103 }
104
105 size_t ssl3_pending(const SSL *s)
106 {
107     size_t i, num = 0;
108     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
109
110     if (sc == NULL)
111         return 0;
112
113     if (SSL_CONNECTION_IS_DTLS(sc)) {
114         TLS_RECORD *rdata;
115         pitem *item, *iter;
116
117         iter = pqueue_iterator(sc->rlayer.d->buffered_app_data.q);
118         while ((item = pqueue_next(&iter)) != NULL) {
119             rdata = item->data;
120             num += rdata->length;
121         }
122     }
123
124     for (i = 0; i < sc->rlayer.num_recs; i++) {
125         if (sc->rlayer.tlsrecs[i].type != SSL3_RT_APPLICATION_DATA)
126             return num;
127         num += sc->rlayer.tlsrecs[i].length;
128     }
129
130     num += sc->rrlmethod->app_data_pending(sc->rrl);
131
132     return num;
133 }
134
135 void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len)
136 {
137     ctx->default_read_buf_len = len;
138 }
139
140 void SSL_set_default_read_buffer_len(SSL *s, size_t len)
141 {
142     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
143
144     if (sc == NULL)
145         return;
146     sc->default_read_buf_len = len;
147 }
148
149 const char *SSL_rstate_string_long(const SSL *s)
150 {
151     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
152
153     if (sc == NULL)
154         return NULL;
155
156     switch (sc->rlayer.rstate) {
157     case SSL_ST_READ_HEADER:
158         return "read header";
159     case SSL_ST_READ_BODY:
160         return "read body";
161     case SSL_ST_READ_DONE:
162         return "read done";
163     default:
164         return "unknown";
165     }
166 }
167
168 const char *SSL_rstate_string(const SSL *s)
169 {
170     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
171
172     if (sc == NULL)
173         return NULL;
174
175     switch (sc->rlayer.rstate) {
176     case SSL_ST_READ_HEADER:
177         return "RH";
178     case SSL_ST_READ_BODY:
179         return "RB";
180     case SSL_ST_READ_DONE:
181         return "RD";
182     default:
183         return "unknown";
184     }
185 }
186
187
188 /*
189  * Call this to write data in records of type 'type' It will return <= 0 if
190  * not all data has been sent or non-blocking IO.
191  */
192 int ssl3_write_bytes(SSL *ssl, int type, const void *buf_, size_t len,
193                      size_t *written)
194 {
195     const unsigned char *buf = buf_;
196     size_t tot;
197     size_t n, max_send_fragment, split_send_fragment, maxpipes;
198 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
199     size_t nw;
200 #endif
201     SSL3_BUFFER *wb;
202     int i;
203     size_t tmpwrit;
204     SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
205
206     if (s == NULL)
207         return -1;
208
209     wb = &s->rlayer.wbuf[0];
210     s->rwstate = SSL_NOTHING;
211     tot = s->rlayer.wnum;
212     /*
213      * ensure that if we end up with a smaller value of data to write out
214      * than the original len from a write which didn't complete for
215      * non-blocking I/O and also somehow ended up avoiding the check for
216      * this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be
217      * possible to end up with (len-tot) as a large number that will then
218      * promptly send beyond the end of the users buffer ... so we trap and
219      * report the error in a way the user will notice
220      */
221     if ((len < s->rlayer.wnum)
222         || ((wb->left != 0) && (len < (s->rlayer.wnum + s->rlayer.wpend_tot)))) {
223         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_LENGTH);
224         return -1;
225     }
226
227     if (s->early_data_state == SSL_EARLY_DATA_WRITING
228             && !ossl_early_data_count_ok(s, len, 0, 1)) {
229         /* SSLfatal() already called */
230         return -1;
231     }
232
233     s->rlayer.wnum = 0;
234
235     /*
236      * If we are supposed to be sending a KeyUpdate or NewSessionTicket then go
237      * into init unless we have writes pending - in which case we should finish
238      * doing that first.
239      */
240     if (wb->left == 0 && (s->key_update != SSL_KEY_UPDATE_NONE
241                           || s->ext.extra_tickets_expected > 0))
242         ossl_statem_set_in_init(s, 1);
243
244     /*
245      * When writing early data on the server side we could be "in_init" in
246      * between receiving the EoED and the CF - but we don't want to handle those
247      * messages yet.
248      */
249     if (SSL_in_init(ssl) && !ossl_statem_get_in_handshake(s)
250             && s->early_data_state != SSL_EARLY_DATA_UNAUTH_WRITING) {
251         i = s->handshake_func(ssl);
252         /* SSLfatal() already called */
253         if (i < 0)
254             return i;
255         if (i == 0) {
256             return -1;
257         }
258     }
259
260     /*
261      * first check if there is a SSL3_BUFFER still being written out.  This
262      * will happen with non blocking IO
263      */
264     if (wb->left != 0) {
265         /* SSLfatal() already called if appropriate */
266         i = ssl3_write_pending(s, type, &buf[tot], s->rlayer.wpend_tot,
267                                &tmpwrit);
268         if (i <= 0) {
269             /* XXX should we ssl3_release_write_buffer if i<0? */
270             s->rlayer.wnum = tot;
271             return i;
272         }
273         tot += tmpwrit;               /* this might be last fragment */
274     }
275 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
276     /*
277      * Depending on platform multi-block can deliver several *times*
278      * better performance. Downside is that it has to allocate
279      * jumbo buffer to accommodate up to 8 records, but the
280      * compromise is considered worthy.
281      */
282     if (type == SSL3_RT_APPLICATION_DATA
283             && len >= 4 * (max_send_fragment = ssl_get_max_send_fragment(s))
284             && s->compress == NULL
285             && s->msg_callback == NULL
286             && !SSL_WRITE_ETM(s)
287             && SSL_USE_EXPLICIT_IV(s)
288             && !BIO_get_ktls_send(s->wbio)
289             && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx))
290                 & EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK) != 0) {
291         unsigned char aad[13];
292         EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param;
293         size_t packlen;
294         int packleni;
295
296         /* minimize address aliasing conflicts */
297         if ((max_send_fragment & 0xfff) == 0)
298             max_send_fragment -= 512;
299
300         if (tot == 0 || wb->buf == NULL) { /* allocate jumbo buffer */
301             ssl3_release_write_buffer(s);
302
303             packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
304                                           EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE,
305                                           (int)max_send_fragment, NULL);
306
307             if (len >= 8 * max_send_fragment)
308                 packlen *= 8;
309             else
310                 packlen *= 4;
311
312             if (!ssl3_setup_write_buffer(s, 1, packlen)) {
313                 /* SSLfatal() already called */
314                 return -1;
315             }
316         } else if (tot == len) { /* done? */
317             /* free jumbo buffer */
318             ssl3_release_write_buffer(s);
319             *written = tot;
320             return 1;
321         }
322
323         n = (len - tot);
324         for (;;) {
325             if (n < 4 * max_send_fragment) {
326                 /* free jumbo buffer */
327                 ssl3_release_write_buffer(s);
328                 break;
329             }
330
331             if (s->s3.alert_dispatch) {
332                 i = ssl->method->ssl_dispatch_alert(ssl);
333                 if (i <= 0) {
334                     /* SSLfatal() already called if appropriate */
335                     s->rlayer.wnum = tot;
336                     return i;
337                 }
338             }
339
340             if (n >= 8 * max_send_fragment)
341                 nw = max_send_fragment * (mb_param.interleave = 8);
342             else
343                 nw = max_send_fragment * (mb_param.interleave = 4);
344
345             memcpy(aad, s->rlayer.write_sequence, 8);
346             aad[8] = type;
347             aad[9] = (unsigned char)(s->version >> 8);
348             aad[10] = (unsigned char)(s->version);
349             aad[11] = 0;
350             aad[12] = 0;
351             mb_param.out = NULL;
352             mb_param.inp = aad;
353             mb_param.len = nw;
354
355             packleni = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
356                                           EVP_CTRL_TLS1_1_MULTIBLOCK_AAD,
357                                           sizeof(mb_param), &mb_param);
358             packlen = (size_t)packleni;
359             if (packleni <= 0 || packlen > wb->len) { /* never happens */
360                 /* free jumbo buffer */
361                 ssl3_release_write_buffer(s);
362                 break;
363             }
364
365             mb_param.out = wb->buf;
366             mb_param.inp = &buf[tot];
367             mb_param.len = nw;
368
369             if (EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
370                                     EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT,
371                                     sizeof(mb_param), &mb_param) <= 0)
372                 return -1;
373
374             s->rlayer.write_sequence[7] += mb_param.interleave;
375             if (s->rlayer.write_sequence[7] < mb_param.interleave) {
376                 int j = 6;
377                 while (j >= 0 && (++s->rlayer.write_sequence[j--]) == 0) ;
378             }
379
380             wb->offset = 0;
381             wb->left = packlen;
382
383             s->rlayer.wpend_tot = nw;
384             s->rlayer.wpend_buf = &buf[tot];
385             s->rlayer.wpend_type = type;
386             s->rlayer.wpend_ret = nw;
387
388             i = ssl3_write_pending(s, type, &buf[tot], nw, &tmpwrit);
389             if (i <= 0) {
390                 /* SSLfatal() already called if appropriate */
391                 if (i < 0 && (!s->wbio || !BIO_should_retry(s->wbio))) {
392                     /* free jumbo buffer */
393                     ssl3_release_write_buffer(s);
394                 }
395                 s->rlayer.wnum = tot;
396                 return i;
397             }
398             if (tmpwrit == n) {
399                 /* free jumbo buffer */
400                 ssl3_release_write_buffer(s);
401                 *written = tot + tmpwrit;
402                 return 1;
403             }
404             n -= tmpwrit;
405             tot += tmpwrit;
406         }
407     } else
408 #endif  /* !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK */
409     if (tot == len) {           /* done? */
410         if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_CONNECTION_IS_DTLS(s))
411             ssl3_release_write_buffer(s);
412
413         *written = tot;
414         return 1;
415     }
416
417     n = (len - tot);
418
419     max_send_fragment = ssl_get_max_send_fragment(s);
420     split_send_fragment = ssl_get_split_send_fragment(s);
421     /*
422      * If max_pipelines is 0 then this means "undefined" and we default to
423      * 1 pipeline. Similarly if the cipher does not support pipelined
424      * processing then we also only use 1 pipeline, or if we're not using
425      * explicit IVs
426      */
427     maxpipes = s->max_pipelines;
428     if (maxpipes > SSL_MAX_PIPELINES) {
429         /*
430          * We should have prevented this when we set max_pipelines so we
431          * shouldn't get here
432          */
433         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
434         return -1;
435     }
436     if (maxpipes == 0
437         || s->enc_write_ctx == NULL
438         || (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx))
439             & EVP_CIPH_FLAG_PIPELINE) == 0
440         || !SSL_USE_EXPLICIT_IV(s))
441         maxpipes = 1;
442     if (max_send_fragment == 0
443             || split_send_fragment == 0
444             || split_send_fragment > max_send_fragment) {
445         /*
446          * We should have prevented this when we set/get the split and max send
447          * fragments so we shouldn't get here
448          */
449         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
450         return -1;
451     }
452
453     for (;;) {
454         size_t pipelens[SSL_MAX_PIPELINES], tmppipelen, remain;
455         size_t numpipes, j;
456
457         if (n == 0)
458             numpipes = 1;
459         else
460             numpipes = ((n - 1) / split_send_fragment) + 1;
461         if (numpipes > maxpipes)
462             numpipes = maxpipes;
463
464         if (n / numpipes >= max_send_fragment) {
465             /*
466              * We have enough data to completely fill all available
467              * pipelines
468              */
469             for (j = 0; j < numpipes; j++) {
470                 pipelens[j] = max_send_fragment;
471             }
472         } else {
473             /* We can partially fill all available pipelines */
474             tmppipelen = n / numpipes;
475             remain = n % numpipes;
476             for (j = 0; j < numpipes; j++) {
477                 pipelens[j] = tmppipelen;
478                 if (j < remain)
479                     pipelens[j]++;
480             }
481         }
482
483         i = do_ssl3_write(s, type, &(buf[tot]), pipelens, numpipes, 0,
484                           &tmpwrit);
485         if (i <= 0) {
486             /* SSLfatal() already called if appropriate */
487             /* XXX should we ssl3_release_write_buffer if i<0? */
488             s->rlayer.wnum = tot;
489             return i;
490         }
491
492         if (tmpwrit == n ||
493             (type == SSL3_RT_APPLICATION_DATA &&
494              (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
495             /*
496              * next chunk of data should get another prepended empty fragment
497              * in ciphersuites with known-IV weakness:
498              */
499             s->s3.empty_fragment_done = 0;
500
501             if (tmpwrit == n
502                     && (s->mode & SSL_MODE_RELEASE_BUFFERS) != 0
503                     && !SSL_CONNECTION_IS_DTLS(s))
504                 ssl3_release_write_buffer(s);
505
506             *written = tot + tmpwrit;
507             return 1;
508         }
509
510         n -= tmpwrit;
511         tot += tmpwrit;
512     }
513 }
514
515 int do_ssl3_write(SSL_CONNECTION *s, int type, const unsigned char *buf,
516                   size_t *pipelens, size_t numpipes,
517                   int create_empty_fragment, size_t *written)
518 {
519     WPACKET pkt[SSL_MAX_PIPELINES];
520     SSL3_RECORD wr[SSL_MAX_PIPELINES];
521     WPACKET *thispkt;
522     SSL3_RECORD *thiswr;
523     unsigned char *recordstart;
524     int i, mac_size, clear = 0;
525     size_t prefix_len = 0;
526     int eivlen = 0;
527     size_t align = 0;
528     SSL3_BUFFER *wb;
529     SSL_SESSION *sess;
530     size_t totlen = 0, len, wpinited = 0;
531     size_t j;
532     int using_ktls;
533     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
534
535     for (j = 0; j < numpipes; j++)
536         totlen += pipelens[j];
537     /*
538      * first check if there is a SSL3_BUFFER still being written out.  This
539      * will happen with non blocking IO
540      */
541     if (RECORD_LAYER_write_pending(&s->rlayer)) {
542         /* Calls SSLfatal() as required */
543         return ssl3_write_pending(s, type, buf, totlen, written);
544     }
545
546     /* If we have an alert to send, lets send it */
547     if (s->s3.alert_dispatch) {
548         i = ssl->method->ssl_dispatch_alert(ssl);
549         if (i <= 0) {
550             /* SSLfatal() already called if appropriate */
551             return i;
552         }
553         /* if it went, fall through and send more stuff */
554     }
555
556     if (s->rlayer.numwpipes < numpipes) {
557         if (!ssl3_setup_write_buffer(s, numpipes, 0)) {
558             /* SSLfatal() already called */
559             return -1;
560         }
561     }
562
563     if (totlen == 0 && !create_empty_fragment)
564         return 0;
565
566     sess = s->session;
567
568     if ((sess == NULL)
569             || (s->enc_write_ctx == NULL)
570             || (EVP_MD_CTX_get0_md(s->write_hash) == NULL)) {
571         clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */
572         mac_size = 0;
573     } else {
574         mac_size = EVP_MD_CTX_get_size(s->write_hash);
575         if (mac_size < 0) {
576             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
577             goto err;
578         }
579     }
580
581     /*
582      * 'create_empty_fragment' is true only when this function calls itself
583      */
584     if (!clear && !create_empty_fragment && !s->s3.empty_fragment_done) {
585         /*
586          * countermeasure against known-IV weakness in CBC ciphersuites (see
587          * http://www.openssl.org/~bodo/tls-cbc.txt)
588          */
589
590         if (s->s3.need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) {
591             /*
592              * recursive function call with 'create_empty_fragment' set; this
593              * prepares and buffers the data for an empty fragment (these
594              * 'prefix_len' bytes are sent out later together with the actual
595              * payload)
596              */
597             size_t tmppipelen = 0;
598             int ret;
599
600             ret = do_ssl3_write(s, type, buf, &tmppipelen, 1, 1, &prefix_len);
601             if (ret <= 0) {
602                 /* SSLfatal() already called if appropriate */
603                 goto err;
604             }
605
606             if (prefix_len >
607                 (SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD)) {
608                 /* insufficient space */
609                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
610                 goto err;
611             }
612         }
613
614         s->s3.empty_fragment_done = 1;
615     }
616
617     using_ktls = BIO_get_ktls_send(s->wbio);
618     if (using_ktls) {
619         /*
620          * ktls doesn't modify the buffer, but to avoid a warning we need to
621          * discard the const qualifier.
622          * This doesn't leak memory because the buffers have been released when
623          * switching to ktls.
624          */
625         SSL3_BUFFER_set_buf(&s->rlayer.wbuf[0], (unsigned char *)buf);
626         SSL3_BUFFER_set_offset(&s->rlayer.wbuf[0], 0);
627         SSL3_BUFFER_set_app_buffer(&s->rlayer.wbuf[0], 1);
628         goto wpacket_init_complete;
629     }
630
631     if (create_empty_fragment) {
632         wb = &s->rlayer.wbuf[0];
633 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
634         /*
635          * extra fragment would be couple of cipher blocks, which would be
636          * multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real
637          * payload, then we can just pretend we simply have two headers.
638          */
639         align = (size_t)SSL3_BUFFER_get_buf(wb) + 2 * SSL3_RT_HEADER_LENGTH;
640         align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
641 #endif
642         SSL3_BUFFER_set_offset(wb, align);
643         if (!WPACKET_init_static_len(&pkt[0], SSL3_BUFFER_get_buf(wb),
644                                      SSL3_BUFFER_get_len(wb), 0)
645                 || !WPACKET_allocate_bytes(&pkt[0], align, NULL)) {
646             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
647             goto err;
648         }
649         wpinited = 1;
650     } else if (prefix_len) {
651         wb = &s->rlayer.wbuf[0];
652         if (!WPACKET_init_static_len(&pkt[0],
653                                      SSL3_BUFFER_get_buf(wb),
654                                      SSL3_BUFFER_get_len(wb), 0)
655                 || !WPACKET_allocate_bytes(&pkt[0], SSL3_BUFFER_get_offset(wb)
656                                                     + prefix_len, NULL)) {
657             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
658             goto err;
659         }
660         wpinited = 1;
661     } else {
662         for (j = 0; j < numpipes; j++) {
663             thispkt = &pkt[j];
664
665             wb = &s->rlayer.wbuf[j];
666 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
667             align = (size_t)SSL3_BUFFER_get_buf(wb) + SSL3_RT_HEADER_LENGTH;
668             align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
669 #endif
670             SSL3_BUFFER_set_offset(wb, align);
671             if (!WPACKET_init_static_len(thispkt, SSL3_BUFFER_get_buf(wb),
672                                          SSL3_BUFFER_get_len(wb), 0)
673                     || !WPACKET_allocate_bytes(thispkt, align, NULL)) {
674                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
675                 goto err;
676             }
677             wpinited++;
678         }
679     }
680
681     /* Explicit IV length, block ciphers appropriate version flag */
682     if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s)
683         && !SSL_CONNECTION_TREAT_AS_TLS13(s)) {
684         int mode = EVP_CIPHER_CTX_get_mode(s->enc_write_ctx);
685         if (mode == EVP_CIPH_CBC_MODE) {
686             eivlen = EVP_CIPHER_CTX_get_iv_length(s->enc_write_ctx);
687             if (eivlen < 0) {
688                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
689                 goto err;
690             }
691             if (eivlen <= 1)
692                 eivlen = 0;
693         } else if (mode == EVP_CIPH_GCM_MODE) {
694             /* Need explicit part of IV for GCM mode */
695             eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
696         } else if (mode == EVP_CIPH_CCM_MODE) {
697             eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;
698         }
699     }
700
701  wpacket_init_complete:
702
703     totlen = 0;
704     /* Clear our SSL3_RECORD structures */
705     memset(wr, 0, sizeof(wr));
706     for (j = 0; j < numpipes; j++) {
707         unsigned int version = (s->version == TLS1_3_VERSION) ? TLS1_2_VERSION
708                                                               : s->version;
709         unsigned char *compressdata = NULL;
710         size_t maxcomplen;
711         unsigned int rectype;
712
713         thispkt = &pkt[j];
714         thiswr = &wr[j];
715
716         /*
717          * In TLSv1.3, once encrypting, we always use application data for the
718          * record type
719          */
720         if (SSL_CONNECTION_TREAT_AS_TLS13(s)
721                 && s->enc_write_ctx != NULL
722                 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
723                     || type != SSL3_RT_ALERT))
724             rectype = SSL3_RT_APPLICATION_DATA;
725         else
726             rectype = type;
727         SSL3_RECORD_set_type(thiswr, rectype);
728
729         /*
730          * Some servers hang if initial client hello is larger than 256 bytes
731          * and record version number > TLS 1.0
732          */
733         if (SSL_get_state(ssl) == TLS_ST_CW_CLNT_HELLO
734                 && !s->renegotiate
735                 && TLS1_get_version(ssl) > TLS1_VERSION
736                 && s->hello_retry_request == SSL_HRR_NONE)
737             version = TLS1_VERSION;
738         SSL3_RECORD_set_rec_version(thiswr, version);
739
740         maxcomplen = pipelens[j];
741         if (s->compress != NULL)
742             maxcomplen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
743
744         /*
745          * When using offload kernel will write the header.
746          * Otherwise write the header now
747          */
748         if (!using_ktls
749                 && (!WPACKET_put_bytes_u8(thispkt, rectype)
750                 || !WPACKET_put_bytes_u16(thispkt, version)
751                 || !WPACKET_start_sub_packet_u16(thispkt)
752                 || (eivlen > 0
753                     && !WPACKET_allocate_bytes(thispkt, eivlen, NULL))
754                 || (maxcomplen > 0
755                     && !WPACKET_reserve_bytes(thispkt, maxcomplen,
756                                               &compressdata)))) {
757             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
758             goto err;
759         }
760
761         /* lets setup the record stuff. */
762         SSL3_RECORD_set_data(thiswr, compressdata);
763         SSL3_RECORD_set_length(thiswr, pipelens[j]);
764         SSL3_RECORD_set_input(thiswr, (unsigned char *)&buf[totlen]);
765         totlen += pipelens[j];
766
767         /*
768          * we now 'read' from thiswr->input, thiswr->length bytes into
769          * thiswr->data
770          */
771
772         /* first we compress */
773         if (s->compress != NULL) {
774             if (!ssl3_do_compress(s, thiswr)
775                     || !WPACKET_allocate_bytes(thispkt, thiswr->length, NULL)) {
776                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COMPRESSION_FAILURE);
777                 goto err;
778             }
779         } else {
780             if (using_ktls) {
781                 SSL3_RECORD_reset_data(&wr[j]);
782             } else {
783                 if (!WPACKET_memcpy(thispkt, thiswr->input, thiswr->length)) {
784                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
785                     goto err;
786                 }
787                 SSL3_RECORD_reset_input(&wr[j]);
788             }
789         }
790
791         if (SSL_CONNECTION_TREAT_AS_TLS13(s)
792                 && !using_ktls
793                 && s->enc_write_ctx != NULL
794                 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
795                     || type != SSL3_RT_ALERT)) {
796             size_t rlen, max_send_fragment;
797
798             if (!WPACKET_put_bytes_u8(thispkt, type)) {
799                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
800                 goto err;
801             }
802             SSL3_RECORD_add_length(thiswr, 1);
803
804             /* Add TLS1.3 padding */
805             max_send_fragment = ssl_get_max_send_fragment(s);
806             rlen = SSL3_RECORD_get_length(thiswr);
807             if (rlen < max_send_fragment) {
808                 size_t padding = 0;
809                 size_t max_padding = max_send_fragment - rlen;
810                 if (s->record_padding_cb != NULL) {
811                     padding = s->record_padding_cb(ssl, type, rlen, s->record_padding_arg);
812                 } else if (s->block_padding > 0) {
813                     size_t mask = s->block_padding - 1;
814                     size_t remainder;
815
816                     /* optimize for power of 2 */
817                     if ((s->block_padding & mask) == 0)
818                         remainder = rlen & mask;
819                     else
820                         remainder = rlen % s->block_padding;
821                     /* don't want to add a block of padding if we don't have to */
822                     if (remainder == 0)
823                         padding = 0;
824                     else
825                         padding = s->block_padding - remainder;
826                 }
827                 if (padding > 0) {
828                     /* do not allow the record to exceed max plaintext length */
829                     if (padding > max_padding)
830                         padding = max_padding;
831                     if (!WPACKET_memset(thispkt, 0, padding)) {
832                         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
833                                  ERR_R_INTERNAL_ERROR);
834                         goto err;
835                     }
836                     SSL3_RECORD_add_length(thiswr, padding);
837                 }
838             }
839         }
840
841         /*
842          * we should still have the output to thiswr->data and the input from
843          * wr->input. Length should be thiswr->length. thiswr->data still points
844          * in the wb->buf
845          */
846
847         if (!using_ktls && !SSL_WRITE_ETM(s) && mac_size != 0) {
848             unsigned char *mac;
849
850             if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
851                     || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
852                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
853                 goto err;
854             }
855         }
856
857         /*
858          * Reserve some bytes for any growth that may occur during encryption.
859          * This will be at most one cipher block or the tag length if using
860          * AEAD. SSL_RT_MAX_CIPHER_BLOCK_SIZE covers either case.
861          */
862         if (!using_ktls) {
863             if (!WPACKET_reserve_bytes(thispkt,
864                                         SSL_RT_MAX_CIPHER_BLOCK_SIZE,
865                                         NULL)
866                 /*
867                  * We also need next the amount of bytes written to this
868                  * sub-packet
869                  */
870                 || !WPACKET_get_length(thispkt, &len)) {
871             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
872             goto err;
873             }
874
875             /* Get a pointer to the start of this record excluding header */
876             recordstart = WPACKET_get_curr(thispkt) - len;
877             SSL3_RECORD_set_data(thiswr, recordstart);
878             SSL3_RECORD_reset_input(thiswr);
879             SSL3_RECORD_set_length(thiswr, len);
880         }
881     }
882
883     if (s->statem.enc_write_state == ENC_WRITE_STATE_WRITE_PLAIN_ALERTS) {
884         /*
885          * We haven't actually negotiated the version yet, but we're trying to
886          * send early data - so we need to use the tls13enc function.
887          */
888         if (tls13_enc(s, wr, numpipes, 1, NULL, mac_size) < 1) {
889             if (!ossl_statem_in_error(s)) {
890                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
891             }
892             goto err;
893         }
894     } else {
895         if (!using_ktls) {
896             if (ssl->method->ssl3_enc->enc(s, wr, numpipes, 1, NULL,
897                                          mac_size) < 1) {
898                 if (!ossl_statem_in_error(s)) {
899                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
900                 }
901                 goto err;
902             }
903         }
904     }
905
906     for (j = 0; j < numpipes; j++) {
907         size_t origlen;
908
909         thispkt = &pkt[j];
910         thiswr = &wr[j];
911
912         if (using_ktls)
913             goto mac_done;
914
915         /* Allocate bytes for the encryption overhead */
916         if (!WPACKET_get_length(thispkt, &origlen)
917                    /* Encryption should never shrink the data! */
918                 || origlen > thiswr->length
919                 || (thiswr->length > origlen
920                     && !WPACKET_allocate_bytes(thispkt,
921                                                thiswr->length - origlen,
922                                                NULL))) {
923             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
924             goto err;
925         }
926         if (SSL_WRITE_ETM(s) && mac_size != 0) {
927             unsigned char *mac;
928
929             if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
930                     || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
931                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
932                 goto err;
933             }
934             SSL3_RECORD_add_length(thiswr, mac_size);
935         }
936
937         if (!WPACKET_get_length(thispkt, &len)
938                 || !WPACKET_close(thispkt)) {
939             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
940             goto err;
941         }
942
943         if (s->msg_callback) {
944             recordstart = WPACKET_get_curr(thispkt) - len
945                           - SSL3_RT_HEADER_LENGTH;
946             s->msg_callback(1, thiswr->rec_version, SSL3_RT_HEADER, recordstart,
947                             SSL3_RT_HEADER_LENGTH, ssl,
948                             s->msg_callback_arg);
949
950             if (SSL_CONNECTION_TREAT_AS_TLS13(s) && s->enc_write_ctx != NULL) {
951                 unsigned char ctype = type;
952
953                 s->msg_callback(1, thiswr->rec_version, SSL3_RT_INNER_CONTENT_TYPE,
954                                 &ctype, 1, ssl, s->msg_callback_arg);
955             }
956         }
957
958         if (!WPACKET_finish(thispkt)) {
959             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
960             goto err;
961         }
962
963         /* header is added by the kernel when using offload */
964         SSL3_RECORD_add_length(thiswr, SSL3_RT_HEADER_LENGTH);
965
966         if (create_empty_fragment) {
967             /*
968              * we are in a recursive call; just return the length, don't write
969              * out anything here
970              */
971             if (j > 0) {
972                 /* We should never be pipelining an empty fragment!! */
973                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
974                 goto err;
975             }
976             *written = SSL3_RECORD_get_length(thiswr);
977             return 1;
978         }
979
980  mac_done:
981         /*
982          * we should now have thiswr->data pointing to the encrypted data, which
983          * is thiswr->length long
984          */
985         SSL3_RECORD_set_type(thiswr, type); /* not needed but helps for
986                                              * debugging */
987
988         /* now let's set up wb */
989         SSL3_BUFFER_set_left(&s->rlayer.wbuf[j],
990                              prefix_len + SSL3_RECORD_get_length(thiswr));
991     }
992
993     /*
994      * memorize arguments so that ssl3_write_pending can detect bad write
995      * retries later
996      */
997     s->rlayer.wpend_tot = totlen;
998     s->rlayer.wpend_buf = buf;
999     s->rlayer.wpend_type = type;
1000     s->rlayer.wpend_ret = totlen;
1001
1002     /* we now just need to write the buffer */
1003     return ssl3_write_pending(s, type, buf, totlen, written);
1004  err:
1005     for (j = 0; j < wpinited; j++)
1006         WPACKET_cleanup(&pkt[j]);
1007     return -1;
1008 }
1009
1010 /* if SSL3_BUFFER_get_left() != 0, we need to call this
1011  *
1012  * Return values are as per SSL_write()
1013  */
1014 int ssl3_write_pending(SSL_CONNECTION *s, int type, const unsigned char *buf,
1015                        size_t len, size_t *written)
1016 {
1017     int i;
1018     SSL3_BUFFER *wb = s->rlayer.wbuf;
1019     size_t currbuf = 0;
1020     size_t tmpwrit = 0;
1021
1022     if ((s->rlayer.wpend_tot > len)
1023         || (!(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)
1024             && (s->rlayer.wpend_buf != buf))
1025         || (s->rlayer.wpend_type != type)) {
1026         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_WRITE_RETRY);
1027         return -1;
1028     }
1029
1030     for (;;) {
1031         /* Loop until we find a buffer we haven't written out yet */
1032         if (SSL3_BUFFER_get_left(&wb[currbuf]) == 0
1033             && currbuf < s->rlayer.numwpipes - 1) {
1034             currbuf++;
1035             continue;
1036         }
1037         clear_sys_error();
1038         if (s->wbio != NULL) {
1039             s->rwstate = SSL_WRITING;
1040
1041             /*
1042              * To prevent coalescing of control and data messages,
1043              * such as in buffer_write, we flush the BIO
1044              */
1045             if (BIO_get_ktls_send(s->wbio) && type != SSL3_RT_APPLICATION_DATA) {
1046                 i = BIO_flush(s->wbio);
1047                 if (i <= 0)
1048                     return i;
1049                 BIO_set_ktls_ctrl_msg(s->wbio, type);
1050             }
1051             i = BIO_write(s->wbio, (char *)
1052                           &(SSL3_BUFFER_get_buf(&wb[currbuf])
1053                             [SSL3_BUFFER_get_offset(&wb[currbuf])]),
1054                           (unsigned int)SSL3_BUFFER_get_left(&wb[currbuf]));
1055             if (i >= 0)
1056                 tmpwrit = i;
1057         } else {
1058             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BIO_NOT_SET);
1059             i = -1;
1060         }
1061
1062         /*
1063          * When an empty fragment is sent on a connection using KTLS,
1064          * it is sent as a write of zero bytes.  If this zero byte
1065          * write succeeds, i will be 0 rather than a non-zero value.
1066          * Treat i == 0 as success rather than an error for zero byte
1067          * writes to permit this case.
1068          */
1069         if (i >= 0 && tmpwrit == SSL3_BUFFER_get_left(&wb[currbuf])) {
1070             SSL3_BUFFER_set_left(&wb[currbuf], 0);
1071             SSL3_BUFFER_add_offset(&wb[currbuf], tmpwrit);
1072             if (currbuf + 1 < s->rlayer.numwpipes)
1073                 continue;
1074             s->rwstate = SSL_NOTHING;
1075             *written = s->rlayer.wpend_ret;
1076             return 1;
1077         } else if (i <= 0) {
1078             if (SSL_CONNECTION_IS_DTLS(s)) {
1079                 /*
1080                  * For DTLS, just drop it. That's kind of the whole point in
1081                  * using a datagram service
1082                  */
1083                 SSL3_BUFFER_set_left(&wb[currbuf], 0);
1084             }
1085             return i;
1086         }
1087         SSL3_BUFFER_add_offset(&wb[currbuf], tmpwrit);
1088         SSL3_BUFFER_sub_left(&wb[currbuf], tmpwrit);
1089     }
1090 }
1091
1092 int ossl_tls_handle_rlayer_return(SSL_CONNECTION *s, int ret, char *file,
1093                                   int line)
1094 {
1095     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1096
1097     if (ret == OSSL_RECORD_RETURN_RETRY) {
1098         s->rwstate = SSL_READING;
1099         ret = -1;
1100     } else {
1101         s->rwstate = SSL_NOTHING;
1102         if (ret == OSSL_RECORD_RETURN_EOF) {
1103             if (s->options & SSL_OP_IGNORE_UNEXPECTED_EOF) {
1104                 SSL_set_shutdown(ssl, SSL_RECEIVED_SHUTDOWN);
1105                 s->s3.warn_alert = SSL_AD_CLOSE_NOTIFY;
1106             } else {
1107                 ERR_new();
1108                 ERR_set_debug(file, line, 0);
1109                 ossl_statem_fatal(s, SSL_AD_DECODE_ERROR,
1110                                   SSL_R_UNEXPECTED_EOF_WHILE_READING, NULL);
1111             }
1112         } else if (ret == OSSL_RECORD_RETURN_FATAL) {
1113             ERR_new();
1114             ERR_set_debug(file, line, 0);
1115             ossl_statem_fatal(s, s->rrlmethod->get_alert_code(s->rrl),
1116                               SSL_R_RECORD_LAYER_FAILURE, NULL);
1117         }
1118         /*
1119          * The record layer distinguishes the cases of EOF, non-fatal
1120          * err and retry. Upper layers do not.
1121          * If we got a retry or success then *ret is already correct,
1122          * otherwise we need to convert the return value.
1123          */
1124         if (ret == OSSL_RECORD_RETURN_NON_FATAL_ERR || ret == OSSL_RECORD_RETURN_EOF)
1125             ret = 0;
1126         else if (ret < OSSL_RECORD_RETURN_NON_FATAL_ERR)
1127             ret = -1;
1128     }
1129
1130     return ret;
1131 }
1132
1133 void ssl_release_record(SSL_CONNECTION *s, TLS_RECORD *rr)
1134 {
1135     if (rr->rechandle != NULL) {
1136         /* The record layer allocated the buffers for this record */
1137         s->rrlmethod->release_record(s->rrl, rr->rechandle);
1138     } else {
1139         /* We allocated the buffers for this record (only happens with DTLS) */
1140         OPENSSL_free(rr->data);
1141     }
1142     s->rlayer.curr_rec++;
1143 }
1144
1145 /*-
1146  * Return up to 'len' payload bytes received in 'type' records.
1147  * 'type' is one of the following:
1148  *
1149  *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
1150  *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
1151  *   -  0 (during a shutdown, no data has to be returned)
1152  *
1153  * If we don't have stored data to work from, read a SSL/TLS record first
1154  * (possibly multiple records if we still don't have anything to return).
1155  *
1156  * This function must handle any surprises the peer may have for us, such as
1157  * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
1158  * messages are treated as if they were handshake messages *if* the |recvd_type|
1159  * argument is non NULL.
1160  * Also if record payloads contain fragments too small to process, we store
1161  * them until there is enough for the respective protocol (the record protocol
1162  * may use arbitrary fragmentation and even interleaving):
1163  *     Change cipher spec protocol
1164  *             just 1 byte needed, no need for keeping anything stored
1165  *     Alert protocol
1166  *             2 bytes needed (AlertLevel, AlertDescription)
1167  *     Handshake protocol
1168  *             4 bytes needed (HandshakeType, uint24 length) -- we just have
1169  *             to detect unexpected Client Hello and Hello Request messages
1170  *             here, anything else is handled by higher layers
1171  *     Application data protocol
1172  *             none of our business
1173  */
1174 int ssl3_read_bytes(SSL *ssl, int type, int *recvd_type, unsigned char *buf,
1175                     size_t len, int peek, size_t *readbytes)
1176 {
1177     int i, j, ret;
1178     size_t n, curr_rec, totalbytes;
1179     TLS_RECORD *rr;
1180     void (*cb) (const SSL *ssl, int type2, int val) = NULL;
1181     int is_tls13;
1182     SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
1183
1184     is_tls13 = SSL_CONNECTION_IS_TLS13(s);
1185
1186     if ((type != 0
1187             && (type != SSL3_RT_APPLICATION_DATA)
1188             && (type != SSL3_RT_HANDSHAKE))
1189         || (peek && (type != SSL3_RT_APPLICATION_DATA))) {
1190         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1191         return -1;
1192     }
1193
1194     if ((type == SSL3_RT_HANDSHAKE) && (s->rlayer.handshake_fragment_len > 0))
1195         /* (partially) satisfy request from storage */
1196     {
1197         unsigned char *src = s->rlayer.handshake_fragment;
1198         unsigned char *dst = buf;
1199         unsigned int k;
1200
1201         /* peek == 0 */
1202         n = 0;
1203         while ((len > 0) && (s->rlayer.handshake_fragment_len > 0)) {
1204             *dst++ = *src++;
1205             len--;
1206             s->rlayer.handshake_fragment_len--;
1207             n++;
1208         }
1209         /* move any remaining fragment bytes: */
1210         for (k = 0; k < s->rlayer.handshake_fragment_len; k++)
1211             s->rlayer.handshake_fragment[k] = *src++;
1212
1213         if (recvd_type != NULL)
1214             *recvd_type = SSL3_RT_HANDSHAKE;
1215
1216         *readbytes = n;
1217         return 1;
1218     }
1219
1220     /*
1221      * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
1222      */
1223
1224     if (!ossl_statem_get_in_handshake(s) && SSL_in_init(ssl)) {
1225         /* type == SSL3_RT_APPLICATION_DATA */
1226         i = s->handshake_func(ssl);
1227         /* SSLfatal() already called */
1228         if (i < 0)
1229             return i;
1230         if (i == 0)
1231             return -1;
1232     }
1233  start:
1234     s->rwstate = SSL_NOTHING;
1235
1236     /*-
1237      * For each record 'i' up to |num_recs]
1238      * rr[i].type     - is the type of record
1239      * rr[i].data,    - data
1240      * rr[i].off,     - offset into 'data' for next read
1241      * rr[i].length,  - number of bytes.
1242      */
1243     /* get new records if necessary */
1244     if (s->rlayer.curr_rec >= s->rlayer.num_recs) {
1245         s->rlayer.curr_rec = s->rlayer.num_recs = 0;
1246         do {
1247             rr = &s->rlayer.tlsrecs[s->rlayer.num_recs];
1248
1249             ret = HANDLE_RLAYER_RETURN(s,
1250                     s->rrlmethod->read_record(s->rrl, &rr->rechandle,
1251                                               &rr->version, &rr->type,
1252                                               &rr->data, &rr->length,
1253                                               NULL, NULL));
1254             if (ret <= 0) {
1255                 /* SSLfatal() already called if appropriate */
1256                 return ret;
1257             }
1258             rr->off = 0;
1259             s->rlayer.num_recs++;
1260         } while (s->rrlmethod->processed_read_pending(s->rrl)
1261                  && s->rlayer.num_recs < SSL_MAX_PIPELINES);
1262     }
1263     rr = &s->rlayer.tlsrecs[s->rlayer.curr_rec];
1264
1265     if (s->rlayer.handshake_fragment_len > 0
1266             && SSL3_RECORD_get_type(rr) != SSL3_RT_HANDSHAKE
1267             && SSL_CONNECTION_IS_TLS13(s)) {
1268         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1269                  SSL_R_MIXED_HANDSHAKE_AND_NON_HANDSHAKE_DATA);
1270         return -1;
1271     }
1272
1273     /*
1274      * Reset the count of consecutive warning alerts if we've got a non-empty
1275      * record that isn't an alert.
1276      */
1277     if (rr->type != SSL3_RT_ALERT && rr->length != 0)
1278         s->rlayer.alert_count = 0;
1279
1280     /* we now have a packet which can be read and processed */
1281
1282     if (s->s3.change_cipher_spec /* set when we receive ChangeCipherSpec,
1283                                   * reset by ssl3_get_finished */
1284         && (rr->type != SSL3_RT_HANDSHAKE)) {
1285         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1286                  SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
1287         return -1;
1288     }
1289
1290     /*
1291      * If the other end has shut down, throw anything we read away (even in
1292      * 'peek' mode)
1293      */
1294     if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1295         s->rlayer.curr_rec++;
1296         s->rwstate = SSL_NOTHING;
1297         return 0;
1298     }
1299
1300     if (type == rr->type
1301         || (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
1302             && type == SSL3_RT_HANDSHAKE && recvd_type != NULL
1303             && !is_tls13)) {
1304         /*
1305          * SSL3_RT_APPLICATION_DATA or
1306          * SSL3_RT_HANDSHAKE or
1307          * SSL3_RT_CHANGE_CIPHER_SPEC
1308          */
1309         /*
1310          * make sure that we are not getting application data when we are
1311          * doing a handshake for the first time
1312          */
1313         if (SSL_in_init(ssl) && type == SSL3_RT_APPLICATION_DATA
1314             && s->enc_read_ctx == NULL) {
1315             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_APP_DATA_IN_HANDSHAKE);
1316             return -1;
1317         }
1318
1319         if (type == SSL3_RT_HANDSHAKE
1320             && rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
1321             && s->rlayer.handshake_fragment_len > 0) {
1322             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
1323             return -1;
1324         }
1325
1326         if (recvd_type != NULL)
1327             *recvd_type = rr->type;
1328
1329         if (len == 0) {
1330             /*
1331              * Skip a zero length record. This ensures multiple calls to
1332              * SSL_read() with a zero length buffer will eventually cause
1333              * SSL_pending() to report data as being available.
1334              */
1335             if (rr->length == 0)
1336                 ssl_release_record(s, rr);
1337
1338             return 0;
1339         }
1340
1341         totalbytes = 0;
1342         curr_rec = s->rlayer.curr_rec;
1343         do {
1344             if (len - totalbytes > rr->length)
1345                 n = rr->length;
1346             else
1347                 n = len - totalbytes;
1348
1349             memcpy(buf, &(rr->data[rr->off]), n);
1350             buf += n;
1351             if (peek) {
1352                 /* Mark any zero length record as consumed CVE-2016-6305 */
1353                 if (rr->length == 0)
1354                     ssl_release_record(s, rr);
1355             } else {
1356                 if (s->options & SSL_OP_CLEANSE_PLAINTEXT)
1357                     OPENSSL_cleanse(&(rr->data[rr->off]), n);
1358                 rr->length -= n;
1359                 rr->off += n;
1360                 if (rr->length == 0) {
1361                     /* TODO(RECLAYER): What to do with this? Is it needed? */
1362                     #if 0
1363                     s->rlayer.rstate = SSL_ST_READ_HEADER;
1364                     #endif
1365                     ssl_release_record(s, rr);
1366                 }
1367             }
1368             if (rr->length == 0
1369                 || (peek && n == rr->length)) {
1370                 rr++;
1371                 curr_rec++;
1372             }
1373             totalbytes += n;
1374         } while (type == SSL3_RT_APPLICATION_DATA
1375                     && curr_rec < s->rlayer.num_recs
1376                     && totalbytes < len);
1377         if (totalbytes == 0) {
1378             /* We must have read empty records. Get more data */
1379             goto start;
1380         }
1381         /* TODO(RECLAYER): FIX ME */
1382 #if 0
1383         if (!peek && curr_rec == s->rlayer.num_recs
1384             && (s->mode & SSL_MODE_RELEASE_BUFFERS)
1385             && SSL3_BUFFER_get_left(rbuf) == 0)
1386             ssl3_release_read_buffer(s);
1387 #endif
1388         *readbytes = totalbytes;
1389         return 1;
1390     }
1391
1392     /*
1393      * If we get here, then type != rr->type; if we have a handshake message,
1394      * then it was unexpected (Hello Request or Client Hello) or invalid (we
1395      * were actually expecting a CCS).
1396      */
1397
1398     /*
1399      * Lets just double check that we've not got an SSLv2 record
1400      */
1401     if (rr->version == SSL2_VERSION) {
1402         /*
1403          * Should never happen. ssl3_get_record() should only give us an SSLv2
1404          * record back if this is the first packet and we are looking for an
1405          * initial ClientHello. Therefore |type| should always be equal to
1406          * |rr->type|. If not then something has gone horribly wrong
1407          */
1408         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1409         return -1;
1410     }
1411
1412     if (ssl->method->version == TLS_ANY_VERSION
1413         && (s->server || rr->type != SSL3_RT_ALERT)) {
1414         /*
1415          * If we've got this far and still haven't decided on what version
1416          * we're using then this must be a client side alert we're dealing
1417          * with. We shouldn't be receiving anything other than a ClientHello
1418          * if we are a server.
1419          */
1420         s->version = rr->version;
1421         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
1422         return -1;
1423     }
1424
1425     /*-
1426      * s->rlayer.handshake_fragment_len == 4  iff  rr->type == SSL3_RT_HANDSHAKE;
1427      * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
1428      */
1429
1430     if (rr->type == SSL3_RT_ALERT) {
1431         unsigned int alert_level, alert_descr;
1432         unsigned char *alert_bytes = rr->data
1433                                      + rr->off;
1434         PACKET alert;
1435
1436         if (!PACKET_buf_init(&alert, alert_bytes, rr->length)
1437                 || !PACKET_get_1(&alert, &alert_level)
1438                 || !PACKET_get_1(&alert, &alert_descr)
1439                 || PACKET_remaining(&alert) != 0) {
1440             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_INVALID_ALERT);
1441             return -1;
1442         }
1443
1444         if (s->msg_callback)
1445             s->msg_callback(0, s->version, SSL3_RT_ALERT, alert_bytes, 2, ssl,
1446                             s->msg_callback_arg);
1447
1448         if (s->info_callback != NULL)
1449             cb = s->info_callback;
1450         else if (ssl->ctx->info_callback != NULL)
1451             cb = ssl->ctx->info_callback;
1452
1453         if (cb != NULL) {
1454             j = (alert_level << 8) | alert_descr;
1455             cb(ssl, SSL_CB_READ_ALERT, j);
1456         }
1457
1458         if ((!is_tls13 && alert_level == SSL3_AL_WARNING)
1459                 || (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED)) {
1460             s->s3.warn_alert = alert_descr;
1461             ssl_release_record(s, rr);
1462
1463             s->rlayer.alert_count++;
1464             if (s->rlayer.alert_count == MAX_WARN_ALERT_COUNT) {
1465                 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1466                          SSL_R_TOO_MANY_WARN_ALERTS);
1467                 return -1;
1468             }
1469         }
1470
1471         /*
1472          * Apart from close_notify the only other warning alert in TLSv1.3
1473          * is user_cancelled - which we just ignore.
1474          */
1475         if (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED) {
1476             goto start;
1477         } else if (alert_descr == SSL_AD_CLOSE_NOTIFY
1478                 && (is_tls13 || alert_level == SSL3_AL_WARNING)) {
1479             s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1480             return 0;
1481         } else if (alert_level == SSL3_AL_FATAL || is_tls13) {
1482             s->rwstate = SSL_NOTHING;
1483             s->s3.fatal_alert = alert_descr;
1484             SSLfatal_data(s, SSL_AD_NO_ALERT,
1485                           SSL_AD_REASON_OFFSET + alert_descr,
1486                           "SSL alert number %d", alert_descr);
1487             s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1488             ssl_release_record(s, rr);
1489             SSL_CTX_remove_session(s->session_ctx, s->session);
1490             return 0;
1491         } else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
1492             /*
1493              * This is a warning but we receive it if we requested
1494              * renegotiation and the peer denied it. Terminate with a fatal
1495              * alert because if application tried to renegotiate it
1496              * presumably had a good reason and expects it to succeed. In
1497              * future we might have a renegotiation where we don't care if
1498              * the peer refused it where we carry on.
1499              */
1500             SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_RENEGOTIATION);
1501             return -1;
1502         } else if (alert_level == SSL3_AL_WARNING) {
1503             /* We ignore any other warning alert in TLSv1.2 and below */
1504             goto start;
1505         }
1506
1507         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_ALERT_TYPE);
1508         return -1;
1509     }
1510
1511     if ((s->shutdown & SSL_SENT_SHUTDOWN) != 0) {
1512         if (rr->type == SSL3_RT_HANDSHAKE) {
1513             BIO *rbio;
1514
1515             /*
1516              * We ignore any handshake messages sent to us unless they are
1517              * TLSv1.3 in which case we want to process them. For all other
1518              * handshake messages we can't do anything reasonable with them
1519              * because we are unable to write any response due to having already
1520              * sent close_notify.
1521              */
1522             if (!SSL_CONNECTION_IS_TLS13(s)) {
1523                 ssl_release_record(s, rr);
1524
1525                 if ((s->mode & SSL_MODE_AUTO_RETRY) != 0)
1526                     goto start;
1527
1528                 s->rwstate = SSL_READING;
1529                 rbio = SSL_get_rbio(ssl);
1530                 BIO_clear_retry_flags(rbio);
1531                 BIO_set_retry_read(rbio);
1532                 return -1;
1533             }
1534         } else {
1535             /*
1536              * The peer is continuing to send application data, but we have
1537              * already sent close_notify. If this was expected we should have
1538              * been called via SSL_read() and this would have been handled
1539              * above.
1540              * No alert sent because we already sent close_notify
1541              */
1542             ssl_release_record(s, rr);
1543             SSLfatal(s, SSL_AD_NO_ALERT,
1544                      SSL_R_APPLICATION_DATA_AFTER_CLOSE_NOTIFY);
1545             return -1;
1546         }
1547     }
1548
1549     /*
1550      * For handshake data we have 'fragment' storage, so fill that so that we
1551      * can process the header at a fixed place. This is done after the
1552      * "SHUTDOWN" code above to avoid filling the fragment storage with data
1553      * that we're just going to discard.
1554      */
1555     if (rr->type == SSL3_RT_HANDSHAKE) {
1556         size_t dest_maxlen = sizeof(s->rlayer.handshake_fragment);
1557         unsigned char *dest = s->rlayer.handshake_fragment;
1558         size_t *dest_len = &s->rlayer.handshake_fragment_len;
1559
1560         n = dest_maxlen - *dest_len; /* available space in 'dest' */
1561         if (rr->length < n)
1562             n = rr->length; /* available bytes */
1563
1564         /* now move 'n' bytes: */
1565         memcpy(dest + *dest_len, rr->data + rr->off, n);
1566         rr->off += n;
1567         rr->length -= n;
1568         *dest_len += n;
1569         if (rr->length == 0)
1570             ssl_release_record(s, rr);
1571
1572         if (*dest_len < dest_maxlen)
1573             goto start;     /* fragment was too small */
1574     }
1575
1576     if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1577         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
1578         return -1;
1579     }
1580
1581     /*
1582      * Unexpected handshake message (ClientHello, NewSessionTicket (TLS1.3) or
1583      * protocol violation)
1584      */
1585     if ((s->rlayer.handshake_fragment_len >= 4)
1586             && !ossl_statem_get_in_handshake(s)) {
1587         int ined = (s->early_data_state == SSL_EARLY_DATA_READING);
1588
1589         /* We found handshake data, so we're going back into init */
1590         ossl_statem_set_in_init(s, 1);
1591
1592         i = s->handshake_func(ssl);
1593         /* SSLfatal() already called if appropriate */
1594         if (i < 0)
1595             return i;
1596         if (i == 0) {
1597             return -1;
1598         }
1599
1600         /*
1601          * If we were actually trying to read early data and we found a
1602          * handshake message, then we don't want to continue to try and read
1603          * the application data any more. It won't be "early" now.
1604          */
1605         if (ined)
1606             return -1;
1607
1608         if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1609             if (!RECORD_LAYER_read_pending(&s->rlayer)) {
1610                 BIO *bio;
1611                 /*
1612                  * In the case where we try to read application data, but we
1613                  * trigger an SSL handshake, we return -1 with the retry
1614                  * option set.  Otherwise renegotiation may cause nasty
1615                  * problems in the blocking world
1616                  */
1617                 s->rwstate = SSL_READING;
1618                 bio = SSL_get_rbio(ssl);
1619                 BIO_clear_retry_flags(bio);
1620                 BIO_set_retry_read(bio);
1621                 return -1;
1622             }
1623         }
1624         goto start;
1625     }
1626
1627     switch (rr->type) {
1628     default:
1629         /*
1630          * TLS 1.0 and 1.1 say you SHOULD ignore unrecognised record types, but
1631          * TLS 1.2 says you MUST send an unexpected message alert. We use the
1632          * TLS 1.2 behaviour for all protocol versions to prevent issues where
1633          * no progress is being made and the peer continually sends unrecognised
1634          * record types, using up resources processing them.
1635          */
1636         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1637         return -1;
1638     case SSL3_RT_CHANGE_CIPHER_SPEC:
1639     case SSL3_RT_ALERT:
1640     case SSL3_RT_HANDSHAKE:
1641         /*
1642          * we already handled all of these, with the possible exception of
1643          * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
1644          * that should not happen when type != rr->type
1645          */
1646         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, ERR_R_INTERNAL_ERROR);
1647         return -1;
1648     case SSL3_RT_APPLICATION_DATA:
1649         /*
1650          * At this point, we were expecting handshake data, but have
1651          * application data.  If the library was running inside ssl3_read()
1652          * (i.e. in_read_app_data is set) and it makes sense to read
1653          * application data at this point (session renegotiation not yet
1654          * started), we will indulge it.
1655          */
1656         if (ossl_statem_app_data_allowed(s)) {
1657             s->s3.in_read_app_data = 2;
1658             return -1;
1659         } else if (ossl_statem_skip_early_data(s)) {
1660             /*
1661              * This can happen after a client sends a CH followed by early_data,
1662              * but the server responds with a HelloRetryRequest. The server
1663              * reads the next record from the client expecting to find a
1664              * plaintext ClientHello but gets a record which appears to be
1665              * application data. The trial decrypt "works" because null
1666              * decryption was applied. We just skip it and move on to the next
1667              * record.
1668              */
1669             if (!ossl_early_data_count_ok(s, rr->length,
1670                                           EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
1671                 /* SSLfatal() already called */
1672                 return -1;
1673             }
1674             ssl_release_record(s, rr);
1675             goto start;
1676         } else {
1677             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1678             return -1;
1679         }
1680     }
1681 }
1682
1683 void ssl3_record_sequence_update(unsigned char *seq)
1684 {
1685     int i;
1686
1687     for (i = 7; i >= 0; i--) {
1688         ++seq[i];
1689         if (seq[i] != 0)
1690             break;
1691     }
1692 }
1693
1694 /*
1695  * Returns true if the current rrec was sent in SSLv2 backwards compatible
1696  * format and false otherwise.
1697  */
1698 int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl)
1699 {
1700     if (SSL_CONNECTION_IS_DTLS(rl->s))
1701         return 0;
1702     return rl->tlsrecs[0].version == SSL2_VERSION;
1703 }
1704
1705 /*
1706  * Returns the length in bytes of the current rrec
1707  */
1708 size_t RECORD_LAYER_get_rrec_length(RECORD_LAYER *rl)
1709 {
1710     return SSL3_RECORD_get_length(&rl->rrec[0]);
1711 }
1712
1713 static OSSL_FUNC_rlayer_msg_callback_fn rlayer_msg_callback_wrapper;
1714 static void rlayer_msg_callback_wrapper(int write_p, int version,
1715                                         int content_type, const void *buf,
1716                                         size_t len, void *cbarg)
1717 {
1718     SSL_CONNECTION *s = cbarg;
1719     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1720
1721     if (s->msg_callback != NULL)
1722         s->msg_callback(write_p, version, content_type, buf, len, ssl,
1723                         s->msg_callback_arg);
1724 }
1725
1726 static OSSL_FUNC_rlayer_security_fn rlayer_security_wrapper;
1727 static int rlayer_security_wrapper(void *cbarg, int op, int bits, int nid,
1728                                    void *other)
1729 {
1730     SSL_CONNECTION *s = cbarg;
1731
1732     return ssl_security(s, op, bits, nid, other);
1733 }
1734
1735 static const OSSL_DISPATCH rlayer_dispatch[] = {
1736     { OSSL_FUNC_RLAYER_SKIP_EARLY_DATA, (void (*)(void))ossl_statem_skip_early_data },
1737     { OSSL_FUNC_RLAYER_MSG_CALLBACK, (void (*)(void))rlayer_msg_callback_wrapper },
1738     { OSSL_FUNC_RLAYER_SECURITY, (void (*)(void))rlayer_security_wrapper },
1739     { 0, NULL }
1740 };
1741
1742 static const OSSL_RECORD_METHOD *ssl_select_next_record_layer(SSL_CONNECTION *s,
1743                                                               int level)
1744 {
1745
1746     if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE) {
1747         if (SSL_CONNECTION_IS_DTLS(s))
1748             return &ossl_dtls_record_method;
1749
1750         return &ossl_tls_record_method;
1751     }
1752
1753 #ifndef OPENSSL_NO_KTLS
1754     /* KTLS does not support renegotiation */
1755     if (level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION
1756             && (s->options & SSL_OP_ENABLE_KTLS) != 0
1757             && (SSL_CONNECTION_IS_TLS13(s) || SSL_IS_FIRST_HANDSHAKE(s)))
1758         return &ossl_ktls_record_method;
1759 #endif
1760
1761     /* Default to the current OSSL_RECORD_METHOD */
1762     return s->rrlmethod;
1763 }
1764
1765 static int ssl_post_record_layer_select(SSL_CONNECTION *s)
1766 {
1767 #ifndef OPENSSL_NO_KTLS
1768     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1769
1770     if (s->rrlmethod == &ossl_ktls_record_method) {
1771         /* KTLS does not support renegotiation so disallow it */
1772         SSL_set_options(ssl, SSL_OP_NO_RENEGOTIATION);
1773     }
1774 #endif
1775     if (SSL_IS_FIRST_HANDSHAKE(s) && s->rrlmethod->set_first_handshake != NULL)
1776         s->rrlmethod->set_first_handshake(s->rrl, 1);
1777
1778     if (s->max_pipelines != 0 && s->rrlmethod->set_max_pipelines != NULL)
1779         s->rrlmethod->set_max_pipelines(s->rrl, s->max_pipelines);
1780
1781     return 1;
1782 }
1783
1784 int ssl_set_new_record_layer(SSL_CONNECTION *s, int version,
1785                              int direction, int level,
1786                              unsigned char *key, size_t keylen,
1787                              unsigned char *iv,  size_t ivlen,
1788                              unsigned char *mackey, size_t mackeylen,
1789                              const EVP_CIPHER *ciph, size_t taglen,
1790                              int mactype, const EVP_MD *md,
1791                              const SSL_COMP *comp)
1792 {
1793     OSSL_PARAM options[5], *opts = options;
1794     OSSL_PARAM settings[6], *set =  settings;
1795     const OSSL_RECORD_METHOD *origmeth = s->rrlmethod;
1796     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1797     const OSSL_RECORD_METHOD *meth;
1798     int use_etm, stream_mac = 0, tlstree = 0;
1799     unsigned int maxfrag = SSL3_RT_MAX_PLAIN_LENGTH;
1800     int use_early_data = 0;
1801     uint32_t max_early_data;
1802
1803     meth = ssl_select_next_record_layer(s, level);
1804
1805     if (s->rrlmethod != NULL && !s->rrlmethod->free(s->rrl)) {
1806         ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1807         return 0;
1808     }
1809
1810     if (meth != NULL)
1811         s->rrlmethod = meth;
1812
1813     if (!ossl_assert(s->rrlmethod != NULL)) {
1814         ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1815         return 0;
1816     }
1817
1818     /* Parameters that *may* be supported by a record layer if passed */
1819     *opts++ = OSSL_PARAM_construct_uint64(OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS,
1820                                           &s->options);
1821     *opts++ = OSSL_PARAM_construct_uint32(OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE,
1822                                           &s->mode);
1823     *opts++ = OSSL_PARAM_construct_size_t(OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN,
1824                                           &s->default_read_buf_len);
1825     *opts++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD,
1826                                        &s->rlayer.read_ahead);
1827     *opts = OSSL_PARAM_construct_end();
1828
1829     /* Parameters that *must* be supported by a record layer if passed */
1830     if (direction == OSSL_RECORD_DIRECTION_READ) {
1831         use_etm = SSL_READ_ETM(s) ? 1 : 0;
1832         if ((s->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM) != 0)
1833             stream_mac = 1;
1834
1835         if ((s->mac_flags & SSL_MAC_FLAG_READ_MAC_TLSTREE) != 0)
1836             tlstree = 1;
1837     } else {
1838         use_etm = SSL_WRITE_ETM(s) ? 1 : 0;
1839         if ((s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM) != 0)
1840             stream_mac = 1;
1841
1842         if ((s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_TLSTREE) != 0)
1843             tlstree = 1;
1844     }
1845
1846     if (use_etm)
1847         *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM,
1848                                           &use_etm);
1849
1850     if (stream_mac)
1851         *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC,
1852                                           &stream_mac);
1853
1854     if (tlstree)
1855         *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE,
1856                                           &tlstree);
1857
1858     if (s->session != NULL && USE_MAX_FRAGMENT_LENGTH_EXT(s->session))
1859         maxfrag = GET_MAX_FRAGMENT_LENGTH(s->session);
1860
1861     if (maxfrag != SSL3_RT_MAX_PLAIN_LENGTH)
1862         *set++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN,
1863                                            &maxfrag);
1864
1865     /*
1866      * The record layer must check the amount of early data sent or received
1867      * using the early keys. A server also needs to worry about rejected early
1868      * data that might arrive when the handshake keys are in force.
1869      */
1870     /* TODO(RECLAYER): Check this when doing the "write" record layer */
1871     if (s->server && direction == OSSL_RECORD_DIRECTION_READ) {
1872         use_early_data = (level == OSSL_RECORD_PROTECTION_LEVEL_EARLY
1873                           || level == OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE);
1874     } else if (!s->server && direction == OSSL_RECORD_DIRECTION_WRITE) {
1875         use_early_data = (level == OSSL_RECORD_PROTECTION_LEVEL_EARLY);
1876     }
1877     if (use_early_data) {
1878         max_early_data = ossl_get_max_early_data(s);
1879
1880         if (max_early_data != 0)
1881             *set++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA,
1882                                             &max_early_data);
1883     }
1884
1885     *set = OSSL_PARAM_construct_end();
1886
1887     for (;;) {
1888         int rlret;
1889         BIO *prev = s->rrlnext;
1890         unsigned int epoch = 0;;
1891
1892         if (SSL_CONNECTION_IS_DTLS(s)
1893                 && level != OSSL_RECORD_PROTECTION_LEVEL_NONE)
1894             epoch =  DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer) + 1; /* new epoch */
1895
1896         s->rrlnext = BIO_new(BIO_s_mem());
1897
1898         if (s->rrlnext == NULL) {
1899             BIO_free(prev);
1900             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1901             return 0;
1902         }
1903
1904         rlret = s->rrlmethod->new_record_layer(sctx->libctx, sctx->propq,
1905                                                version, s->server, direction,
1906                                                level, epoch, key, keylen, iv,
1907                                                ivlen, mackey, mackeylen, ciph,
1908                                                taglen, mactype, md, comp, prev,
1909                                                s->rbio, s->rrlnext, NULL, NULL,
1910                                                settings, options,
1911                                                rlayer_dispatch, s, &s->rrl);
1912         BIO_free(prev);
1913         switch (rlret) {
1914         case OSSL_RECORD_RETURN_FATAL:
1915             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_RECORD_LAYER_FAILURE);
1916             return 0;
1917
1918         case OSSL_RECORD_RETURN_NON_FATAL_ERR:
1919             if (s->rrlmethod != origmeth && origmeth != NULL) {
1920                 /*
1921                  * We tried a new record layer method, but it didn't work out,
1922                  * so we fallback to the original method and try again
1923                  */
1924                 s->rrlmethod = origmeth;
1925                 continue;
1926             }
1927             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_NO_SUITABLE_RECORD_LAYER);
1928             return 0;
1929
1930         case OSSL_RECORD_RETURN_SUCCESS:
1931             break;
1932
1933         default:
1934             /* Should not happen */
1935             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1936             return 0;
1937         }
1938         break;
1939     }
1940
1941     return ssl_post_record_layer_select(s);
1942 }