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