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