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