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