Remove unneccesary KTLS code from non-KTLS specific files
[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 <openssl/param_build.h>
19 #include "record_local.h"
20 #include "internal/packet.h"
21
22 #if     defined(OPENSSL_SMALL_FOOTPRINT) || \
23         !(      defined(AES_ASM) &&     ( \
24                 defined(__x86_64)       || defined(__x86_64__)  || \
25                 defined(_M_AMD64)       || defined(_M_X64)      ) \
26         )
27 # undef EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
28 # define EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK 0
29 #endif
30
31 void RECORD_LAYER_init(RECORD_LAYER *rl, SSL_CONNECTION *s)
32 {
33     rl->s = s;
34     RECORD_LAYER_set_first_record(&s->rlayer);
35     SSL3_RECORD_clear(rl->rrec, SSL_MAX_PIPELINES);
36 }
37
38 void RECORD_LAYER_clear(RECORD_LAYER *rl)
39 {
40     rl->rstate = SSL_ST_READ_HEADER;
41
42     /*
43      * Do I need to clear read_ahead? As far as I can tell read_ahead did not
44      * previously get reset by SSL_clear...so I'll keep it that way..but is
45      * that right?
46      */
47
48     rl->packet = NULL;
49     rl->packet_length = 0;
50     rl->wnum = 0;
51     memset(rl->handshake_fragment, 0, sizeof(rl->handshake_fragment));
52     rl->handshake_fragment_len = 0;
53     rl->wpend_tot = 0;
54     rl->wpend_type = 0;
55     rl->wpend_ret = 0;
56     rl->wpend_buf = NULL;
57
58     SSL3_BUFFER_clear(&rl->rbuf);
59     ssl3_release_write_buffer(rl->s);
60     rl->numrpipes = 0;
61     SSL3_RECORD_clear(rl->rrec, SSL_MAX_PIPELINES);
62
63     RECORD_LAYER_reset_read_sequence(rl);
64     RECORD_LAYER_reset_write_sequence(rl);
65
66     if (rl->d)
67         DTLS_RECORD_LAYER_clear(rl);
68 }
69
70 void RECORD_LAYER_release(RECORD_LAYER *rl)
71 {
72     if (SSL3_BUFFER_is_initialised(&rl->rbuf))
73         ssl3_release_read_buffer(rl->s);
74     if (rl->numwpipes > 0)
75         ssl3_release_write_buffer(rl->s);
76     SSL3_RECORD_release(rl->rrec, SSL_MAX_PIPELINES);
77 }
78
79 /* Checks if we have unprocessed read ahead data pending */
80 int RECORD_LAYER_read_pending(const RECORD_LAYER *rl)
81 {
82     /*
83      * TODO(RECLAYER): Temporarily do it the old way until DTLS is converted to
84      * the new record layer code
85      */
86     if (SSL_CONNECTION_IS_DTLS(rl->s))
87         return SSL3_BUFFER_get_left(&rl->rbuf) != 0;
88
89     return rl->s->rrlmethod->unprocessed_read_pending(rl->s->rrl);
90 }
91
92 /* Checks if we have decrypted unread record data pending */
93 int RECORD_LAYER_processed_read_pending(const RECORD_LAYER *rl)
94 {
95     /*
96      * TODO(RECLAYER): Temporarily do it the old way until DTLS is converted to
97      * the new record layer code
98      */
99     if (SSL_CONNECTION_IS_DTLS(rl->s)) {
100         const SSL3_RECORD *rr = rl->rrec;
101
102         size_t curr_rec = 0, num_recs = RECORD_LAYER_get_numrpipes(rl);
103
104         while (curr_rec < num_recs && SSL3_RECORD_is_read(&rr[curr_rec]))
105             curr_rec++;
106
107         return curr_rec < num_recs;
108     }
109
110     return (rl->curr_rec < rl->num_recs)
111            || rl->s->rrlmethod->processed_read_pending(rl->s->rrl);
112 }
113
114 int RECORD_LAYER_write_pending(const RECORD_LAYER *rl)
115 {
116     return (rl->numwpipes > 0)
117         && SSL3_BUFFER_get_left(&rl->wbuf[rl->numwpipes - 1]) != 0;
118 }
119
120 void RECORD_LAYER_reset_read_sequence(RECORD_LAYER *rl)
121 {
122     memset(rl->read_sequence, 0, sizeof(rl->read_sequence));
123 }
124
125 void RECORD_LAYER_reset_write_sequence(RECORD_LAYER *rl)
126 {
127     memset(rl->write_sequence, 0, sizeof(rl->write_sequence));
128 }
129
130 size_t ssl3_pending(const SSL *s)
131 {
132     size_t i, num = 0;
133     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
134
135     if (sc == NULL)
136         return 0;
137
138     if (sc->rlayer.rstate == SSL_ST_READ_BODY)
139         return 0;
140
141     /*
142      * TODO(RECLAYER): We need to do it the old way temporary for DTLS until
143      * that is converted to use the new record layer code
144      */
145     if (SSL_CONNECTION_IS_DTLS(sc)) {
146         DTLS1_RECORD_DATA *rdata;
147         pitem *item, *iter;
148
149         iter = pqueue_iterator(sc->rlayer.d->buffered_app_data.q);
150         while ((item = pqueue_next(&iter)) != NULL) {
151             rdata = item->data;
152             num += rdata->rrec.length;
153         }
154
155         for (i = 0; i < RECORD_LAYER_get_numrpipes(&sc->rlayer); i++) {
156             if (SSL3_RECORD_get_type(&sc->rlayer.rrec[i])
157                 != SSL3_RT_APPLICATION_DATA)
158                 return 0;
159             num += SSL3_RECORD_get_length(&sc->rlayer.rrec[i]);
160         }
161     } else {
162         for (i = 0; i <sc->rlayer.num_recs; i++) {
163             if (sc->rlayer.tlsrecs[i].type != SSL3_RT_APPLICATION_DATA)
164                 return 0;
165             num += sc->rlayer.tlsrecs[i].length;
166         }
167     }
168
169     return num;
170 }
171
172 void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len)
173 {
174     ctx->default_read_buf_len = len;
175 }
176
177 void SSL_set_default_read_buffer_len(SSL *s, size_t len)
178 {
179     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
180
181     if (sc == NULL)
182         return;
183     SSL3_BUFFER_set_default_len(sc->rrlmethod->get0_rbuf(sc->rrl), len);
184 }
185
186 const char *SSL_rstate_string_long(const SSL *s)
187 {
188     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
189
190     if (sc == NULL)
191         return NULL;
192
193     switch (sc->rlayer.rstate) {
194     case SSL_ST_READ_HEADER:
195         return "read header";
196     case SSL_ST_READ_BODY:
197         return "read body";
198     case SSL_ST_READ_DONE:
199         return "read done";
200     default:
201         return "unknown";
202     }
203 }
204
205 const char *SSL_rstate_string(const SSL *s)
206 {
207     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
208
209     if (sc == NULL)
210         return NULL;
211
212     switch (sc->rlayer.rstate) {
213     case SSL_ST_READ_HEADER:
214         return "RH";
215     case SSL_ST_READ_BODY:
216         return "RB";
217     case SSL_ST_READ_DONE:
218         return "RD";
219     default:
220         return "unknown";
221     }
222 }
223
224
225 /*
226  * Call this to write data in records of type 'type' It will return <= 0 if
227  * not all data has been sent or non-blocking IO.
228  */
229 int ssl3_write_bytes(SSL *ssl, int type, const void *buf_, size_t len,
230                      size_t *written)
231 {
232     const unsigned char *buf = buf_;
233     size_t tot;
234     size_t n, max_send_fragment, split_send_fragment, maxpipes;
235 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
236     size_t nw;
237 #endif
238     SSL3_BUFFER *wb;
239     int i;
240     size_t tmpwrit;
241     SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
242
243     if (s == NULL)
244         return -1;
245
246     wb = &s->rlayer.wbuf[0];
247     s->rwstate = SSL_NOTHING;
248     tot = s->rlayer.wnum;
249     /*
250      * ensure that if we end up with a smaller value of data to write out
251      * than the original len from a write which didn't complete for
252      * non-blocking I/O and also somehow ended up avoiding the check for
253      * this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be
254      * possible to end up with (len-tot) as a large number that will then
255      * promptly send beyond the end of the users buffer ... so we trap and
256      * report the error in a way the user will notice
257      */
258     if ((len < s->rlayer.wnum)
259         || ((wb->left != 0) && (len < (s->rlayer.wnum + s->rlayer.wpend_tot)))) {
260         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_LENGTH);
261         return -1;
262     }
263
264     if (s->early_data_state == SSL_EARLY_DATA_WRITING
265             && !ossl_early_data_count_ok(s, len, 0, 1)) {
266         /* SSLfatal() already called */
267         return -1;
268     }
269
270     s->rlayer.wnum = 0;
271
272     /*
273      * If we are supposed to be sending a KeyUpdate or NewSessionTicket then go
274      * into init unless we have writes pending - in which case we should finish
275      * doing that first.
276      */
277     if (wb->left == 0 && (s->key_update != SSL_KEY_UPDATE_NONE
278                           || s->ext.extra_tickets_expected > 0))
279         ossl_statem_set_in_init(s, 1);
280
281     /*
282      * When writing early data on the server side we could be "in_init" in
283      * between receiving the EoED and the CF - but we don't want to handle those
284      * messages yet.
285      */
286     if (SSL_in_init(ssl) && !ossl_statem_get_in_handshake(s)
287             && s->early_data_state != SSL_EARLY_DATA_UNAUTH_WRITING) {
288         i = s->handshake_func(ssl);
289         /* SSLfatal() already called */
290         if (i < 0)
291             return i;
292         if (i == 0) {
293             return -1;
294         }
295     }
296
297     /*
298      * first check if there is a SSL3_BUFFER still being written out.  This
299      * will happen with non blocking IO
300      */
301     if (wb->left != 0) {
302         /* SSLfatal() already called if appropriate */
303         i = ssl3_write_pending(s, type, &buf[tot], s->rlayer.wpend_tot,
304                                &tmpwrit);
305         if (i <= 0) {
306             /* XXX should we ssl3_release_write_buffer if i<0? */
307             s->rlayer.wnum = tot;
308             return i;
309         }
310         tot += tmpwrit;               /* this might be last fragment */
311     }
312 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
313     /*
314      * Depending on platform multi-block can deliver several *times*
315      * better performance. Downside is that it has to allocate
316      * jumbo buffer to accommodate up to 8 records, but the
317      * compromise is considered worthy.
318      */
319     if (type == SSL3_RT_APPLICATION_DATA
320             && len >= 4 * (max_send_fragment = ssl_get_max_send_fragment(s))
321             && s->compress == NULL
322             && s->msg_callback == NULL
323             && !SSL_WRITE_ETM(s)
324             && SSL_USE_EXPLICIT_IV(s)
325             && !BIO_get_ktls_send(s->wbio)
326             && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx))
327                 & EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK) != 0) {
328         unsigned char aad[13];
329         EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param;
330         size_t packlen;
331         int packleni;
332
333         /* minimize address aliasing conflicts */
334         if ((max_send_fragment & 0xfff) == 0)
335             max_send_fragment -= 512;
336
337         if (tot == 0 || wb->buf == NULL) { /* allocate jumbo buffer */
338             ssl3_release_write_buffer(s);
339
340             packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
341                                           EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE,
342                                           (int)max_send_fragment, NULL);
343
344             if (len >= 8 * max_send_fragment)
345                 packlen *= 8;
346             else
347                 packlen *= 4;
348
349             if (!ssl3_setup_write_buffer(s, 1, packlen)) {
350                 /* SSLfatal() already called */
351                 return -1;
352             }
353         } else if (tot == len) { /* done? */
354             /* free jumbo buffer */
355             ssl3_release_write_buffer(s);
356             *written = tot;
357             return 1;
358         }
359
360         n = (len - tot);
361         for (;;) {
362             if (n < 4 * max_send_fragment) {
363                 /* free jumbo buffer */
364                 ssl3_release_write_buffer(s);
365                 break;
366             }
367
368             if (s->s3.alert_dispatch) {
369                 i = ssl->method->ssl_dispatch_alert(ssl);
370                 if (i <= 0) {
371                     /* SSLfatal() already called if appropriate */
372                     s->rlayer.wnum = tot;
373                     return i;
374                 }
375             }
376
377             if (n >= 8 * max_send_fragment)
378                 nw = max_send_fragment * (mb_param.interleave = 8);
379             else
380                 nw = max_send_fragment * (mb_param.interleave = 4);
381
382             memcpy(aad, s->rlayer.write_sequence, 8);
383             aad[8] = type;
384             aad[9] = (unsigned char)(s->version >> 8);
385             aad[10] = (unsigned char)(s->version);
386             aad[11] = 0;
387             aad[12] = 0;
388             mb_param.out = NULL;
389             mb_param.inp = aad;
390             mb_param.len = nw;
391
392             packleni = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
393                                           EVP_CTRL_TLS1_1_MULTIBLOCK_AAD,
394                                           sizeof(mb_param), &mb_param);
395             packlen = (size_t)packleni;
396             if (packleni <= 0 || packlen > wb->len) { /* never happens */
397                 /* free jumbo buffer */
398                 ssl3_release_write_buffer(s);
399                 break;
400             }
401
402             mb_param.out = wb->buf;
403             mb_param.inp = &buf[tot];
404             mb_param.len = nw;
405
406             if (EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
407                                     EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT,
408                                     sizeof(mb_param), &mb_param) <= 0)
409                 return -1;
410
411             s->rlayer.write_sequence[7] += mb_param.interleave;
412             if (s->rlayer.write_sequence[7] < mb_param.interleave) {
413                 int j = 6;
414                 while (j >= 0 && (++s->rlayer.write_sequence[j--]) == 0) ;
415             }
416
417             wb->offset = 0;
418             wb->left = packlen;
419
420             s->rlayer.wpend_tot = nw;
421             s->rlayer.wpend_buf = &buf[tot];
422             s->rlayer.wpend_type = type;
423             s->rlayer.wpend_ret = nw;
424
425             i = ssl3_write_pending(s, type, &buf[tot], nw, &tmpwrit);
426             if (i <= 0) {
427                 /* SSLfatal() already called if appropriate */
428                 if (i < 0 && (!s->wbio || !BIO_should_retry(s->wbio))) {
429                     /* free jumbo buffer */
430                     ssl3_release_write_buffer(s);
431                 }
432                 s->rlayer.wnum = tot;
433                 return i;
434             }
435             if (tmpwrit == n) {
436                 /* free jumbo buffer */
437                 ssl3_release_write_buffer(s);
438                 *written = tot + tmpwrit;
439                 return 1;
440             }
441             n -= tmpwrit;
442             tot += tmpwrit;
443         }
444     } else
445 #endif  /* !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK */
446     if (tot == len) {           /* done? */
447         if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_CONNECTION_IS_DTLS(s))
448             ssl3_release_write_buffer(s);
449
450         *written = tot;
451         return 1;
452     }
453
454     n = (len - tot);
455
456     max_send_fragment = ssl_get_max_send_fragment(s);
457     split_send_fragment = ssl_get_split_send_fragment(s);
458     /*
459      * If max_pipelines is 0 then this means "undefined" and we default to
460      * 1 pipeline. Similarly if the cipher does not support pipelined
461      * processing then we also only use 1 pipeline, or if we're not using
462      * explicit IVs
463      */
464     maxpipes = s->max_pipelines;
465     if (maxpipes > SSL_MAX_PIPELINES) {
466         /*
467          * We should have prevented this when we set max_pipelines so we
468          * shouldn't get here
469          */
470         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
471         return -1;
472     }
473     if (maxpipes == 0
474         || s->enc_write_ctx == NULL
475         || (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx))
476             & EVP_CIPH_FLAG_PIPELINE) == 0
477         || !SSL_USE_EXPLICIT_IV(s))
478         maxpipes = 1;
479     if (max_send_fragment == 0
480             || split_send_fragment == 0
481             || split_send_fragment > max_send_fragment) {
482         /*
483          * We should have prevented this when we set/get the split and max send
484          * fragments so we shouldn't get here
485          */
486         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
487         return -1;
488     }
489
490     for (;;) {
491         size_t pipelens[SSL_MAX_PIPELINES], tmppipelen, remain;
492         size_t numpipes, j;
493
494         if (n == 0)
495             numpipes = 1;
496         else
497             numpipes = ((n - 1) / split_send_fragment) + 1;
498         if (numpipes > maxpipes)
499             numpipes = maxpipes;
500
501         if (n / numpipes >= max_send_fragment) {
502             /*
503              * We have enough data to completely fill all available
504              * pipelines
505              */
506             for (j = 0; j < numpipes; j++) {
507                 pipelens[j] = max_send_fragment;
508             }
509         } else {
510             /* We can partially fill all available pipelines */
511             tmppipelen = n / numpipes;
512             remain = n % numpipes;
513             for (j = 0; j < numpipes; j++) {
514                 pipelens[j] = tmppipelen;
515                 if (j < remain)
516                     pipelens[j]++;
517             }
518         }
519
520         i = do_ssl3_write(s, type, &(buf[tot]), pipelens, numpipes, 0,
521                           &tmpwrit);
522         if (i <= 0) {
523             /* SSLfatal() already called if appropriate */
524             /* XXX should we ssl3_release_write_buffer if i<0? */
525             s->rlayer.wnum = tot;
526             return i;
527         }
528
529         if (tmpwrit == n ||
530             (type == SSL3_RT_APPLICATION_DATA &&
531              (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
532             /*
533              * next chunk of data should get another prepended empty fragment
534              * in ciphersuites with known-IV weakness:
535              */
536             s->s3.empty_fragment_done = 0;
537
538             if (tmpwrit == n
539                     && (s->mode & SSL_MODE_RELEASE_BUFFERS) != 0
540                     && !SSL_CONNECTION_IS_DTLS(s))
541                 ssl3_release_write_buffer(s);
542
543             *written = tot + tmpwrit;
544             return 1;
545         }
546
547         n -= tmpwrit;
548         tot += tmpwrit;
549     }
550 }
551
552 int do_ssl3_write(SSL_CONNECTION *s, int type, const unsigned char *buf,
553                   size_t *pipelens, size_t numpipes,
554                   int create_empty_fragment, size_t *written)
555 {
556     WPACKET pkt[SSL_MAX_PIPELINES];
557     SSL3_RECORD wr[SSL_MAX_PIPELINES];
558     WPACKET *thispkt;
559     SSL3_RECORD *thiswr;
560     unsigned char *recordstart;
561     int i, mac_size, clear = 0;
562     size_t prefix_len = 0;
563     int eivlen = 0;
564     size_t align = 0;
565     SSL3_BUFFER *wb;
566     SSL_SESSION *sess;
567     size_t totlen = 0, len, wpinited = 0;
568     size_t j;
569     int using_ktls;
570     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
571
572     for (j = 0; j < numpipes; j++)
573         totlen += pipelens[j];
574     /*
575      * first check if there is a SSL3_BUFFER still being written out.  This
576      * will happen with non blocking IO
577      */
578     if (RECORD_LAYER_write_pending(&s->rlayer)) {
579         /* Calls SSLfatal() as required */
580         return ssl3_write_pending(s, type, buf, totlen, written);
581     }
582
583     /* If we have an alert to send, lets send it */
584     if (s->s3.alert_dispatch) {
585         i = ssl->method->ssl_dispatch_alert(ssl);
586         if (i <= 0) {
587             /* SSLfatal() already called if appropriate */
588             return i;
589         }
590         /* if it went, fall through and send more stuff */
591     }
592
593     if (s->rlayer.numwpipes < numpipes) {
594         if (!ssl3_setup_write_buffer(s, numpipes, 0)) {
595             /* SSLfatal() already called */
596             return -1;
597         }
598     }
599
600     if (totlen == 0 && !create_empty_fragment)
601         return 0;
602
603     sess = s->session;
604
605     if ((sess == NULL)
606             || (s->enc_write_ctx == NULL)
607             || (EVP_MD_CTX_get0_md(s->write_hash) == NULL)) {
608         clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */
609         mac_size = 0;
610     } else {
611         mac_size = EVP_MD_CTX_get_size(s->write_hash);
612         if (mac_size < 0) {
613             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
614             goto err;
615         }
616     }
617
618     /*
619      * 'create_empty_fragment' is true only when this function calls itself
620      */
621     if (!clear && !create_empty_fragment && !s->s3.empty_fragment_done) {
622         /*
623          * countermeasure against known-IV weakness in CBC ciphersuites (see
624          * http://www.openssl.org/~bodo/tls-cbc.txt)
625          */
626
627         if (s->s3.need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) {
628             /*
629              * recursive function call with 'create_empty_fragment' set; this
630              * prepares and buffers the data for an empty fragment (these
631              * 'prefix_len' bytes are sent out later together with the actual
632              * payload)
633              */
634             size_t tmppipelen = 0;
635             int ret;
636
637             ret = do_ssl3_write(s, type, buf, &tmppipelen, 1, 1, &prefix_len);
638             if (ret <= 0) {
639                 /* SSLfatal() already called if appropriate */
640                 goto err;
641             }
642
643             if (prefix_len >
644                 (SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD)) {
645                 /* insufficient space */
646                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
647                 goto err;
648             }
649         }
650
651         s->s3.empty_fragment_done = 1;
652     }
653
654     using_ktls = BIO_get_ktls_send(s->wbio);
655     if (using_ktls) {
656         /*
657          * ktls doesn't modify the buffer, but to avoid a warning we need to
658          * discard the const qualifier.
659          * This doesn't leak memory because the buffers have been released when
660          * switching to ktls.
661          */
662         SSL3_BUFFER_set_buf(&s->rlayer.wbuf[0], (unsigned char *)buf);
663         SSL3_BUFFER_set_offset(&s->rlayer.wbuf[0], 0);
664         SSL3_BUFFER_set_app_buffer(&s->rlayer.wbuf[0], 1);
665         goto wpacket_init_complete;
666     }
667
668     if (create_empty_fragment) {
669         wb = &s->rlayer.wbuf[0];
670 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
671         /*
672          * extra fragment would be couple of cipher blocks, which would be
673          * multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real
674          * payload, then we can just pretend we simply have two headers.
675          */
676         align = (size_t)SSL3_BUFFER_get_buf(wb) + 2 * SSL3_RT_HEADER_LENGTH;
677         align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
678 #endif
679         SSL3_BUFFER_set_offset(wb, align);
680         if (!WPACKET_init_static_len(&pkt[0], SSL3_BUFFER_get_buf(wb),
681                                      SSL3_BUFFER_get_len(wb), 0)
682                 || !WPACKET_allocate_bytes(&pkt[0], align, NULL)) {
683             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
684             goto err;
685         }
686         wpinited = 1;
687     } else if (prefix_len) {
688         wb = &s->rlayer.wbuf[0];
689         if (!WPACKET_init_static_len(&pkt[0],
690                                      SSL3_BUFFER_get_buf(wb),
691                                      SSL3_BUFFER_get_len(wb), 0)
692                 || !WPACKET_allocate_bytes(&pkt[0], SSL3_BUFFER_get_offset(wb)
693                                                     + prefix_len, NULL)) {
694             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
695             goto err;
696         }
697         wpinited = 1;
698     } else {
699         for (j = 0; j < numpipes; j++) {
700             thispkt = &pkt[j];
701
702             wb = &s->rlayer.wbuf[j];
703 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
704             align = (size_t)SSL3_BUFFER_get_buf(wb) + SSL3_RT_HEADER_LENGTH;
705             align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
706 #endif
707             SSL3_BUFFER_set_offset(wb, align);
708             if (!WPACKET_init_static_len(thispkt, SSL3_BUFFER_get_buf(wb),
709                                          SSL3_BUFFER_get_len(wb), 0)
710                     || !WPACKET_allocate_bytes(thispkt, align, NULL)) {
711                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
712                 goto err;
713             }
714             wpinited++;
715         }
716     }
717
718     /* Explicit IV length, block ciphers appropriate version flag */
719     if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s)
720         && !SSL_CONNECTION_TREAT_AS_TLS13(s)) {
721         int mode = EVP_CIPHER_CTX_get_mode(s->enc_write_ctx);
722         if (mode == EVP_CIPH_CBC_MODE) {
723             eivlen = EVP_CIPHER_CTX_get_iv_length(s->enc_write_ctx);
724             if (eivlen < 0) {
725                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
726                 goto err;
727             }
728             if (eivlen <= 1)
729                 eivlen = 0;
730         } else if (mode == EVP_CIPH_GCM_MODE) {
731             /* Need explicit part of IV for GCM mode */
732             eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
733         } else if (mode == EVP_CIPH_CCM_MODE) {
734             eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;
735         }
736     }
737
738  wpacket_init_complete:
739
740     totlen = 0;
741     /* Clear our SSL3_RECORD structures */
742     memset(wr, 0, sizeof(wr));
743     for (j = 0; j < numpipes; j++) {
744         unsigned int version = (s->version == TLS1_3_VERSION) ? TLS1_2_VERSION
745                                                               : s->version;
746         unsigned char *compressdata = NULL;
747         size_t maxcomplen;
748         unsigned int rectype;
749
750         thispkt = &pkt[j];
751         thiswr = &wr[j];
752
753         /*
754          * In TLSv1.3, once encrypting, we always use application data for the
755          * record type
756          */
757         if (SSL_CONNECTION_TREAT_AS_TLS13(s)
758                 && s->enc_write_ctx != NULL
759                 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
760                     || type != SSL3_RT_ALERT))
761             rectype = SSL3_RT_APPLICATION_DATA;
762         else
763             rectype = type;
764         SSL3_RECORD_set_type(thiswr, rectype);
765
766         /*
767          * Some servers hang if initial client hello is larger than 256 bytes
768          * and record version number > TLS 1.0
769          */
770         if (SSL_get_state(ssl) == TLS_ST_CW_CLNT_HELLO
771                 && !s->renegotiate
772                 && TLS1_get_version(ssl) > TLS1_VERSION
773                 && s->hello_retry_request == SSL_HRR_NONE)
774             version = TLS1_VERSION;
775         SSL3_RECORD_set_rec_version(thiswr, version);
776
777         maxcomplen = pipelens[j];
778         if (s->compress != NULL)
779             maxcomplen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
780
781         /*
782          * When using offload kernel will write the header.
783          * Otherwise write the header now
784          */
785         if (!using_ktls
786                 && (!WPACKET_put_bytes_u8(thispkt, rectype)
787                 || !WPACKET_put_bytes_u16(thispkt, version)
788                 || !WPACKET_start_sub_packet_u16(thispkt)
789                 || (eivlen > 0
790                     && !WPACKET_allocate_bytes(thispkt, eivlen, NULL))
791                 || (maxcomplen > 0
792                     && !WPACKET_reserve_bytes(thispkt, maxcomplen,
793                                               &compressdata)))) {
794             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
795             goto err;
796         }
797
798         /* lets setup the record stuff. */
799         SSL3_RECORD_set_data(thiswr, compressdata);
800         SSL3_RECORD_set_length(thiswr, pipelens[j]);
801         SSL3_RECORD_set_input(thiswr, (unsigned char *)&buf[totlen]);
802         totlen += pipelens[j];
803
804         /*
805          * we now 'read' from thiswr->input, thiswr->length bytes into
806          * thiswr->data
807          */
808
809         /* first we compress */
810         if (s->compress != NULL) {
811             if (!ssl3_do_compress(s, thiswr)
812                     || !WPACKET_allocate_bytes(thispkt, thiswr->length, NULL)) {
813                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COMPRESSION_FAILURE);
814                 goto err;
815             }
816         } else {
817             if (using_ktls) {
818                 SSL3_RECORD_reset_data(&wr[j]);
819             } else {
820                 if (!WPACKET_memcpy(thispkt, thiswr->input, thiswr->length)) {
821                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
822                     goto err;
823                 }
824                 SSL3_RECORD_reset_input(&wr[j]);
825             }
826         }
827
828         if (SSL_CONNECTION_TREAT_AS_TLS13(s)
829                 && !using_ktls
830                 && s->enc_write_ctx != NULL
831                 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
832                     || type != SSL3_RT_ALERT)) {
833             size_t rlen, max_send_fragment;
834
835             if (!WPACKET_put_bytes_u8(thispkt, type)) {
836                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
837                 goto err;
838             }
839             SSL3_RECORD_add_length(thiswr, 1);
840
841             /* Add TLS1.3 padding */
842             max_send_fragment = ssl_get_max_send_fragment(s);
843             rlen = SSL3_RECORD_get_length(thiswr);
844             if (rlen < max_send_fragment) {
845                 size_t padding = 0;
846                 size_t max_padding = max_send_fragment - rlen;
847                 if (s->record_padding_cb != NULL) {
848                     padding = s->record_padding_cb(ssl, type, rlen, s->record_padding_arg);
849                 } else if (s->block_padding > 0) {
850                     size_t mask = s->block_padding - 1;
851                     size_t remainder;
852
853                     /* optimize for power of 2 */
854                     if ((s->block_padding & mask) == 0)
855                         remainder = rlen & mask;
856                     else
857                         remainder = rlen % s->block_padding;
858                     /* don't want to add a block of padding if we don't have to */
859                     if (remainder == 0)
860                         padding = 0;
861                     else
862                         padding = s->block_padding - remainder;
863                 }
864                 if (padding > 0) {
865                     /* do not allow the record to exceed max plaintext length */
866                     if (padding > max_padding)
867                         padding = max_padding;
868                     if (!WPACKET_memset(thispkt, 0, padding)) {
869                         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
870                                  ERR_R_INTERNAL_ERROR);
871                         goto err;
872                     }
873                     SSL3_RECORD_add_length(thiswr, padding);
874                 }
875             }
876         }
877
878         /*
879          * we should still have the output to thiswr->data and the input from
880          * wr->input. Length should be thiswr->length. thiswr->data still points
881          * in the wb->buf
882          */
883
884         if (!using_ktls && !SSL_WRITE_ETM(s) && mac_size != 0) {
885             unsigned char *mac;
886
887             if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
888                     || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
889                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
890                 goto err;
891             }
892         }
893
894         /*
895          * Reserve some bytes for any growth that may occur during encryption.
896          * This will be at most one cipher block or the tag length if using
897          * AEAD. SSL_RT_MAX_CIPHER_BLOCK_SIZE covers either case.
898          */
899         if (!using_ktls) {
900             if (!WPACKET_reserve_bytes(thispkt,
901                                         SSL_RT_MAX_CIPHER_BLOCK_SIZE,
902                                         NULL)
903                 /*
904                  * We also need next the amount of bytes written to this
905                  * sub-packet
906                  */
907                 || !WPACKET_get_length(thispkt, &len)) {
908             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
909             goto err;
910             }
911
912             /* Get a pointer to the start of this record excluding header */
913             recordstart = WPACKET_get_curr(thispkt) - len;
914             SSL3_RECORD_set_data(thiswr, recordstart);
915             SSL3_RECORD_reset_input(thiswr);
916             SSL3_RECORD_set_length(thiswr, len);
917         }
918     }
919
920     if (s->statem.enc_write_state == ENC_WRITE_STATE_WRITE_PLAIN_ALERTS) {
921         /*
922          * We haven't actually negotiated the version yet, but we're trying to
923          * send early data - so we need to use the tls13enc function.
924          */
925         if (tls13_enc(s, wr, numpipes, 1, NULL, mac_size) < 1) {
926             if (!ossl_statem_in_error(s)) {
927                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
928             }
929             goto err;
930         }
931     } else {
932         if (!using_ktls) {
933             if (ssl->method->ssl3_enc->enc(s, wr, numpipes, 1, NULL,
934                                          mac_size) < 1) {
935                 if (!ossl_statem_in_error(s)) {
936                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
937                 }
938                 goto err;
939             }
940         }
941     }
942
943     for (j = 0; j < numpipes; j++) {
944         size_t origlen;
945
946         thispkt = &pkt[j];
947         thiswr = &wr[j];
948
949         if (using_ktls)
950             goto mac_done;
951
952         /* Allocate bytes for the encryption overhead */
953         if (!WPACKET_get_length(thispkt, &origlen)
954                    /* Encryption should never shrink the data! */
955                 || origlen > thiswr->length
956                 || (thiswr->length > origlen
957                     && !WPACKET_allocate_bytes(thispkt,
958                                                thiswr->length - origlen,
959                                                NULL))) {
960             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
961             goto err;
962         }
963         if (SSL_WRITE_ETM(s) && mac_size != 0) {
964             unsigned char *mac;
965
966             if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
967                     || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
968                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
969                 goto err;
970             }
971             SSL3_RECORD_add_length(thiswr, mac_size);
972         }
973
974         if (!WPACKET_get_length(thispkt, &len)
975                 || !WPACKET_close(thispkt)) {
976             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
977             goto err;
978         }
979
980         if (s->msg_callback) {
981             recordstart = WPACKET_get_curr(thispkt) - len
982                           - SSL3_RT_HEADER_LENGTH;
983             s->msg_callback(1, thiswr->rec_version, SSL3_RT_HEADER, recordstart,
984                             SSL3_RT_HEADER_LENGTH, ssl,
985                             s->msg_callback_arg);
986
987             if (SSL_CONNECTION_TREAT_AS_TLS13(s) && s->enc_write_ctx != NULL) {
988                 unsigned char ctype = type;
989
990                 s->msg_callback(1, thiswr->rec_version, SSL3_RT_INNER_CONTENT_TYPE,
991                                 &ctype, 1, ssl, s->msg_callback_arg);
992             }
993         }
994
995         if (!WPACKET_finish(thispkt)) {
996             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
997             goto err;
998         }
999
1000         /* header is added by the kernel when using offload */
1001         SSL3_RECORD_add_length(thiswr, SSL3_RT_HEADER_LENGTH);
1002
1003         if (create_empty_fragment) {
1004             /*
1005              * we are in a recursive call; just return the length, don't write
1006              * out anything here
1007              */
1008             if (j > 0) {
1009                 /* We should never be pipelining an empty fragment!! */
1010                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1011                 goto err;
1012             }
1013             *written = SSL3_RECORD_get_length(thiswr);
1014             return 1;
1015         }
1016
1017  mac_done:
1018         /*
1019          * we should now have thiswr->data pointing to the encrypted data, which
1020          * is thiswr->length long
1021          */
1022         SSL3_RECORD_set_type(thiswr, type); /* not needed but helps for
1023                                              * debugging */
1024
1025         /* now let's set up wb */
1026         SSL3_BUFFER_set_left(&s->rlayer.wbuf[j],
1027                              prefix_len + SSL3_RECORD_get_length(thiswr));
1028     }
1029
1030     /*
1031      * memorize arguments so that ssl3_write_pending can detect bad write
1032      * retries later
1033      */
1034     s->rlayer.wpend_tot = totlen;
1035     s->rlayer.wpend_buf = buf;
1036     s->rlayer.wpend_type = type;
1037     s->rlayer.wpend_ret = totlen;
1038
1039     /* we now just need to write the buffer */
1040     return ssl3_write_pending(s, type, buf, totlen, written);
1041  err:
1042     for (j = 0; j < wpinited; j++)
1043         WPACKET_cleanup(&pkt[j]);
1044     return -1;
1045 }
1046
1047 /* if SSL3_BUFFER_get_left() != 0, we need to call this
1048  *
1049  * Return values are as per SSL_write()
1050  */
1051 int ssl3_write_pending(SSL_CONNECTION *s, int type, const unsigned char *buf,
1052                        size_t len, size_t *written)
1053 {
1054     int i;
1055     SSL3_BUFFER *wb = s->rlayer.wbuf;
1056     size_t currbuf = 0;
1057     size_t tmpwrit = 0;
1058
1059     if ((s->rlayer.wpend_tot > len)
1060         || (!(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)
1061             && (s->rlayer.wpend_buf != buf))
1062         || (s->rlayer.wpend_type != type)) {
1063         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_WRITE_RETRY);
1064         return -1;
1065     }
1066
1067     for (;;) {
1068         /* Loop until we find a buffer we haven't written out yet */
1069         if (SSL3_BUFFER_get_left(&wb[currbuf]) == 0
1070             && currbuf < s->rlayer.numwpipes - 1) {
1071             currbuf++;
1072             continue;
1073         }
1074         clear_sys_error();
1075         if (s->wbio != NULL) {
1076             s->rwstate = SSL_WRITING;
1077
1078             /*
1079              * To prevent coalescing of control and data messages,
1080              * such as in buffer_write, we flush the BIO
1081              */
1082             if (BIO_get_ktls_send(s->wbio) && type != SSL3_RT_APPLICATION_DATA) {
1083                 i = BIO_flush(s->wbio);
1084                 if (i <= 0)
1085                     return i;
1086                 BIO_set_ktls_ctrl_msg(s->wbio, type);
1087             }
1088             i = BIO_write(s->wbio, (char *)
1089                           &(SSL3_BUFFER_get_buf(&wb[currbuf])
1090                             [SSL3_BUFFER_get_offset(&wb[currbuf])]),
1091                           (unsigned int)SSL3_BUFFER_get_left(&wb[currbuf]));
1092             if (i >= 0)
1093                 tmpwrit = i;
1094         } else {
1095             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BIO_NOT_SET);
1096             i = -1;
1097         }
1098
1099         /*
1100          * When an empty fragment is sent on a connection using KTLS,
1101          * it is sent as a write of zero bytes.  If this zero byte
1102          * write succeeds, i will be 0 rather than a non-zero value.
1103          * Treat i == 0 as success rather than an error for zero byte
1104          * writes to permit this case.
1105          */
1106         if (i >= 0 && tmpwrit == SSL3_BUFFER_get_left(&wb[currbuf])) {
1107             SSL3_BUFFER_set_left(&wb[currbuf], 0);
1108             SSL3_BUFFER_add_offset(&wb[currbuf], tmpwrit);
1109             if (currbuf + 1 < s->rlayer.numwpipes)
1110                 continue;
1111             s->rwstate = SSL_NOTHING;
1112             *written = s->rlayer.wpend_ret;
1113             return 1;
1114         } else if (i <= 0) {
1115             if (SSL_CONNECTION_IS_DTLS(s)) {
1116                 /*
1117                  * For DTLS, just drop it. That's kind of the whole point in
1118                  * using a datagram service
1119                  */
1120                 SSL3_BUFFER_set_left(&wb[currbuf], 0);
1121             }
1122             return i;
1123         }
1124         SSL3_BUFFER_add_offset(&wb[currbuf], tmpwrit);
1125         SSL3_BUFFER_sub_left(&wb[currbuf], tmpwrit);
1126     }
1127 }
1128
1129 int ossl_tls_handle_rlayer_return(SSL_CONNECTION *s, int ret, char *file,
1130                                   int line)
1131 {
1132     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1133
1134     if (ret == OSSL_RECORD_RETURN_RETRY) {
1135         s->rwstate = SSL_READING;
1136         ret = -1;
1137     } else {
1138         s->rwstate = SSL_NOTHING;
1139         if (ret == OSSL_RECORD_RETURN_EOF) {
1140             if (s->options & SSL_OP_IGNORE_UNEXPECTED_EOF) {
1141                 SSL_set_shutdown(ssl, SSL_RECEIVED_SHUTDOWN);
1142                 s->s3.warn_alert = SSL_AD_CLOSE_NOTIFY;
1143             } else {
1144                 ERR_new();
1145                 ERR_set_debug(file, line, 0);
1146                 ossl_statem_fatal(s, SSL_AD_DECODE_ERROR,
1147                                   SSL_R_UNEXPECTED_EOF_WHILE_READING, NULL);
1148             }
1149         } else if (ret == OSSL_RECORD_RETURN_FATAL) {
1150             ERR_new();
1151             ERR_set_debug(file, line, 0);
1152             ossl_statem_fatal(s, s->rrlmethod->get_alert_code(s->rrl),
1153                               SSL_R_RECORD_LAYER_FAILURE, NULL);
1154         }
1155         /*
1156          * The record layer distinguishes the cases of EOF, non-fatal
1157          * err and retry. Upper layers do not.
1158          * If we got a retry or success then *ret is already correct,
1159          * otherwise we need to convert the return value.
1160          */
1161         /*
1162          * TODO(RECLAYER): What does a non fatal err that isn't a retry even
1163          * mean???
1164          */
1165         if (ret == OSSL_RECORD_RETURN_NON_FATAL_ERR || ret == OSSL_RECORD_RETURN_EOF)
1166             ret = 0;
1167         else if (ret < OSSL_RECORD_RETURN_NON_FATAL_ERR)
1168             ret = -1;
1169     }
1170
1171     return ret;
1172 }
1173
1174 /*-
1175  * Return up to 'len' payload bytes received in 'type' records.
1176  * 'type' is one of the following:
1177  *
1178  *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
1179  *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
1180  *   -  0 (during a shutdown, no data has to be returned)
1181  *
1182  * If we don't have stored data to work from, read a SSL/TLS record first
1183  * (possibly multiple records if we still don't have anything to return).
1184  *
1185  * This function must handle any surprises the peer may have for us, such as
1186  * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
1187  * messages are treated as if they were handshake messages *if* the |recvd_type|
1188  * argument is non NULL.
1189  * Also if record payloads contain fragments too small to process, we store
1190  * them until there is enough for the respective protocol (the record protocol
1191  * may use arbitrary fragmentation and even interleaving):
1192  *     Change cipher spec protocol
1193  *             just 1 byte needed, no need for keeping anything stored
1194  *     Alert protocol
1195  *             2 bytes needed (AlertLevel, AlertDescription)
1196  *     Handshake protocol
1197  *             4 bytes needed (HandshakeType, uint24 length) -- we just have
1198  *             to detect unexpected Client Hello and Hello Request messages
1199  *             here, anything else is handled by higher layers
1200  *     Application data protocol
1201  *             none of our business
1202  */
1203 int ssl3_read_bytes(SSL *ssl, int type, int *recvd_type, unsigned char *buf,
1204                     size_t len, int peek, size_t *readbytes)
1205 {
1206     int i, j, ret;
1207     size_t n, curr_rec, totalbytes;
1208     TLS_RECORD *rr;
1209     void (*cb) (const SSL *ssl, int type2, int val) = NULL;
1210     int is_tls13;
1211     SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
1212
1213     is_tls13 = SSL_CONNECTION_IS_TLS13(s);
1214
1215     if ((type != 0
1216             && (type != SSL3_RT_APPLICATION_DATA)
1217             && (type != SSL3_RT_HANDSHAKE))
1218         || (peek && (type != SSL3_RT_APPLICATION_DATA))) {
1219         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1220         return -1;
1221     }
1222
1223     if ((type == SSL3_RT_HANDSHAKE) && (s->rlayer.handshake_fragment_len > 0))
1224         /* (partially) satisfy request from storage */
1225     {
1226         unsigned char *src = s->rlayer.handshake_fragment;
1227         unsigned char *dst = buf;
1228         unsigned int k;
1229
1230         /* peek == 0 */
1231         n = 0;
1232         while ((len > 0) && (s->rlayer.handshake_fragment_len > 0)) {
1233             *dst++ = *src++;
1234             len--;
1235             s->rlayer.handshake_fragment_len--;
1236             n++;
1237         }
1238         /* move any remaining fragment bytes: */
1239         for (k = 0; k < s->rlayer.handshake_fragment_len; k++)
1240             s->rlayer.handshake_fragment[k] = *src++;
1241
1242         if (recvd_type != NULL)
1243             *recvd_type = SSL3_RT_HANDSHAKE;
1244
1245         *readbytes = n;
1246         return 1;
1247     }
1248
1249     /*
1250      * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
1251      */
1252
1253     if (!ossl_statem_get_in_handshake(s) && SSL_in_init(ssl)) {
1254         /* type == SSL3_RT_APPLICATION_DATA */
1255         i = s->handshake_func(ssl);
1256         /* SSLfatal() already called */
1257         if (i < 0)
1258             return i;
1259         if (i == 0)
1260             return -1;
1261     }
1262  start:
1263     s->rwstate = SSL_NOTHING;
1264
1265     /*-
1266      * For each record 'i' up to |num_recs]
1267      * rr[i].type     - is the type of record
1268      * rr[i].data,    - data
1269      * rr[i].off,     - offset into 'data' for next read
1270      * rr[i].length,  - number of bytes.
1271      */
1272     /* get new records if necessary */
1273     if (s->rlayer.curr_rec >= s->rlayer.num_recs) {
1274         s->rlayer.curr_rec = s->rlayer.num_recs = 0;
1275         do {
1276             rr = &s->rlayer.tlsrecs[s->rlayer.num_recs];
1277
1278             ret = HANDLE_RLAYER_RETURN(s,
1279                     s->rrlmethod->read_record(s->rrl, &rr->rechandle,
1280                                               &rr->version, &rr->type,
1281                                               &rr->data, &rr->length,
1282                                               NULL, NULL, s));
1283             if (ret <= 0) {
1284                 /* SSLfatal() already called if appropriate */
1285                 return ret;
1286             }
1287             rr->off = 0;
1288             s->rlayer.num_recs++;
1289         } while (s->rrlmethod->processed_read_pending(s->rrl)
1290                  && s->rlayer.num_recs < SSL_MAX_PIPELINES);
1291     }
1292     rr = &s->rlayer.tlsrecs[s->rlayer.curr_rec];
1293
1294     if (s->rlayer.handshake_fragment_len > 0
1295             && SSL3_RECORD_get_type(rr) != SSL3_RT_HANDSHAKE
1296             && SSL_CONNECTION_IS_TLS13(s)) {
1297         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1298                  SSL_R_MIXED_HANDSHAKE_AND_NON_HANDSHAKE_DATA);
1299         return -1;
1300     }
1301
1302     /*
1303      * Reset the count of consecutive warning alerts if we've got a non-empty
1304      * record that isn't an alert.
1305      */
1306     if (rr->type != SSL3_RT_ALERT && rr->length != 0)
1307         s->rlayer.alert_count = 0;
1308
1309     /* we now have a packet which can be read and processed */
1310
1311     if (s->s3.change_cipher_spec /* set when we receive ChangeCipherSpec,
1312                                   * reset by ssl3_get_finished */
1313         && (rr->type != SSL3_RT_HANDSHAKE)) {
1314         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1315                  SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
1316         return -1;
1317     }
1318
1319     /*
1320      * If the other end has shut down, throw anything we read away (even in
1321      * 'peek' mode)
1322      */
1323     if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1324         s->rlayer.curr_rec++;
1325         s->rwstate = SSL_NOTHING;
1326         return 0;
1327     }
1328
1329     if (type == rr->type
1330         || (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
1331             && type == SSL3_RT_HANDSHAKE && recvd_type != NULL
1332             && !is_tls13)) {
1333         /*
1334          * SSL3_RT_APPLICATION_DATA or
1335          * SSL3_RT_HANDSHAKE or
1336          * SSL3_RT_CHANGE_CIPHER_SPEC
1337          */
1338         /*
1339          * make sure that we are not getting application data when we are
1340          * doing a handshake for the first time
1341          */
1342         if (SSL_in_init(ssl) && type == SSL3_RT_APPLICATION_DATA
1343             && s->enc_read_ctx == NULL) {
1344             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_APP_DATA_IN_HANDSHAKE);
1345             return -1;
1346         }
1347
1348         if (type == SSL3_RT_HANDSHAKE
1349             && rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
1350             && s->rlayer.handshake_fragment_len > 0) {
1351             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
1352             return -1;
1353         }
1354
1355         if (recvd_type != NULL)
1356             *recvd_type = rr->type;
1357
1358         if (len == 0) {
1359             /*
1360              * Skip a zero length record. This ensures multiple calls to
1361              * SSL_read() with a zero length buffer will eventually cause
1362              * SSL_pending() to report data as being available.
1363              */
1364             if (rr->length == 0) {
1365                 s->rrlmethod->release_record(s->rrl, rr->rechandle);
1366                 s->rlayer.curr_rec++;
1367             }
1368             return 0;
1369         }
1370
1371         totalbytes = 0;
1372         curr_rec = s->rlayer.curr_rec;
1373         do {
1374             if (len - totalbytes > rr->length)
1375                 n = rr->length;
1376             else
1377                 n = len - totalbytes;
1378
1379             memcpy(buf, &(rr->data[rr->off]), n);
1380             buf += n;
1381             if (peek) {
1382                 /* Mark any zero length record as consumed CVE-2016-6305 */
1383                 if (rr->length == 0) {
1384                     s->rrlmethod->release_record(s->rrl, rr->rechandle);
1385                     s->rlayer.curr_rec++;
1386                 }
1387             } else {
1388                 if (s->options & SSL_OP_CLEANSE_PLAINTEXT)
1389                     OPENSSL_cleanse(&(rr->data[rr->off]), n);
1390                 rr->length -= n;
1391                 rr->off += n;
1392                 if (rr->length == 0) {
1393                     /* TODO(RECLAYER): What to do with this? Is it needed? */
1394                     #if 0
1395                     s->rlayer.rstate = SSL_ST_READ_HEADER;
1396                     #endif
1397                     s->rrlmethod->release_record(s->rrl, rr->rechandle);
1398                     s->rlayer.curr_rec++;
1399                 }
1400             }
1401             if (rr->length == 0
1402                 || (peek && n == rr->length)) {
1403                 rr++;
1404                 curr_rec++;
1405             }
1406             totalbytes += n;
1407         } while (type == SSL3_RT_APPLICATION_DATA
1408                     && curr_rec < s->rlayer.num_recs
1409                     && totalbytes < len);
1410         if (totalbytes == 0) {
1411             /* We must have read empty records. Get more data */
1412             goto start;
1413         }
1414         /* TODO(RECLAYER): FIX ME */
1415 #if 0
1416         if (!peek && curr_rec == s->rlayer.num_recs
1417             && (s->mode & SSL_MODE_RELEASE_BUFFERS)
1418             && SSL3_BUFFER_get_left(rbuf) == 0)
1419             ssl3_release_read_buffer(s);
1420 #endif
1421         *readbytes = totalbytes;
1422         return 1;
1423     }
1424
1425     /*
1426      * If we get here, then type != rr->type; if we have a handshake message,
1427      * then it was unexpected (Hello Request or Client Hello) or invalid (we
1428      * were actually expecting a CCS).
1429      */
1430
1431     /*
1432      * Lets just double check that we've not got an SSLv2 record
1433      */
1434     if (rr->version == SSL2_VERSION) {
1435         /*
1436          * Should never happen. ssl3_get_record() should only give us an SSLv2
1437          * record back if this is the first packet and we are looking for an
1438          * initial ClientHello. Therefore |type| should always be equal to
1439          * |rr->type|. If not then something has gone horribly wrong
1440          */
1441         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1442         return -1;
1443     }
1444
1445     if (ssl->method->version == TLS_ANY_VERSION
1446         && (s->server || rr->type != SSL3_RT_ALERT)) {
1447         /*
1448          * If we've got this far and still haven't decided on what version
1449          * we're using then this must be a client side alert we're dealing
1450          * with. We shouldn't be receiving anything other than a ClientHello
1451          * if we are a server.
1452          */
1453         s->version = rr->version;
1454         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
1455         return -1;
1456     }
1457
1458     /*-
1459      * s->rlayer.handshake_fragment_len == 4  iff  rr->type == SSL3_RT_HANDSHAKE;
1460      * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
1461      */
1462
1463     if (rr->type == SSL3_RT_ALERT) {
1464         unsigned int alert_level, alert_descr;
1465         unsigned char *alert_bytes = rr->data
1466                                      + rr->off;
1467         PACKET alert;
1468
1469         if (!PACKET_buf_init(&alert, alert_bytes, rr->length)
1470                 || !PACKET_get_1(&alert, &alert_level)
1471                 || !PACKET_get_1(&alert, &alert_descr)
1472                 || PACKET_remaining(&alert) != 0) {
1473             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_INVALID_ALERT);
1474             return -1;
1475         }
1476
1477         if (s->msg_callback)
1478             s->msg_callback(0, s->version, SSL3_RT_ALERT, alert_bytes, 2, ssl,
1479                             s->msg_callback_arg);
1480
1481         if (s->info_callback != NULL)
1482             cb = s->info_callback;
1483         else if (ssl->ctx->info_callback != NULL)
1484             cb = ssl->ctx->info_callback;
1485
1486         if (cb != NULL) {
1487             j = (alert_level << 8) | alert_descr;
1488             cb(ssl, SSL_CB_READ_ALERT, j);
1489         }
1490
1491         if ((!is_tls13 && alert_level == SSL3_AL_WARNING)
1492                 || (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED)) {
1493             s->s3.warn_alert = alert_descr;
1494             s->rrlmethod->release_record(s->rrl, rr->rechandle);
1495             s->rlayer.curr_rec++;
1496
1497             s->rlayer.alert_count++;
1498             if (s->rlayer.alert_count == MAX_WARN_ALERT_COUNT) {
1499                 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1500                          SSL_R_TOO_MANY_WARN_ALERTS);
1501                 return -1;
1502             }
1503         }
1504
1505         /*
1506          * Apart from close_notify the only other warning alert in TLSv1.3
1507          * is user_cancelled - which we just ignore.
1508          */
1509         if (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED) {
1510             goto start;
1511         } else if (alert_descr == SSL_AD_CLOSE_NOTIFY
1512                 && (is_tls13 || alert_level == SSL3_AL_WARNING)) {
1513             s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1514             return 0;
1515         } else if (alert_level == SSL3_AL_FATAL || is_tls13) {
1516             s->rwstate = SSL_NOTHING;
1517             s->s3.fatal_alert = alert_descr;
1518             SSLfatal_data(s, SSL_AD_NO_ALERT,
1519                           SSL_AD_REASON_OFFSET + alert_descr,
1520                           "SSL alert number %d", alert_descr);
1521             s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1522             s->rrlmethod->release_record(s->rrl, rr->rechandle);
1523             s->rlayer.curr_rec++;
1524             SSL_CTX_remove_session(s->session_ctx, s->session);
1525             return 0;
1526         } else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
1527             /*
1528              * This is a warning but we receive it if we requested
1529              * renegotiation and the peer denied it. Terminate with a fatal
1530              * alert because if application tried to renegotiate it
1531              * presumably had a good reason and expects it to succeed. In
1532              * future we might have a renegotiation where we don't care if
1533              * the peer refused it where we carry on.
1534              */
1535             SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_RENEGOTIATION);
1536             return -1;
1537         } else if (alert_level == SSL3_AL_WARNING) {
1538             /* We ignore any other warning alert in TLSv1.2 and below */
1539             goto start;
1540         }
1541
1542         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_ALERT_TYPE);
1543         return -1;
1544     }
1545
1546     if ((s->shutdown & SSL_SENT_SHUTDOWN) != 0) {
1547         if (rr->type == SSL3_RT_HANDSHAKE) {
1548             BIO *rbio;
1549
1550             /*
1551              * We ignore any handshake messages sent to us unless they are
1552              * TLSv1.3 in which case we want to process them. For all other
1553              * handshake messages we can't do anything reasonable with them
1554              * because we are unable to write any response due to having already
1555              * sent close_notify.
1556              */
1557             if (!SSL_CONNECTION_IS_TLS13(s)) {
1558                 s->rrlmethod->release_record(s->rrl, rr->rechandle);
1559                 s->rlayer.curr_rec++;
1560
1561                 if ((s->mode & SSL_MODE_AUTO_RETRY) != 0)
1562                     goto start;
1563
1564                 s->rwstate = SSL_READING;
1565                 rbio = SSL_get_rbio(ssl);
1566                 BIO_clear_retry_flags(rbio);
1567                 BIO_set_retry_read(rbio);
1568                 return -1;
1569             }
1570         } else {
1571             /*
1572              * The peer is continuing to send application data, but we have
1573              * already sent close_notify. If this was expected we should have
1574              * been called via SSL_read() and this would have been handled
1575              * above.
1576              * No alert sent because we already sent close_notify
1577              */
1578             s->rrlmethod->release_record(s->rrl, rr->rechandle);
1579             s->rlayer.curr_rec++;
1580             SSLfatal(s, SSL_AD_NO_ALERT,
1581                      SSL_R_APPLICATION_DATA_AFTER_CLOSE_NOTIFY);
1582             return -1;
1583         }
1584     }
1585
1586     /*
1587      * For handshake data we have 'fragment' storage, so fill that so that we
1588      * can process the header at a fixed place. This is done after the
1589      * "SHUTDOWN" code above to avoid filling the fragment storage with data
1590      * that we're just going to discard.
1591      */
1592     if (rr->type == SSL3_RT_HANDSHAKE) {
1593         size_t dest_maxlen = sizeof(s->rlayer.handshake_fragment);
1594         unsigned char *dest = s->rlayer.handshake_fragment;
1595         size_t *dest_len = &s->rlayer.handshake_fragment_len;
1596
1597         n = dest_maxlen - *dest_len; /* available space in 'dest' */
1598         if (rr->length < n)
1599             n = rr->length; /* available bytes */
1600
1601         /* now move 'n' bytes: */
1602         memcpy(dest + *dest_len, rr->data + rr->off, n);
1603         rr->off += n;
1604         rr->length -= n;
1605         *dest_len += n;
1606         if (rr->length == 0) {
1607             s->rrlmethod->release_record(s->rrl, rr->rechandle);
1608             s->rlayer.curr_rec++;
1609         }
1610
1611         if (*dest_len < dest_maxlen)
1612             goto start;     /* fragment was too small */
1613     }
1614
1615     if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1616         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
1617         return -1;
1618     }
1619
1620     /*
1621      * Unexpected handshake message (ClientHello, NewSessionTicket (TLS1.3) or
1622      * protocol violation)
1623      */
1624     if ((s->rlayer.handshake_fragment_len >= 4)
1625             && !ossl_statem_get_in_handshake(s)) {
1626         int ined = (s->early_data_state == SSL_EARLY_DATA_READING);
1627
1628         /* We found handshake data, so we're going back into init */
1629         ossl_statem_set_in_init(s, 1);
1630
1631         i = s->handshake_func(ssl);
1632         /* SSLfatal() already called if appropriate */
1633         if (i < 0)
1634             return i;
1635         if (i == 0) {
1636             return -1;
1637         }
1638
1639         /*
1640          * If we were actually trying to read early data and we found a
1641          * handshake message, then we don't want to continue to try and read
1642          * the application data any more. It won't be "early" now.
1643          */
1644         if (ined)
1645             return -1;
1646
1647         if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1648             if (!RECORD_LAYER_read_pending(&s->rlayer)) {
1649                 BIO *bio;
1650                 /*
1651                  * In the case where we try to read application data, but we
1652                  * trigger an SSL handshake, we return -1 with the retry
1653                  * option set.  Otherwise renegotiation may cause nasty
1654                  * problems in the blocking world
1655                  */
1656                 s->rwstate = SSL_READING;
1657                 bio = SSL_get_rbio(ssl);
1658                 BIO_clear_retry_flags(bio);
1659                 BIO_set_retry_read(bio);
1660                 return -1;
1661             }
1662         }
1663         goto start;
1664     }
1665
1666     switch (rr->type) {
1667     default:
1668         /*
1669          * TLS 1.0 and 1.1 say you SHOULD ignore unrecognised record types, but
1670          * TLS 1.2 says you MUST send an unexpected message alert. We use the
1671          * TLS 1.2 behaviour for all protocol versions to prevent issues where
1672          * no progress is being made and the peer continually sends unrecognised
1673          * record types, using up resources processing them.
1674          */
1675         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1676         return -1;
1677     case SSL3_RT_CHANGE_CIPHER_SPEC:
1678     case SSL3_RT_ALERT:
1679     case SSL3_RT_HANDSHAKE:
1680         /*
1681          * we already handled all of these, with the possible exception of
1682          * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
1683          * that should not happen when type != rr->type
1684          */
1685         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, ERR_R_INTERNAL_ERROR);
1686         return -1;
1687     case SSL3_RT_APPLICATION_DATA:
1688         /*
1689          * At this point, we were expecting handshake data, but have
1690          * application data.  If the library was running inside ssl3_read()
1691          * (i.e. in_read_app_data is set) and it makes sense to read
1692          * application data at this point (session renegotiation not yet
1693          * started), we will indulge it.
1694          */
1695         if (ossl_statem_app_data_allowed(s)) {
1696             s->s3.in_read_app_data = 2;
1697             return -1;
1698         } else if (ossl_statem_skip_early_data(s)) {
1699             /*
1700              * This can happen after a client sends a CH followed by early_data,
1701              * but the server responds with a HelloRetryRequest. The server
1702              * reads the next record from the client expecting to find a
1703              * plaintext ClientHello but gets a record which appears to be
1704              * application data. The trial decrypt "works" because null
1705              * decryption was applied. We just skip it and move on to the next
1706              * record.
1707              */
1708             if (!ossl_early_data_count_ok(s, rr->length,
1709                                           EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
1710                 /* SSLfatal() already called */
1711                 return -1;
1712             }
1713             s->rrlmethod->release_record(s->rrl, rr->rechandle);
1714             s->rlayer.curr_rec++;
1715             goto start;
1716         } else {
1717             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1718             return -1;
1719         }
1720     }
1721 }
1722
1723 void ssl3_record_sequence_update(unsigned char *seq)
1724 {
1725     int i;
1726
1727     for (i = 7; i >= 0; i--) {
1728         ++seq[i];
1729         if (seq[i] != 0)
1730             break;
1731     }
1732 }
1733
1734 /*
1735  * Returns true if the current rrec was sent in SSLv2 backwards compatible
1736  * format and false otherwise.
1737  */
1738 int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl)
1739 {
1740     if (SSL_CONNECTION_IS_DTLS(rl->s))
1741         return 0;
1742     return rl->tlsrecs[0].version == SSL2_VERSION;
1743 }
1744
1745 /*
1746  * Returns the length in bytes of the current rrec
1747  */
1748 size_t RECORD_LAYER_get_rrec_length(RECORD_LAYER *rl)
1749 {
1750     return SSL3_RECORD_get_length(&rl->rrec[0]);
1751 }
1752
1753 static const OSSL_RECORD_METHOD *ssl_select_next_record_layer(SSL_CONNECTION *s,
1754                                                               int level)
1755 {
1756
1757     if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE) {
1758         if (SSL_CONNECTION_IS_DTLS(s))
1759             return &ossl_dtls_record_method;
1760
1761         return &ossl_tls_record_method;
1762     }
1763
1764 #ifndef OPENSSL_NO_KTLS
1765     /* KTLS does not support renegotiation */
1766     if (level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION
1767             && (s->options & SSL_OP_ENABLE_KTLS) != 0
1768             && (SSL_CONNECTION_IS_TLS13(s) || SSL_IS_FIRST_HANDSHAKE(s)))
1769         return &ossl_ktls_record_method;
1770 #endif
1771
1772     /* Default to the current OSSL_RECORD_METHOD */
1773     return s->rrlmethod;
1774 }
1775
1776 static int ssl_post_record_layer_select(SSL_CONNECTION *s)
1777 {
1778 #ifndef OPENSSL_NO_KTLS
1779     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1780
1781     if (s->rrlmethod == &ossl_ktls_record_method) {
1782         /* KTLS does not support renegotiation so disallow it */
1783         SSL_set_options(ssl, SSL_OP_NO_RENEGOTIATION);
1784     }
1785 #endif
1786     if (SSL_IS_FIRST_HANDSHAKE(s) && s->rrlmethod->set_first_handshake != NULL)
1787         s->rrlmethod->set_first_handshake(s->rrl, 1);
1788     return 1;
1789 }
1790
1791 int ssl_set_new_record_layer(SSL_CONNECTION *s, int version,
1792                              int direction, int level,
1793                              unsigned char *key, size_t keylen,
1794                              unsigned char *iv,  size_t ivlen,
1795                              unsigned char *mackey, size_t mackeylen,
1796                              const EVP_CIPHER *ciph, size_t taglen,
1797                              int mactype, const EVP_MD *md,
1798                              const SSL_COMP *comp)
1799 {
1800     OSSL_PARAM_BLD *tmpl = NULL;
1801     OSSL_PARAM *options = NULL;
1802     const OSSL_RECORD_METHOD *origmeth = s->rrlmethod;
1803     int ret = 0;
1804     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1805     const OSSL_RECORD_METHOD *meth;
1806
1807     meth = ssl_select_next_record_layer(s, level);
1808
1809     if (s->rrlmethod != NULL)
1810         s->rrlmethod->free(s->rrl);
1811
1812     if (meth != NULL)
1813         s->rrlmethod = meth;
1814
1815     if (!ossl_assert(s->rrlmethod != NULL)) {
1816         ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1817         return 0;
1818     }
1819
1820     if ((tmpl = OSSL_PARAM_BLD_new()) == NULL
1821             || !OSSL_PARAM_BLD_push_uint64(tmpl,
1822                                            OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS,
1823                                            s->options)
1824             || !OSSL_PARAM_BLD_push_uint32(tmpl,
1825                                            OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE,
1826                                            s->mode)
1827             || !OSSL_PARAM_BLD_push_int(tmpl,
1828                                         OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD,
1829                                         s->rlayer.read_ahead)
1830             || (options = OSSL_PARAM_BLD_to_param(tmpl)) == NULL) {
1831         ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1832         goto err;
1833     }
1834
1835     for (;;) {
1836         int rlret;
1837
1838         rlret = s->rrlmethod->new_record_layer(sctx->libctx, sctx->propq,
1839                                                version, s->server, direction,
1840                                                level, key, keylen, iv, ivlen,
1841                                                mackey, mackeylen, ciph, taglen,
1842                                                mactype, md, comp,  s->rbio,
1843                                                NULL, NULL, NULL, options,
1844                                                &s->rrl, s);
1845         switch (rlret) {
1846         case OSSL_RECORD_RETURN_FATAL:
1847             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_RECORD_LAYER_FAILURE);
1848             goto err;
1849
1850         case OSSL_RECORD_RETURN_NON_FATAL_ERR:
1851             if (s->rrlmethod != origmeth && origmeth != NULL) {
1852                 /*
1853                  * We tried a new record layer method, but it didn't work out,
1854                  * so we fallback to the original method and try again
1855                  */
1856                 s->rrlmethod = origmeth;
1857                 continue;
1858             }
1859             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_NO_SUITABLE_RECORD_LAYER);
1860             goto err;
1861
1862         case OSSL_RECORD_RETURN_SUCCESS:
1863             break;
1864
1865         default:
1866             /* Should not happen */
1867             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1868             goto err;
1869         }
1870         break;
1871     }
1872
1873     ret = ssl_post_record_layer_select(s);
1874  err:
1875     OSSL_PARAM_free(options);
1876     OSSL_PARAM_BLD_free(tmpl);
1877
1878     return ret;
1879 }