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