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