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