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