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