Pipeline output/input buf arrays must live until the EVP_Cipher is called
[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 void RECORD_LAYER_init(RECORD_LAYER *rl, SSL_CONNECTION *s)
22 {
23     rl->s = s;
24 }
25
26 void RECORD_LAYER_clear(RECORD_LAYER *rl)
27 {
28     rl->wnum = 0;
29     memset(rl->handshake_fragment, 0, sizeof(rl->handshake_fragment));
30     rl->handshake_fragment_len = 0;
31     rl->wpend_tot = 0;
32     rl->wpend_type = 0;
33     rl->wpend_ret = 0;
34     rl->wpend_buf = NULL;
35
36     if (rl->rrlmethod != NULL)
37         rl->rrlmethod->free(rl->rrl); /* Ignore return value */
38     if (rl->wrlmethod != NULL)
39         rl->wrlmethod->free(rl->wrl); /* Ignore return value */
40     BIO_free(rl->rrlnext);
41     rl->rrlmethod = NULL;
42     rl->wrlmethod = NULL;
43     rl->rrlnext = NULL;
44     rl->rrl = NULL;
45     rl->wrl = NULL;
46
47     if (rl->d)
48         DTLS_RECORD_LAYER_clear(rl);
49 }
50
51 /* Checks if we have unprocessed read ahead data pending */
52 int RECORD_LAYER_read_pending(const RECORD_LAYER *rl)
53 {
54     return rl->rrlmethod->unprocessed_read_pending(rl->rrl);
55 }
56
57 /* Checks if we have decrypted unread record data pending */
58 int RECORD_LAYER_processed_read_pending(const RECORD_LAYER *rl)
59 {
60     return (rl->curr_rec < rl->num_recs)
61            || rl->rrlmethod->processed_read_pending(rl->rrl);
62 }
63
64 int RECORD_LAYER_write_pending(const RECORD_LAYER *rl)
65 {
66     return rl->wpend_tot > 0;
67 }
68
69 size_t ssl3_pending(const SSL *s)
70 {
71     size_t i, num = 0;
72     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
73
74     if (sc == NULL)
75         return 0;
76
77     if (SSL_CONNECTION_IS_DTLS(sc)) {
78         TLS_RECORD *rdata;
79         pitem *item, *iter;
80
81         iter = pqueue_iterator(sc->rlayer.d->buffered_app_data.q);
82         while ((item = pqueue_next(&iter)) != NULL) {
83             rdata = item->data;
84             num += rdata->length;
85         }
86     }
87
88     for (i = 0; i < sc->rlayer.num_recs; i++) {
89         if (sc->rlayer.tlsrecs[i].type != SSL3_RT_APPLICATION_DATA)
90             return num;
91         num += sc->rlayer.tlsrecs[i].length;
92     }
93
94     num += sc->rlayer.rrlmethod->app_data_pending(sc->rlayer.rrl);
95
96     return num;
97 }
98
99 void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len)
100 {
101     ctx->default_read_buf_len = len;
102 }
103
104 void SSL_set_default_read_buffer_len(SSL *s, size_t len)
105 {
106     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
107
108     if (sc == NULL)
109         return;
110     sc->rlayer.default_read_buf_len = len;
111 }
112
113 const char *SSL_rstate_string_long(const SSL *s)
114 {
115     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
116     const char *lng;
117
118     if (sc == NULL)
119         return NULL;
120
121     if (sc->rlayer.rrlmethod == NULL || sc->rlayer.rrl == NULL)
122         return "unknown";
123
124     sc->rlayer.rrlmethod->get_state(sc->rlayer.rrl, NULL, &lng);
125
126     return lng;
127 }
128
129 const char *SSL_rstate_string(const SSL *s)
130 {
131     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
132     const char *shrt;
133
134     if (sc == NULL)
135         return NULL;
136
137     if (sc->rlayer.rrlmethod == NULL || sc->rlayer.rrl == NULL)
138         return "unknown";
139
140     sc->rlayer.rrlmethod->get_state(sc->rlayer.rrl, &shrt, NULL);
141
142     return shrt;
143 }
144
145 static int tls_write_check_pending(SSL_CONNECTION *s, int type,
146                                    const unsigned char *buf, size_t len)
147 {
148     if (s->rlayer.wpend_tot == 0)
149         return 0;
150
151     /* We have pending data, so do some sanity checks */
152     if ((s->rlayer.wpend_tot > len)
153         || (!(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)
154             && (s->rlayer.wpend_buf != buf))
155         || (s->rlayer.wpend_type != type)) {
156         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_WRITE_RETRY);
157         return -1;
158     }
159     return 1;
160 }
161
162 /*
163  * Call this to write data in records of type 'type' It will return <= 0 if
164  * not all data has been sent or non-blocking IO.
165  */
166 int ssl3_write_bytes(SSL *ssl, int type, const void *buf_, size_t len,
167                      size_t *written)
168 {
169     const unsigned char *buf = buf_;
170     size_t tot;
171     size_t n, max_send_fragment, split_send_fragment, maxpipes;
172     int i;
173     SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
174     OSSL_RECORD_TEMPLATE tmpls[SSL_MAX_PIPELINES];
175     unsigned int recversion;
176
177     if (s == NULL)
178         return -1;
179
180     s->rwstate = SSL_NOTHING;
181     tot = s->rlayer.wnum;
182     /*
183      * ensure that if we end up with a smaller value of data to write out
184      * than the original len from a write which didn't complete for
185      * non-blocking I/O and also somehow ended up avoiding the check for
186      * this in tls_write_check_pending/SSL_R_BAD_WRITE_RETRY as it must never be
187      * possible to end up with (len-tot) as a large number that will then
188      * promptly send beyond the end of the users buffer ... so we trap and
189      * report the error in a way the user will notice
190      */
191     if ((len < s->rlayer.wnum)
192         || ((s->rlayer.wpend_tot != 0)
193             && (len < (s->rlayer.wnum + s->rlayer.wpend_tot)))) {
194         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_LENGTH);
195         return -1;
196     }
197
198     if (s->early_data_state == SSL_EARLY_DATA_WRITING
199             && !ossl_early_data_count_ok(s, len, 0, 1)) {
200         /* SSLfatal() already called */
201         return -1;
202     }
203
204     s->rlayer.wnum = 0;
205
206     /*
207      * If we are supposed to be sending a KeyUpdate or NewSessionTicket then go
208      * into init unless we have writes pending - in which case we should finish
209      * doing that first.
210      */
211     if (s->rlayer.wpend_tot == 0 && (s->key_update != SSL_KEY_UPDATE_NONE
212                                      || s->ext.extra_tickets_expected > 0))
213         ossl_statem_set_in_init(s, 1);
214
215     /*
216      * When writing early data on the server side we could be "in_init" in
217      * between receiving the EoED and the CF - but we don't want to handle those
218      * messages yet.
219      */
220     if (SSL_in_init(ssl) && !ossl_statem_get_in_handshake(s)
221             && s->early_data_state != SSL_EARLY_DATA_UNAUTH_WRITING) {
222         i = s->handshake_func(ssl);
223         /* SSLfatal() already called */
224         if (i < 0)
225             return i;
226         if (i == 0) {
227             return -1;
228         }
229     }
230
231     i = tls_write_check_pending(s, type, buf, len);
232     if (i < 0) {
233         /* SSLfatal() already called */
234         return i;
235     } else if (i > 0) {
236         /* Retry needed */
237         i = HANDLE_RLAYER_WRITE_RETURN(s,
238                 s->rlayer.wrlmethod->retry_write_records(s->rlayer.wrl));
239         if (i <= 0)
240             return i;
241         tot += s->rlayer.wpend_tot;
242         s->rlayer.wpend_tot = 0;
243     } /* else no retry required */
244
245     if (tot == 0) {
246         /*
247          * We've not previously sent any data for this write so memorize
248          * arguments so that we can detect bad write retries later
249          */
250         s->rlayer.wpend_tot = 0;
251         s->rlayer.wpend_type = type;
252         s->rlayer.wpend_buf = buf;
253         s->rlayer.wpend_ret = len;
254     }
255
256     if (tot == len) {           /* done? */
257         *written = tot;
258         return 1;
259     }
260
261     /* If we have an alert to send, lets send it */
262     if (s->s3.alert_dispatch) {
263         i = ssl->method->ssl_dispatch_alert(ssl);
264         if (i <= 0) {
265             /* SSLfatal() already called if appropriate */
266             return i;
267         }
268         /* if it went, fall through and send more stuff */
269     }
270
271     n = (len - tot);
272
273     max_send_fragment = ssl_get_max_send_fragment(s);
274     split_send_fragment = ssl_get_split_send_fragment(s);
275
276     if (max_send_fragment == 0
277             || split_send_fragment == 0
278             || split_send_fragment > max_send_fragment) {
279         /*
280          * We should have prevented this when we set/get the split and max send
281          * fragments so we shouldn't get here
282          */
283         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
284         return -1;
285     }
286
287     /*
288      * Some servers hang if initial client hello is larger than 256 bytes
289      * and record version number > TLS 1.0
290      */
291     recversion = (s->version == TLS1_3_VERSION) ? TLS1_2_VERSION : s->version;
292     if (SSL_get_state(ssl) == TLS_ST_CW_CLNT_HELLO
293             && !s->renegotiate
294             && TLS1_get_version(ssl) > TLS1_VERSION
295             && s->hello_retry_request == SSL_HRR_NONE)
296         recversion = TLS1_VERSION;
297
298     for (;;) {
299         size_t tmppipelen, remain;
300         size_t j, lensofar = 0;
301
302         /*
303         * Ask the record layer how it would like to split the amount of data
304         * that we have, and how many of those records it would like in one go.
305         */
306         maxpipes = s->rlayer.wrlmethod->get_max_records(s->rlayer.wrl, type, n,
307                                                         max_send_fragment,
308                                                         &split_send_fragment);
309         /*
310         * If max_pipelines is 0 then this means "undefined" and we default to
311         * whatever the record layer wants to do. Otherwise we use the smallest
312         * value from the number requested by the record layer, and max number
313         * configured by the user.
314         */
315         if (s->max_pipelines > 0 && maxpipes > s->max_pipelines)
316             maxpipes = s->max_pipelines;
317
318         if (maxpipes > SSL_MAX_PIPELINES)
319             maxpipes = SSL_MAX_PIPELINES;
320
321         if (split_send_fragment > max_send_fragment) {
322             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
323             return -1;
324         }
325
326         if (n / maxpipes >= split_send_fragment) {
327             /*
328              * We have enough data to completely fill all available
329              * pipelines
330              */
331             for (j = 0; j < maxpipes; j++) {
332                 tmpls[j].type = type;
333                 tmpls[j].version = recversion;
334                 tmpls[j].buf = &(buf[tot]) + (j * split_send_fragment);
335                 tmpls[j].buflen = split_send_fragment;
336             }
337             /* Remember how much data we are going to be sending */
338             s->rlayer.wpend_tot = maxpipes * split_send_fragment;
339         } else {
340             /* We can partially fill all available pipelines */
341             tmppipelen = n / maxpipes;
342             remain = n % maxpipes;
343             /*
344              * If there is a remainder we add an extra byte to the first few
345              * pipelines
346              */
347             if (remain > 0)
348                 tmppipelen++;
349             for (j = 0; j < maxpipes; j++) {
350                 tmpls[j].type = type;
351                 tmpls[j].version = recversion;
352                 tmpls[j].buf = &(buf[tot]) + lensofar;
353                 tmpls[j].buflen = tmppipelen;
354                 lensofar += tmppipelen;
355                 if (j + 1 == remain)
356                     tmppipelen--;
357             }
358             /* Remember how much data we are going to be sending */
359             s->rlayer.wpend_tot = n;
360         }
361
362         i = HANDLE_RLAYER_WRITE_RETURN(s,
363             s->rlayer.wrlmethod->write_records(s->rlayer.wrl, tmpls, maxpipes));
364         if (i <= 0) {
365             /* SSLfatal() already called if appropriate */
366             s->rlayer.wnum = tot;
367             return i;
368         }
369
370         if (s->rlayer.wpend_tot == n
371                 || (type == SSL3_RT_APPLICATION_DATA
372                     && (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE) != 0)) {
373             *written = tot + s->rlayer.wpend_tot;
374             s->rlayer.wpend_tot = 0;
375             return 1;
376         }
377
378         n -= s->rlayer.wpend_tot;
379         tot += s->rlayer.wpend_tot;
380     }
381 }
382
383 int ossl_tls_handle_rlayer_return(SSL_CONNECTION *s, int writing, int ret,
384                                   char *file, int line)
385 {
386     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
387
388     if (ret == OSSL_RECORD_RETURN_RETRY) {
389         s->rwstate = writing ? SSL_WRITING : SSL_READING;
390         ret = -1;
391     } else {
392         s->rwstate = SSL_NOTHING;
393         if (ret == OSSL_RECORD_RETURN_EOF) {
394             if (writing) {
395                 /*
396                  * This shouldn't happen with a writing operation. We treat it
397                  * as fatal.
398                  */
399                 ERR_new();
400                 ERR_set_debug(file, line, 0);
401                 ossl_statem_fatal(s, SSL_AD_INTERNAL_ERROR,
402                                   ERR_R_INTERNAL_ERROR, NULL);
403                 ret = OSSL_RECORD_RETURN_FATAL;
404             } else if ((s->options & SSL_OP_IGNORE_UNEXPECTED_EOF) != 0) {
405                 SSL_set_shutdown(ssl, SSL_RECEIVED_SHUTDOWN);
406                 s->s3.warn_alert = SSL_AD_CLOSE_NOTIFY;
407             } else {
408                 ERR_new();
409                 ERR_set_debug(file, line, 0);
410                 ossl_statem_fatal(s, SSL_AD_DECODE_ERROR,
411                                   SSL_R_UNEXPECTED_EOF_WHILE_READING, NULL);
412             }
413         } else if (ret == OSSL_RECORD_RETURN_FATAL) {
414             int al = s->rlayer.rrlmethod->get_alert_code(s->rlayer.rrl);
415
416             if (al != SSL_AD_NO_ALERT) {
417                 ERR_new();
418                 ERR_set_debug(file, line, 0);
419                 ossl_statem_fatal(s, al, SSL_R_RECORD_LAYER_FAILURE, NULL);
420             }
421             /*
422              * else some failure but there is no alert code. We don't log an
423              * error for this. The record layer should have logged an error
424              * already or, if not, its due to some sys call error which will be
425              * reported via SSL_ERROR_SYSCALL and errno.
426              */
427         }
428         /*
429          * The record layer distinguishes the cases of EOF, non-fatal
430          * err and retry. Upper layers do not.
431          * If we got a retry or success then *ret is already correct,
432          * otherwise we need to convert the return value.
433          */
434         if (ret == OSSL_RECORD_RETURN_NON_FATAL_ERR || ret == OSSL_RECORD_RETURN_EOF)
435             ret = 0;
436         else if (ret < OSSL_RECORD_RETURN_NON_FATAL_ERR)
437             ret = -1;
438     }
439
440     return ret;
441 }
442
443 void ssl_release_record(SSL_CONNECTION *s, TLS_RECORD *rr)
444 {
445     if (rr->rechandle != NULL) {
446         /* The record layer allocated the buffers for this record */
447         s->rlayer.rrlmethod->release_record(s->rlayer.rrl, rr->rechandle);
448     } else {
449         /* We allocated the buffers for this record (only happens with DTLS) */
450         OPENSSL_free(rr->data);
451     }
452     s->rlayer.curr_rec++;
453 }
454
455 /*-
456  * Return up to 'len' payload bytes received in 'type' records.
457  * 'type' is one of the following:
458  *
459  *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
460  *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
461  *   -  0 (during a shutdown, no data has to be returned)
462  *
463  * If we don't have stored data to work from, read a SSL/TLS record first
464  * (possibly multiple records if we still don't have anything to return).
465  *
466  * This function must handle any surprises the peer may have for us, such as
467  * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
468  * messages are treated as if they were handshake messages *if* the |recvd_type|
469  * argument is non NULL.
470  * Also if record payloads contain fragments too small to process, we store
471  * them until there is enough for the respective protocol (the record protocol
472  * may use arbitrary fragmentation and even interleaving):
473  *     Change cipher spec protocol
474  *             just 1 byte needed, no need for keeping anything stored
475  *     Alert protocol
476  *             2 bytes needed (AlertLevel, AlertDescription)
477  *     Handshake protocol
478  *             4 bytes needed (HandshakeType, uint24 length) -- we just have
479  *             to detect unexpected Client Hello and Hello Request messages
480  *             here, anything else is handled by higher layers
481  *     Application data protocol
482  *             none of our business
483  */
484 int ssl3_read_bytes(SSL *ssl, int type, int *recvd_type, unsigned char *buf,
485                     size_t len, int peek, size_t *readbytes)
486 {
487     int i, j, ret;
488     size_t n, curr_rec, totalbytes;
489     TLS_RECORD *rr;
490     void (*cb) (const SSL *ssl, int type2, int val) = NULL;
491     int is_tls13;
492     SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
493
494     is_tls13 = SSL_CONNECTION_IS_TLS13(s);
495
496     if ((type != 0
497             && (type != SSL3_RT_APPLICATION_DATA)
498             && (type != SSL3_RT_HANDSHAKE))
499         || (peek && (type != SSL3_RT_APPLICATION_DATA))) {
500         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
501         return -1;
502     }
503
504     if ((type == SSL3_RT_HANDSHAKE) && (s->rlayer.handshake_fragment_len > 0))
505         /* (partially) satisfy request from storage */
506     {
507         unsigned char *src = s->rlayer.handshake_fragment;
508         unsigned char *dst = buf;
509         unsigned int k;
510
511         /* peek == 0 */
512         n = 0;
513         while ((len > 0) && (s->rlayer.handshake_fragment_len > 0)) {
514             *dst++ = *src++;
515             len--;
516             s->rlayer.handshake_fragment_len--;
517             n++;
518         }
519         /* move any remaining fragment bytes: */
520         for (k = 0; k < s->rlayer.handshake_fragment_len; k++)
521             s->rlayer.handshake_fragment[k] = *src++;
522
523         if (recvd_type != NULL)
524             *recvd_type = SSL3_RT_HANDSHAKE;
525
526         *readbytes = n;
527         return 1;
528     }
529
530     /*
531      * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
532      */
533
534     if (!ossl_statem_get_in_handshake(s) && SSL_in_init(ssl)) {
535         /* type == SSL3_RT_APPLICATION_DATA */
536         i = s->handshake_func(ssl);
537         /* SSLfatal() already called */
538         if (i < 0)
539             return i;
540         if (i == 0)
541             return -1;
542     }
543  start:
544     s->rwstate = SSL_NOTHING;
545
546     /*-
547      * For each record 'i' up to |num_recs]
548      * rr[i].type     - is the type of record
549      * rr[i].data,    - data
550      * rr[i].off,     - offset into 'data' for next read
551      * rr[i].length,  - number of bytes.
552      */
553     /* get new records if necessary */
554     if (s->rlayer.curr_rec >= s->rlayer.num_recs) {
555         s->rlayer.curr_rec = s->rlayer.num_recs = 0;
556         do {
557             rr = &s->rlayer.tlsrecs[s->rlayer.num_recs];
558
559             ret = HANDLE_RLAYER_READ_RETURN(s,
560                     s->rlayer.rrlmethod->read_record(s->rlayer.rrl,
561                                                      &rr->rechandle,
562                                                      &rr->version, &rr->type,
563                                                      &rr->data, &rr->length,
564                                                      NULL, NULL));
565             if (ret <= 0) {
566                 /* SSLfatal() already called if appropriate */
567                 return ret;
568             }
569             rr->off = 0;
570             s->rlayer.num_recs++;
571         } while (s->rlayer.rrlmethod->processed_read_pending(s->rlayer.rrl)
572                  && s->rlayer.num_recs < SSL_MAX_PIPELINES);
573     }
574     rr = &s->rlayer.tlsrecs[s->rlayer.curr_rec];
575
576     if (s->rlayer.handshake_fragment_len > 0
577             && rr->type != SSL3_RT_HANDSHAKE
578             && SSL_CONNECTION_IS_TLS13(s)) {
579         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
580                  SSL_R_MIXED_HANDSHAKE_AND_NON_HANDSHAKE_DATA);
581         return -1;
582     }
583
584     /*
585      * Reset the count of consecutive warning alerts if we've got a non-empty
586      * record that isn't an alert.
587      */
588     if (rr->type != SSL3_RT_ALERT && rr->length != 0)
589         s->rlayer.alert_count = 0;
590
591     /* we now have a packet which can be read and processed */
592
593     if (s->s3.change_cipher_spec /* set when we receive ChangeCipherSpec,
594                                   * reset by ssl3_get_finished */
595         && (rr->type != SSL3_RT_HANDSHAKE)) {
596         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
597                  SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
598         return -1;
599     }
600
601     /*
602      * If the other end has shut down, throw anything we read away (even in
603      * 'peek' mode)
604      */
605     if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
606         s->rlayer.curr_rec++;
607         s->rwstate = SSL_NOTHING;
608         return 0;
609     }
610
611     if (type == rr->type
612         || (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
613             && type == SSL3_RT_HANDSHAKE && recvd_type != NULL
614             && !is_tls13)) {
615         /*
616          * SSL3_RT_APPLICATION_DATA or
617          * SSL3_RT_HANDSHAKE or
618          * SSL3_RT_CHANGE_CIPHER_SPEC
619          */
620         /*
621          * make sure that we are not getting application data when we are
622          * doing a handshake for the first time
623          */
624         if (SSL_in_init(ssl) && type == SSL3_RT_APPLICATION_DATA
625             && s->enc_read_ctx == NULL) {
626             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_APP_DATA_IN_HANDSHAKE);
627             return -1;
628         }
629
630         if (type == SSL3_RT_HANDSHAKE
631             && rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
632             && s->rlayer.handshake_fragment_len > 0) {
633             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
634             return -1;
635         }
636
637         if (recvd_type != NULL)
638             *recvd_type = rr->type;
639
640         if (len == 0) {
641             /*
642              * Skip a zero length record. This ensures multiple calls to
643              * SSL_read() with a zero length buffer will eventually cause
644              * SSL_pending() to report data as being available.
645              */
646             if (rr->length == 0)
647                 ssl_release_record(s, rr);
648
649             return 0;
650         }
651
652         totalbytes = 0;
653         curr_rec = s->rlayer.curr_rec;
654         do {
655             if (len - totalbytes > rr->length)
656                 n = rr->length;
657             else
658                 n = len - totalbytes;
659
660             memcpy(buf, &(rr->data[rr->off]), n);
661             buf += n;
662             if (peek) {
663                 /* Mark any zero length record as consumed CVE-2016-6305 */
664                 if (rr->length == 0)
665                     ssl_release_record(s, rr);
666             } else {
667                 if (s->options & SSL_OP_CLEANSE_PLAINTEXT)
668                     OPENSSL_cleanse(&(rr->data[rr->off]), n);
669                 rr->length -= n;
670                 rr->off += n;
671                 if (rr->length == 0)
672                     ssl_release_record(s, rr);
673             }
674             if (rr->length == 0
675                 || (peek && n == rr->length)) {
676                 rr++;
677                 curr_rec++;
678             }
679             totalbytes += n;
680         } while (type == SSL3_RT_APPLICATION_DATA
681                     && curr_rec < s->rlayer.num_recs
682                     && totalbytes < len);
683         if (totalbytes == 0) {
684             /* We must have read empty records. Get more data */
685             goto start;
686         }
687         *readbytes = totalbytes;
688         return 1;
689     }
690
691     /*
692      * If we get here, then type != rr->type; if we have a handshake message,
693      * then it was unexpected (Hello Request or Client Hello) or invalid (we
694      * were actually expecting a CCS).
695      */
696
697     /*
698      * Lets just double check that we've not got an SSLv2 record
699      */
700     if (rr->version == SSL2_VERSION) {
701         /*
702          * Should never happen. ssl3_get_record() should only give us an SSLv2
703          * record back if this is the first packet and we are looking for an
704          * initial ClientHello. Therefore |type| should always be equal to
705          * |rr->type|. If not then something has gone horribly wrong
706          */
707         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
708         return -1;
709     }
710
711     if (ssl->method->version == TLS_ANY_VERSION
712         && (s->server || rr->type != SSL3_RT_ALERT)) {
713         /*
714          * If we've got this far and still haven't decided on what version
715          * we're using then this must be a client side alert we're dealing
716          * with. We shouldn't be receiving anything other than a ClientHello
717          * if we are a server.
718          */
719         s->version = rr->version;
720         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
721         return -1;
722     }
723
724     /*-
725      * s->rlayer.handshake_fragment_len == 4  iff  rr->type == SSL3_RT_HANDSHAKE;
726      * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
727      */
728
729     if (rr->type == SSL3_RT_ALERT) {
730         unsigned int alert_level, alert_descr;
731         unsigned char *alert_bytes = rr->data
732                                      + rr->off;
733         PACKET alert;
734
735         if (!PACKET_buf_init(&alert, alert_bytes, rr->length)
736                 || !PACKET_get_1(&alert, &alert_level)
737                 || !PACKET_get_1(&alert, &alert_descr)
738                 || PACKET_remaining(&alert) != 0) {
739             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_INVALID_ALERT);
740             return -1;
741         }
742
743         if (s->msg_callback)
744             s->msg_callback(0, s->version, SSL3_RT_ALERT, alert_bytes, 2, ssl,
745                             s->msg_callback_arg);
746
747         if (s->info_callback != NULL)
748             cb = s->info_callback;
749         else if (ssl->ctx->info_callback != NULL)
750             cb = ssl->ctx->info_callback;
751
752         if (cb != NULL) {
753             j = (alert_level << 8) | alert_descr;
754             cb(ssl, SSL_CB_READ_ALERT, j);
755         }
756
757         if ((!is_tls13 && alert_level == SSL3_AL_WARNING)
758                 || (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED)) {
759             s->s3.warn_alert = alert_descr;
760             ssl_release_record(s, rr);
761
762             s->rlayer.alert_count++;
763             if (s->rlayer.alert_count == MAX_WARN_ALERT_COUNT) {
764                 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
765                          SSL_R_TOO_MANY_WARN_ALERTS);
766                 return -1;
767             }
768         }
769
770         /*
771          * Apart from close_notify the only other warning alert in TLSv1.3
772          * is user_cancelled - which we just ignore.
773          */
774         if (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED) {
775             goto start;
776         } else if (alert_descr == SSL_AD_CLOSE_NOTIFY
777                 && (is_tls13 || alert_level == SSL3_AL_WARNING)) {
778             s->shutdown |= SSL_RECEIVED_SHUTDOWN;
779             return 0;
780         } else if (alert_level == SSL3_AL_FATAL || is_tls13) {
781             s->rwstate = SSL_NOTHING;
782             s->s3.fatal_alert = alert_descr;
783             SSLfatal_data(s, SSL_AD_NO_ALERT,
784                           SSL_AD_REASON_OFFSET + alert_descr,
785                           "SSL alert number %d", alert_descr);
786             s->shutdown |= SSL_RECEIVED_SHUTDOWN;
787             ssl_release_record(s, rr);
788             SSL_CTX_remove_session(s->session_ctx, s->session);
789             return 0;
790         } else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
791             /*
792              * This is a warning but we receive it if we requested
793              * renegotiation and the peer denied it. Terminate with a fatal
794              * alert because if application tried to renegotiate it
795              * presumably had a good reason and expects it to succeed. In
796              * future we might have a renegotiation where we don't care if
797              * the peer refused it where we carry on.
798              */
799             SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_RENEGOTIATION);
800             return -1;
801         } else if (alert_level == SSL3_AL_WARNING) {
802             /* We ignore any other warning alert in TLSv1.2 and below */
803             goto start;
804         }
805
806         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_ALERT_TYPE);
807         return -1;
808     }
809
810     if ((s->shutdown & SSL_SENT_SHUTDOWN) != 0) {
811         if (rr->type == SSL3_RT_HANDSHAKE) {
812             BIO *rbio;
813
814             /*
815              * We ignore any handshake messages sent to us unless they are
816              * TLSv1.3 in which case we want to process them. For all other
817              * handshake messages we can't do anything reasonable with them
818              * because we are unable to write any response due to having already
819              * sent close_notify.
820              */
821             if (!SSL_CONNECTION_IS_TLS13(s)) {
822                 ssl_release_record(s, rr);
823
824                 if ((s->mode & SSL_MODE_AUTO_RETRY) != 0)
825                     goto start;
826
827                 s->rwstate = SSL_READING;
828                 rbio = SSL_get_rbio(ssl);
829                 BIO_clear_retry_flags(rbio);
830                 BIO_set_retry_read(rbio);
831                 return -1;
832             }
833         } else {
834             /*
835              * The peer is continuing to send application data, but we have
836              * already sent close_notify. If this was expected we should have
837              * been called via SSL_read() and this would have been handled
838              * above.
839              * No alert sent because we already sent close_notify
840              */
841             ssl_release_record(s, rr);
842             SSLfatal(s, SSL_AD_NO_ALERT,
843                      SSL_R_APPLICATION_DATA_AFTER_CLOSE_NOTIFY);
844             return -1;
845         }
846     }
847
848     /*
849      * For handshake data we have 'fragment' storage, so fill that so that we
850      * can process the header at a fixed place. This is done after the
851      * "SHUTDOWN" code above to avoid filling the fragment storage with data
852      * that we're just going to discard.
853      */
854     if (rr->type == SSL3_RT_HANDSHAKE) {
855         size_t dest_maxlen = sizeof(s->rlayer.handshake_fragment);
856         unsigned char *dest = s->rlayer.handshake_fragment;
857         size_t *dest_len = &s->rlayer.handshake_fragment_len;
858
859         n = dest_maxlen - *dest_len; /* available space in 'dest' */
860         if (rr->length < n)
861             n = rr->length; /* available bytes */
862
863         /* now move 'n' bytes: */
864         memcpy(dest + *dest_len, rr->data + rr->off, n);
865         rr->off += n;
866         rr->length -= n;
867         *dest_len += n;
868         if (rr->length == 0)
869             ssl_release_record(s, rr);
870
871         if (*dest_len < dest_maxlen)
872             goto start;     /* fragment was too small */
873     }
874
875     if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
876         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
877         return -1;
878     }
879
880     /*
881      * Unexpected handshake message (ClientHello, NewSessionTicket (TLS1.3) or
882      * protocol violation)
883      */
884     if ((s->rlayer.handshake_fragment_len >= 4)
885             && !ossl_statem_get_in_handshake(s)) {
886         int ined = (s->early_data_state == SSL_EARLY_DATA_READING);
887
888         /* We found handshake data, so we're going back into init */
889         ossl_statem_set_in_init(s, 1);
890
891         i = s->handshake_func(ssl);
892         /* SSLfatal() already called if appropriate */
893         if (i < 0)
894             return i;
895         if (i == 0) {
896             return -1;
897         }
898
899         /*
900          * If we were actually trying to read early data and we found a
901          * handshake message, then we don't want to continue to try and read
902          * the application data any more. It won't be "early" now.
903          */
904         if (ined)
905             return -1;
906
907         if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
908             if (!RECORD_LAYER_read_pending(&s->rlayer)) {
909                 BIO *bio;
910                 /*
911                  * In the case where we try to read application data, but we
912                  * trigger an SSL handshake, we return -1 with the retry
913                  * option set.  Otherwise renegotiation may cause nasty
914                  * problems in the blocking world
915                  */
916                 s->rwstate = SSL_READING;
917                 bio = SSL_get_rbio(ssl);
918                 BIO_clear_retry_flags(bio);
919                 BIO_set_retry_read(bio);
920                 return -1;
921             }
922         }
923         goto start;
924     }
925
926     switch (rr->type) {
927     default:
928         /*
929          * TLS 1.0 and 1.1 say you SHOULD ignore unrecognised record types, but
930          * TLS 1.2 says you MUST send an unexpected message alert. We use the
931          * TLS 1.2 behaviour for all protocol versions to prevent issues where
932          * no progress is being made and the peer continually sends unrecognised
933          * record types, using up resources processing them.
934          */
935         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
936         return -1;
937     case SSL3_RT_CHANGE_CIPHER_SPEC:
938     case SSL3_RT_ALERT:
939     case SSL3_RT_HANDSHAKE:
940         /*
941          * we already handled all of these, with the possible exception of
942          * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
943          * that should not happen when type != rr->type
944          */
945         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, ERR_R_INTERNAL_ERROR);
946         return -1;
947     case SSL3_RT_APPLICATION_DATA:
948         /*
949          * At this point, we were expecting handshake data, but have
950          * application data.  If the library was running inside ssl3_read()
951          * (i.e. in_read_app_data is set) and it makes sense to read
952          * application data at this point (session renegotiation not yet
953          * started), we will indulge it.
954          */
955         if (ossl_statem_app_data_allowed(s)) {
956             s->s3.in_read_app_data = 2;
957             return -1;
958         } else if (ossl_statem_skip_early_data(s)) {
959             /*
960              * This can happen after a client sends a CH followed by early_data,
961              * but the server responds with a HelloRetryRequest. The server
962              * reads the next record from the client expecting to find a
963              * plaintext ClientHello but gets a record which appears to be
964              * application data. The trial decrypt "works" because null
965              * decryption was applied. We just skip it and move on to the next
966              * record.
967              */
968             if (!ossl_early_data_count_ok(s, rr->length,
969                                           EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
970                 /* SSLfatal() already called */
971                 return -1;
972             }
973             ssl_release_record(s, rr);
974             goto start;
975         } else {
976             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
977             return -1;
978         }
979     }
980 }
981
982 /*
983  * Returns true if the current rrec was sent in SSLv2 backwards compatible
984  * format and false otherwise.
985  */
986 int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl)
987 {
988     if (SSL_CONNECTION_IS_DTLS(rl->s))
989         return 0;
990     return rl->tlsrecs[0].version == SSL2_VERSION;
991 }
992
993 static OSSL_FUNC_rlayer_msg_callback_fn rlayer_msg_callback_wrapper;
994 static void rlayer_msg_callback_wrapper(int write_p, int version,
995                                         int content_type, const void *buf,
996                                         size_t len, void *cbarg)
997 {
998     SSL_CONNECTION *s = cbarg;
999     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1000
1001     if (s->msg_callback != NULL)
1002         s->msg_callback(write_p, version, content_type, buf, len, ssl,
1003                         s->msg_callback_arg);
1004 }
1005
1006 static OSSL_FUNC_rlayer_security_fn rlayer_security_wrapper;
1007 static int rlayer_security_wrapper(void *cbarg, int op, int bits, int nid,
1008                                    void *other)
1009 {
1010     SSL_CONNECTION *s = cbarg;
1011
1012     return ssl_security(s, op, bits, nid, other);
1013 }
1014
1015 static OSSL_FUNC_rlayer_padding_fn rlayer_padding_wrapper;
1016 static size_t rlayer_padding_wrapper(void *cbarg, int type, size_t len)
1017 {
1018     SSL_CONNECTION *s = cbarg;
1019     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1020
1021     return s->rlayer.record_padding_cb(ssl, type, len,
1022                                        s->rlayer.record_padding_arg);
1023 }
1024
1025 static const OSSL_DISPATCH rlayer_dispatch[] = {
1026     { OSSL_FUNC_RLAYER_SKIP_EARLY_DATA, (void (*)(void))ossl_statem_skip_early_data },
1027     { OSSL_FUNC_RLAYER_MSG_CALLBACK, (void (*)(void))rlayer_msg_callback_wrapper },
1028     { OSSL_FUNC_RLAYER_SECURITY, (void (*)(void))rlayer_security_wrapper },
1029     { OSSL_FUNC_RLAYER_PADDING, (void (*)(void))rlayer_padding_wrapper },
1030     { 0, NULL }
1031 };
1032
1033 static const OSSL_RECORD_METHOD *ssl_select_next_record_layer(SSL_CONNECTION *s,
1034                                                               int direction,
1035                                                               int level)
1036 {
1037
1038     if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE) {
1039         if (SSL_CONNECTION_IS_DTLS(s))
1040             return &ossl_dtls_record_method;
1041
1042         return &ossl_tls_record_method;
1043     }
1044
1045 #ifndef OPENSSL_NO_KTLS
1046     /* KTLS does not support renegotiation */
1047     if (level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION
1048             && (s->options & SSL_OP_ENABLE_KTLS) != 0
1049             && (SSL_CONNECTION_IS_TLS13(s) || SSL_IS_FIRST_HANDSHAKE(s)))
1050         return &ossl_ktls_record_method;
1051 #endif
1052
1053     /* Default to the current OSSL_RECORD_METHOD */
1054     return direction == OSSL_RECORD_DIRECTION_READ ? s->rlayer.rrlmethod
1055                                                    : s->rlayer.wrlmethod;
1056 }
1057
1058 static int ssl_post_record_layer_select(SSL_CONNECTION *s, int direction)
1059 {
1060     const OSSL_RECORD_METHOD *thismethod;
1061     OSSL_RECORD_LAYER *thisrl;
1062
1063     if (direction == OSSL_RECORD_DIRECTION_READ) {
1064         thismethod = s->rlayer.rrlmethod;
1065         thisrl = s->rlayer.rrl;
1066     } else {
1067         thismethod = s->rlayer.wrlmethod;
1068         thisrl = s->rlayer.wrl;
1069     }
1070
1071 #ifndef OPENSSL_NO_KTLS
1072     {
1073         SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1074
1075         if (s->rlayer.rrlmethod == &ossl_ktls_record_method) {
1076             /* KTLS does not support renegotiation so disallow it */
1077             SSL_set_options(ssl, SSL_OP_NO_RENEGOTIATION);
1078         }
1079     }
1080 #endif
1081     if (SSL_IS_FIRST_HANDSHAKE(s) && thismethod->set_first_handshake != NULL)
1082         thismethod->set_first_handshake(thisrl, 1);
1083
1084     if (s->max_pipelines != 0 && thismethod->set_max_pipelines != NULL)
1085         thismethod->set_max_pipelines(thisrl, s->max_pipelines);
1086
1087     return 1;
1088 }
1089
1090 int ssl_set_new_record_layer(SSL_CONNECTION *s, int version,
1091                              int direction, int level,
1092                              unsigned char *key, size_t keylen,
1093                              unsigned char *iv,  size_t ivlen,
1094                              unsigned char *mackey, size_t mackeylen,
1095                              const EVP_CIPHER *ciph, size_t taglen,
1096                              int mactype, const EVP_MD *md,
1097                              const SSL_COMP *comp)
1098 {
1099     OSSL_PARAM options[5], *opts = options;
1100     OSSL_PARAM settings[6], *set =  settings;
1101     const OSSL_RECORD_METHOD **thismethod;
1102     OSSL_RECORD_LAYER **thisrl, *newrl = NULL;
1103     BIO *thisbio;
1104     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1105     const OSSL_RECORD_METHOD *meth;
1106     int use_etm, stream_mac = 0, tlstree = 0;
1107     unsigned int maxfrag = (direction == OSSL_RECORD_DIRECTION_WRITE)
1108                            ? ssl_get_max_send_fragment(s)
1109                            : SSL3_RT_MAX_PLAIN_LENGTH;
1110     int use_early_data = 0;
1111     uint32_t max_early_data;
1112     COMP_METHOD *compm = (comp == NULL) ? NULL : comp->method;
1113
1114     meth = ssl_select_next_record_layer(s, direction, level);
1115
1116     if (direction == OSSL_RECORD_DIRECTION_READ) {
1117         thismethod = &s->rlayer.rrlmethod;
1118         thisrl = &s->rlayer.rrl;
1119         thisbio = s->rbio;
1120     } else {
1121         thismethod = &s->rlayer.wrlmethod;
1122         thisrl = &s->rlayer.wrl;
1123         thisbio = s->wbio;
1124     }
1125
1126     if (meth == NULL)
1127         meth = *thismethod;
1128
1129     if (!ossl_assert(meth != NULL)) {
1130         ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1131         return 0;
1132     }
1133
1134     /* Parameters that *may* be supported by a record layer if passed */
1135     *opts++ = OSSL_PARAM_construct_uint64(OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS,
1136                                           &s->options);
1137     *opts++ = OSSL_PARAM_construct_uint32(OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE,
1138                                           &s->mode);
1139     if (direction == OSSL_RECORD_DIRECTION_READ) {
1140         *opts++ = OSSL_PARAM_construct_size_t(OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN,
1141                                               &s->rlayer.default_read_buf_len);
1142         *opts++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD,
1143                                            &s->rlayer.read_ahead);
1144     } else {
1145         *opts++ = OSSL_PARAM_construct_size_t(OSSL_LIBSSL_RECORD_LAYER_PARAM_BLOCK_PADDING,
1146                                               &s->rlayer.block_padding);
1147     }
1148     *opts = OSSL_PARAM_construct_end();
1149
1150     /* Parameters that *must* be supported by a record layer if passed */
1151     if (direction == OSSL_RECORD_DIRECTION_READ) {
1152         use_etm = SSL_READ_ETM(s) ? 1 : 0;
1153         if ((s->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM) != 0)
1154             stream_mac = 1;
1155
1156         if ((s->mac_flags & SSL_MAC_FLAG_READ_MAC_TLSTREE) != 0)
1157             tlstree = 1;
1158     } else {
1159         use_etm = SSL_WRITE_ETM(s) ? 1 : 0;
1160         if ((s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM) != 0)
1161             stream_mac = 1;
1162
1163         if ((s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_TLSTREE) != 0)
1164             tlstree = 1;
1165     }
1166
1167     if (use_etm)
1168         *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM,
1169                                           &use_etm);
1170
1171     if (stream_mac)
1172         *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC,
1173                                           &stream_mac);
1174
1175     if (tlstree)
1176         *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE,
1177                                           &tlstree);
1178
1179     /*
1180      * We only need to do this for the read side. The write side should already
1181      * have the correct value due to the ssl_get_max_send_fragment() call above
1182      */
1183     if (direction == OSSL_RECORD_DIRECTION_READ
1184             && s->session != NULL
1185             && USE_MAX_FRAGMENT_LENGTH_EXT(s->session))
1186         maxfrag = GET_MAX_FRAGMENT_LENGTH(s->session);
1187
1188
1189     if (maxfrag != SSL3_RT_MAX_PLAIN_LENGTH)
1190         *set++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN,
1191                                            &maxfrag);
1192
1193     /*
1194      * The record layer must check the amount of early data sent or received
1195      * using the early keys. A server also needs to worry about rejected early
1196      * data that might arrive when the handshake keys are in force.
1197      */
1198     if (s->server && direction == OSSL_RECORD_DIRECTION_READ) {
1199         use_early_data = (level == OSSL_RECORD_PROTECTION_LEVEL_EARLY
1200                           || level == OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE);
1201     } else if (!s->server && direction == OSSL_RECORD_DIRECTION_WRITE) {
1202         use_early_data = (level == OSSL_RECORD_PROTECTION_LEVEL_EARLY);
1203     }
1204     if (use_early_data) {
1205         max_early_data = ossl_get_max_early_data(s);
1206
1207         if (max_early_data != 0)
1208             *set++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA,
1209                                                &max_early_data);
1210     }
1211
1212     *set = OSSL_PARAM_construct_end();
1213
1214     for (;;) {
1215         int rlret;
1216         BIO *prev = NULL;
1217         BIO *next = NULL;
1218         unsigned int epoch = 0;
1219         OSSL_DISPATCH rlayer_dispatch_tmp[OSSL_NELEM(rlayer_dispatch)];
1220         size_t i, j;
1221
1222         if (direction == OSSL_RECORD_DIRECTION_READ) {
1223             prev = s->rlayer.rrlnext;
1224             if (SSL_CONNECTION_IS_DTLS(s)
1225                     && level != OSSL_RECORD_PROTECTION_LEVEL_NONE)
1226                 epoch =  DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer) + 1; /* new epoch */
1227
1228             if (SSL_CONNECTION_IS_DTLS(s))
1229                 next = BIO_new(BIO_s_dgram_mem());
1230             else
1231                 next = BIO_new(BIO_s_mem());
1232
1233             if (next == NULL) {
1234                 BIO_free(prev);
1235                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1236                 return 0;
1237             }
1238             s->rlayer.rrlnext = next;
1239         } else {
1240             if (SSL_CONNECTION_IS_DTLS(s)
1241                     && level != OSSL_RECORD_PROTECTION_LEVEL_NONE)
1242                 epoch =  DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) + 1; /* new epoch */
1243         }
1244
1245         /*
1246          * Create a copy of the dispatch array, missing out wrappers for
1247          * callbacks that we don't need.
1248          */
1249         for (i = 0, j = 0; i < OSSL_NELEM(rlayer_dispatch); i++) {
1250             switch (rlayer_dispatch[i].function_id) {
1251             case OSSL_FUNC_RLAYER_MSG_CALLBACK:
1252                 if (s->msg_callback == NULL)
1253                     continue;
1254                 break;
1255             case OSSL_FUNC_RLAYER_PADDING:
1256                 if (s->rlayer.record_padding_cb == NULL)
1257                     continue;
1258                 break;
1259             default:
1260                 break;
1261             }
1262             rlayer_dispatch_tmp[j++] = rlayer_dispatch[i];
1263         }
1264
1265         rlret = meth->new_record_layer(sctx->libctx, sctx->propq, version,
1266                                        s->server, direction, level, epoch,
1267                                        key, keylen, iv, ivlen, mackey,
1268                                        mackeylen, ciph, taglen, mactype, md,
1269                                        compm, prev, thisbio, next, NULL, NULL,
1270                                        settings, options, rlayer_dispatch_tmp,
1271                                        s, &newrl);
1272         BIO_free(prev);
1273         switch (rlret) {
1274         case OSSL_RECORD_RETURN_FATAL:
1275             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_RECORD_LAYER_FAILURE);
1276             return 0;
1277
1278         case OSSL_RECORD_RETURN_NON_FATAL_ERR:
1279             if (*thismethod != meth && *thismethod != NULL) {
1280                 /*
1281                  * We tried a new record layer method, but it didn't work out,
1282                  * so we fallback to the original method and try again
1283                  */
1284                 meth = *thismethod;
1285                 continue;
1286             }
1287             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_NO_SUITABLE_RECORD_LAYER);
1288             return 0;
1289
1290         case OSSL_RECORD_RETURN_SUCCESS:
1291             break;
1292
1293         default:
1294             /* Should not happen */
1295             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1296             return 0;
1297         }
1298         break;
1299     }
1300
1301     /*
1302      * Free the old record layer if we have one except in the case of DTLS when
1303      * writing. In that case the record layer is still referenced by buffered
1304      * messages for potential retransmit. Only when those buffered messages get
1305      * freed do we free the record layer object (see dtls1_hm_fragment_free)
1306      */
1307     if (!SSL_CONNECTION_IS_DTLS(s) || direction == OSSL_RECORD_DIRECTION_READ) {
1308         if (*thismethod != NULL && !(*thismethod)->free(*thisrl)) {
1309             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1310             return 0;
1311         }
1312     }
1313
1314     *thisrl = newrl;
1315     *thismethod = meth;
1316
1317     return ssl_post_record_layer_select(s, direction);
1318 }
1319
1320 int ssl_set_record_protocol_version(SSL_CONNECTION *s, int vers)
1321 {
1322     if (!ossl_assert(s->rlayer.rrlmethod != NULL)
1323             || !ossl_assert(s->rlayer.wrlmethod != NULL))
1324         return 0;
1325     s->rlayer.rrlmethod->set_protocol_version(s->rlayer.rrl, s->version);
1326     s->rlayer.wrlmethod->set_protocol_version(s->rlayer.wrl, s->version);
1327
1328     return 1;
1329 }